gpt4 book ai didi

python - Pytest 断言超时?

转载 作者:行者123 更新时间:2023-12-05 02:09:21 27 4
gpt4 key购买 nike

有没有办法断言 Pytest 测试用例由于 pytest 超时而失败?我想运行一个我希望运行没有问题的生命周期测试,直到遇到 pytest 超时。我用 @pytest.mark.timeout(6000) 注释测试以覆盖默认的 pytest 超时,当遇到 6000 秒超时时,测试失败并显示 E Failed: Timeout >6000.0s

我已经尝试将 with pytest.raises(pytest.TimeoutExpired) 添加到我的测试中以捕捉最终的超时,但这似乎并没有起到作用。有没有办法正确捕捉 pytest 引发的超时?

最佳答案

不幸的是,pytest-timeout plugin ,它提供了 @pytest.mark.timeout 标记,不提供捕捉超时的方法(source 供引用)。

使用提供超时功能的库作为上下文管理器可能会更幸运,例如来自 Thomas Ahle 的库的 answer

import signal

class Timeout:
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise TimeoutError(self.error_message)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0)

def test_it_doesnt_succeed():
try:
with Timeout(seconds=6):
do_the_thing()
except TimeoutError:
pass
else:
raise AssertionError('Expected the thing to timeout!')

关于python - Pytest 断言超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59994077/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com