TESTS · COLLECTION · FIXTURES · CASES · SEAMS · FAKES · MOCKS · PATCHES · COVERAGE

Testing in Python:
how pytest, fixtures and mocks work

A test is a small function that calls your code and checks what comes back. The pytest tool finds those functions, runs each one on its own and tells you which failed. Fixtures and mocks are how a test gets everything the code needs without touching the real world.

A small team-chat product bills its customers per seat, once a month. Its billing package works out what each customer owes, charges their card through a payment provider, saves an invoice and emails a receipt. When a card is declined, it marks the subscription as overdue and tries again three days later. Each chapter tests one more piece of that package, starting with the price calculation and ending with the call to the payment provider.

Here is one whole test run. Most boxes won’t mean much yet; each chapter explains one of them.

MapRead it top to bottom: pytest calls your tests, your tests call your code, your code calls what it depends on. The solid outline is one Python process.

You need to know Python functions, classes, imports and exceptions; no testing experience is assumed. The tutorial teaches pytest 9.2 on Python 3.15 with the standard library’s unittest.mock, checked against their documentation and source on 28 November 2026. The billing package, its customer, the payment provider and its numbers are made up; every default, option and error message comes from the tools. Tap any figure to open it full screen and zoom. Dotted terms are tappable.

A function that asserts: the test

You have a function, monthly_total("team", seats=5), that should return 6000 cents for 5 seats on the Team plan. Today you check it by calling it in a Python shell and reading the number. Nothing repeats that check next month, when someone edits the price table. A test is the same check written down as a function, and pytest is the program that runs every such function and reports what it found. What makes a function a test, and what does pytest tell you when one fails?

STEP 01 / 04

THE MAP SO FAR

Fig 1.1The accent parts are new: the test function, its rewritten assert and the reporter. Faint parts arrive in later chapters.

A test run is one Python process. pytest runs at the top of it. In the middle sits your test function, and below it the code the test calls, billing.pricing.

Three parts are new in this chapter. The test function calls your code and checks the result. pytest rewrites the function’s assert statements, so that a failure can show its values. The reporter prints one character per test, a section for each failure and a summary line. Everything drawn faint belongs to a later chapter.

STEP 02 / 04

A TEST IS A FUNCTION THAT CALLS YOUR CODE AND ASSERTS

Fig 1.2Follow 1 to 5. The accent hop is the assert: nothing raised there means the test passed.

tests/test_pricing.py holds one function, test_team_plan_charges_per_seat. It calls monthly_total("team", seats=5) and asserts that the result equals 6000. Those are the three moves of every test: arrange, act, assert. You prepare the inputs, call the code once, and check what came back. There is no class to inherit from and no special assert method.

assert is ordinary Python: it raises AssertionError when its expression is false. pytest needs nothing more. If the function returns, the test passed, and pytest prints . and 1 passed. If the function raises anything, the test failed.

TESTS/TEST_PRICING.PY: THE FIRST TEST
# tests/test_pricing.py
from billing.pricing import monthly_total


def test_team_plan_charges_per_seat():
    seats = 5                                      # arrange: the inputs

    total = monthly_total("team", seats=seats)     # act: call the code once

    assert total == 6000                           # assert: 5 seats at 1200 cents
ONE RUN, ONE DOT, ONE PASSED
$ pytest
============================= test session starts ==============================
platform darwin -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /Users/ana/relay-billing
configfile: pyproject.toml
testpaths: tests
collected 1 item

tests/test_pricing.py .                                                  [100%]

============================== 1 passed in 0.01s ===============================
STEP 03 / 04

PYTEST REWRITES ASSERT TO SHOW THE VALUES

Fig 1.3The same failing assert, run two ways. The accent column is pytest’s report, which prints both numbers.

The price table has a bug. It says "team": 1000, so the call returns 5000 where 6000 is right. Run by plain Python, the false assert raises AssertionError and prints neither number. pytest uses assertion rewriting: it rewrites the assert statements of a test file as it imports the file. The report can then print assert 5000 == 6000 and, under it, where 5000 = monthly_total('team', seats=5).

The report below comes from the test written with the call inside the assert, which gives pytest a where line to print. Read a report from the bottom. The FAILED line names the test, the E lines give the values, the > line is the assert that failed, and tests/test_pricing.py:5 is where it is.

pytest trims the FAILED line to the width of the terminal, which is why it ends in AssertionErro... here. The full message, with both values, is on the E lines.

THE SAME TEST, WITH THE BUG IN THE PRICE TABLE
$ pytest
...
collected 1 item

tests/test_pricing.py F                                                  [100%]

=================================== FAILURES ===================================
_______________________ test_team_plan_charges_per_seat ________________________

    def test_team_plan_charges_per_seat():
>       assert monthly_total("team", seats=5) == 6000
E       AssertionError: assert 5000 == 6000
E        +  where 5000 = monthly_total('team', seats=5)

tests/test_pricing.py:5: AssertionError
=========================== short test summary info ============================
FAILED tests/test_pricing.py::test_team_plan_charges_per_seat - AssertionErro...
============================== 1 failed in 0.03s ===============================
STEP 04 / 04

AN EXPECTED ERROR IS ASSERTED WITH PYTEST.RAISES

Fig 1.4Four things the block can do. The accent row is the one a missing check would hide.

Zero seats must be refused, so this test has to check for an error. with pytest.raises(ValueError, match="at least 1"): passes only when the block raises a ValueError whose message contains that text. match is a regular-expression search, so the pattern can sit anywhere in the message.

Every other outcome fails. If nothing is raised, the test fails with Failed: DID NOT RAISE ValueError. If the message is different, it fails with Regex pattern did not match., followed by the expected regex and the actual message. An exception of another type is not caught at all: it passes straight through and fails the test with its own traceback.

A TEST THAT EXPECTS AN ERROR
import pytest

from billing.pricing import monthly_total


def test_zero_seats_is_rejected():
    with pytest.raises(ValueError, match="at least 1"):
        monthly_total("team", seats=0)

# if the call returned a number instead, the test fails with:
#   Failed: DID NOT RAISE ValueError

COMMON QUESTIONS

Do tests have to live in a class?
No. A plain function is a complete test. A class whose name starts with Test only groups related tests, and it must not define __init__.
Should I use unittest.TestCase?
pytest runs existing TestCase classes unchanged, so old tests keep working. New tests are plain functions with assert; you don’t need self.assertEqual.
How many asserts can one test have?
As many as it takes to check one behaviour. A test stops at its first failing assert, so two unrelated checks in one test hide the second failure.

WHAT YOU NOW KNOW

  • A test is a function that calls your code and asserts on the result; it passes by returning.
  • pytest rewrites assert in test files, so a failure prints assert 5000 == 6000 and where 5000 came from.
  • pytest.raises(ValueError, match=…) checks an expected error and fails with DID NOT RAISE ValueError when nothing is raised.
DEEP DIVE: what the rewriter does to a file, comparing floats and money, reading bigger diffs, naming tests

What the rewriter does to a file

pytest installs an import hook. When Python imports a test file, the hook rewrites the module’s syntax tree before it is compiled and caches the result as __pycache__/test_pricing.cpython-315-pytest-9.2.0.pyc. Since pytest 9.2 that cache file is hash-based: it is reused only while the source still has the same hash.

The hook rewrites files whose names match the test-file patterns, test_*.py and *_test.py by default, files named on the command line, and modules passed to pytest.register_assert_rewrite. --assert=plain turns it off. Under python -O rewritten modules still check their asserts. Asserts everywhere else vanish, and pytest prints a warning about it.

Comparing floats and money

0.1 + 0.2 == 0.3 is False in Python, so an exact assert on floats fails for the wrong reason. pytest.approx(0.3) compares within a relative tolerance of 1e-6 and an absolute tolerance of 1e-12, and 0.1 + 0.2 == pytest.approx(0.3) passes.

The billing package keeps money in integer cents, so 6000 means exactly $60.00 and its tests never need approx.

Reading bigger diffs

When two dicts differ, the report prints Differing items: with the pairs that disagree, and the hint Use -v to get more diff. With -v it adds a complete diff headed Full diff: (-: missing in left side, +: extra in left side). Long strings skip their identical start and end, and -vv shows everything.

Naming tests

The test’s name is printed on the FAILED line, and it is often the only part of a report that gets read. Make it state the behaviour, not the function under test: test_zero_seats_is_rejected says what broke, and test_monthly_total_2 says only where to start looking.

ERRORS THIS CHAPTER EXPLAINS

Failed: DID NOT RAISE ValueError
the block finished without raising
check that the code still rejects that input, and that the call sits inside the with block
Regex pattern did not match.
the right exception arrived with a different message
fix the pattern, or wrap it in re.escape() when the message has brackets or dots
a bare AssertionError with no values
the assert is in a module pytest didn’t rewrite
register the module with pytest.register_assert_rewrite, or move the assert into the test

How pytest finds your tests: collection

You have one test file, and typing pytest ran it. You never told pytest where the file was or which function in it was the test. Before any test runs, pytest walks the project and builds a list of everything it is going to run. That step is called collection, and most cases of “my test didn’t run” are decided there. How does pytest decide what is a test, and how do you run just one?

STEP 01 / 04

THE MAP SO FAR

Fig 2.1The accent parts are new: the config, the collector and the list of test items it builds.

Three parts sit in front of the test function. The config in pyproject.toml fixes the options every run uses and the project’s root directory, which pytest calls the rootdir. The collector walks the test paths and picks out the tests.

That walk is called collection. Its output is a list of test items, one per test, each with an address of its own. The whole list exists before any test function is called.

STEP 02 / 04

COLLECTION PICKS FILES AND FUNCTIONS BY NAME

Fig 2.2One row per name pytest met. The accent row is a file of tests it never opened.

pytest looks for a config file in the directory you run it from, then in each directory above it. The directory that holds the file becomes the rootdir, and the header prints both as rootdir: and configfile: pyproject.toml. The file is written in TOML. pytest reads its [tool.pytest] table, where testpaths = ["tests"] says where to walk.

Names decide the rest. A file must match test_*.py or *_test.py. Inside it, pytest collects functions whose names start with test and classes whose names start with Test. tests/pricing_checks.py and a function called check_total match nothing, so pytest skips them and prints no message. The header line collected 3 items is the count of what it kept.

PYPROJECT.TOML: THE PYTEST CONFIG
# pyproject.toml
[dependency-groups]
dev = ["pytest>=9.2"]

[tool.pytest]
minversion = "9.0"
testpaths = ["tests"]              # where collection starts
addopts = ["-ra"]                  # always list what failed, errored or was skipped
strict = true                      # unknown options and markers become errors
markers = [
    "integration: needs the payment sandbox and a network",
]
STEP 03 / 04

EVERY TEST HAS AN ADDRESS, THE NODE ID

Fig 2.3The tree is what collection built. Follow the accent path: directory, file, then two colons and the function.

Each test item has a node ID: the file’s path, then ::, then the function’s name. For the first test that is tests/test_pricing.py::test_team_plan_charges_per_seat. Pass a node ID to pytest and only that test runs.

The other selectors work on the same list. -k coupon runs the tests whose names contain “coupon”, and -k "coupon and not expired" combines two conditions. --collect-only -q prints every node ID and runs nothing. --lf reruns only what failed last time, and -x stops at the first failure.

FIVE WAYS TO CHOOSE WHAT RUNS
$ pytest tests/test_pricing.py::test_zero_seats_is_rejected   # one test, by node ID
$ pytest -k "coupon and not expired"                          # by words in the name
$ pytest --lf                                                 # only what failed last time
$ pytest -x                                                   # stop at the first failure
$ pytest --collect-only -q                                    # list every test, run none
tests/test_pricing.py::test_team_plan_charges_per_seat
tests/test_pricing.py::test_zero_seats_is_rejected
tests/test_pricing.py::test_coupon_takes_a_quarter_off

