Sub topic 3
Your first test data factory
This chapter builds a small test data factory in Python and uses it in two tests. It assumes you can write and run tests with a runner such as pytest. It also assumes you know what a dataclass is and what a test fixture or setup step does. Later chapters cover defaults, overrides, sequences, relationships and traits in depth. This chapter gives you the core mechanism that those chapters extend.
The problem a factory solves
Suppose you test a login rule: inactive users cannot log in. Each test needs a User, and the User has four fields. Written inline, the setup looks like this:
from dataclasses import dataclass
@dataclass
class User:
id: int
email: str
role: str
active: bool
def can_log_in(user):
return user.active
def test_inactive_user_cannot_log_in():
user = User(id=1, email="[email protected]", role="member", active=False)
assert can_log_in(user) is False
def test_active_user_can_log_in():
user = User(id=2, email="[email protected]", role="member", active=True)
assert can_log_in(user) is TrueTwo things are wrong here, and both get worse as the suite grows.
- Every test repeats all four fields. If you add a required field such as
created_at, you must edit every test that builds aUser. - A reader cannot tell which field matters. Only
activediffers between the tests, but the reader has to compare the lines to see that.
A shared module-level fixture fixes the first problem and creates a new one. Tests then depend on values defined far away, and a change made for one test can break another.
What a test data factory is
A test data factory is a function (or class) that returns a valid object. It supplies a default for every field. The caller passes only the values the test cares about.
The factory holds the knowledge of how to build a valid object. A test states only how its object differs from an ordinary one.
Writing the factory
Here is a first version that does the job:
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 function has four parts.
**overridescollects any keyword arguments the caller passes into a dictionary. A call with no arguments gives an empty dictionary._user_idsis a counter created once at import time. Each call tonext(_user_ids)returns a new number, so every user gets a differentidandemail. The chapter on sequences covers this in detail.defaultsholds one valid value for every field ofUser.{**defaults, **overrides}builds a new dictionary. When both dictionaries have the same key, the later one wins, so the caller's values replace the defaults.User(**...)then passes that dictionary to the constructor as keyword arguments.
Calling it shows the behavior:
print(make_user())
print(make_user(role="admin"))The first call prints a User with id=1, email='[email protected]', role='member' and active=True. The second prints id=2, email='[email protected]', role='admin' and active=True. The counter has moved on, and only role changed.
Using it in tests
Now rewrite the two tests from the start of the chapter:
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 first test reads as "an ordinary user, except inactive." The second needs no arguments, because the defaults already describe an active member. Nothing in either test mentions id or email, because the rule under test does not depend on them.
If you later add a required field to User, you add one default to make_user. Neither test changes.
Why the factory returns a new object each time
Each call builds a fresh User. That matters because tests share a process. If a factory returned one shared object, a test that modified it (for example by setting user.active = False) would change the object that later tests receive. Those tests would then pass or fail depending on the order in which they run.
With a factory, each test owns its data. You can mutate it freely and no other test sees the change.
Fixtures and factories together
A factory does not replace your test runner's fixture mechanism. The two do different jobs. A fixture controls when setup and teardown happen. A factory controls what the data looks like. They combine well. In pytest, a fixture can return the factory function itself, so tests can request one object or ten:
import pytest
@pytest.fixture
def user_factory():
return make_user
def test_two_users_have_different_emails(user_factory):
first = user_factory()
second = user_factory()
assert first.email != second.emailFor a pure function like this one you do not need the fixture. You can import make_user directly. The fixture wrapper becomes useful when the factory needs a database session or other resource that the fixture provides.
Common errors
A misspelled override
make_user(activ=False)This raises a TypeError that says User.__init__() got an unexpected keyword argument 'activ'. This is useful behavior. Because the factory passes every key through to the constructor, a typo fails loudly instead of being silently ignored. Do not add code that filters unknown keys, because that would hide this protection.
Defaults that are invalid together
Each default must be valid by itself, and the set of defaults must be valid together. If User had a rule that admins must have a verified email, a default role of "member" is fine. The problem appears when a test overrides role="admin" and the unverified default email now produces an invalid object. Check that common single-field overrides still give a valid object, or handle the dependency in the factory.
Mutable defaults shared between calls
Suppose User had a tags list field. This factory has a bug:
_SHARED_DEFAULTS = {"role": "member", "tags": []}
def make_user_with_tags(**overrides):
return {**_SHARED_DEFAULTS, **overrides}
a = make_user_with_tags()
b = make_user_with_tags()
a["tags"].append("beta")
print(b["tags"])This prints ['beta']. Both results point to the same list, so a change through a is visible through b. The fix is to create the dictionary inside the function, as make_user does. The defaults are then rebuilt, including any lists, on every call.
Hidden coupling to default values
Suppose a test asserts user.email == "[email protected]". It passes when run alone and fails when another test runs first, because the counter has moved on. If a test needs a specific value, pass it explicitly:
user = make_user(email="[email protected]")
assert user.email == "[email protected]"The rule is that a test may depend only on values it set itself or on facts the factory guarantees, such as "the user is active." It must not depend on the exact generated values.
Where the factory should live
For now, keep the factory in a plain module that tests import, for example tests/factories.py. Keep it out of your application code, so that production code never imports test helpers. Chapter 12 covers how to organize factories as a suite grows.
Checking your understanding
A quick checklist for a first factory:
| Question | Expected answer |
|---|---|
| Can you call it with no arguments? | Yes, and the result is valid. |
| Does each call return a new object? | Yes. |
| Do two calls produce different ids and emails? | Yes, because of the counter. |
| Does an override replace only that field? | Yes. |
| Does a misspelled field name fail? | Yes, with a `TypeError`. |
Exercise
A teammate writes make_user so that defaults is a dictionary defined once at module level, and the dictionary contains "email": "[email protected]". Two tests each call make_user() and one of them also saves the user to a table that requires unique emails. What goes wrong, and how do you fix it?
Show answer
Every call returns a user with the same email, so the second save violates the uniqueness rule, and the failure depends on which tests run together. Generate the email inside the function from a counter, as in f"user{n}@example.com" with n = next(_user_ids). Also build the defaults dictionary inside the function so mutable values are not shared between calls.
Exercise
Write a factory make_product(**overrides) for Product(id: int, name: str, price_cents: int) with a unique id per call, a default name of "Widget" and a default price of 500. Then write a test that checks make_product(price_cents=0).price_cents == 0.
Show answer
from dataclasses import dataclass from itertools import count @dataclass class Product: id: int name: str pricecents: int productids = count(1) def makeproduct(overrides): defaults = { "id": next(productids), "name": "Widget", "price_cents": 500, } return Product({defaults, overrides}) def testpricecanbeoverridden(): assert makeproduct(pricecents=0).price_cents == 0