Verify pytest-timeout enforces test time limits
Preconditions (2)
✅ Expected Result: The test fails due to timeout after 2 seconds with a timeout error reported by pytest-timeout
import time import pytest @pytest.mark.timeout(2) def test_sleep_timeout(): time.sleep(5) # To run this test, execute: pytest -v --timeout=2 test_timeout.py
This test uses the @pytest.mark.timeout(2) decorator to set a 2-second timeout on the test function.
The test function sleeps for 5 seconds, which is longer than the timeout.
When run, pytest-timeout will interrupt the test after 2 seconds and mark it as failed due to timeout.
This shows how pytest-timeout enforces time limits on tests to prevent long-running or hanging tests.
Now add data-driven testing with 3 different sleep durations and verify timeout enforcement accordingly
pytest-timeout in test cases?@pytest.mark.timeout(5) using a positional argument.@pytest.mark.timeout(2)
def test_sleep():
import time
time.sleep(3)
@pytest.mark.timeout(3)
def test_loop():
for i in range(5):
time.sleep(1)
time.sleep(1) but does not import the time module.@pytest.mark.timeout to each test. Which is the best way to do this?pytestmark = pytest.mark.timeout(10) applies the timeout decorator to all tests in the file automatically.Pass the test and this pattern moves unknown