3 tests collected in 0.01s
STEP 04 / 04

TESTS IMPORT YOUR PACKAGE THE WAY ITS USERS DO

Fig 2.4Two ways the import can resolve. The accent column is the editable install, which every test file shares.

The code lives in src/billing and the tests in tests/, outside the package. A test file can import billing only if the virtual environment knows where the package is. An editable install tells it: pip install -e . --group dev, or uv sync. After that, from billing.pricing import monthly_total finds the installed package, the way a user’s code would.

Without the install, the import fails while pytest is still collecting. The report shows ERROR collecting tests/test_pricing.py with ModuleNotFoundError: No module named 'billing' under it, then Interrupted: 1 error during collection. No test runs, not even the tests in files that imported cleanly.

THE PROJECT LAYOUT, AND THE INSTALL COMMAND
relay-billing/
├── pyproject.toml           project metadata and the pytest config
├── src/
│   └── billing/             the package: what users import
│       ├── pricing.py
│       ├── renewals.py
│       ├── gateway.py
│       ├── repo.py
│       └── mailer.py
└── tests/                   outside the package
    ├── test_pricing.py
    └── test_repo.py

$ pip install -e . --group dev      # or: uv sync

COMMON QUESTIONS

Where should tests live?
In a tests/ directory beside src/, one test file per module: src/billing/pricing.py and tests/test_pricing.py. pytest’s own guide recommends this layout.
pytest printed “no tests ran”. What happened?
Nothing matched the naming rules or the path you gave, and the run exits with code 5. Check the file name, the function name and testpaths.
Why did pytest run a helper named testing_data?
Functions are matched by prefix, and testing_data starts with test. Name helpers without that prefix, or keep them in a module that isn’t a test file.

WHAT YOU NOW KNOW

  • Collection walks testpaths and picks test_*.py files, test… functions and Test… classes by name.
  • Each test gets a node ID: its file path, two colons and the function name. You can run a test by that ID.
  • An import error in a test file stops the run during collection, before any test starts.
DEEP DIVE: which config file wins, native TOML and strict mode, import modes, exit codes

Which config file wins

Inside one directory pytest checks seven file names in this order: pytest.toml, .pytest.toml, pytest.ini, .pytest.ini, pyproject.toml, tox.ini and setup.cfg. The search starts at the common ancestor of the paths you passed and walks upward. The first match wins, and nothing is merged.

pyproject.toml counts only when it has a [tool.pytest] table, or the older [tool.pytest.ini_options]. When the config is split across two files, the header says which one pytest ignored: configfile: pytest.ini (WARNING: ignoring pytest config in pyproject.toml!).

Native TOML and strict mode

Since pytest 9.0 the [tool.pytest] table takes real TOML types, so addopts and testpaths are lists. A string there fails with config option 'addopts' expects a list for type 'args', got str. One file can’t hold both [tool.pytest] and [tool.pytest.ini_options].

strict = true turns on 4 checks: unknown config keys, unregistered markers, duplicate parametrize IDs and xfail tests that pass unexpectedly. Chapter 05 meets two of them. pytest’s documentation advises the setting only with a pinned pytest version, because a later release may add checks.

Import modes

The default import mode, prepend, inserts each test file’s base directory at the front of sys.path. Two files named test_pricing.py in different folders then compete for one module name, which is the “import file mismatch” error.

pytest’s documentation recommends importlib mode for new projects, set with addopts = ["--import-mode=importlib"], and says the default stays prepend “for the foreseeable future”. The alternative to an editable install is pythonpath = ["src"], which puts that folder on sys.path for the run.

Exit codes

pytest ends with one of 7 exit codes, and a script that runs it reads that number, not the report. A CI job treats every code except 0 as a failed job. So a run that collects nothing fails the build with code 5, although no test failed.

One row per exit code. The accent row is the run that printed no failure and still did not pass.

ERRORS THIS CHAPTER EXPLAINS

ModuleNotFoundError: No module named 'billing'
the package isn’t installed in this environment
run pip install -e ., or set pythonpath
import file mismatch:
two test files share a base name
rename one, or use importlib mode
PytestCollectionWarning: cannot collect test class 'TestCoupons' because it has a __init__ constructor
a test class defines __init__
move the setup into a fixture (chapter 03)
collected 0 items
the names or the paths match nothing
compare them against the naming rules

Setup a test asks for by name: fixtures

The pricing tests needed nothing but arguments. The next module is different. InvoiceRepo saves invoices in a SQLite database, so every test of it needs a database with the right tables, created before the test and closed after it, whether the test passes or not. Pasting that setup into each test buries the three lines that matter. pytest’s answer is the fixture. How does a test get the things it needs, and who cleans them up?

STEP 01 / 04

THE MAP SO FAR

Fig 3.1The accent parts are new: the fixtures, and the runner that calls them before and after each test.

Beside the test function sit fixtures: functions that build what a test needs. This chapter writes two, db for a database connection and repo for the object under test.

Above them is the runner. It takes each test item from the list and runs it in three phases. In setup the fixtures run. In the call phase your test function runs. In teardown the cleanup code of the fixtures runs.

STEP 02 / 04

A TEST GETS A FIXTURE BY NAMING IT AS A PARAMETER

Fig 3.2The test names repo, and repo names db. The accent link is that match of names; pytest does the rest.

@pytest.fixture above def db() makes db a fixture. It opens an in-memory SQLite database, creates the tables and returns the connection. A test declared def test_saved_invoice_is_read_back(repo) receives whatever the fixture repo returns. repo takes db the same way, so pytest runs db first.

The parameter name is the whole link: you write no import and no call. By default each test gets a fresh result, so two tests that take db get two separate databases.

The test itself stays short. It saves an invoice of 6000 cents for sub_1042, reads the invoices of that subscription back, and asserts that the list holds exactly that one.

TESTS/TEST_REPO.PY: TWO FIXTURES AND A TEST
# tests/test_repo.py
import sqlite3

import pytest

from billing.repo import SCHEMA, InvoiceRepo


@pytest.fixture
def db():
    conn = sqlite3.connect(":memory:")        # a database that lives in memory
    conn.executescript(SCHEMA)                # create the tables
    return conn


@pytest.fixture
def repo(db):                                 # a fixture can ask for a fixture
    return InvoiceRepo(db)


def test_saved_invoice_is_read_back(repo):    # the name "repo" is the request
    invoice = repo.add_invoice("sub_1042", 6000, charge_id="ch_9001")

    assert repo.invoices_for("sub_1042") == [invoice]
STEP 03 / 04

CODE AFTER YIELD IS THE CLEANUP

Fig 3.3Follow 1 to 5 across the runner, the fixtures and the test. The accent messages are cleanup, in reverse order.

A fixture that needs cleanup uses yield in place of return. The lines before yield are setup, the yielded value goes to the test, and the lines after it run when the test has finished, pass or fail. That cleanup is the fixture’s teardown. In db it is one line, conn.close().

When a test uses several fixtures, teardown runs in the reverse order of setup: repo is torn down before the db it depends on. pytest --setup-show prints each step as a SETUP or TEARDOWN line around the test.

DB AGAIN, WITH ITS CLEANUP AFTER THE YIELD
@pytest.fixture
def db():
    conn = sqlite3.connect(":memory:")
    conn.executescript(SCHEMA)
    yield conn             # the test runs here, holding conn
    conn.close()           # cleanup: runs after the test, pass or fail
THE ORDER PYTEST RAN THEM IN
$ pytest --setup-show tests/test_repo.py
...
collected 1 item

tests/test_repo.py
        SETUP    F db
        SETUP    F repo (fixtures used: db)
        tests/test_repo.py::test_saved_invoice_is_read_back (fixtures used: db, repo) .
        TEARDOWN F repo
        TEARDOWN F db

============================== 1 passed in 0.01s ===============================
STEP 04 / 04

A BROKEN FIXTURE IS AN ERROR, A BROKEN TEST IS A FAILURE

Fig 3.4One row per phase. The accent row is setup: an exception there means the test never ran.

The phase decides the word. An exception in the call phase is a failure: the letter F and a FAILED line. An exception in setup or teardown is an error: the letter E and a heading such as ERROR at setup of test_saved_invoice_is_read_back. When setup fails, the test body never runs.

In the report below the schema has a typo, so db raises near "TABEL": syntax error before the test starts, and the summary reads 1 error. A test whose body passes and whose cleanup raises is counted twice: 1 passed, 1 error. So when a test shows ERROR, read its fixtures before you read the test.

A FIXTURE THAT RAISES DURING SETUP
$ pytest tests/test_repo.py
...
collected 1 item

tests/test_repo.py E                                                     [100%]

==================================== ERRORS ====================================
______________ ERROR at setup of test_saved_invoice_is_read_back _______________

    @pytest.fixture
    def db():
        conn = sqlite3.connect(":memory:")
>       conn.executescript(SCHEMA)
E       sqlite3.OperationalError: near "TABEL": syntax error

tests/test_repo.py:12: OperationalError
=========================== short test summary info ============================
ERROR tests/test_repo.py::test_saved_invoice_is_read_back - sqlite3.Operation...
=============================== 1 error in 0.02s ===============================

COMMON QUESTIONS

Can I call a fixture like a normal function?
No. Calling it directly fails with “Fixture "db" called directly.” Name it as a parameter, in a test or in another fixture.
How do I see which fixtures exist and which ran?
pytest --fixtures lists every fixture a test file can use, with its docstring. pytest --setup-show prints each setup and teardown around every test.
Why not setUp and tearDown methods?
Those run for every test in a class, needed or not. A fixture runs only for the tests that name it, and fixtures build on each other.

WHAT YOU NOW KNOW

  • A fixture is a function marked @pytest.fixture; a test receives its result by naming it as a parameter.
  • Code after yield is cleanup. It runs after the test, pass or fail, in the reverse order of setup.
  • A fixture that raises is reported as ERROR, and in setup that means the test body never runs; a test that raises is FAILED.
DEEP DIVE: the order fixtures run in, a fixture that returns a factory, request and addfinalizer, usefixtures

The order fixtures run in

Three things decide the order, and nothing else does. One is how long each fixture lives, which chapter 04 covers. One is dependencies: a fixture runs after every fixture it names. The third is autouse=True, which runs a fixture for tests that never name it.

The order of a test’s parameters, the order of the definitions in the file and the alphabetical order of the names decide nothing you can rely on. When one fixture must run before another, make the second one take the first as a parameter.

A fixture that returns a factory

Some tests need several subscriptions, or an unusual one. A fixture can return a function: make_sub hands the test a function that builds a subscription with the plan and seats it is given, 5 seats on the team plan by default. A factory whose products need cleanup keeps them in a list, uses yield in place of return, and cleans up the whole list after it.

A FIXTURE THAT RETURNS A FUNCTION
@pytest.fixture
def make_sub(repo):
    def make(sub_id="sub_1042", plan="team", seats=5):
        sub = Subscription(sub_id, "cus_77", "billing@fernhill.example", plan=plan, seats=seats)
        repo.add_subscription(sub)
        return sub

    return make                               # the test receives the function


def test_larger_team_pays_more(make_sub):
    small = make_sub("sub_1", plan="starter", seats=1)
    large = make_sub("sub_2", plan="team", seats=40)

    assert monthly_total(small.plan, small.seats) < monthly_total(large.plan, large.seats)

request and addfinalizer

The built-in request fixture tells a fixture which test asked for it: request.node.name is that test’s name. request.addfinalizer(fn) is the older form of cleanup after yield. It is still the way to register cleanup inside a loop, one finalizer for each resource the loop opens.

usefixtures

