How to specify test timeout for python unittest?
我使用的是
据我所知,
您可以从pypi中尝试
1 2 3 4 5 6 7 8 9 10 11 | 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 ... |
要创建全局超时,可以替换调用
1 | unittest.main() |
具有
1 | timeout_decorator.timeout(GLOBAL_TIMEOUT)(unittest.main)() |
基于这个答案,我使用
这种方法也使用
1 2 3 4 5 6 | import signal ... class TestTimeout(Exception): pass |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 2 3 | def test_foo(self): with test_timeout(5): # test has 5 seconds to complete ... foo unit test code ... |
使用这种方法,超时的测试将由于引发TestTimeout异常而导致错误。
或者,您可以将