0
0
PyTesttesting~8 mins

pytest-timeout for time limits - Framework Patterns

Choose your learning style9 modes available
Framework Mode - pytest-timeout for time limits
Folder Structure
project-root/
├── tests/
│   ├── test_example.py
│   ├── test_login.py
│   └── __init__.py
├── conftest.py
├── pytest.ini
├── requirements.txt
└── utils/
    └── helpers.py
  
Test Framework Layers
  • Tests: Located in tests/, contain test functions using pytest syntax.
  • Fixtures & Hooks: Defined in conftest.py for setup and teardown.
  • Utilities: Helper functions in utils/ to keep tests clean.
  • Configuration: pytest.ini to configure pytest and plugins like pytest-timeout.
Configuration Patterns

Use pytest.ini to set global timeout for tests with pytest-timeout plugin.

[pytest]
addopts = --timeout=5
timeout_method = thread
  

Override timeout per test using decorator:

import pytest

@pytest.mark.timeout(10)
def test_long_running():
    # test code here
    pass
  

Manage environment variables and credentials securely using conftest.py fixtures or external config files.

Test Reporting and CI/CD Integration
  • Use pytest's built-in reporting with --junitxml=report.xml for CI systems.
  • Timeout failures appear as test failures with clear timeout error messages.
  • Integrate with CI tools (GitHub Actions, Jenkins) to run tests with time limits enforced.
  • Use pytest plugins like pytest-html for readable HTML reports showing timeout results.
Best Practices
  1. Set reasonable global timeout to catch hanging tests early.
  2. Use per-test timeout overrides for tests known to take longer.
  3. Prefer thread timeout method for compatibility and safety.
  4. Keep test code clean by using fixtures for setup and teardown.
  5. Integrate timeout failures clearly in CI reports for quick debugging.
Self Check

Where would you add a new test that requires a 15-second timeout override in this framework structure?

Key Result
Use pytest-timeout plugin configured in pytest.ini and per-test decorators to enforce time limits on tests.