@pytest.mark.usefixtures("db") is for a test that needs a fixture’s effect and not its value: the setup and the cleanup run, and the test takes no parameter. The decorator goes on tests. Applying a mark to a fixture is an error since pytest 9.0.

ERRORS THIS CHAPTER EXPLAINS

fixture 'repoo' not found
a typo, or the fixture is defined where this test can’t see it (chapter 04)
fix the name, or move the fixture
Fixture "db" called directly.
the fixture was called as a function
take it as a parameter
ERROR at teardown of …
the code after yield raised
fix the cleanup; the test’s own result is reported separately

Sharing setup: conftest.py, scope and built-in fixtures

The db and repo fixtures live in one test file, and a second file now needs them. Copying them is the wrong answer, and importing them from another test file is fragile. As the suite grows, building the same tables again for every single test also starts to cost time. Two settings answer both problems: where a fixture is defined, and its scope. Where do shared fixtures live, and how often does each one run?

STEP 01 / 04

THE MAP SO FAR

Fig 4.1The accent parts are new: conftest.py, the scope setting and tmp_path, which holds a real SQLite file.

Three parts join the tests’ side of the map. conftest.py is a file of fixtures that pytest loads by itself, so tests in other files can use them. Each fixture also has a scope, a setting that says how long its result lives before pytest builds a new one.

pytest ships fixtures of its own as well, called built-in fixtures. One of them, tmp_path, hands a test an empty directory. The db fixture will put its database file there, which is why the map draws a SQLite file below your code.

STEP 02 / 04

CONFTEST.PY SHARES FIXTURES WITH EVERY TEST BELOW IT

Fig 4.2A directory tree with two conftest.py files. The accent folder sees the fixtures of both.

Move db and repo out of the test file and into tests/conftest.py. During collection pytest loads every conftest.py it passes, and the fixtures defined there reach all tests in that directory and the directories below it. No test file imports anything. The file also gains sub, a saved subscription for Fernhill Studio.

A deeper folder can have a conftest.py of its own. tests/integration/ holds tests that need the network, and its conftest.py adds sandbox_gateway, a fixture only the tests in that folder can use. When two fixtures share a name, the nearest one wins: the test file’s own, then its folder’s conftest.py, then the parents’.

TESTS/CONFTEST.PY: THREE FIXTURES THAT NO TEST FILE IMPORTS
# tests/conftest.py: pytest loads this file by itself
import sqlite3

import pytest

from billing.repo import SCHEMA, InvoiceRepo, Subscription


@pytest.fixture
def db():
    conn = sqlite3.connect(":memory:")
    conn.executescript(SCHEMA)
    yield conn
    conn.close()


@pytest.fixture
def repo(db):
    return InvoiceRepo(db)


@pytest.fixture
def sub(repo):                                # a saved subscription for Fernhill Studio
    sub = Subscription("sub_1042", "cus_77", "billing@fernhill.example", plan="team", seats=5)
    repo.add_subscription(sub)
    return sub
STEP 03 / 04

SCOPE DECIDES HOW OFTEN A FIXTURE RUNS

Fig 4.36 tests in 2 files, left to right. Each bar is one fixture’s lifetime; the accent bar spans the whole run.

A fixture’s scope sets how long its result is kept. pytest has 5 scopes. function, the default, builds a new result for every test. class, module (one test file) and package keep it longer, and session builds it once for the whole run. @pytest.fixture(scope="session") on schema reads the SQL file once, and every test shares that one string.

The figure counts an illustrative run of 6 tests in 2 files. A function-scoped fixture is built 6 times, a module-scoped one 2 times and a session-scoped one once. In the output of pytest --setup-show, the letter after each SETUP is the scope: F for function, M for module, S for session.

A wider scope saves time and costs isolation: whatever one test changes in the shared object, the next test sees. Sharing schema is safe because a string can’t be changed. pytest sets up wider scopes first, and a wide fixture can’t use a narrower one: a session fixture that takes the function-scoped db fails with ScopeMismatch.

ONE FIXTURE BUILT PER RUN, ONE BUILT PER TEST
@pytest.fixture(scope="session")              # built once, shared by every test in the run
def schema():
    return Path("src/billing/schema.sql").read_text()


@pytest.fixture                               # scope="function" is the default: once per test
def db(schema):
    conn = sqlite3.connect(":memory:")
    conn.executescript(schema)
    yield conn
    conn.close()
STEP 04 / 04

PYTEST SHIPS FIXTURES FOR FILES, OUTPUT AND LOGS

Fig 4.4Four fixtures pytest provides. The accent row gives each test a directory of its own.

tmp_path is a pathlib.Path to a new, empty directory made for this one test, under pytest-of-<user>/pytest-<N>/. pytest keeps the directories of the last 3 runs, so you can open a failed test’s files afterwards.

The db fixture now takes tmp_path and connects to tmp_path / "billing.db". That is a database file on disk and the same SQLite engine as production, in a place no other test can touch.

capsys captures what the code prints: capsys.readouterr() returns the text written to standard output and standard error. caplog holds the log records the code wrote. monkeypatch is on the list too, and chapter 08 uses it.

THE DATABASE AS A FILE IN TMP_PATH, AND A TEST OF PRINTED OUTPUT
@pytest.fixture
def db(tmp_path, schema):                               # tmp_path: an empty directory for this test
    conn = sqlite3.connect(tmp_path / "billing.db")     # a real file and the real engine
    conn.executescript(schema)
    yield conn
    conn.close()


def test_report_prints_the_total(capsys):
    print_total("team", seats=5)

    assert capsys.readouterr().out == "Total: $60.00\n"

COMMON QUESTIONS

Should the database fixture be session-scoped to save time?
Not at first. A SQLite file in tmp_path takes milliseconds to create. Keep it per test, and widen the scope only when pytest --durations=10 shows setup is where the time goes.
What is an autouse fixture?
A fixture declared with autouse=True runs for every test in its reach, without being named. Use it for guards, such as blocking network access, and never for test data.
Can test files import helpers from each other?
Put shared helpers in an ordinary module, such as tests/helpers.py, and import that. Fixtures go in conftest.py, where no import is needed.

WHAT YOU NOW KNOW

  • Fixtures in conftest.py are available, with no import, to every test in that directory and below.
  • Scope sets a fixture’s lifetime: function by default, up to session; a wider scope shares one object between tests.
  • tmp_path gives each test its own empty directory, so the database can be a real SQLite file.
DEEP DIVE: autouse fixtures, sharing one expensive resource safely, tmp_path details, captured output and logs

Autouse fixtures

An autouse fixture runs for every test in its reach. Defined in a conftest.py, it covers that directory and the ones below; defined in a test file, it covers that file. Within its scope it runs before the fixtures a test names.

pytest’s own documentation shows the usual guard: an autouse fixture that deletes requests.sessions.Session.request for the length of each test. A test that then tries a real HTTP call through the requests library fails at once.

Sharing one expensive resource safely

When setup is slow, split it in two. A session-scoped fixture does the expensive part once: it builds a database engine, or a template file with the schema already loaded. A function-scoped fixture then hands each test a clean state, by copying the template file or by opening a transaction and rolling it back in teardown.

A session-scoped fixture can’t take tmp_path, which is function-scoped. tmp_path_factory is the session-scoped way to get a directory: tmp_path_factory.mktemp("data") returns a new one.

tmp_path details

The directory is named after the test: its name cut to 30 characters, plus a number. The setting tmp_path_retention_count defaults to 3 runs, and tmp_path_retention_policy defaults to all. Set the policy to failed to keep only the directories of failing tests.

tmpdir is the older fixture for the same job. It is still present, and tmp_path replaces it.

Captured output and logs

pytest captures standard output and standard error for every test, whether or not the test names capsys. It prints them, under a Captured stdout call heading, only for tests that fail. -s turns capture off, so printed lines appear as they happen.

caplog.at_level(logging.WARNING) sets the level that is captured inside a with block. Since pytest 9.1, caplog also captures loggers that don’t propagate to the root logger.

ERRORS THIS CHAPTER EXPLAINS

ScopeMismatch: You tried to access the function scoped fixture db with a session scoped request object.
a wide fixture depends on a narrower one
widen the inner fixture, or narrow the outer one
fixture 'sandbox_gateway' not found in a test outside tests/integration/
the fixture’s conftest.py is in a folder this test is not under
move the fixture up to a conftest.py both folders share

One test, many cases: parametrize and markers

The price rules have more cases than one test covers: two plans, one seat and several, a coupon, zero seats, an unknown plan. One function per case repeats the same three lines. One loop inside a single test stops at the first failing case and reports one result for all of them. Some tests also shouldn’t run everywhere: the slow ones, and the ones that need the network. How do you run one test over many inputs, and choose which tests run?

STEP 01 / 04

THE MAP SO FAR

Fig 5.1The accent chips are new: parametrize, which multiplies a test, and markers, which label it.

Two chips on the test function are new. parametrize takes one test function and a list of argument rows, and makes one test item per row. The multiplying happens while pytest collects, before anything runs, so each row gets a node ID of its own.

A marker is a label you attach to a test with a decorator. A run can select tests by marker, skip them, or expect them to fail. parametrize is itself a marker, which is why it is written @pytest.mark.parametrize.

STEP 02 / 04

PARAMETRIZE MAKES ONE TEST PER CASE

Fig 5.2One function goes in at the left and three tests come out. The accent test fails by itself, named by its case.

@pytest.mark.parametrize takes the argument names and a list of rows. Above test_monthly_total, three rows give three test items. Each item receives one row as its arguments, runs alone and reports alone.

pytest builds each node ID from the row’s values, as in test_monthly_total[team-5-6000]. With chapter 01’s bug still in the price table (Team at 1000 cents a seat), the Starter case passes and the two Team cases fail. Each failure has its own line in the report, and the line names the case.

ONE FUNCTION, THREE ROWS, THREE TESTS
import pytest

from billing.pricing import monthly_total


@pytest.mark.parametrize(
    ("plan", "seats", "expected"),
    [
        ("starter", 1, 800),
        ("team", 1, 1200),
        ("team", 5, 6000),
    ],
)
def test_monthly_total(plan, seats, expected):
    assert monthly_total(plan, seats=seats) == expected

# three tests:  test_monthly_total[starter-1-800]
#               test_monthly_total[team-1-1200]
#               test_monthly_total[team-5-6000]
STEP 03 / 04

WRITE THE EXPECTED VALUE, NEVER COMPUTE IT

Fig 5.3One row per case, with its ID, inputs and expected total. The accent row is the coupon: 4500, written out.

Give each case a name you would want to read in a failure. pytest.param("team", 5, "LAUNCH25", 4500, id="coupon-25-percent") replaces the ID built from the values, so the FAILED line says test_monthly_total[coupon-25-percent], and -k coupon runs that case alone.

The expected column holds literals: 800, 1200, 6000 and 4500 cents. A reviewer checks them against the price list, with no formula to work through.

The inputs that must be refused go in a second parametrized test, built on pytest.raises. One test then never mixes cases that return a total with cases that raise.

NAMED CASES, AND A SECOND TEST FOR INPUT THAT MUST BE REFUSED
CASES = [
    pytest.param("starter", 1, None, 800, id="starter-one-seat"),
    pytest.param("team", 1, None, 1200, id="team-one-seat"),
    pytest.param("team", 5, None, 6000, id="team-five-seats"),
    pytest.param("team", 5, "LAUNCH25", 4500, id="coupon-25-percent"),
]


@pytest.mark.parametrize(("plan", "seats", "coupon", "expected"), CASES)
def test_monthly_total(plan, seats, coupon, expected):
    assert monthly_total(plan, seats=seats, coupon=coupon) == expected


