首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pytest断言超时?

Pytest断言超时?
EN

Stack Overflow用户
提问于 2020-01-31 04:34:51
回答 1查看 840关注 0票数 1

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-31 12:32:56

不幸的是,提供@pytest.mark.timeout标记的pytest-timeout plugin没有提供捕捉超时的方法(参考source)。

您可能会更幸运地使用提供超时功能的库作为上下文管理器,比如Thomas Ahleanswer

代码语言:javascript
复制
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!')
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59994077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档