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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With