如何为python unittest指定测试超时? [英] How to specify test timeout for python unittest?

查看:36
本文介绍了如何为python unittest指定测试超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 框架 unittest.是否可以通过框架的能力指定测试超时?如果不是,是否可以为所有测试优雅地指定 timeout 并为某些单独的测试指定一个私有值?
我想为所有测试定义一个全局超时(默认情况下他们会使用它),并为一些可能需要很长时间的测试定义一个超时.

I'm using python framework unittest. Is it possible to specify by framework's abilities a timeout for test? If no, is it possible to specify gracefully a timeout for all tests and for some separated tests a private value for each one?
I want to define a global timeout for all tests (they will use it by default) and a timeout for some test that can take a long time.

推荐答案

据我所知 unittest 不包含任何对测试超时的支持.

As far as I know unittest does not contain any support for tests timeout.

您可以尝试来自 PyPI 的 timeout-decorator 库.将装饰器应用于单个测试以使其在耗时过长时终止:

You can try timeout-decorator library from PyPI. Apply the decorator on individual tests to make them terminate if they take too long:

import timeout_decorator

class TestCaseWithTimeouts(unittest.TestCase):

    # ... whatever ...

    @timeout_decorator.timeout(LOCAL_TIMEOUT)
    def test_that_can_take_too_long(self):
        sleep(float('inf'))

    # ... whatever else ...

要创建全局超时,可以替换调用

To create a global timeout, you can replace call

unittest.main()

timeout_decorator.timeout(GLOBAL_TIMEOUT)(unittest.main)()

这篇关于如何为python unittest指定测试超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