Consider this pytest test using pytest-timeout to limit execution time to 1 second.
import time
import pytest
@pytest.mark.timeout(1)
def test_sleep():
time.sleep(2)
What is the test result when you run this?
import time import pytest @pytest.mark.timeout(1) def test_sleep(): time.sleep(2)
Think about what pytest-timeout does when a test runs longer than allowed.
The @pytest.mark.timeout(1) decorator stops the test if it runs longer than 1 second. Since time.sleep(2) sleeps for 2 seconds, the test fails due to timeout.
You want to test that a function long_task() times out after 1 second using pytest-timeout. Which assertion correctly verifies the timeout?
import pytest @pytest.mark.timeout(1) def test_long_task(): long_task()
Check which exception pytest-timeout raises on timeout.
pytest-timeout raises TimeoutError when a test times out. So the correct way to assert timeout is using pytest.raises(TimeoutError).
This test uses pytest-timeout but the test runs longer than the timeout without stopping:
import time
import pytest
@pytest.mark.timeout(1)
def test_wait():
time.sleep(3)
What is the most likely reason the timeout is ignored?
Check if the plugin is installed and enabled.
If pytest-timeout is not installed or not enabled, the @pytest.mark.timeout decorator has no effect and tests run without timeout.
You want to apply a 2-second timeout to all tests in your pytest suite without adding decorators to each test. Which is the best way?
Think about pytest configuration options.
You can set a global timeout by passing --timeout=2 on the command line or adding timeout = 2 under the [pytest] section in pytest.ini. This applies timeout to all tests automatically.
timeout_method=thread in pytest-timeout?pytest-timeout supports different timeout methods. What happens when you set timeout_method=thread?
Consider how threads can interrupt test execution.
With timeout_method=thread, pytest-timeout uses a separate thread to raise a timeout exception inside the test thread. This stops the test by exception without killing the whole process.