pytest-timeout

2.4.0 · active · verified Sat Mar 28

pytest-timeout is an actively maintained pytest plugin designed to automatically abort excessively long-running or hanging tests. It helps in maintaining efficient test suites by enforcing timeout limits at various levels (global, session, per-test) and provides different methods to terminate tests. The current version is 2.4.0 and it is part of the pytest-dev organization, implying regular updates and maintenance.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to apply timeouts using `pytest-timeout`. It shows setting a global timeout via `pytest.ini` (or `PYTEST_TIMEOUT` environment variable), and overriding it for specific tests using the `@pytest.mark.timeout` decorator. The example includes tests that should pass and one designed to explicitly time out.

import pytest
import time
import os

# Example pytest.ini content (can be placed in a file named pytest.ini)
# [pytest]
# timeout = 5

# Or set via environment variable (e.g., in CI/CD)
# export PYTEST_TIMEOUT=10

# A test that should pass within the global timeout (if set to > 1)
def test_fast_operation():
    time.sleep(1) # Simulates a quick operation
    assert True

# A test with a specific timeout marker, overriding global settings
@pytest.mark.timeout(os.environ.get('PYTEST_LONG_TIMEOUT', 20))
def test_long_running_operation():
    time.sleep(15) # Simulates a potentially long operation
    assert True

# A test designed to time out if default or global timeout is low
@pytest.mark.timeout(2)
def test_should_timeout():
    time.sleep(3) # This will exceed the 2-second mark
    assert False, "Should not reach here if timeout works"

# To run these tests:
# 1. Save as a Python file (e.g., test_timeouts.py)
# 2. Run from your terminal: pytest test_timeouts.py
#    (or pytest test_timeouts.py --timeout=5 to set a global CLI timeout)

view raw JSON →