有没有办法断言Pytest测试用例由于pytest超时而失败?我想运行一个寿命测试,我希望该测试运行时没有问题,直到遇到最严重的超时。我使用@pytest.mark.timeout( 6000 )注释测试,以覆盖默认的pytest超时,当遇到6000秒的超时时,测试将失败,并显示E Failed: Timeout >6000.0s。
我尝试将with pytest.raises(pytest.TimeoutExpired)添加到我的测试中,以捕捉最终的超时,但这似乎没有起到作用。有没有办法正确地捕捉pytest引发的超时?
发布于 2020-01-31 12:32:56
不幸的是,提供@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!')https://stackoverflow.com/questions/59994077
复制相似问题