@pytest.mark.parametrize(
    ("plan", "seats", "message"),
    [
        pytest.param("team", 0, "at least 1", id="zero-seats"),
        pytest.param("gold", 5, "unknown plan", id="unknown-plan"),
    ],
)
def test_bad_input_is_rejected(plan, seats, message):
    with pytest.raises(ValueError, match=message):
        monthly_total(plan, seats=seats)
STEP 04 / 04

MARKERS LABEL TESTS, AND -m CHOOSES BY LABEL

Fig 5.4One row per marker: what it does and how the run reports it. The accent row is a marker you define.

@pytest.mark.integration labels a test that needs the network; chapter 09 writes 4 of them. The name is your own, so it must be registered: chapter 02’s config already lists integration under markers. Then pytest -m "not integration" leaves those tests out and reports them as deselected.

pytest has built-in markers too. skip(reason=…) never runs the test. skipif(condition, reason=…) skips it when the condition is true, such as on one operating system. xfail, written xfail(reason=…), is for a known bug: the test runs and is expected to fail.

That config also sets strict = true. With it, a marker name that isn’t registered is an error during collection, before any test runs.

ONE MARKER OF YOUR OWN, TWO BUILT-IN ONES
import sys

import pytest


@pytest.mark.integration                  # your own label, registered in pyproject.toml
def test_sandbox_accepts_a_charge(): ...


@pytest.mark.skipif(sys.platform == "win32", reason="uses a Unix socket")
def test_local_socket(): ...


@pytest.mark.xfail(reason="odd cents are rounded down: issue 87")
def test_odd_cent_totals_round_up(): ...

# $ pytest -m "not integration"     leaves the first test out: "1 deselected"

COMMON QUESTIONS

Why not a for loop inside one test?
A loop stops at the first failing case and reports one result. Parametrize runs every case, reports each by name and lets you rerun one by its ID.
What happens when I stack two parametrize decorators?
You get every combination: two plans and three seat counts make six tests. Use it for inputs that vary independently, and a single table when they don’t.
When is xfail right, and when is skip?
skip is for a test that can’t run here, such as one needing an API key. xfail is for a known bug: with strict xfail on, the test fails the run on the day it starts passing, so you remove the marker.

WHAT YOU NOW KNOW

  • parametrize turns one function into one test per case, each with its own ID, such as test_monthly_total[team-5-6000].
  • Expected values are literals: 4500 for 5 Team seats with LAUNCH25, never a formula.
  • Markers label tests; -m "not integration" deselects by label, and strict mode turns a misspelled marker into an error.
DEEP DIVE: how IDs are built, parametrizing a fixture, generated cases with Hypothesis, strict xfail, subtests

How IDs are built

Numbers, strings, booleans and None become their text, joined with -. Any other object becomes the argument’s name and the row’s index: plan0, plan1. Since pytest 9.2 a string longer than 100 characters falls back to that form too.

Two rows that produce the same ID get _0 and _1 added. With strict_parametrization_ids, which strict = true turns on, duplicates are a collection error. Since 9.2 ids= must be passed by keyword, and passing a generator as the list of cases is deprecated.

Parametrizing a fixture

@pytest.fixture(params=[…]) gives a fixture a list of values, and the fixture reads the current one from request.param. Every test that uses the fixture then runs once per value. Chapter 09 uses this to run one set of tests against two objects that must behave alike.

Generated cases with Hypothesis

Hypothesis is a library that generates the cases for you. @given(seats=st.integers(min_value=1, max_value=500)) calls the test with 100 generated seat counts by default. When one fails, Hypothesis reduces it to the smallest input that still fails and reports that one.

It suits rules that hold for every input, such as “one more seat always costs more” or “the total is never negative”. Failing cases are saved in the .hypothesis/ directory.

A RULE CHECKED FOR GENERATED SEAT COUNTS
from hypothesis import given, strategies as st

from billing.pricing import monthly_total


@given(seats=st.integers(min_value=1, max_value=500))
def test_one_more_seat_always_costs_more(seats):
    assert monthly_total("team", seats=seats + 1) > monthly_total("team", seats=seats)

Strict xfail

The option is strict_xfail since pytest 9.0; the old name xfail_strict still works, and strict = true turns the option on. Strict: an xfail test that passes is reported as FAILED … - [XPASS(strict)] and fails the run. Not strict: it is counted as xpassed and the run stays green.

Subtests

The subtests fixture, built in since pytest 9.0, reports several checks inside one test separately. A check that fails is listed as SUBFAILED[…]. It fits cases that are only known while the test runs.

ERRORS THIS CHAPTER EXPLAINS

'intergration' not found in `markers` configuration option
strict markers met a name that isn’t registered
fix the spelling, or register the name in the config
Unknown 'parameterize' mark, did you mean 'parametrize'?
the common misspelling of the marker
drop the extra “e”
Unknown marker(s) in '-m' expression
with strict markers, since pytest 9.2: the name after -m isn’t registered
check the names with pytest --markers

Code that calls the outside: seams and fakes

Every test so far ran code that needs only its arguments, or a database file that pytest can create in a moment. charge_renewal is different. It charges a card through the payment provider’s HTTP API, reads today’s date and sends an email. Run as it stands, a test would move real money, pass only on some days and fail whenever the network does. How do you test code whose dependencies you can’t use in a test?

STEP 01 / 05

THE MAP SO FAR

Fig 6.1The accent parts are new: four parameters on charge_renewal, and two stand-ins passed through them.

Below your code, outside the process, sit the four things charge_renewal needs: the payment API, the system clock, the production database and the mail server. Each one is a dependency, something your code calls and does not contain.

The row of parameters on charge_renewal is new: gateway=, clock=, repo= and mailer=. Through them the caller chooses which of each the function uses. That row is the seam. In a test, two of the parameters get a stand-in written by hand, FakeGateway and a fixed clock, and the database is the SQLite file from chapter 04.

STEP 02 / 05

A HARD-WIRED DEPENDENCY CAN’T BE REPLACED

Fig 6.2Three arrows leave the function, each to something a test can’t control. The accent arrow charges a real card.

The first version of charge_renewal(sub) names its dependencies inside its body. It calls httpx2.post with PayGate’s address, https://api.paygate.example/v1/charges. When the charge fails it reads date.today() to set the retry date. When the charge succeeds it opens a connection to the mail server and sends the receipt.

A test of this function has four problems. It charges a real card. Its result depends on the day it runs. It needs the network. And it can’t produce a declined card on demand, which is the case most worth testing. A unit test has to be fast and give the same result on every run, and this one can be neither.

BILLING/RENEWALS.PY, VERSION 1: EVERY DEPENDENCY IN THE BODY
# billing/renewals.py, version 1
def charge_renewal(sub):
    amount = monthly_total(sub.plan, sub.seats)
    reply = httpx2.post(                                    # a real charge on a real card
        "https://api.paygate.example/v1/charges",
        json={"customer": sub.customer_id, "amount": amount},
    )
    if reply.json()["status"] != "success":
        sub.status = "past_due"
        sub.retry_on = date.today() + timedelta(days=3)     # whatever day the test runs
        return None
    with smtplib.SMTP("mail.relay.example") as smtp:        # a real email
        smtp.sendmail("billing@relay.example", sub.email, RECEIPT)
    return reply.json()["id"]
STEP 03 / 05

PASS THE DEPENDENCY IN, AND A TEST CAN PASS ANOTHER

Fig 6.3The same function, called two ways. The accent column is what a test passes for each parameter.

The second version is charge_renewal(sub, *, gateway, clock, repo, mailer). The work is the same: charge the card, then record what happened. The body no longer names an address, a system clock or a mail server. It calls gateway.charge(…), clock() and mailer.send_receipt(…) on whatever objects it was given.

Production code builds the real four once, in main(), and passes them. A test passes four others. A place where behaviour can change without editing the code there is called a seam, and handing a function its collaborators as arguments is called dependency injection. It needs no framework: keyword arguments are enough.

BILLING/RENEWALS.PY, VERSION 2: FOUR PARAMETERS
# billing/renewals.py, version 2
def charge_renewal(sub, *, gateway, clock, repo, mailer):
    amount = monthly_total(sub.plan, sub.seats)
    try:
        charge = gateway.charge(sub.customer_id, amount_cents=amount)
    except CardDeclined:
        retry_on = clock().date() + timedelta(days=RETRY_DAYS)
        repo.mark_past_due(sub.id, retry_on=retry_on)
        return None
    invoice = repo.add_invoice(sub.id, amount, charge_id=charge.id)
    mailer.send_receipt(sub.email, invoice_id=invoice.id)
    return invoice


def main():                                   # production builds the real four, once
    gateway = PaymentGateway(paygate_client())
    repo = InvoiceRepo(sqlite3.connect("billing.db"))
    for sub in repo.due_today():
        charge_renewal(sub, gateway=gateway, clock=utc_now, repo=repo, mailer=Mailer())
STEP 04 / 05

FIVE KINDS OF STAND-IN SHARE ONE NAME: TEST DOUBLE

Fig 6.4Five kinds of test double, each with a billing example. The accent row is the one this chapter builds.

Any object that stands in for a production object during a test is a test double. There are five kinds. A dummy is passed around and never used: it only fills a parameter. A stub returns canned answers to the calls made during the test. A spy is a stub that also records how it was called.

A mock is told in advance which calls to expect, and fails the test when the calls it receives are different. A fake is a working implementation that takes a shortcut, such as keeping its data in memory, which makes it unfit for production.

In everyday Python talk all five are called “mocks”. The kind still matters, because it says what the test can check: only the result the code produced from the double’s answers, or also the calls the code made to the double.

STEP 05 / 05

A FAKE IS A SMALL WORKING IMPLEMENTATION

Fig 6.5Follow 1 to 6 through one declined renewal. The accent box is the fake gateway, which refuses the charge.

FakeGateway has the real gateway’s method, charge(customer_id, amount_cents). It appends each charge to a list and returns a Charge with status succeeded. For a customer it was told to decline, it raises CardDeclined and records nothing.

The clock is simpler, a stub: one function that always returns 1 December 2026, 09:00 UTC. The database stays real, a SQLite file in tmp_path. The mailer is a dummy, None, because a declined renewal sends no receipt.

The decline test passes FakeGateway(decline={"cus_77"}) and asserts on the outcome: the saved subscription has status past_due, its retry_on is 4 December, 3 days after the renewal, and it has no invoice.

TESTS/FAKES.PY: A GATEWAY THAT KEEPS ITS CHARGES IN A LIST
# tests/fakes.py
from billing.gateway import CardDeclined, Charge


class FakeGateway:
    """A working gateway that keeps its charges in a list."""

    def __init__(self, decline=()):
        self.decline = set(decline)           # customers whose cards are refused
        self.charges = []                     # every (customer, amount) charged so far

    def charge(self, customer_id, amount_cents):
        if customer_id in self.decline:
            raise CardDeclined("card_declined")
        self.charges.append((customer_id, amount_cents))
        number = 9000 + len(self.charges)     # ch_9001, ch_9002, and so on
        return Charge(f"ch_{number}", "succeeded", amount_cents)
TESTS/TEST_RENEWALS.PY: THE DECLINED RENEWAL
# tests/test_renewals.py
from datetime import UTC, date, datetime

from billing.renewals import charge_renewal
from tests.fakes import FakeGateway


def fixed_clock():
    return datetime(2026, 12, 1, 9, 0, tzinfo=UTC)


def test_declined_card_marks_the_subscription_past_due(repo, sub):
    gateway = FakeGateway(decline={"cus_77"})          # this customer is refused

    charge_renewal(sub, gateway=gateway, clock=fixed_clock, repo=repo, mailer=None)

    saved = repo.get_subscription("sub_1042")
    assert saved.status == "past_due"
    assert saved.retry_on == date(2026, 12, 4)         # three days later
    assert repo.invoices_for("sub_1042") == []

COMMON QUESTIONS

