有没有办法断言 Pytest 测试用例由于 pytest 超时而失败?我想运行一个寿命测试,希望运行不会出现问题,直到遇到 pytest 超时。我用 @pytest.mark.timeout(6000) 注释测试以覆盖默认的 pytest 超时,当遇到 6000 秒超时时,测试失败并显示E Failed: Timeout >6000.0s.
我尝试添加with pytest.raises(pytest.TimeoutExpired)到我的测试中以捕获最终的超时,但这似乎并不能解决问题。有没有办法正确捕获 pytest 引发的超时?
不幸的是,提供标记的pytest-timeout 插件@pytest.mark.timeout没有提供捕获超时的方法(参考源)。
您可能会发现使用提供超时功能的库作为上下文管理器会更幸运,例如Thomas Ahle的回答中的库
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!')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3599 次 |
| 最近记录: |