Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 511
Jury Avatar asked Jan 12 '16 12:01

Jury


People also ask

Is pytest faster than unittest?

The code in pytest is simple, compact, and efficient. For unittest, we will have to import modules, create a class and define the testing functions within that class. But for pytest, we only have to define the testing function. Pytest is also fast and efficient.

What is test runner in Python?

A new Python-based project called Python Test Runner ( ptr ), that allows developers to run Python unit test suites. The main difference between ptr and existing test runners is that ptr crawls a repository to find Python projects with unit tests defined in their setup files.

Can pytest run unittest tests?

pytest supports running Python unittest -based tests out of the box. It's meant for leveraging existing unittest -based test suites to use pytest as a test runner and also allow to incrementally adapt the test suite to take full advantage of pytest's features.


1 Answers

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)() 
like image 142
Lav Avatar answered Sep 24 '22 06:09

Lav