If you have ever watched ten thousand green dots scroll past a CI log and then had one red F ruin your afternoon, you have pytest to thank for both experiences. The library is so good at hiding its work that most of us treat it like weather: it just happens. But when a fixture stalls and the traceback dumps you into the middle of an unfamiliar module, or when a failed assert quotes both operands plus a plausible explanation you never wrote, you are looking at deliberate machinery — roughly 33,500 lines of Python spread across 78 files in the src/_pytest package of the pytest-dev/pytest repository. None of it is magic.
The pain every long-term pytest user eventually meets is the invisible layer. Why did a conftest.py three directories up override my option? Why did this fixture execute for a test I never mentioned it in? Why is my failure output smarter than my own assert? These questions have concrete answers: they fall out of a plugin hook system built on pluggy, a collection engine that converts your directory tree into live Python objects, a fixture engine that caches values per scope and chains teardown calls, and an import-time rewriter that rebuilds your assert statements into more expressive forms before CPython ever executes them. Once you see the four mechanisms, the “mystery” behavior becomes predictable.
This article is that map. Below are two diagrams — a six-area overview and a 34-symbol detail view — plus sections following the life of a test run: parse arguments and load plugins, collect items, wire fixtures, run setup-call-teardown, rewrite assertions on import, and render the report. Every file, symbol, and line number was checked against the real tree on branch main, so the links land on code that exists.
The six working areas of pytest's src/_pytest package and how a run flows through them, from argument parsing to terminal output.
Reading the overview from left to right traces one test session end to end. The first cluster parses your command line; the second turns directories into test items; the third resolves which fixtures each item needs; the fourth runs the three execution phases; the fifth rewrites asserts as modules are imported; and the last renders every result. Nine anchor symbols hold the structure together:
- Config, L1179 is the central object: option values, the hook caller, and the plugin manager all hang off one instance.
- PytestPluginManager, L493 subclasses pluggy’s
PluginManagerand decides which plugins participate in a run. - Session, L592 is the root collector — a directory tree wearing a class.
- perform_collect, L792 expands collectors recursively until only items remain.
- FixtureManager, L1771 indexes every fixture definition and computes the closure each item needs.
- pytest_fixture_setup, L1391 computes a fixture’s value and registers its teardown for later.
- pytest_runtestloop, L400 walks
session.itemsone test at a time. - AssertionRewritingHook, L73 intercepts test module imports to rewrite asserts before they run.
- TerminalReporter, L388 turns report objects into the progress line and the final summary you actually read.
A detail view: 34 classes, functions, and hook anchors mapped to their real files, including the fixture cache and the bytecode cache for rewritten modules.
One Config Object, Two Hook Markers, Fifty-Plus Hooks
The command-line journey starts in src/_pytest/config/__init__.py, a 2,196-line module that is arguably the real main of the project. Its main() function at line 214 builds the configuration and dispatches a single hook call, pytest_cmdline_main, whose default implementation lives at line 379 of main.py. That is the pattern for the whole codebase: one specification, one or more implementations, little direct coupling.
Two markers make the system work. In config/__init__.py, line 103 defines hookimpl = HookimplMarker("pytest"), and in src/_pytest/hookspec.py, line 46 defines the matching hookspec = HookspecMarker("pytest"). Pluggy scans registered plugin objects for these markers, so any module that decorates functions with @pytest.hookimpl can reshape a run without pytest knowing its name in advance. The documented contract is the 896-line hookspec.py, which defines 52 hook functions. The execution contract alone is a chain of seven: pytest_runtest_protocol at line 620, pytest_runtest_setup at 698, pytest_runtest_call at 717, pytest_runtest_teardown at 733, pytest_runtest_makereport at 758, and pytest_runtest_logreport at 777. Collection has its own family, including pytest_collection at 227, pytest_ignore_collect at 303, and pytest_collect_file at 365.
Plugin discovery is deliberately boring: PytestPluginManager at line 493 subclasses pluggy’s PluginManager and, at line 1551, filters installed distributions for entry points in the pytest11 group. That is the same distribution mechanism setuptools standardized, which is why pip install pytest-xdist works as a plugin without any further wiring. Parsing itself happens in Config.parse at line 1711, which folds addopts from ini files into the arguments plugins registered, which is exactly why an inherited conftest.py can quietly change your command line.
Collection: Walking the Tree to Items
With configuration settled, main.py takes over. Session, defined at line 592, extends nodes.Collector — the abstract collector at line 586 of nodes.py. The node hierarchy is compact: Node at line 148 provides the nodeid string, keywords, and marker API; FSCollector at 646 adds filesystem responsibilities; and Item at line 745 is the leaf that a runner eventually executes. A session is simply the collector whose children are everything pytest found.
The hook implementation pytest_collection at line 396 triggers the real work in perform_collect at line 792, which expands collectors recursively until only items remain. Most of the interesting expansion lives in src/_pytest/python.py, 1,686 lines of Python-specific knowledge: Module at line 583 collects a test file, Package at line 666 recurses through directories, Class at line 772, and Function at line 1736 represents one runnable test function. Parametrization is a second, tree-shaped expansion: Metafunc at line 1342 feeds each parameter set to pytest_generate_tests (hookspec at line 552 of hookspec.py), multiplying one function into many items with distinct nodeids.
Collection also imports your test modules, one layer above the cpython importlib machinery pytest builds on — and every such import passes through pytest’s own finder first, which is the hook into assertion rewriting.
From Fixture Lookup to Teardown Stack: Build Facts
Fixtures are where pytest spends most of its complexity budget, and the numbers show it: src/_pytest/fixtures.py is 2,276 lines, the largest module in the package. The design has three pillars. FixtureRequest, an abstract base at line 501, is the interface tests see when they name a fixture parameter. FixtureDef at line 1119 is the bookkeeping object for one fixture, and its cached_result slot at line 1196 is the reason a session-scoped fixture runs once no matter how many tests consume it: execute() at line 1240 checks the cache key before ever calling your function. FixtureManager at line 1771 ties it together, keeping per-plugin fixture indexes and computing the closure of transitive dependencies each item requires.
Execution then becomes a small, strict loop. pytest_fixture_setup at line 1391 computes a value for a given scope and pushes finalizers onto SetupState at line 460 of runner.py — a stack, not a set, so teardown happens in exact reverse dependency order even when fixtures were requested out of order. TopRequest at line 842 is the session-level request used for collecting session-scoped fixtures early. Each phase is wrapped by CallInfo at line 293, which records duration and captures the exception, and call_and_report at line 236 converts a finished phase into a report. Three engineering details worth stealing for your own systems: the cache is keyed per scope rather than per test, teardown is scheduled at setup time rather than trusted to a later pass, and every phase produces its own report object so partial failures remain diagnosable.
Assertion Rewriting: AST Surgery at Import Time
The feature that made pytest famous lives in src/_pytest/assertion/. The 214-line __init__.py installs the machinery during pytest_configure at line 84 and stores it in AssertionState at line 125. The engine, rewrite.py, is 1,058 lines of import-system integration: AssertionRewritingHook at line 73 implements both a meta-path finder and a loader, so when a collector imports test_something.py, the hook runs first and decides whether to hand back a rewritten module.
The transformation itself is a pure cpython AST job, and the code reads like a tutorial on ast usage. _rewrite_test at line 334 reads the source, computes importlib.util.source_hash at line 337, parses the module with ast.parse at line 339, and lets rewrite_asserts at line 421 walk the tree, decomposing each assert into named intermediate expressions so a failure can print every operand. The result is compiled at line 341 and cached: _write_pyc at line 312 writes the first eight bytes of the 64-bit source hash (line 308) as a stamp, and the fast path at line 377 validates data[8:16] before trusting a cached file. The same discipline of careful Python AST analysis is what mypy applies statically, which is why reading rewrite.py feels familiar if you have read a type checker. When an assert does fail, the explanation is assembled through the pytest_assertrepr_compare hookspec at line 938 of hookspec.py — again a hook, so plugins can teach pytest to explain new object types.
Reports, Serialization, and the Terminal
Results become objects in src/_pytest/reports.py, 612 lines with a tidy hierarchy: BaseReport at line 63 carries serialization helpers, TestReport at line 324 represents one setup, call, or teardown phase, and CollectReport at line 484 captures what happened while gathering collectors. The hookspecs pytest_report_to_serializable at line 792 and pytest_report_from_serializable at line 813 exist so report objects can cross process boundaries — the mechanism plugins like xdist use to ferry results from workers back to the controller.
The last hop is src/_pytest/terminal.py, 1,591 lines that define TerminalReporter at line 388. It subscribes to pytest_runtest_logreport, prints progress through _outrep_summary at line 1271, and produces the final percentage-annotated summary. Everything on screen derives from the same report objects every other consumer gets: one data shape, and the terminal, JUnit XML writers, and cache plugins merely project it differently.
Honest Limits
This tour covers only Enjoyed this post? Never miss out on future posts by following us src/_pytest as it exists on branch main in late November 2026; the repository also carries an extensive testing/ suite, docs, and a changelog that we did not walk, and the tree moves, so line numbers drift with every merge. The fixture engine has significant branches we compressed into two paragraphs — parametrized fixtures, autouse ordering, and the error paths around cached_result each deserve their own article. We likewise skipped capture.py, junitxml.py, the unittest.py compatibility layer, and the warning subsystem, all real subsystems rather than utilities. The diagrams show dependency flow, not a complete import graph, and the 52-hook count includes a few core implementations sharing the file with the specifications. Treat every number here as a photograph of one commit, not a portrait of the project; the architecture has been stable for years, but the specific line numbers will age.