Is it still a unit test if it uses a real SQLite file?
Stricter definitions say a unit test reads no files and opens no connections. What you need is a test that is fast, repeatable and independent of the others, and SQLite in a temporary directory is all three.
Do I need a dependency-injection library?
No. Arguments, plus one function that builds the real objects at startup, cover most programs. A library earns its place when the wiring itself becomes hard to follow.
How do I keep the fake’s methods in step with the real class?
Describe the shared methods once as a typing.Protocol, and a type checker reports a fake that falls behind. Chapter 09 adds tests that check its behaviour too.

WHAT YOU NOW KNOW

  • Code that calls the network, the clock or a mail server directly can’t be controlled by a test.
  • charge_renewal(sub, *, gateway, clock, repo, mailer) takes its dependencies as arguments: that parameter list is the seam.
  • A fake such as FakeGateway is a small working implementation; the decline test only tells it which customer to refuse.
DEEP DIVE: where the five names come from, a Protocol for the gateway, a clock you can advance, default arguments as seams, keeping decisions in pure functions

Where the five names come from

Gerard Meszaros named the test double, after the stunt double in a film, and sorted the five kinds in his book “xUnit Test Patterns”. Martin Fowler’s short note “Test Double” (2006) is the version most people read. His article “Mocks Aren’t Stubs” (2004, revised 2007) separates two ways of checking: by the state the code leaves behind, or by the calls it made.

“Seam” is Michael Feathers’ word, from “Working Effectively with Legacy Code”. His definition: “a place where you can alter behavior in your program without editing in that place.” The parameter list of charge_renewal is such a place.

A Protocol for the gateway

charge_renewal never checks which class its gateway is. It calls charge(customer_id, amount_cents) and expects a Charge back. A typing.Protocol writes that expectation down as a class with one method and no body.

ONE PROTOCOL, TWO GATEWAYS
from typing import Protocol

from billing.gateway import Charge


class Gateway(Protocol):
    def charge(self, customer_id: str, amount_cents: int) -> Charge: ...


def charge_renewal(sub, *, gateway: Gateway, clock, repo, mailer): ...

# PaymentGateway and FakeGateway both match, with no shared base class.
# A type checker reports a fake whose charge() takes other arguments.

The real gateway class in billing/gateway.py and FakeGateway both satisfy it with no inheritance, because a protocol is matched by the methods a class has. The design-patterns tutorial covers both ideas, in its protocols chapter and its dependency-injection chapter.

A clock you can advance

A fixed clock is enough for one renewal. The retry needs time to pass: charge on 1 December, wait 3 days, charge again. A small FakeClock class with a now() method and an advance(days=3) method does that. The test passes clock.now as the clock, runs the renewal, advances the clock and runs it again.

Default arguments as seams

def charge_renewal(sub, *, clock=utc_now) gives the parameter a default, so production call sites stay short and a test can still pass its own clock. The cost: a test that forgets the argument uses the real clock, and nothing reports it. With required keyword arguments, as in version 2, the same mistake is a TypeError.

Keeping decisions in pure functions

The more of the logic that lives in functions like monthly_total, which take values and return values, the less needs any double. charge_renewal decides almost nothing: it asks for the amount, calls the gateway and records the outcome. Code shaped this way needs a few tests with stand-ins and many tests with none.

An object that records every call: Mock

The fake gateway is a class of its own, and it earns its place because many tests use it. The mailer is a different case. A declined renewal never reached it, so None was enough. A paid renewal sends a receipt: one test needs to know that it went to the right address, and another needs the mailer to fail with a timeout. Writing a class for each is slow. Python’s standard library ships a ready-made test double that you configure in a line, unittest.mock.Mock. What does a Mock do for you, and what does it fail to check?

STEP 01 / 04

THE MAP SO FAR

Fig 7.1The accent part is new: a Mock standing in for the mailer on the right-hand lane.

On the mailer’s lane, the stand-in is a Mock: an object from the standard library’s unittest.mock module. It accepts any call, records it, and answers with whatever the test told it to answer.

It reaches the code the way the fake gateway did. The test builds it and passes it as mailer=. Nothing in charge_renewal changes, and the mail server below the lane is never contacted. The map’s label also says autospec, a word step 04 explains.

STEP 02 / 04

A MOCK ACCEPTS ANY CALL AND REMEMBERS IT

Fig 7.2Follow 1 to 4. The accent box is the Mock’s record of the call, which the test checks afterwards.

mailer = Mock() builds the stand-in. During the paid renewal the code calls mailer.send_receipt("billing@fernhill.example", invoice_id="inv_3001"), and the call works though nobody defined send_receipt. A Mock creates each attribute the first time it is read, and every attribute is another Mock.

Each call is recorded with its arguments. After the act, the test asserts on the record: mailer.send_receipt.assert_called_once_with(…) passes only if there was exactly one call, with exactly those arguments. Different arguments fail with the message expected call not found. and two lines under it, Expected: and Actual:, that show the two calls.

A MOCK AS THE MAILER, AND THE ASSERTION ON ITS RECORD
from unittest.mock import Mock


def test_receipt_goes_to_the_billing_address(repo, sub):
    mailer = Mock()                                    # accepts any call

    charge_renewal(sub, gateway=FakeGateway(), clock=fixed_clock, repo=repo, mailer=mailer)

    mailer.send_receipt.assert_called_once_with(
        "billing@fernhill.example", invoice_id="inv_3001"
    )

# had the receipt gone to another address, the assert would fail with:
#   AssertionError: expected call not found.
#   Expected: send_receipt('billing@fernhill.example', invoice_id='inv_3001')
#     Actual: send_receipt('office@fernhill.example', invoice_id='inv_3001')
STEP 03 / 04

RETURN_VALUE AND SIDE_EFFECT SCRIPT THE ANSWERS

Fig 7.3What you set on the left, what each call then does in the middle. The accent row makes the call raise.

Left alone, a call on a Mock returns another Mock. Two attributes change that. gateway.charge.return_value = Charge("ch_9001", "succeeded", 6000) makes every call return that charge. mailer.send_receipt.side_effect = TimeoutError(…) makes the call raise the exception.

A list gives one answer per call, in order. [CardDeclined("card_declined"), Charge(…)] declines the first charge and accepts the second, which is the retry in two lines. A list that runs out raises StopIteration. side_effect can also be a function: the Mock calls it with the same arguments and returns its result.

SCRIPTING WHAT A MOCK RETURNS AND WHAT IT RAISES
gateway = Mock()
gateway.charge.return_value = Charge("ch_9001", "succeeded", 6000)   # every call returns this

mailer = Mock()
mailer.send_receipt.side_effect = TimeoutError("smtp timed out")     # the call raises

gateway.charge.side_effect = [                 # one answer per call, in order
    CardDeclined("card_declined"),             # first call: raised
    Charge("ch_9002", "succeeded", 6000),      # second call: returned
]
STEP 04 / 04

A BARE MOCK PASSES TESTS THAT SHOULD FAIL

Fig 7.4Three calls, sent to two mocks. The accent column was built from the real class and refuses the two wrong ones.

Suppose the code calls gateway.charge("cus_77", amount=6000), and the real method’s parameter is amount_cents. A bare Mock() accepts the call, the test is green, and production fails with a TypeError. The test compared the code with a stand-in that agrees to everything.

create_autospec(PaymentGateway, instance=True) builds the mock from the real gateway class in billing/gateway.py. Building a mock from the real thing is called autospec. The same call now raises TypeError: missing a required argument: 'amount_cents', and a method the class doesn’t have raises AttributeError: Mock object has no attribute 'refund'.

Autospec checks names and call signatures. It knows nothing about what the real method returns or raises: that part is still yours to script, and it can still be wrong. Give every Mock that stands in for a real class its spec.

THE SAME CALLS, AGAINST TWO MOCKS
from unittest.mock import Mock, create_autospec

from billing.gateway import PaymentGateway

bare = Mock()
bare.charge("cus_77", amount=6000)             # accepted: the test stays green

gateway = create_autospec(PaymentGateway, instance=True)
gateway.charge("cus_77", amount=6000)
# TypeError: missing a required argument: 'amount_cents'

gateway.refund("ch_9001")
# AttributeError: Mock object has no attribute 'refund'

gateway.charge("cus_77", amount_cents=6000)    # the real signature is accepted

COMMON QUESTIONS

Mock or MagicMock?
MagicMock is a Mock that also answers Python’s special methods, so it works with len(), a with block and iteration. With create_autospec you rarely choose by hand.
What about async def code?
AsyncMock returns something you can await, and autospec picks it for async def methods. A plain MagicMock in an await fails with TypeError: 'MagicMock' object can't be awaited.
Should a test assert on every call the code makes?
No. Assert on a call when the call is the outcome, such as an email sent. When the code returns or stores a result, assert on that result. Chapter 09 comes back to this choice.

WHAT YOU NOW KNOW

  • A Mock accepts any call, records it, and lets the test check it with assert_called_once_with(…).
  • return_value sets the answer; side_effect raises an exception or gives one answer per call from a list.
  • A bare Mock accepts wrong arguments; create_autospec(PaymentGateway, instance=True) rejects them with a TypeError.
DEEP DIVE: spec, spec_set and autospec, what autospec can’t see, the assertions that guard themselves, matching loosely with ANY, spying with wraps, sealing a mock

spec, spec_set and autospec

Mock(spec=Mailer) gives the mock the attribute names of the real class. Reading a name the class doesn’t have raises AttributeError, and the mock passes isinstance(mailer, Mailer). spec_set=Mailer also refuses to set an attribute the class doesn’t have. Neither one checks how a method is called.

Only autospec checks call signatures, and it does so for every method of the class. With instance=True, create_autospec returns a mock of an instance, which can’t itself be called. An async def method becomes an AsyncMock.

What autospec can’t see

Autospec reads the class, not an instance. An attribute that __init__ creates doesn’t exist on the class, so the autospecced mock doesn’t know it and raises AttributeError when the code reads it. The mock documentation gives two fixes: declare the attribute on the class with a default value, or pass an instance as the spec. Since Python 3.14, the fields of a dataclass are picked up.

The assertions that guard themselves

A Mock creates any attribute you read, so a misspelled assertion was once a method that did nothing. Today mailer.send_receipt.assret_called_once() raises AttributeError, with the message in the list below. The check covers unknown names that start with assert, assret, asert, aseert or assrt, since Python 3.10.

Since Python 3.12 the names that lost their assert_ prefix raise the same way: called_once_with, called_with, not_called and the rest. A missing pair of parentheses is different. It is valid Python, the mock can’t see it, and only a linter reports it.

The messages in the list below are worded as Python 3.15 prints them. Earlier versions word some of them differently.

Matching loosely with ANY

unittest.mock.ANY compares equal to everything. assert_called_once_with("billing@fernhill.example", invoice_id=ANY) checks the address and accepts any invoice. To read what was sent, look at the last call’s keyword arguments: mailer.send_receipt.call_args.kwargs["invoice_id"].

Spying with wraps, and sealing a mock

Mock(wraps=real_mailer) passes each call through to the real object and still records it, which makes it a spy. An explicit return_value stops the pass-through. seal(mock) does the opposite of a bare Mock: once a mock is sealed, reading an attribute you didn’t configure raises AttributeError, so the mock stops growing new ones.

ERRORS THIS CHAPTER EXPLAINS

expected call not found.
the mock was called, with other arguments
compare the Expected: and Actual: lines under it
Expected 'send_receipt' to be called once. Called 2 times.
the code sent the receipt twice
read the Calls: line, which lists both calls
AttributeError: Mock object has no attribute 'send_reciept'
a spec caught a method name the real class doesn’t have
fix the spelling where the method is called
TypeError: 'MagicMock' object can't be awaited
an async def method was replaced by a mock that isn’t async
use autospec, or AsyncMock
'assret_called_once' is not a valid assertion. Use a spec for the mock if 'assret_called_once' is meant to be an attribute
an assertion method is misspelled
write assert_called_once()

