Test Overview
This test checks that a function completes within a set time limit using pytest-timeout. It verifies the test fails if the function runs too long.
This test checks that a function completes within a set time limit using pytest-timeout. It verifies the test fails if the function runs too long.
import time import pytest @pytest.mark.timeout(2) def test_sleep_short(): time.sleep(1) # Sleeps less than timeout, should pass @pytest.mark.timeout(2) def test_sleep_long(): time.sleep(3) # Sleeps longer than timeout, should fail
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test runner starts and loads test_sleep_short | pytest environment ready, test_sleep_short loaded | — | PASS |
| 2 | test_sleep_short executes time.sleep(1) | Function running, sleeping for 1 second | Check if test completes within 2 seconds timeout | PASS |
| 3 | test_sleep_short finishes before timeout | Function completed normally | Test passes as execution time < 2 seconds | PASS |
| 4 | Test runner starts and loads test_sleep_long | pytest environment ready, test_sleep_long loaded | — | PASS |
| 5 | test_sleep_long executes time.sleep(3) | Function running, sleeping for 3 seconds | Check if test completes within 2 seconds timeout | FAIL |
| 6 | Timeout triggers after 2 seconds, test_sleep_long interrupted | Test interrupted by pytest-timeout plugin | Test fails due to exceeding time limit | FAIL |
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