Sub topic 2
Static fixtures versus factories
This chapter assumes you can write pytest tests, read a Python dataclass, and know what a setup step or fixture is. It compares two ways to supply test data and shows where each one fits.
What a static fixture is
A static fixture is a fixed piece of test data defined once and reused. In pytest it is usually a function marked with @pytest.fixture that returns a ready-made object.
import pytest
from dataclasses import dataclass
@dataclass
class User:
id: int
email: str
role: str
active: bool
@pytest.fixture
def user():
return User(id=1, email="[email protected]", role="member", active=True)
def test_member_has_member_role(user):
assert user.role == "member"
def test_inactive_user_flag(user):
user.active = False
assert user.active is FalseThis works well at first. The data is easy to read and every test sees the same values. The costs show up as the suite grows.
Where static fixtures break down
- Hidden dependencies. A test that uses the
userfixture depends on values defined elsewhere. To see whytest_member_has_member_rolepasses, you must open the fixture. - Variants multiply. You need an inactive user, an admin, and an admin with no email. Each becomes another fixture, or the test mutates the shared one, as
test_inactive_user_flagdoes. Mutation is safe only while the fixture is rebuilt for every test. Widen its scope tomoduleorsessionand one test's change leaks into the next. - Fixed unique values. Every test gets
id=1and the same email. If the code under test enforces uniqueness, or you need two users, you must write a second fixture with different values. - Wide change surface. Adding a required field to
Usermeans editing every fixture and every inline copy of the setup.
What a factory changes
A factory is a function that builds a new object on each call. It supplies valid defaults and accepts overrides, so the test states only the values it cares about.
from itertools import count
_user_ids = count(1)
def make_user(**overrides):
n = next(_user_ids)
defaults = {
"id": n,
"email": f"user{n}@example.com",
"role": "member",
"active": True,
}
return User(**{**defaults, **overrides})
def can_log_in(user):
return user.active
def test_inactive_user_cannot_log_in():
user = make_user(active=False)
assert can_log_in(user) is False
def test_two_users_have_different_emails():
first = make_user()
second = make_user()
assert first.email != second.emailThe next chapter builds this function step by step. For now, compare it with the fixture:
make_user(active=False)puts the one relevant difference in the test body.- Each call returns a new object, so no test can disturb another.
- The counter gives each user a unique id and email.
- Adding a required field means changing one default in one place.
Choosing between them
| Concern | Static fixture | Factory |
|---|---|---|
| Reading the test | Must open the fixture to see values | Differences appear in the test |
| Variants | One fixture per variant | One call with overrides |
| Unique values | Fixed unless duplicated | Generated per call |
| Isolation | Depends on scope and no mutation | New object each call |
| Good for | Large, read-only reference data | Objects that vary between tests |
A common mistake when switching
Teams sometimes keep the fixture and call the factory inside it with no overrides. That gives you a tidy fixture, but every test still depends on hidden values. Call the factory inside the test, and pass only the fields that test depends on.
Exercise
A module-scoped fixture returns one User. One test sets user.active = False, and a later test that expects an active user now fails. Name the cause, and explain how a factory avoids it.
Show answer
The fixture is shared across tests, so the first test's mutation changes the object the later test receives. A factory builds a new object on each call, so make_user(active=False) affects only that test, and a plain make_user() elsewhere still returns an active user.