pytest

On this page 7

pytest is an open-source testing framework for Python that discovers and runs test functions written with the plain assert statement, and enriches them with fixtures, parametrization and plugins. In software testing within programming, it is the de facto standard runner for Python unit tests and integration tests, and it also executes tests written for the standard library module unittest.

Its design favors minimal boilerplate: a test is an ordinary function whose name starts with test_, and pytest rewrites assertions so that a failure reports the actual compared values without special assertion methods. This combination makes small tests quick to write and large test suites manageable.

How pytest discovers and runs tests

pytest works in three phases: collection, execution and reporting. During collection it walks the configured directories, imports files that match test_*.py or *_test.py, and gathers functions prefixed with test_ and classes prefixed with Test that have no __init__ method.

Before importing test modules, pytest applies assertion rewriting, an import hook that transforms each assert into code that records intermediate values. When assert result == expected fails, the report shows both values and, for lists, dictionaries or strings, a detailed difference.

Each test ends with one of several outcomes, and the summary line reports how many tests fell into each category.

OutcomeMeaningTypical cause
PassedTest body completed without errorBehavior matches expectations
FailedAn assertion or exception occurred in the testRegression or incorrect expectation
ErrorA fixture failed during setup or teardownBroken environment or fixture code
SkippedTest was deliberately not runPlatform or dependency condition
XfailTest failed as expectedKnown bug marked with xfail
XpassTest marked xfail passed unexpectedlyBug fixed or marker outdated
Test outcomes reported by pytest

Fixtures, parametrization and markers

Fixtures are the core mechanism of pytest for preparing test preconditions. A fixture is a function decorated with @pytest.fixture; a test requests it simply by naming it as a parameter, and pytest performs dependency injection at run time. Code after a yield statement inside the fixture runs as teardown.

The fixture scope controls how often a fixture is created and therefore balances isolation against speed.

ScopeCreated once perGood fitRisk
functionTest function (default)Mutable objects, temporary dataSlower for expensive setup
classTest classGrouped tests sharing stateOrder dependence inside the class
moduleTest fileDatabase schema, loaded modelsState leaks between tests in a file
packageTest packageShared services for a subsystemHarder to reason about lifetime
sessionEntire test runContainers, compiled assetsHidden coupling across the suite
Fixture scopes and their trade-offs

Fixtures placed in a conftest.py file become available to every test in that directory and below, without imports. Built-in fixtures cover common needs: tmp_path for temporary directories, monkeypatch for patching attributes and environment variables, and capsys for capturing standard output.

Parametrization with @pytest.mark.parametrize runs one test function against many input sets, each reported as a separate test with its own identifier. Markers such as skip, skipif and xfail, or custom markers like slow, label tests so that the -m option can select or exclude them.

pytest compared with other test runners

pytest differs from xUnit-style frameworks mainly in how it handles setup and assertions. The following table compares it with the standard library and with JUnit, the reference framework of the xUnit family.

AspectpytestStandard unittestJUnit
LanguagePythonPython (standard library)Java and JVM languages
Test formPlain functions or classesSubclasses of TestCaseAnnotated methods
AssertionsPlain assert with rewritingassertEqual and related methodsAssertion library calls
Setup modelInjected fixtures with scopessetUp and tearDown methodsLifecycle annotations
ParametrizationBuilt-in decoratorManual loops or subTestParameterized test extension
ExtensibilityHook-based pluginsLimitedExtension model
pytest, unittest and JUnit compared

Because pytest can run existing unittest suites unchanged, teams typically migrate gradually: new tests use fixtures and plain asserts, while legacy TestCase classes keep working.

Plugins and configuration

pytest exposes hook functions at every stage of collection and execution, and plugins implement those hooks. More than a thousand community plugins exist, and several are standard in professional projects.

  • pytest-cov measures test coverage through the coverage library and can fail the run below a threshold.
  • pytest-xdist distributes tests across CPU cores or machines with the -n option.
  • pytest-mock provides a mocker fixture around the standard mocking library with automatic cleanup.
  • pytest-asyncio runs coroutine tests inside an event loop.
  • Hypothesis integrates property-based testing, generating many inputs from declared strategies.

Configuration lives in pyproject.toml, pytest.ini or tox.ini. Common settings include testpaths, registered markers, default options in addopts and `–strict-markers`, which turns typos in marker names into errors instead of silently creating new markers.

Common pitfalls in pytest suites

Most problems in large pytest suites come from shared state and implicit fixture behavior, not from the framework itself. The table links frequent symptoms to causes and fixes.

SymptomLikely causeFix
Tests pass alone but fail togetherBroad fixture scope or global stateNarrow the scope or reset state
Flaky test under parallel runsShared files, ports or database rowsUse tmp_path and unique resources
Test silently never runsName lacks the test_ prefixRename or adjust collection settings
Slow suite despite small testsExpensive function-scoped setupCache data in a wider-scoped fixture
Fixture origin unclearDeeply nested conftest.py filesInspect with --fixtures and simplify
Symptoms, causes and fixes

Excessive autouse fixtures, which apply to tests without being requested, deserve particular caution: they make test behavior depend on code that is not visible in the test itself.

Put simply

pytest is a tool that automatically checks Python code. A developer writes short statements such as “this function should return 5”, and pytest runs all of them and reports which ones hold and which do not.

It also prepares whatever each check needs, such as a temporary folder or sample data, much like a kitchen assistant who lays out ingredients before each recipe. The main benefit is fast, repeatable confidence that code still works after every change.

In practice

A data engineering team maintains a Python library that cleans customer records before loading them into a warehouse. The suite holds about 1,800 pytest tests: a session-scoped fixture starts a PostgreSQL container once, and function-scoped fixtures wrap each test in a transaction that is rolled back afterward.

A single parametrized test checks forty malformed phone number formats in about twenty lines of code. With pytest-xdist on eight cores, the full run drops from eleven minutes to under two minutes, and pytest-cov blocks merges when coverage falls below 85 percent. When a refactoring breaks date parsing, the rewritten assertion shows the exact mismatched values, and the developer fixes the defect within minutes.