Sub topic 2
Static fixtures versus factories
This chapter compares two ways to supply test data: fixed fixtures and factories. It assumes you can write and run pytest tests and use Python dataclasses. It also assumes you know what a setup step is. The previous chapter covered why test data becomes a problem. This one looks at the two main answers and when each fits.
What "static fixture" means here
The word "fixture" covers two different things, so this chapter separates them.
- A fixture mechanism is a framework feature that runs setup code before a test. pytest's
@pytest.fixtureis one. - A static fixture is a piece of test data with hard-coded values. It might be a constant, a JSON file, a database dump, or a fixture function that always returns the same object.
A static fixture can be built with a fixture mechanism, but the two are not the same. The comparison in this chapter is about the data: do you write out each object by hand, or do you generate it from a function that knows the defaults?
The static fixture approach
Here is a typical static setup. A module defines one User and every test uses it.
from dataclasses import dataclass
@dataclass
class User:
id: int
email: str
role: str
active: bool
DEFAULT_USER = User(id=1, email="[email protected]", role="member", active=True)
def deactivate(user):
user.active = False
def test_deactivate_marks_user_inactive():
deactivate(DEFAULT_USER)
assert DEFAULT_USER.active is False
def test_default_user_is_active():
assert DEFAULT_USER.active is TrueRun in file order, both tests pass. Run test_default_user_is_active after the first test, for example with pytest -p no:randomly after reordering, or with a random-order plugin, and it fails. The first test mutated an object that both tests share. The failure appears in a test that did nothing wrong, and it depends on execution order.
A function-scoped pytest fixture avoids this particular bug because it builds a new object for each test:
import pytest
@pytest.fixture
def user():
return User(id=1, email="[email protected]", role="member", active=True)That solves the shared-state problem. The fixture still has the other weaknesses of static data, covered next.
Where static fixtures break down
Variants multiply
Suppose tests need an active member, an inactive member, an admin, and an inactive admin. You write four fixtures:
@pytest.fixture
def active_user():
return User(id=1, email="[email protected]", role="member", active=True)
@pytest.fixture
def inactive_user():
return User(id=2, email="[email protected]", role="member", active=False)
@pytest.fixture
def admin_user():
return User(id=3, email="[email protected]", role="admin", active=True)
@pytest.fixture
def inactive_admin_user():
return User(id=4, email="[email protected]", role="admin", active=False)Each new field or value that matters doubles the possible combinations. The names also hide what differs. To learn what makes inactive_user inactive, you have to open the fixture and compare it to its neighbors.
Values collide
Every fixture has a hand-picked id and email. If a test needs two active users, it cannot use active_user twice. Both objects would have the same id and email. If the system under test enforces unique emails, the test fails for a reason unrelated to its purpose. You end up inventing yet another fixture, such as second_active_user.
The test hides its own intent
A test that depends on one field should make that field visible. With a static fixture, the field is somewhere else:
def test_inactive_user_cannot_log_in(inactive_user):
assert can_log_in(inactive_user) is FalseA reader must trust the fixture's name and open it to confirm which attribute it sets. When someone later edits inactive_user for another test, this test can change meaning without any change to its own text.
One edit breaks many tests
If you add a required field to User, you update every hand-written constructor call. A fixture file with thirty objects needs thirty edits. If a fixture is shared across modules, a change to satisfy one test can break assertions in a distant one.
The factory approach
A test data factory is a function that returns a valid object with sensible defaults. Callers override only what they care about. This is the factory from the spine for this tutorial:
from dataclasses import dataclass
from itertools import count
@dataclass
class User:
id: int
email: str
role: str
active: bool
_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})The four fixtures above collapse into direct calls:
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_active_user_can_log_in():
user = make_user()
assert can_log_in(user) is TrueThe line make_user(active=False) is the only difference between the two tests, and it is visible in the test body. An inactive admin is make_user(active=False, role="admin"). No new fixture is needed. Two users in one test get different ids and emails because the counter advances on each call. Adding a field to User means editing one function.
The later chapters on defaults, overrides, and sequences explain each of these pieces. Here you only need to see that the factory moves the shared knowledge (what a valid user looks like) into one place and leaves the per-test knowledge in the test.
Side-by-side comparison
| Concern | Static fixtures | Factories |
|---|---|---|
| Where values live | Spread across many named fixtures | Defaults in one function, differences in each test |
| Adding a variant | New fixture and new name | New keyword argument at the call site |
| Several objects of one kind | Needs a fixture per object | Call the factory again |
| Unique ids and emails | Hand-picked, collision-prone | Generated by a counter |
| Reading a test | Open the fixture to see the data | Differences visible in the test |
| Adding a required field | Edit every literal | Edit the factory |
| Upfront cost | Very low | A small function to write and maintain |
| Exact, known data | Natural fit | Possible by overriding every field |
Combining both: a fixture that returns a factory
Factories and the pytest fixture mechanism work together. You can register the factory itself, or an object built by it, as a fixture:
import pytest
@pytest.fixture
def user():
return make_user()
def test_new_user_has_member_role(user):
assert user.role == "member"The fixture mechanism gives you pytest's dependency injection and scoping. The factory gives you the data. A fixture like this builds a fresh object per test, and the test can still call make_user(...) directly when it needs an override.
Keep the fixture thin. If you find yourself adding admin_user, inactive_user, and inactive_admin_user fixtures again, you have rebuilt the static fixture problem on top of a factory. Call the factory with overrides in the test instead.
When static data is the right choice
Factories are not always better. Prefer static data in these cases:
- Reference data that the system reads but never changes, such as a list of country codes or tax rates. A shared constant or file is accurate and costs nothing.
- Golden files. If you compare output to a stored expected result, the input and the expected output must both be exact and reviewable as a pair.
- Captured real-world payloads. A saved API response from a third party documents what that service actually sends. Generating similar data could hide a mismatch.
- Large, realistic datasets for performance or integration tests, where building each row through a factory would be slow or would not reproduce real distributions.
- Regression cases. A bug triggered by one specific input is best pinned by that exact input, written literally in the test.
A useful rule: if the test is about the exact value, write the value in the test. If the test is about a property of the object and the other fields only need to be valid, use a factory.
Common mistakes when switching
- Making the factory defaults too clever. Defaults should describe an ordinary, valid object. Unusual defaults surprise readers and make tests depend on hidden behavior.
- Keeping the old fixtures "just in case". Two sources of truth drift apart. Migrate a test file at a time and delete the fixtures you replace.
- Overriding everything. If every call passes six keyword arguments, the factory is not saving you anything, and the test probably needs exact data. Write the literal object instead.
- Asserting on a default. If a test checks
user.role == "member"only because the factory defaults to that, it will break when the default changes. Set the value explicitly in tests that depend on it.
Exercise
A test file has the fixtures active_user, inactive_user, and admin_user. A new test needs two active users with different emails. Why is this awkward with static fixtures, and what does the factory version look like?
Show answer
Each static fixture returns one fixed object, so requesting active_user twice gives the same object (or two objects with the same email). You would have to add a new fixture such as second_active_user with a different email. With the factory, call it twice: first = make_user() and second = make_user(). The counter gives each user a different id and email, so no new fixture is needed.
Exercise
A module-level constant DEFAULT_USER is used by many tests. One test calls deactivate(DEFAULT_USER). Describe the failure this can cause and name two ways to remove it.
Show answer
Later tests that expect DEFAULT_USER.active to be true fail, but only when they run after the mutating test, so the failure depends on test order. One fix is a function-scoped pytest fixture that builds a new User for each test. Another is to call a factory such as make_user() inside each test, which returns a new object every time.
Exercise
Which of these is better served by a static fixture than by a factory? (a) A user who is inactive. (b) A saved JSON response from a payment provider's API, used to test your parser. (c) Three orders for the same customer.
Show answer
(b). The test is about the exact shape the provider sends, so the real payload should be stored literally. (a) and (c) are variants and related objects, which factories handle with make_user(active=False) and make_order(customer=alice).