Lesson 50 of 59Testing
pytest in Depth
Go beyond the basics with fixture scopes, conftest layering, advanced parametrize, mocking done right, async tests, coverage, Hypothesis and a fast suite.
You can already write a test, use a fixture, and call your API with TestClient. That gets you a test suite. Keeping it useful as the codebase grows is a different skill. Suites rot in predictable ways: setup copied into 200 files, mocks so detailed that every refactor breaks 40 tests, a run that takes eleven minutes so nobody runs it locally, a test that fails one time in twenty. This lesson covers the pytest features and habits that prevent each of those.
Fixture scopes
By default a fixture is created fresh for every test that asks for it. That is the safe choice, but some setup is expensive: starting a database container, creating every table, loading a large file. The scope argument controls how long one fixture value lives.
function scope: every test gets a fresh value, so no test can leak state into another. Use this unless you have a reason not to.
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from app.models import Base
@pytest.fixture(scope="session")
def engine():
engine = create_engine("postgresql+psycopg://test:test@localhost:5433/test")
Base.metadata.create_all(engine) # once per run
yield engine
Base.metadata.drop_all(engine)
engine.dispose()
@pytest.fixture
def db(engine):
connection = engine.connect()
transaction = connection.begin()
session = Session(bind=connection, join_transaction_mode="create_savepoint")
yield session # the test runs here
session.close()
transaction.rollback() # undo everything the test did
connection.close()Each test sees an empty database, but creating the tables happened once. join_transaction_mode="create_savepoint" makes a session.commit() inside your app code commit only to a savepoint, so the outer rollback still erases it.
There is one rule: a fixture can only use fixtures with the same or a longer scope. A session fixture that asks for a function fixture fails with ScopeMismatch, because the session value would outlive the thing it depends on.
seeded_db asks for the default-scoped fixture tmp_path. What happens?autouse=True applies a fixture to every test in its scope without anyone asking for it. Use it sparingly, for things every test truly needs, like clearing app.dependency_overrides or blocking real network calls. Invisible setup is hard to debug.
conftest.py layering
pytest loads every conftest.py from the root of your tests down to the folder of the test being run. Fixtures in a deeper conftest.py are only visible to tests in that folder and can override a fixture with the same name from above.
tests/
conftest.py # engine, db, client: shared by everything
unit/
conftest.py # overrides `db` with an in-memory fake: no database at all
test_pricing.py
api/
conftest.py # `as_admin`, `as_user` login fixtures
test_orders.pyThis keeps unit tests free of database setup while API tests get the real thing, without either folder knowing about the other. Run pytest --fixtures to list every fixture available at a given path, with its docstring.
Parametrize, further
You know @pytest.mark.parametrize with a list of rows. Four more tricks make it much more useful:
import pytest
from app.services.shipping import shipping_cost
@pytest.mark.parametrize(
("weight_kg", "expected"),
[
pytest.param(0.5, 4.99, id="small"),
pytest.param(5, 9.99, id="medium"),
pytest.param(30, 24.99, id="heavy"),
pytest.param(-1, None, id="negative", marks=pytest.mark.xfail(raises=ValueError)),
],
)
def test_cost_by_weight(weight_kg, expected):
assert shipping_cost(weight_kg) == expected
@pytest.mark.parametrize("country", ["DE", "FR", "US"])
@pytest.mark.parametrize("express", [True, False])
def test_cost_is_positive(country, express):
assert shipping_cost(1, country=country, express=express) > 0pytest.param(..., id="small")gives each case a readable name in the report, instead oftest_cost_by_weight[0.5-4.99].marks=attaches a mark to one case, likexfailfor a known bug orskipfor a platform.- Stacking two
parametrizedecorators runs every combination. - Parametrized fixtures (
@pytest.fixture(params=["sqlite", "postgres"]), readingrequest.paraminside) run every test that uses the fixture once per value. That is how you run one suite against two backends.
How many tests does test_cost_is_positive above produce?
@pytest.mark.parametrize("country", ["DE", "FR", "US"])
@pytest.mark.parametrize("express", [True, False])
def test_cost_is_positive(country, express): ...Built-in fixtures worth knowing
Match each built-in fixture to its job.
caplog deserves a mention because logging is often the only visible effect of an error path: assert "payment failed" in caplog.text, or check caplog.records for level and fields.
Mocking with unittest.mock
monkeypatch.setattr replaces things. unittest.mock gives you the replacement objects, and they record how they were used. The tools you will reach for most:
patch("module.name")replaces a name for the duration of awithblock or decorated test.side_effectmakes a mock raise an exception, or return a different value on each call.create_autospec(SomeClass, instance=True)builds a mock that has the same methods and signatures as the real class, so calling it wrong fails just like real code would.AsyncMockfor anything that is awaited.
Press Run (⌘ Enter) to see what happens.The retry logic is tested without a real payment provider or real timeouts, and the autospec catches a call that a plain Mock would have happily accepted.
Patch where the name is looked up
The most common mocking bug: patching the place a function is defined instead of the place it is used. If app/orders.py does from app.billing import charge_card, then orders has its own reference called charge_card. Patching app.billing.charge_card changes the billing module, but orders still holds the original.
from unittest.mock import patch
from app.orders import place_order
def test_place_order_charges_card():
with patch("app.orders.charge_card", return_value="r-1") as charge: # where it is used
place_order(user_id=1, total=500)
charge.assert_called_once_with(1, 500)app/notify.py has from app.email import send_email and calls it. In a test of app.notify, which patch actually replaces the call?When not to mock
Mocks are a trade: speed and control in exchange for realism. Over-mocked suites test how the code is written instead of what it does, and break on every refactor while missing real bugs.
- Mock at the boundaries you do not control: payment providers, email, third-party HTTP APIs, the clock, randomness.
- Do not mock your own code's internals. If testing a service means patching three of its private helpers, test through its public function instead.
- Prefer a fake or the real thing when it is cheap. A test database in a rolled-back transaction catches SQL bugs that a mocked repository never will. An in-memory fake mailer is simpler to read than a mock with five assertions.
- Wrap what you do not own. Put a third-party SDK behind a small class of your own and mock or fake that, so your tests do not depend on the SDK's internals.
Testing async code
pytest itself does not run coroutines. Two plugins add that:
- pytest-asyncio: mark tests with
@pytest.mark.asyncio, or setasyncio_mode = "auto"in config so everyasync deftest runs on an event loop. - anyio's plugin, which FastAPI's own documentation uses: mark tests with
@pytest.mark.anyio.
import pytest
from httpx import ASGITransport, AsyncClient
from app.main import app
@pytest.mark.anyio
async def test_list_orders():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
response = await client.get("/orders")
assert response.status_code == 200Use async tests when the code under test is async and you need to await it directly, for example an async repository or a service that calls asyncio.gather. For plain route tests, the synchronous TestClient works fine even when your routes are async def.
Factories as fixtures
Data factories from the testing lesson become more powerful as fixtures, because they can use other fixtures, like the database session:
@pytest.fixture
def make_order(db, make_user):
def _make_order(*, user=None, total=1000, status="paid"):
order = Order(user=user or make_user(), total=total, status=status)
db.add(order)
db.flush() # assigns an id without committing
return order
return _make_order
def test_refund_only_paid_orders(make_order):
pending = make_order(status="pending")
with pytest.raises(RefundError):
refund(pending)The fixture returns a function, so one test can create as many orders as it needs, each with only the fields that matter overridden. Libraries like polyfactory and factory_boy generate the defaults for you.
Coverage that means something
pytest-cov measures which lines ran. Two settings make the number more honest:
[tool.coverage.run]
branch = true # count both sides of every if, not just lines
source = ["app"]
[tool.coverage.report]
show_missing = true
fail_under = 85 # CI fails if coverage drops below thisBranch coverage catches the if whose else path never ran, which line coverage reports as fully covered. Use the missing-lines report to find untested error paths, and remember that coverage only tells you code ran, never that a test checked its result.
Property-based testing with Hypothesis
Example-based tests check the cases you thought of. Property-based testing states a rule that must hold for all inputs, then generates hundreds of inputs looking for one that breaks it. When it finds one, it shrinks it to the smallest failing example.
from hypothesis import given, strategies as st
from app.rle import decode, encode
@given(st.text())
def test_decode_reverses_encode(text):
assert decode(encode(text)) == textGood properties are round trips (decode of encode returns the input), invariants (sorting keeps the same length and items), and agreement with a slower but obviously correct version. Here is the idea, including shrinking, with only the standard library:
Press Run (⌘ Enter) to see what happens.The random failing string is long and messy; the shrunk one, ten as, points straight at the bug. Hypothesis does this far more cleverly and remembers failing examples between runs.
Organisation and fast tests
A suite that runs in seconds gets run constantly. One that takes ten minutes gets skipped. Habits that keep it fast and tidy:
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "--strict-markers"
markers = ["slow: talks to real services or takes over a second"]uv run pytest --lf # rerun only the tests that failed last timeuv run pytest -m "not slow" # skip slow tests while you iterateuv run pytest --durations=10 # list the ten slowest testsuv add --dev pytest-xdistuv run pytest -n auto # run tests in parallel on every CPU core- Register your markers. With
--strict-markers, a typo like@pytest.mark.slwois an error instead of a silently ignored mark. - Never
time.sleepin tests. Inject the clock, or use a library like time-machine to freeze it. - Keep tests independent. Parallel runs with xdist expose tests that depend on each other's leftovers; that is a bug in the tests, not in xdist.
- Fix flaky tests immediately. A test that fails randomly teaches everyone to ignore red builds.
- fixture scope
- How long one fixture value lives: function (default), class, module, package or session.
- conftest.py
- A file of fixtures pytest loads automatically for tests in its folder and below.
- autospec
- A mock built from a real class or function, so calls with the wrong signature fail.
- side_effect
- A mock setting that raises an exception or returns a different value on each call.
- branch coverage
- Coverage that checks both outcomes of each condition ran, not just each line.
- property-based testing
- Testing a rule against many generated inputs and shrinking any failure to the smallest example.
- flaky test
- A test that sometimes passes and sometimes fails without any code change.