From e88b7e77401403a6a9a54ece953944234e08e2f2 Mon Sep 17 00:00:00 2001 From: Ted Blackman Date: Thu, 21 Jan 2016 15:34:42 -0800 Subject: [PATCH] timed() now enforces time limit. --- nose/tools/nontrivial.py | 20 ++++++++++---------- unit_tests/test_tools.py | 3 ++- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/nose/tools/nontrivial.py b/nose/tools/nontrivial.py index 28397324..c8dafea6 100644 --- a/nose/tools/nontrivial.py +++ b/nose/tools/nontrivial.py @@ -1,8 +1,5 @@ """Tools not exempt from being descended into in tracebacks""" -import time - - __all__ = ['make_decorator', 'raises', 'set_trace', 'timed', 'with_setup', 'TimeExpired', 'istest', 'nottest'] @@ -83,22 +80,25 @@ def set_trace(): def timed(limit): - """Test must finish within specified time limit to pass. + import multiprocessing + from multiprocessing.pool import ThreadPool + """Test must finish within specified time limit to pass. Example use:: - @timed(.1) def test_that_fails(): time.sleep(.2) """ def decorate(func): def newfunc(*arg, **kw): - start = time.time() - result = func(*arg, **kw) - end = time.time() - if end - start > limit: + pool = ThreadPool(1) + async_result = pool.apply_async(func, args=arg, kwds=kw) + + try: + return async_result.get(timeout=limit) + except multiprocessing.TimeoutError: raise TimeExpired("Time limit (%s) exceeded" % limit) - return result + newfunc = make_decorator(func)(newfunc) return newfunc return decorate diff --git a/unit_tests/test_tools.py b/unit_tests/test_tools.py index 2a6451c4..9ccc968a 100644 --- a/unit_tests/test_tools.py +++ b/unit_tests/test_tools.py @@ -91,8 +91,9 @@ def quick(): def check_result(): return 42 check_result = timed(.2)(check_result) + result = check_result() - assert 42 == check_result() + assert 42 == result, result quick() try: