是否有办法断言Pytest测试用例由于pytest超时而失败?我想运行一个长寿测试,我希望它不会出现问题,直到遇到pytest超时。我用@ pytest.mark.timeout(6000)注释了测试以覆盖默认的pytest超时,当遇到6000秒的超时时,测试失败,并显示E Failed: Timeout >6000.0s
。
我尝试在测试中添加with pytest.raises(pytest.TimeoutExpired)
来捕获最终的超时,但这似乎并没有解决问题。有没有办法正确捕捉pytest引起的超时?
答案 0 :(得分:1)
不幸的是,提供@pytest.mark.timeout
标记的pytest-timeout plugin没有提供捕获超时的方法(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!')