Replacing a name for one test: patch and monkeypatch

Passing dependencies in works for code you can shape. The reminder job is older code. send_reminders reads its sender address from an environment variable, takes today’s date from the system, and calls a send_email function that it imported at the top of the file. It has no parameter to pass a double through. For code like this, Python lets a test point a name at something else for the length of one test. How do you replace something the code looks up by name, and where?

STEP 01 / 04

THE MAP SO FAR

Fig 8.1The accent chip is new: patch and monkeypatch, which put a stand-in behind a name.

Between your code and the stand-ins sits one more part, a pair of tools. patch comes from the standard library’s unittest.mock, and monkeypatch is a fixture built into pytest. Both point a name at a stand-in while one test runs, then point it back.

The name can be a module attribute, such as a function or a constant, an environment variable or a dictionary key. The code under test is not edited and gets no new parameter. It looks the name up as it always did and finds the stand-in. Both tools are for code that has no seam.

STEP 02 / 04

A PATCH LASTS FOR ONE TEST, THEN IS UNDONE

Fig 8.2Three moments: before, during and after the test. The accent step puts the original back.

monkeypatch is a fixture, so a test asks for it by name. monkeypatch.setenv("BILLING_FROM", "billing@relay.example") sets the variable that send_reminders reads. monkeypatch.setattr("billing.renewals.RETRY_DAYS", 1) would replace a module constant the same way. pytest undoes both when the test has finished, pass or fail.

patch("billing.reminders.send_email", autospec=True), used as a with block, replaces the function with an autospecced mock for the length of the block and hands you that mock as send_email. When the block ends, the name points at the real function again. The assertion on the mock comes after the block.

TESTS/TEST_REMINDERS.PY: A VARIABLE AND A FUNCTION, REPLACED FOR ONE TEST
# tests/test_reminders.py
from unittest.mock import patch

from billing.reminders import send_reminders


def test_overdue_customer_gets_a_reminder(repo, past_due_sub, monkeypatch):
    monkeypatch.setenv("BILLING_FROM", "billing@relay.example")    # undone after the test

    with patch("billing.reminders.send_email", autospec=True) as send_email:
        send_reminders(repo)                                       # send_email is a mock here

    send_email.assert_called_once_with(
        "billing@relay.example", "billing@fernhill.example", "Your payment is overdue"
    )
STEP 03 / 04

PATCH THE NAME WHERE THE CODE LOOKS IT UP

Fig 8.3Two modules, two names, one function. The accent patch rebinds the name that reminders.py reads.

reminders.py begins with from billing.mailer import send_email. That line creates a second name, billing.reminders.send_email, for the same function object. From then on send_reminders looks the function up under that second name, in its own module.

patch("billing.mailer.send_email") rebinds the name inside mailer. The name in reminders still points at the original, so the real email goes out and the mock reports no calls. Patch billing.reminders.send_email, the name the code under test reads.

THE PATCH THAT DOES NOTHING, AND THE PATCH THAT WORKS
# billing/reminders.py begins:
#     from billing.mailer import send_email
# so one function has two names:
#     billing.mailer.send_email         where it is defined
#     billing.reminders.send_email      where send_reminders() looks it up

with patch("billing.mailer.send_email") as send_email:       # the wrong name
    send_reminders(repo)                                     # the real email goes out
send_email.assert_called_once()
# AssertionError: Expected 'send_email' to have been called once. Called 0 times.

with patch("billing.reminders.send_email") as send_email:    # the name the code reads
    send_reminders(repo)
send_email.assert_called_once()                              # passes
STEP 04 / 04

TIME NEEDS A TOOL OF ITS OWN

Fig 8.4Three ways to fix the date in a test, with what each one costs. The accent row needs no patch.

send_reminders takes today’s date from date.today(). Patching the standard type directly fails: patch.object(datetime.datetime, "now") raises TypeError: cannot set 'now' attribute of immutable type 'datetime.datetime', because the type is written in C and its attributes can’t be replaced.

There are three ways out, best first. Pass a clock in, as chapter 06 did. Use the time-machine package (3.6.0 here): time_machine.travel(later, tick=False) moves the clock for date.today(), datetime.now() and time.time(), and tick=False holds it still. Or patch the name date in the module under test, which changes it for that module only.

The sample travels to the day after the retry date of 4 December. The reminder is then due, and the test asserts that one email was sent.

MOVING THE CLOCK WITH TIME-MACHINE
from datetime import UTC, datetime

import time_machine


def test_reminder_goes_out_once_the_retry_date_has_passed(repo, past_due_sub, monkeypatch):
    monkeypatch.setenv("BILLING_FROM", "billing@relay.example")
    later = datetime(2026, 12, 5, 12, 0, tzinfo=UTC)         # the day after the retry date

    with time_machine.travel(later, tick=False):             # date.today() is 5 December
        with patch("billing.reminders.send_email", autospec=True) as send_email:
            send_reminders(repo)

    send_email.assert_called_once()

COMMON QUESTIONS

monkeypatch, mock.patch or mocker?
All three undo themselves. Use monkeypatch for environment variables and plain replacements, and patch when you want a mock with autospec. mocker comes from the pytest-mock plugin: it is patch as a fixture, with no with block.
Why did @patch hand my test its mocks in the wrong order?
Stacked @patch decorators pass their mocks bottom-up: the decorator nearest the function supplies the first argument. A with block or mocker avoids the puzzle.
Can I stop every test from reaching the network?
Yes. pytest’s docs show an autouse fixture that removes the HTTP library’s request method, and the pytest-socket plugin’s --disable-socket makes any socket use fail.

WHAT YOU NOW KNOW

  • monkeypatch and patch point a name at a stand-in for one test and restore the original afterwards.
  • Patch where the name is looked up: billing.reminders.send_email, not billing.mailer.send_email.
  • datetime.now can’t be patched directly; pass a clock in, or use time-machine’s travel(…, tick=False).
DEEP DIVE: the rest of the patch family, monkeypatch’s methods, the mocker fixture, patching for more than one test, why pytest’s docs prefer a seam

The rest of the patch family

patch.object(obj, "name") patches an attribute of an object you already hold. patch.dict(os.environ, {…}) changes a dictionary and restores a copy of the original afterwards. patch.multiple patches several names of one target at once. Passing new= supplies your own replacement, and then no mock is handed to the test.

When you supply nothing, patch builds a MagicMock. Every patcher also has start() and stop(), for a patch that begins in one place and ends in another. Since Python 3.14 a second start() raises RuntimeError: Patch is already started.

monkeypatch’s methods

The fixture’s methods are setattr, delattr, setitem, delitem, setenv, delenv, syspath_prepend, chdir and context. context() is a with block for a patch that must end before the test does. With the default raising=True, setattr on a name that doesn’t exist is an error, so a typo can’t create a new attribute.

The mocker fixture

pytest-mock 3.17.0 adds a fixture, mocker, that wraps the same patchers: mocker.patch(…), mocker.patch.object, mocker.spy(obj, "name"), mocker.stub() and mocker.create_autospec. Everything it patched is undone at teardown, so the test needs no with block. A spy calls the real function and keeps its last result in spy_return and its last exception in spy_exception.

THE STEP 02 TEST, WITH MOCKER
def test_overdue_customer_gets_a_reminder(repo, past_due_sub, monkeypatch, mocker):
    monkeypatch.setenv("BILLING_FROM", "billing@relay.example")
    send_email = mocker.patch("billing.reminders.send_email", autospec=True)

    send_reminders(repo)                  # no with block: mocker undoes the patch itself

    send_email.assert_called_once_with(
        "billing@relay.example", "billing@fernhill.example", "Your payment is overdue"
    )

Using mocker.patch as a context manager warns. The plugin also changes what a failed mock assertion prints: a failed assert_called_once_with gains a pytest introspection follows: section, even on plain unittest.mock objects. Every sample in this tutorial shows the output without the plugin installed.

Patching for more than one test

monkeypatch is function-scoped, so a fixture with module or session scope can’t ask for it. A wider fixture opens its own patcher with with pytest.MonkeyPatch.context() as mp: and yields inside the block. pytest-mock has module_mocker and session_mocker for the same job.

Why pytest’s docs prefer a seam

Since pytest 9.1 the monkeypatch page gives two pieces of advice. The first is step 03’s rule: “Prefer patching the reference that your code uses instead of patching the original object in the standard library.” The second is what chapter 06 did: “For code that you control, a safer long-term pattern is to make dependencies explicit so they can be passed into the code under test instead of patched globally.”

The reason is what a patch names: a module path and an attribute. Move send_email to another module, or rename it, and the test breaks though the behaviour is the same. An argument has no such tie to the layout of the code.

ERRORS THIS CHAPTER EXPLAINS

AttributeError: <module 'billing.reminders' from '…'> does not have the attribute 'send_emial'
the patched name doesn’t exist in that module
fix the spelling; don’t reach for create=True
AttributeError: module 'billing' has no attribute 'remindrs'
a module in the patch target is misspelled
fix the path: a wrong module name is reported as a missing attribute of its package
TypeError: Need a valid target to patch. You supplied: 'send_email'
the target has no module path
write package.module.name
AssertionError: Expected 'send_email' to have been called once. Called 0 times.
the patch moved a name the code doesn’t read
patch the name in the module that calls the function
TypeError: cannot set 'now' attribute of immutable type 'datetime.datetime'
a type written in C can’t be patched
pass a clock in, or use time-machine
ScopeMismatch: You tried to access the function scoped fixture monkeypatch with a session scoped request object.
monkeypatch was requested by a fixture with a wider scope
use pytest.MonkeyPatch.context()

Mock what you own: the adapter and its tests

The renewal tests are fast and green, with a fake gateway and a mocked mailer. They show that charge_renewal does the right thing with the answers you gave it. They say nothing about the payment provider itself: its URL, its field names, what a declined card really looks like. Every test double carries your belief about the real thing. Which code should a stand-in replace, and what checks that it tells the truth?

STEP 01 / 05

THE MAP SO FAR

Fig 9.1The accent parts are new: the adapter, and the one line that leaves the process during a test.

The last part of your code is the adapter, PaymentGateway: the one class that speaks the payment provider’s HTTP API. It sits in your code beside the pricing module, and in production charge_renewal receives it through the gateway= parameter.

Its line down to the payment API is the only one on the map that leaves the process during a test run. Most tests never use that line, because a fake or a mock stands in for the adapter. Only the tests that carry the integration marker from chapter 05 follow it to the provider.

STEP 02 / 05

A DOUBLE OF SOMEONE ELSE’S API IS A GUESS

Fig 9.2The test’s reply beside what PayGate really sends. The accent row is a declined card: wrong status code, wrong body.

Version 1 of charge_renewal, the one from chapter 06 with its HTTP call inside, decided on one comparison: reply.json()["status"] != "success". Its test, below, patched the HTTP call and returned a reply built by hand. The author wrote that reply from memory: status 200 with "success" for a paid charge, and the same status code with "declined" for a refused one.

PayGate really answers "succeeded", and a declined card is HTTP 402 with the error code card_declined. The code and its test shared one wrong belief, so the tests were green. The first real renewal got the real word, failed the comparison and marked a paying customer as overdue.

PayGate is an invented vendor. Its answers are modelled on the way real card providers reply.

THE OLD TEST: A REPLY WRITTEN FROM MEMORY
def test_paid_renewal_stays_active(sub):
    reply = Mock(status_code=200)
    reply.json.return_value = {"id": "ch_9001", "status": "success"}    # written from memory

    with (
        patch("billing.renewals.httpx2.post", return_value=reply),
        patch("billing.renewals.smtplib"),
    ):
        charge_renewal(sub)

    assert sub.status == "active"         # green, and wrong about PayGate

