0
0
PyTesttesting~5 mins

pytest-timeout for time limits

Choose your learning style9 modes available
Introduction

Sometimes tests take too long and slow down your work. pytest-timeout helps stop tests that run longer than you want.

You want to stop a test if it runs more than 5 seconds to save time.
You have a test that might get stuck in a loop and never finish.
You want to make sure your code runs fast enough by setting a max time.
You run many tests and want to avoid waiting too long for one slow test.
Syntax
PyTest
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.

Examples
This test must finish in 3 seconds or pytest will stop it.
PyTest
import pytest

@pytest.mark.timeout(3)
def test_fast():
    assert 1 + 1 == 2
This test will fail because it sleeps for 2 seconds but timeout is 1 second.
PyTest
import pytest

@pytest.mark.timeout(1)
def test_slow():
    import time
    time.sleep(2)
    assert True
Sample Program

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.

PyTest
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
OutputSuccess
Important Notes

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.

Summary

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.