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

后端 未结 1 1947
滥情空心
滥情空心 2021-01-14 14:31

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 PyU

相关标签:
1条回答
  • 2021-01-14 15:10

    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
    
    0 讨论(0)
提交回复
热议问题