# what PayGate really sends:
#   a paid charge      200   {"id": "ch_9001", "status": "succeeded"}
#   a declined card    402   {"error": {"code": "card_declined"}}
STEP 03 / 05

WRAP THE VENDOR IN ONE CLASS YOU OWN

Fig 9.3Follow 1 to 4 to PayGate and back. The accent box is the adapter: doubles replace it, and nothing past it.

PaymentGateway.charge(customer_id, amount_cents) returns a Charge or raises CardDeclined. Everything the package knows about PayGate lives in this one small class and the HTTP client it is given: the URL, the API key, the JSON field names and the meaning of a 402. The rest of the package, and every other test, sees only that method.

Now a double replaces your own interface, which changes only when you change it. That is the rule this chapter is named for: don’t mock what you don’t own. The pattern itself has a chapter in the design-patterns tutorial, the adapter chapter.

BILLING/GATEWAY.PY: THE ADAPTER
# billing/gateway.py
import httpx2


class PaymentGateway:
    def __init__(self, client: httpx2.Client):
        self._client = client                       # the HTTP client is passed in

    def charge(self, customer_id: str, amount_cents: int) -> Charge:
        reply = self._client.post(
            "/v1/charges", json={"customer": customer_id, "amount": amount_cents}
        )
        if reply.status_code == 402:                # PayGate: the card was refused
            raise CardDeclined(reply.json()["error"]["code"])
        reply.raise_for_status()                    # any other error status raises
        body = reply.json()
        return Charge(body["id"], body["status"], amount_cents)
STEP 04 / 05

TEST THE ADAPTER FOR REAL, AND THE FAKE WITH THE SAME TESTS

Fig 9.4One set of tests runs against two gateways. The accent box is the tests; only the right-hand path leaves the process.

The adapter takes its HTTP client as an argument, so its unit tests pass a client built on httpx2 2.16.2’s MockTransport(handler). The handler is a function that receives the request and returns a response. The adapter builds a real request and parses a real response, and no socket is opened. The first sample feeds it PayGate’s 402.

An integration test goes further and calls PayGate’s sandbox over the network. The fixture gateway has two values, fake and sandbox, so one set of tests runs against FakeGateway and against the real adapter. Tests run that way are contract tests: when the two runs disagree, the fake is wrong.

The sandbox half carries the integration marker that chapter 05 registered. The suite has 4 such tests, and pytest -m "not integration" leaves them out.

TESTS/TEST_GATEWAY.PY: THE ADAPTER, WITH NO SOCKET
# tests/test_gateway.py
import httpx2
import pytest

from billing.gateway import CardDeclined, PaymentGateway


def declined(request: httpx2.Request) -> httpx2.Response:
    assert request.url.path == "/v1/charges"
    return httpx2.Response(402, json={"error": {"code": "card_declined"}})


def test_a_402_becomes_card_declined():
    client = httpx2.Client(
        base_url="https://api.paygate.example",
        transport=httpx2.MockTransport(declined),      # no socket is opened
    )

    with pytest.raises(CardDeclined, match="card_declined"):
        PaymentGateway(client).charge("cus_77", amount_cents=6000)
ONE SET OF TESTS, TWO GATEWAYS
# tests/integration/test_gateway_contract.py
import pytest

from billing.gateway import CardDeclined
from tests.fakes import FakeGateway


@pytest.fixture(params=["fake", pytest.param("sandbox", marks=pytest.mark.integration)])
def gateway(request):
    if request.param == "fake":
        return FakeGateway(decline={"cus_declined"})
    return request.getfixturevalue("sandbox_gateway")    # the real adapter, PayGate sandbox


def test_charge_reports_the_amount(gateway):
    charge = gateway.charge("cus_77", amount_cents=6000)
    assert (charge.status, charge.amount_cents) == ("succeeded", 6000)


def test_declined_customer_raises(gateway):
    with pytest.raises(CardDeclined):
        gateway.charge("cus_declined", amount_cents=6000)
STEP 05 / 05

ASSERT ON WHAT HAPPENED, NOT ON HOW

Fig 9.5Compare the last row of each column. The accent column checks the result, so a rename doesn’t break it.

A test can check a declined renewal two ways: by the calls the code made, or by the state it left behind. The first way asserts on mocks: gateway.charge.assert_called_once_with(…), repo.mark_past_due.assert_called_once_with(…) and repo.add_invoice.assert_not_called(). Rename mark_past_due and that test fails, though the behaviour is the same.

The second way reads subscription sub_1042 back from the database and asserts that its status is past_due and that it has no invoices. It also asserts that no receipt was sent. For the mailer the call is the outcome, and that is the one case where a test should check a call.

THE DECLINED RENEWAL, CHECKED BY ITS RESULT
def test_declined_card_marks_the_subscription_past_due(repo, sub, mailer):
    gateway = FakeGateway(decline={"cus_77"})

    charge_renewal(sub, gateway=gateway, clock=fixed_clock, repo=repo, mailer=mailer)

    # checking calls: these break when a method is renamed, though nothing changed
    #   repo.mark_past_due.assert_called_once_with("sub_1042", retry_on=date(2026, 12, 4))
    #   repo.add_invoice.assert_not_called()

    # checking state: what a customer or a colleague could observe
    saved = repo.get_subscription("sub_1042")
    assert saved.status == "past_due"
    assert repo.invoices_for("sub_1042") == []
    mailer.send_receipt.assert_not_called()       # here the call itself is the outcome

COMMON QUESTIONS

Isn’t a fake more work than a mock?
Once, yes. One fake serves every test that needs a gateway, reads like ordinary code, and the contract tests keep it honest. A mock’s setup is repeated in every test, and each copy can go stale.
Can I record the real responses and replay them?
Yes. vcrpy, used through pytest-recording, records real HTTP once and replays it. It suits adapter tests. Recordings go stale like any double, so record them again on a schedule.
Should the database be mocked too?
No. Run the real engine: SQLite in tmp_path here, or the production database in a container (testcontainers) when your SQL depends on it. A mocked query result is another guess.

WHAT YOU NOW KNOW

  • A double of a third-party API encodes a guess: the old test’s reply said "success" where PayGate answers "succeeded".
  • PaymentGateway is the one class that speaks to the provider; doubles replace it, and nothing beyond it.
  • Contract tests run against both FakeGateway and the sandbox; other tests assert on state, such as the status past_due.
DEEP DIVE: where the rule comes from, the order of preference, when a mock is the right double, recorded HTTP, the real database in a container

Where the rule comes from

“Only Mock Types You Own” is section 4.1 of “Mock Roles, not Objects”, a 2004 paper by Freeman, Pryce, Mackinnon and Walnes. Its advice is to write “thin wrappers to implement the application abstractions in terms of the underlying infrastructure”. PaymentGateway is such a wrapper.

Hynek Schlawack’s 2022 article “‘Don’t Mock What You Don’t Own’ in 5 Minutes” restates the rule for Python: “there’s a difference between owning an object and owning the API to use it.” He calls it a heuristic, not a law.

The order of preference

“Software Engineering at Google”, chapter 13, puts the choices in an order. First: “A real implementation should be preferred over a test double”. Next: “A fake is often the ideal solution”. Stubbing comes after that, and interaction testing, which checks the calls, is to be “avoided when possible”.

In this tutorial’s terms the order has four rows: the real thing in a temporary place, a fake you own, an autospecced Mock at your own boundary, and a patch on a name. Each step down checks less of the real thing.

Best first. The accent row is the fake: the first choice when the real thing is too slow or can’t be used in a test.

When a mock is the right double

A mock fits three cases. The call is the effect, such as an email sent or an audit record written. You need an error you can’t cause for real, such as a timeout. Or the double stands at the far side of code you own, as the mocked mailer does.

The sources differ on how far to take it. The “mockist” style mocks every collaborator of the object under test. Google’s book says that style is hard to scale.

Recorded HTTP

vcrpy records real HTTP traffic into files it calls cassettes and replays them on later runs. Version 9.4 supports httpx2, and since 8.2.1 it reads cassettes with a safe loader. Filter the API key out of every recording before you commit it.

For httpx, the libraries respx and pytest-httpx patch the client. Neither has released support for httpx2, which is one more reason the adapter’s tests pass a transport in and patch nothing.

The real database in a container

When your SQL depends on the production engine, SQLite is the wrong stand-in. testcontainers 4.15 starts the production database in a container from a session-scoped fixture, so it starts once per run. Mark those tests too, so the default run stays fast.

ERRORS THIS CHAPTER EXPLAINS

green tests, and production failing with KeyError: 'status' or a wrong status
a double answered what the real API doesn’t
add the case to the contract tests
CardDeclined is never raised in production
the adapter maps a status the vendor doesn’t send
test the adapter with the vendor’s documented response through MockTransport

The whole suite: coverage, order and CI

The project now has 212 tests of three kinds (the counts are illustrative): 180 pure unit tests, 28 that use a SQLite file, and 4 that call the payment sandbox. Each passes when you run it alone. A suite raises questions that a single test doesn’t. Which code does no test touch? Do the tests pass in any order? How long does a developer wait for an answer? How do you know what the suite misses, and keep it fast and trustworthy?

STEP 01 / 04

THE MAP SO FAR

Fig 10.1The accent parts are new: three plugins inside pytest, and the CI runner outside your machine.

The last parts are three plugins inside pytest and one machine outside it. A plugin is a separately installed package that adds options or behaviour to pytest. Coverage records which lines of your code ran. Random order shuffles the test items. Parallel workers split the items over several processes.

The CI runner is a machine that runs the whole suite on every push, from a clean checkout. It reads the exit code of the run: zero passes the job, and any other code fails it.

STEP 02 / 04

COVERAGE SHOWS THE LINES NO TEST RAN

Fig 10.2One row per file, as pytest-cov prints it. The accent row’s missing lines handle a payment timeout.

pytest-cov 7.1.0 runs coverage.py 7.17.5 while your tests run, and prints a table when they finish: pytest --cov=billing --cov-branch --cov-report=term-missing. Each file gets a row: its statements, the statements no test ran, its branches, its partial branches, a percentage and the missing line numbers.

In this illustrative table renewals.py shows 89%, and its Missing column says 41-43, 46->48. Lines 41-43 handle a payment that times out, and no test makes one time out. Branch coverage, off by default and turned on by --cov-branch, adds 46->48: an if on line 46 that only ever went one way.

What the table can’t show is whether a test checked anything. A test that calls charge_renewal and asserts nothing covers those lines just the same.

THE COVERAGE TABLE (ILLUSTRATIVE NUMBERS)
$ pytest -m "not integration" --cov=billing --cov-branch --cov-report=term-missing
...
Name                      Stmts   Miss Branch BrPart  Cover   Missing
---------------------------------------------------------------------
src/billing/gateway.py       20      0      2      0   100%
src/billing/mailer.py         8      4      0      0    50%   9-12
src/billing/pricing.py       12      0      4      0   100%
src/billing/renewals.py      30      3      6      1    89%   41-43, 46->48
src/billing/repo.py          16      0      0      0   100%
---------------------------------------------------------------------
TOTAL                        86      7     12      1    92%
STEP 03 / 04

TESTS MUST PASS IN ANY ORDER, AND ALONE

Fig 10.3The same two tests in two orders. The accent order fails, because the reading test relied on the other one running first.

pytest runs tests in file order by default, so a test can come to depend on one that runs before it. The cause is shared state: a module-level cache left filled, an environment variable set without monkeypatch, a file left in the working directory. Here test_price_comes_from_the_cache passes only after another test has filled the price cache.

