pytest

pytest is a test runner and framework for Python that provides test discovery, readable assert failures, powerful fixtures, and an extensible plugin system.

Installation and Setup

Create an isolated environment and install pytest from PyPI:

Shell
(venv) $ python -m pip install pytest

Key Features

  • Discovers tests automatically in files named test_*.py or *_test.py when you run pytest.
  • Rewrites assert statements to display rich introspection when an assertion fails.
  • Provides fixtures for declarative setup and teardown with reusable scopes.
  • Supports parametrization to run the same test with multiple inputs.
  • Loads plugins automatically and exposes hooks for customization and extension.
  • Reads configuration from pytest.ini, pyproject.toml, tox.ini, or setup.cfg to control discovery and behavior.

Usage

Write a minimal test and run it:

Python test_example.py
def inc(x):
    return x + 1

def test_inc():
    assert inc(2) == 3

Runt the test:

Shell
$ pytest -q
.
1 passed in 0.02s

Parametrize a test:

Python
import pytest

@pytest.mark.parametrize(
    "a,b,expected",
    [
        (1, 2, 3),
        (0, 0, 0),
        (-1, 1, 0),
    ],
)
def test_add(a, b, expected):
    assert a + b == expected

Select specific tests or groups:

Python test_math.py
import pytest

@pytest.mark.slow
def test_big():
    assert sum(range(10_000)) > 0
Shell
$ pytest -m slow             # Run only tests marked "slow"
$ pytest tests/test_math.py  # Run tests in one module

Markers help categorize and select tests on the command line.

Tutorial

Effective Python Testing With pytest

In this tutorial, you'll learn how to take your testing to the next level with pytest. You'll cover intermediate and advanced pytest features such as fixtures, marks, parameters, and plugins. With pytest, you can make your test suites fast, effective, and less painful to maintain.

intermediate testing

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Dec. 17, 2025