Sub topic 3
Your first test data factory
This chapter builds a small factory function in Python. It assumes you can write and run tests with a test runner such as pytest, that you know dataclasses, and that you know what a fixture or setup step is.
What a factory is
A test data factory is a function that returns a valid object. It fills every field with a sensible default, and the caller replaces only the fields that matter. Each test then shows just the values it depends on.
Without a factory, every test repeats the full constructor call:
user = User(id=1, email="[email protected]", role="member", active=False)When User gains a required field, every one of those calls breaks. A factory keeps the full list of fields in one place.
The starting point
Here is the object under test. It is a dataclass with four fields.
from dataclasses import dataclass
from itertools import count
@dataclass
class User:
id: int
email: str
role: str
active: boolThe factory supplies defaults and accepts keyword arguments that replace them.
_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})Three parts of this function do the work:
count(1)is an iterator that yields 1, 2, 3, and so on. Each call tonextgives a new number, so every user gets a distinctidandemail.defaultsdescribes a valid, ordinary user: an active member.{**defaults, **overrides}merges the two dictionaries. When a key appears in both, the later one wins, so the caller's value replaces the default.
Using it in tests
Each test overrides only the field it depends on.
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 TrueReading the first test, you see active=False and nothing else. That one value is the difference the test is about. The id, email, and role are irrelevant here, so they do not appear.
Why defaults must be valid
The default object should pass any validation your real code applies. If the defaults were invalid, every test would have to override fields just to get a usable object, and the overrides would no longer signal intent. A reader could not tell which overrides matter and which only repair the object.
Common errors
- Hard-coded unique values. Giving every user the email
[email protected]breaks as soon as a test creates two users and the code requires unique emails. Use the counter. - Typos in override names.
make_user(actvie=False)raises aTypeErrorfrom the dataclass, which is the behavior you want. Without that check, a typo would silently change nothing. - A shared module-level counter that tests rely on. Do not assert that an id equals 1. The counter keeps running across tests, so the number depends on test order. Assert on values you set explicitly.
- Mutable defaults. If a default is a list or dict, build it inside the function. Then each call gets a new object and tests cannot affect one another.
Exercise
Add a display_name field to User and to make_user. What must you change in your existing tests, and why?
Show answer
Add display_name: str to the dataclass and a default such as f"User {n}" to defaults in make_user. No existing test needs to change, because none of them passes display_name and the factory now supplies it. This is the main benefit of a factory: a new required field is added in one place, instead of in every test that builds a User.