pytest-randomly 5.1.0 shuffles the order on every run and prints the seed in the header: Using --randomly-seed=1553614239. Passing that seed back repeats the order exactly, and --randomly-seed=last repeats the previous run. A test that passes and fails with no change to the code is a flaky test; with the seed, this one fails every time, so you can fix it.

Parallel runs need the same independence. pytest-xdist 3.8.0 with -n auto splits the tests over worker processes. Each worker is a separate process that collects the suite itself and builds its own fixtures, so even a session-scoped fixture runs once per worker.

A FAILURE THAT DEPENDS ON THE ORDER, AND THE SEED THAT REPEATS IT
$ pytest -m "not integration"
============================= test session starts ==============================
platform darwin -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
Using --randomly-seed=1553614239
...
FAILED tests/test_pricing.py::test_price_comes_from_the_cache - KeyError: 'team'
================= 1 failed, 207 passed, 4 deselected in 2.34s ==================

$ pytest -m "not integration" --randomly-seed=1553614239    # the same order again
STEP 04 / 04

RUN THE FAST TESTS ALWAYS AND THE SLOW ONES ON PURPOSE

Fig 10.4Three bars on one scale: seconds per kind of test. The accent bar is only 4 tests.

A few slow tests can take most of a suite’s run time. In this illustrative suite, 212 tests take 9.5 s. The 180 unit tests take 0.9 s, the 28 database tests 1.4 s, and the 4 integration tests 7.2 s, which is 76% of the time.

pytest -m "not integration" runs 208 tests in 2.3 s, fast enough to run on every save. CI runs that command on every push. On the main branch it also runs the integration tests, with the sandbox key in PAYGATE_API_KEY. --durations=5 lists the five slowest tests.

That shape has a name, the test pyramid: many small fast tests, and fewer tests that cross a real boundary.

THE FAST TESTS ON EVERY PUSH, THE INTEGRATION TESTS ON MAIN
# .github/workflows/tests.yml
name: tests
on: [push]

jobs:
  fast:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with: { python-version: "3.15" }
      - run: pip install -e . --group dev
      - run: pytest -m "not integration" --cov=billing --cov-branch

  integration:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with: { python-version: "3.15" }
      - run: pip install -e . --group dev
      - run: pytest -m integration
        env:
          PAYGATE_API_KEY: ${{ secrets.PAYGATE_SANDBOX_KEY }}

COMMON QUESTIONS

What coverage percentage should we require?
No number is right for every project. A falling number is a useful alarm; a required one invites empty tests. Review the missing lines in code that matters, such as what happens when a payment times out.
Should CI retry failing tests automatically?
Only as a stopgap with a ticket attached. A retry plugin turns a flaky test green and leaves its cause in place. Reproduce it with the seed and fix the shared state.
When is running in parallel worth it?
When the suite takes minutes. -n auto uses one worker per CPU core. Fix order dependence first: parallel runs make it show up more often, and harder to repeat.

WHAT YOU NOW KNOW

  • Coverage reports lines and branches no test ran, such as lines 41-43 of renewals.py; it can’t judge the asserts.
  • Tests must pass in any order: pytest-randomly shuffles them and prints the seed that repeats a failing order.
  • Run the 208 fast tests on every change and the 4 integration tests on purpose, in CI.
DEEP DIVE: how coverage counts, failing the build on coverage, how xdist divides the work, timeouts and reruns, sizes of test, checking the tests themselves

How coverage counts

coverage.py counts statements by default. It counts branches only with --cov-branch, or with branch = true in its own config. A branch that was never taken prints as two line numbers joined by an arrow, such as 46->48. The comment # pragma: no cover leaves a line out of the count.

On Python 3.14 and later, coverage.py measures through sys.monitoring by default, which makes measurement cheap. Ned Batchelder, its author, on what the number can’t say: “Just because your tests execute the code doesn’t mean they properly test the results.”

Failing the build on coverage

--cov-fail-under=90, or fail_under under [tool.coverage.report], fails a run whose total is below the number. With a total of 86 percent, pytest-cov prints FAIL Required test coverage of 90% not reached. Total coverage: 86.00% and the run exits with code 1, the code for failed tests. The illustrative table’s 92% would pass.

How xdist divides the work

Each worker collects the suite itself, and then the items are shared out. --dist load is the default. loadscope and loadfile keep a module’s tests together, and worksteal rebalances the work between workers.

A session-scoped fixture runs once per worker; the xdist docs show a file-lock pattern that runs it once in total. -s and --pdb don’t work under xdist. With psutil installed, -n auto counts physical cores; without it, logical ones.

Timeouts and reruns

pytest-timeout fails a test that hangs: --timeout=300 sets a limit of 300 seconds per test, and by default there is no limit. pytest-rerunfailures runs a failed test again, for example with --reruns 2. It is the stopgap from the questions above: the run turns green and the cause stays where it was.

Sizes of test

“Software Engineering at Google” sorts tests by what they may touch. Small tests run in one process, medium tests on one machine, and large tests anywhere. The test pyramid, from Mike Cohn in 2009, says the same with a shape: many small tests under a few broad ones.

Checking the tests themselves

Mutation testing changes the code, for example a < to a <=, and runs the suite again. A change that no test notices marks a weak assert, or a missing one. mutmut is one tool that does this for Python.

ERRORS THIS CHAPTER EXPLAINS

a test that fails only in the full run
it depends on what another test left behind
run with the printed seed, then bisect the tests that ran before it
FAIL Required test coverage of 90% not reached. Total coverage: 86.00%
the coverage threshold tripped
read the Missing column before writing tests to move the number
different results with -n auto
tests share files, ports or a database
give each test tmp_path and each worker its own resources

The whole picture

Here is every part from the ten chapters on one map, numbered to match the table below.

Find a number on the map, then its row below: what the part does, what it is attached to and what it checks.

ONE TEST, END TO END

Take the declined renewal. The config (4) sets the root, the collector (5) finds the test and lists it (6). The runner (7) sets up its fixtures (8, 9), with the database in tmp_path (11). The test passes a fake gateway (15) through the seam (14), the code marks the subscription overdue until 4 December, and the rewritten assert (2) checks that. The fixtures clean up, and the reporter (3) prints one dot.

  1. 1test function

    calls your code once and asserts on the result

    attached to
    a test file under tests/
    checks
    whatever its asserts compare
    when wrong
    a green run for a behaviour nobody asserted on
  2. 2assert rewriting

    makes a failing assert print the values on both sides

    attached to
    test files and conftest.py, at import
    checks
    nothing; it only adds detail to failures
    when wrong
    a bare AssertionError with no values, from a helper module
  3. 3reporter

    prints each result, the failure sections and the summary

    attached to
    the pytest process
    checks
    nothing; it reports what the runner found
    when wrong
    a failed CI job: any exit code other than zero
  4. 4config and rootdir

    fix the project root and the options for every run

    attached to
    the first config file found walking upward
    checks
    option names and value types, when strict
    when wrong
    options silently ignored: pytest read a different config file
  5. 5collector

    walks the test paths and picks tests by name

    attached to
    the rootdir and testpaths
    checks
    file, class and function names
    when wrong
    a new test that never runs: its name doesn’t match
  6. 6test items

    list every test to run, each with a node ID

    attached to
    the collector’s output
    checks
    nothing; they are the list
    when wrong
    “collected 0 items”, or fewer items than you wrote
  7. 7runner

    runs each test in three phases: setup, call, teardown

    attached to
    every test item
    checks
    nothing; it runs the phases in order
    when wrong
    ERROR for a broken fixture, FAILED for a broken test
  8. 8fixtures

    build what a test needs and clean it up afterwards

    attached to
    a test’s parameter names
    checks
    nothing; they prepare and tidy
    when wrong
    “fixture not found”, or state left behind by missing cleanup
  9. 9conftest.py

    shares fixtures with every test below its directory

    attached to
    a directory under tests/
    checks
    nothing; it only holds fixtures
    when wrong
    a fixture missing in one folder: its conftest is elsewhere
  10. 10fixture scope

    sets how often a fixture runs and how long it lives

    attached to
    each fixture
    checks
    that a wide fixture uses no narrower one
    when wrong
    tests that pass alone and fail together: shared state
  11. 11tmp_path

    gives each test its own empty directory

    attached to
    any test or fixture that names it
    checks
    nothing; it only creates the directory
    when wrong
    tests colliding on files written somewhere else
  12. 12parametrize

    turns one test function into one test per case

    attached to
    a test function, during collection
    checks
    nothing; it multiplies the test
    when wrong
    one failing case hiding the rest: a loop was used
  13. 13markers

    label tests so a run can select or skip them

    attached to
    tests, classes or single cases
    checks
    that names are registered, when strict
    when wrong
    a misspelled marker’s test running when it should not
  14. 14the seam

    lets the caller choose each dependency

    attached to
    the parameters of your function
    checks
    nothing; it is a place to pass things in
    when wrong
    a test that needs the network: nothing could be passed in
  15. 15fakes

    stand in for a dependency with a small working version

    attached to
    passed in through the seam
    checks
    nothing; they behave as the real thing should
    when wrong
    green tests and a production failure: the fake drifted
  16. 16Mock

    accepts any call, records it and returns scripted answers

    attached to
    passed in, or placed by patch
    checks
    call arguments, and signatures when autospecced
    when wrong
    a test that passes with a wrong call: no spec was given
  17. 17patch and monkeypatch

    point a name at a stand-in for one test

    attached to
    module attributes, environment variables, dict items
    checks
    that the patched name exists
    when wrong
    a mock never called, while the real function ran
  18. 18the adapter

    holds everything your code knows about the vendor’s API

    attached to
    between your code and the payment API
    checks
    the vendor’s status codes and field names
    when wrong
    a paid customer marked overdue: a response was misread
  19. 19integration and contract tests

    run the adapter and the fake against the same checks

    attached to
    the one line that leaves the process
    checks
    that the fake and the real API agree
    when wrong
    a failing contract test, before production finds the difference
  20. 20coverage

    records which lines and branches the tests ran

    attached to
    a plugin inside pytest
    checks
    nothing about quality; only what was executed
    when wrong
    missing line numbers for code no test reaches
  21. 21random order

    shuffles tests each run and prints the seed

    attached to
    a plugin, during collection
    checks
    nothing; it exposes order dependence
    when wrong
    a failure that appears with one seed and not another
  22. 22parallel workers

    split the tests across several processes

    attached to
    a plugin; each worker is a process
    checks
    nothing; they only divide the work
    when wrong
    failures only under -n: tests sharing files or ports
  23. 23CI runner

    runs the whole suite on every push

    attached to
    outside your machine, from a clean checkout
    checks
    the exit code of the run
    when wrong
    a red build for a change that passed on your laptop
  24. ·code under test

    does the work the tests exist for

    attached to
    imported by the tests
    checks
    your business rules
    when wrong
    a failing assert naming the wrong value
  25. ·real dependencies

    are what the code calls in production

    attached to
    outside the test process
    checks
    nothing in a test run
    when wrong
    real emails or charges sent by a test
  26. ·mocker

    offers patch as a fixture, undone automatically

    attached to
    tests that name it (pytest-mock)
    checks
    the same as patch
    when wrong
    the same symptoms as a patch on the wrong name

THREE THINGS TO KEEP

  • A test is a function that calls your code and checks the result. pytest finds it, runs it and reports.
  • Pass dependencies in as arguments. A test can then swap in a stand-in for anything it can’t control.
  • Put stand-ins only where your own code meets the outside. A wrong mock keeps tests green while production breaks.
Read next. FastAPI: how Uvicorn, Starlette and Pydantic fit together for testing a web API with TestClient and dependency overrides, the Adapter pattern and dependency injection in the design patterns series, and Async Python: how one thread checks 100 links for the code an AsyncMock stands in for.
$ pytest -m "not integration"
208 passed, 4 deselected in 2.30s