以下代码再现了我的情况:
from nose.tools import timed
from time import sleep
class Test():
@timed(1)
def test_slow_function(self):
duration = 5
sleep(duration)
pass
运行测试(例如nosetests test.py:Test -s
),我希望在1秒钟后会出现失败结果。
令我惊讶的是,直到测试完成(在这种情况下为5秒钟),它才不会失败。即使1秒后有任何结果也将是失败的。我得到:
...
raise TimeExpired("Time limit (%s) exceeded" % limit)
nose.tools.nontrivial.TimeExpired: Time limit (1) exceeded
----------------------------------------------------------------------
Ran 1 test in 5.006s
FAILED (failures=1)
我想避免测试套件永无止境的可能性(例如,在某些情况下存在无限循环)。哪种方法好?
答案 0 :(得分:1)
@timed
装饰器无法停止执行装饰功能。它所做的只是将实际的执行时间与预期的执行时间进行比较,如果超出预期时间,则会引发失败。
基本上,要监视某个进程并在某些情况下停止该进程(在您的示例中,如果时间太长),则需要并行执行另一个进程,该进程实际上将进行监视。您可以通过以下一种简单且有点技巧的方法来实现此目的:使用nose
的并行测试执行,如下所示:
$ nosetests test.py:Test -s --processes 2 --process-timeout 1
E
======================================================================
ERROR: timesout_nose.Test.test_slow_function
----------------------------------------------------------------------
Traceback (most recent call last):
File "/test.py", line 9, in test_slow_function
sleep(duration)
File "/venv/lib/python3.6/site-packages/nose/plugins/multiprocess.py", line 276, in signalhandler
raise TimedOutException()
nose.plugins.multiprocess.TimedOutException: 'test.Test.test_slow_function'
----------------------------------------------------------------------
Ran 1 test in 1.230s
FAILED (errors=1)
您可以在此处了解更多信息: http://nose.readthedocs.io/en/latest/plugins/multiprocess.html
但是,您将无法像设置装饰器那样设置简单的时间限制。但是您仍然可以用它捕获无限循环。