PyUnit - How to unit test a method that runs into

2019-02-18 18:56发布

问题:

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