0
0
PyTesttesting~15 mins

pytest-timeout for time limits - Build an Automation Script

Choose your learning style9 modes available
Verify pytest-timeout enforces test time limits
Preconditions (2)
Step 1: Create a test function that sleeps for 5 seconds
Step 2: Apply pytest-timeout decorator or marker to set a timeout of 2 seconds
Step 3: Run the test using pytest
Step 4: Observe the test result
✅ Expected Result: The test fails due to timeout after 2 seconds with a timeout error reported by pytest-timeout
Automation Requirements - pytest
Assertions Needed:
Test should fail due to timeout
Timeout error message should be present in test output
Best Practices:
Use pytest-timeout marker or decorator to set time limits
Avoid hardcoded sleep times longer than timeout
Use pytest's capsys or caplog to capture output if needed
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not installing pytest-timeout plugin', 'why_bad': "The timeout marker or option won't work without the plugin installed, so tests won't timeout as expected.", 'correct_approach': 'Install pytest-timeout using pip before running tests that use timeout features.'}
Setting timeout longer than test sleep duration
Using time.sleep in production tests without timeout
Bonus Challenge

Now add data-driven testing with 3 different sleep durations and verify timeout enforcement accordingly

Show Hint