如何在python3中的慢速测试中提前失败(例如设置超时)(最好使用nose)

如何在python3中的慢速测试中提前失败(例如设置超时)(最好使用nose),python,python-3.x,unit-testing,timeout,nose,Python,Python 3.x,Unit Testing,Timeout,Nose,以下代码再现了我的情况: 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秒后出现失败结果。 令我惊讶的是,直到测试完成

以下代码再现了我的情况:

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)

我希望避免测试套件永远不会结束的可能性(例如,在某些情况下存在无限循环)。哪种方法比较好?

@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)
您可以在此处阅读更多内容:

然而,你将无法设置一个简单的时间限制,就像你对装饰师所做的那样。但你仍然可以用它捕捉无限循环