繁体   English   中英

如何为python unittest指定测试超时?

[英]How to specify test timeout for python unittest?

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

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

您可以尝试PyPI的timeout-decorator库。 在各个测试中应用装饰器,如果它们花费太长时间使它们终止:

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 ...

要创建全局超时,您可以替换呼叫

unittest.main()

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

我建了一个unittest使用的超时解决方案with keyowrd, 在此基础上的答案

这种方法也使用signal ,所以它可能只在* nix系统上有效(我只在我的Ubuntu 16.04环境中运行它)。

  1. 导入信号,添加TestTimeout异常:
import signal

...

class TestTimeout(Exception):
    pass
  1. 定义类test_timeout ,它将处理with块:
class test_timeout:
  def __init__(self, seconds, error_message=None):
    if error_message is None:
      error_message = 'test timed out after {}s.'.format(seconds)
    self.seconds = seconds
    self.error_message = error_message

  def handle_timeout(self, signum, frame):
    raise TestTimeout(self.error_message)

  def __enter__(self):
    signal.signal(signal.SIGALRM, self.handle_timeout)
    signal.alarm(self.seconds)

  def __exit__(self, exc_type, exc_val, exc_tb):
    signal.alarm(0)
  1. 在单元测试中嵌入with test_timeout()块:
def test_foo(self):
  with test_timeout(5):  # test has 5 seconds to complete
    ... foo unit test code ...

使用此方法,由于引发TestTimeout异常,超时测试将导致错误。

或者,你可以在try: except TestTimeout: block中包装with test_timeout()块,并以更细的粒度处理异常(例如,跳过测试而不是错误)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM