Sometimes tests take too long and slow down your work. pytest-timeout helps stop tests that run longer than you want.
pytest-timeout for time limits
import pytest @pytest.mark.timeout(seconds) def test_function(): # test code here
Use @pytest.mark.timeout(seconds) above your test function to set a time limit.
The seconds value is how many seconds the test can run before stopping.
import pytest @pytest.mark.timeout(3) def test_fast(): assert 1 + 1 == 2
import pytest @pytest.mark.timeout(1) def test_slow(): import time time.sleep(2) assert True
The first test sleeps 1 second and passes because it is under the 2-second limit.
The second test sleeps 3 seconds but has a 1-second limit, so pytest stops it and marks it as failed due to timeout.
import pytest import time @pytest.mark.timeout(2) def test_quick(): time.sleep(1) assert True @pytest.mark.timeout(1) def test_too_slow(): time.sleep(3) assert True
Make sure to install pytest-timeout plugin with pip install pytest-timeout before using it.
You can set timeout globally in pytest config or per test with the decorator.
Timeout helps catch infinite loops or very slow tests early.
pytest-timeout stops tests that run longer than a set time.
Use @pytest.mark.timeout(seconds) to add a time limit to tests.
This keeps your test runs fast and avoids waiting on stuck tests.