Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a default per test timeout in pytest?

Tags:

python

pytest

I want to enforce that no test takes longer than 3 seconds in pytest.

pytest-timeout (https://pypi.python.org/pypi/pytest-timeout) almost does what I want... but it seems to allow me to either set a global timeout (ie make sure the test suite takes less than 10 minutes) or, an ability to set a decorator on each test manually.

Desired Behavior: Configure pytest with a single setting to fail any individual test which exceeds 3 seconds.

like image 409
user2917346 Avatar asked Apr 24 '17 22:04

user2917346


1 Answers

You can use a local plugin. Place a conftest.py file into your project root or into your tests folder with something like the following to set the default timeout for each test to 3 seconds;

import pytest

def pytest_collection_modifyitems(items):
    for item in items:
        if item.get_marker('timeout') is None:
            item.add_marker(pytest.mark.timeout(3))

Pytest calls the pytest_collection_modifyitems function after it has collected the tests. This is used here to add the timeout marker to all of the tests.

Adding the marker only when it does not already exist (if item.get_marker...) ensures that you can still use the @pytest.mark.timeout decorator on those tests that need a different timeout.

Another possibility would be to assign to the special pytestmark variable somewhere at the top of a test module:

pytestmark = pytest.mark.timeout(3)

This has the disadvantage that you need to add it to each module, and in my tests I got an error message when I then attempted to use the @pytest.mark.timeout decorator anywhere in that module.

like image 117
Marcel M Avatar answered Oct 02 '22 16:10

Marcel M