Skip to content

Lesson 2 of 9 · 24m

Fixtures as Test Architecture

Build small composable fixtures, choose scopes deliberately, and avoid fixture pyramids that hide the behavior being tested.

Fixtures are pytest's superpower and its most abused feature. Used well, they remove setup noise and make the test read like a specification. Used badly, they become a hidden object graph where changing one line breaks forty tests nobody understands.

A fixture is controlled setup, not a junk drawer

import pytest

@pytest.fixture
def user():
    return User(id=7, email="sam@example.test", role="member")

The test receives the constructed object and stays focused on behavior:

def test_display_name_falls_back_to_email(user):
    assert user.display_name == "sam@example.test"

A good fixture answers: "what minimum context does this behavior require?" A bad fixture answers: "what objects have I ever needed near this module?" Keep fixtures small enough to explain in one sentence.

Fixture scope controls reuse

Scopes are function (default), class, module, package, and session:

@pytest.fixture(scope="session")
def postgres_url():
    return "postgresql://postgres:postgres@127.0.0.1:5432/testdb"

Reuse expensive resources at wider scope only when they can be safely shared. A session-scoped database connection is fine if every test resets rows; a session-scoped mutable user object is a trap because one test's mutation becomes another test's input. If order changes behavior, scope is probably wrong.

Use factories for variation

When tests need many shapes of the same object, return a factory instead of one frozen instance:

@pytest.fixture
def make_order():
    def _make(total=100, currency="USD"):
        return Order(total=total, currency=currency)
    return _make

Then the test states its important inputs explicitly:

def test_rejects_negative_total(make_order):
    order = make_order(total=-5)
    assert order.is_valid() is False

This is the sweet spot: reusable construction, visible variation.

Composition beats inheritance

pytest fixtures can depend on other fixtures:

@pytest.fixture
def account(make_order):
    return Account(orders=[make_order(total=10)])

That dependency graph is powerful, but deep chains hide causality. If you need client -> app -> db -> migrations -> container, consider whether the test is still a unit test or should be declared an integration test with slower but clearer setup.

Field notes

  • Never put assertions in fixtures; a fixture failing at setup reports an error, not the behavioral failure you meant.
  • Use yield fixtures for cleanup so teardown runs even when the test fails.
  • Keep conftest.py shallow: shared fixtures yes, global test logic no.
  • Avoid autouse fixtures unless the effect is universal and obvious, like isolating environment variables.
  • Name fixtures after the capability they provide (make_order, db_session) rather than vague nouns (data, context).

Was this lesson helpful?

Sign in to rate