PyUnit - How to unit test a method that runs into an infinite loop for some input?

我的未来我决定 提交于 2019-12-04 01:46:42

问题


A post in 2011 answered this question for NUnit: How to unit test a method that runs into an infinite loop for some input?

Is there a similar TimeoutAttribute in PyUnit that I can use in the same fashion?

I did some searching and found "Duration", but that didn't seem the same.


回答1:


There doesn't appear there is anything in pyunit itself, but as a work around you can roll your own. Here is how to do it using the multiprocessing package.

from functools import wraps
from multiprocessing import Process

class TimeoutError(Exception):
    pass

def timeout(seconds=5, error_message="Timeout"):
    def decorator(func):
        def wrapper(*args, **kwargs):
            process = Process(None, func, None, args, kwargs)
            process.start()
            process.join(seconds)
            if process.is_alive():
                process.terminate()
                raise TimeoutError(error_message)

        return wraps(func)(wrapper)
    return decorator

Here is an example of how to use it:

import time

@timeout()
def test_timeout(a, b, c):
    time.sleep(1)

@timeout(1)
def test_timeout2():
    time.sleep(2)

if __name__ == '__main__':
    test_timeout(1, 2, 3)

    test_value = False
    try:
        test_timeout2()
    except TimeoutError as e:
        test_value = True

    assert test_value


来源:https://stackoverflow.com/questions/14366761/pyunit-how-to-unit-test-a-method-that-runs-into-an-infinite-loop-for-some-inpu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!