Skip to content

pytest: Python Testing Framework

pytest is a Python testing framework that discovers tests by name and reports failures through Python’s assert statement. Fixtures manage test dependencies, parameterization runs tests over multiple inputs, and plugins add coverage measurement and parallel execution.

For setup, see Setting up testing with pytest and uv for a walkthrough. Feature guides cover How to parameterize tests with pytest, How to run tests in parallel with pytest-xdist, and How to measure code coverage with pytest-cov.

When to use pytest

pytest is the recommended default for unit, integration, and end-to-end tests. It collects conventional unittest.TestCase tests without a rewrite, but does not support unittest’s custom load_tests protocol. unittest remains an option for suites that depend on that protocol or cannot install third-party packages. For multi-version test automation, pair pytest with tox or nox.

Key Features

Test Discovery and Execution

  • Automatic discovery of test modules, functions, and methods following naming conventions
  • Simple assertion syntax using Python’s built-in assert
  • Failure reports showing expressions and their values
  • Test selection through command-line options, markers, and paths
  • Parallel test execution through the pytest-xdist plugin

Fixtures

Fixtures manage test dependencies, setup, and teardown:

@pytest.fixture
def api_client():
    client = APIClient()
    yield client
    client.close()

def test_api_call(api_client):
    # The fixture is automatically injected
    response = api_client.get_data()
    assert response.status_code == 200

Fixtures can be scoped to function, class, module, or session levels.

Class-scoped fixtures defined as instance methods without @classmethod are deprecated; apply @classmethod to any such fixtures to remove the warning.

When using --doctest-modules, autouse fixtures with module, package, or session scope defined directly in a test module (not in conftest.py) may run twice: once for the Module collector and once for DoctestModule. Move such fixtures to conftest.py to avoid duplicate execution.

Parameterization

Tests can be run with multiple sets of inputs:

@pytest.mark.parametrize("input,expected", [
    (1, 1),
    (2, 4),
    (3, 9),
    (4, 16),
])
def test_square(input, expected):
    assert input * input == expected

Passing generators or iterators as argvalues is deprecated because they are exhausted after the first collection pass, silently skipping tests on repeated runs. Use a list or tuple instead.

Command-Line Interface

# Run all tests
pytest

# Run tests in a specific file
pytest test_file.py

# Run a specific test
pytest test_file.py::test_function

# Run tests matching a pattern
pytest -k "pattern"

# Run tests with a specific marker
pytest -m slow

# Fail when accumulated warnings exceed a threshold
pytest --max-warnings=5

Configuration

Pytest reads settings from pyproject.toml under [tool.pytest.ini_options]:

[tool.pytest.ini_options]
# Fail the run when warning count exceeds this threshold
max_warnings = 5

# Render string equality failures as "Left:"/"Right:" blocks instead of ndiff output
assertion_text_diff_style = "split"

Pros

  • Minimal boilerplate compared to unittest
  • Fixture dependency injection
  • Plugins for coverage, parallel execution, and other test workflows
  • Detailed error reporting
  • Compatible with other testing tools

Cons

  • Learning curve for advanced features
  • Plugin dependencies can complicate maintenance
  • Fixture complexity can grow in large projects
  • Some patterns differ from unittest paradigms
Last updated on