Timeout Mark
Tests that hang or take too long can block your test suite. The @pytest.mark.timeout decorator ensures tests finish within a time limit.
Installation
The timeout plugin is not built into pytest. Install it separately:
pip install pytest-timeout
Basic Usage
import pytest
import time
@pytest.mark.timeout(5)
def test_quick_operation():
result = fast_function()
assert result is not None
@pytest.mark.timeout(1)
def test_must_finish_quickly():
time.sleep(0.5)
assert True
If the test runs longer than the specified seconds, pytest raises a TimeoutError.
Global Timeout
Set a default timeout for all tests in pytest.ini:
[pytest]
timeout = 30
timeout_method = thread
Individual tests can override this with their own @pytest.mark.timeout.
Timeout Methods
Two methods are available for enforcing timeouts:
signal(default on Unix) - Uses OS signals. Cannot be used in non-main threads.thread- Uses a background thread. Works everywhere but may not interrupt some blocking calls.
[pytest]
timeout = 10
timeout_method = thread