Search code examples
pythonunit-testingtimeout

How to specify test timeout for python unittest?


I'm using python framework unittest. Is it possible to specify by framework's abilities a timeout for test? If no, is it possible to specify gracefully a timeout for all tests and for some separated tests a private value for each one?
I want to define a global timeout for all tests (they will use it by default) and a timeout for some test that can take a long time.


Solution

  • As far as I know unittest does not contain any support for tests timeout.

    You can try timeout-decorator library from PyPI. Apply the decorator on individual tests to make them terminate if they take too long:

    import timeout_decorator
    
    class TestCaseWithTimeouts(unittest.TestCase):
    
        # ... whatever ...
    
        @timeout_decorator.timeout(LOCAL_TIMEOUT)
        def test_that_can_take_too_long(self):
            sleep(float('inf'))
    
        # ... whatever else ...
    

    To create a global timeout, you can replace call

    unittest.main()
    

    with

    timeout_decorator.timeout(GLOBAL_TIMEOUT)(unittest.main)()