Sub topic 12
Organizing and maintaining factories
What this chapter assumes
This chapter assumes you have read the earlier chapters on defaults, overrides, sequences, relationships, and traits. You should be comfortable with a make_user style factory function and with pytest. The examples use Python, and the User and Order dataclasses from earlier chapters live in a module called shop.models.
A factory that works in one test file is easy to write. The harder part comes six months later, when the model has gained fields, three teams import your factories, and nobody remembers why a default is what it is. This chapter covers where factories live, how to name them, how to keep them valid as the model changes, and how to stop them from growing into a second application.
Where factories live
Start with one factories.py next to your tests. When it passes a few hundred lines, or when two people regularly edit it at once, split it into a package with one module per model.
shop/
models.py
tests/
factories/
__init__.py
users.py
orders.py
test_login.py
test_orders.pyEach module owns the factories for one model, plus that model's traits and its own counter. The __init__.py re-exports the public names, so tests import from one place and do not care how the files are split.
# tests/factories/users.py
from itertools import count
from shop.models import User
_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 make_admin(**overrides):
return make_user(**{"role": "admin", **overrides})# tests/factories/orders.py
from itertools import count
from shop.models import Order
from .users import make_user
_order_ids = count(1)
def make_order(customer=None, **overrides):
if customer is None:
customer = make_user()
defaults = {
"id": next(_order_ids),
"customer": customer,
"total_cents": 1000,
"status": "pending",
}
return Order(**{**defaults, **overrides})
def make_cancelled_order(**overrides):
return make_order(**{"status": "cancelled", **overrides})# tests/factories/__init__.py
from .orders import make_cancelled_order, make_order
from .users import make_admin, make_user
__all__ = ["make_admin", "make_cancelled_order", "make_order", "make_user"]A test file now needs a single line: from tests.factories import make_user, make_order. If your project does not treat tests as a package, adjust the import to match your test configuration.
Dependencies point one way
orders.py imports from users.py because an order needs a customer. users.py must never import from orders.py. If a user factory needs to know about orders, you end up with a circular import, and the fix is almost always to build the order in the test or in a scenario helper (described later).
Naming conventions
Consistent names let a reader predict what a call does without opening the factory. Pick a scheme once and write it down in the package docstring or the contributing guide.
| Pattern | Example | Meaning |
|---|---|---|
| `make_<model>` | `make_user` | Builds a valid object with defaults, in memory |
| `make_<trait>_<model>` | `make_admin`, `make_cancelled_order` | Applies one named variant, still accepts overrides |
| `create_<model>` | `create_user` | Persists the object, if you keep a separate persisting variant |
| `make_<model>_with_<thing>` | `make_order_with_items` | Builds the object plus a related collection |
The prefix tells the reader whether the call touches a database. The build-versus-persist chapter explains why that distinction matters, and a naming scheme is how you make it visible at the call site.
Keeping factories in step with the model
Factories are code that your tests depend on, so they need their own safety checks. Two properties make this cheap.
First, passing an unknown keyword to a dataclass fails immediately. A typo in an override does not silently produce a test that checks nothing.
import pytest
from tests.factories import make_user
def test_misspelled_override_fails_loudly():
with pytest.raises(TypeError):
make_user(actve=False)Because the factory merges overrides into a dictionary and passes them to the model constructor, the constructor does the checking. If your factory copies overrides onto an object with setattr, you lose this protection. Prefer the constructor form.
Second, write one smoke test that builds every public factory. When someone adds a required field to User and forgets the factory, this test fails with a clear message instead of fifty unrelated tests failing in confusing ways.
import pytest
from tests.factories import (
make_admin,
make_cancelled_order,
make_order,
make_user,
)
@pytest.mark.parametrize(
"factory",
[make_user, make_admin, make_order, make_cancelled_order],
)
def test_factory_builds_an_object(factory):
first = factory()
second = factory()
assert first.id != second.idThe assertion on id also catches a counter that was accidentally replaced with a constant. Add each new factory and trait to the list when you write it. If the model validates itself, for example in __post_init__, the smoke test checks validity for free, because construction would raise.
Changing a default
Changing a default is the most common maintenance task and the most likely to break distant tests. Work through it in this order:
- Change the default in the factory.
- Run the full suite.
- For each test that fails, ask whether it relied on the old default without saying so.
- Fix the test by passing the value it needs as an override, so the dependency is now visible.
A failure in step 3 is useful information. The test had a hidden dependency, which is exactly what overrides exist to expose. If forty tests fail, do not revert the factory. Check whether those tests share a setup helper that should pass the value explicitly.
Adding a new field with a valid default is safe. Renaming a field is not, because every make_user(old_name=...) call now raises TypeError. That is the desired behavior, and a project-wide search for the old keyword finds every call site.
Counters and shared state
The counters in these modules are module-level state. They keep growing for the whole test session, so the id a test gets depends on how many objects earlier tests made. Two consequences follow:
- Never assert on a specific generated id or email, such as
assert user.id == 1. Assert on values you passed in, or compare against the object you built. - If a test needs a known id, pass it:
make_user(id=42).
If you run tests in parallel across processes, each process has its own counters, so ids can repeat across processes. That is harmless for in-memory objects. For persisted objects with a shared database, use unique values that include the worker name, or give each worker its own database.
Scenarios belong outside factories
Factories grow when people add one more trait for one more test. After a year you may see make_order(with_items=True, shipped=True, paid=True, customer_is_admin=True). Each flag interacts with the others, and the factory becomes hard to reason about.
Keep factories small: one model, defaults, traits that change that model's own fields. Put multi-object setups in a separate module, often called scenarios.py, built by composing factories.
# tests/scenarios.py
from tests.factories import make_order, make_user
def make_shipped_order_for_new_customer(**order_overrides):
customer = make_user()
return make_order(
customer=customer,
**{"status": "shipped", **order_overrides},
)A scenario is allowed to be specific, because its name says what it builds. A factory should stay generic. If a scenario is used by only one test file, leave it in that file.
Routine maintenance
Treat the factories package as production-quality test infrastructure:
- Delete traits no test uses. Search for each trait name before a release, and remove the ones with no callers.
- Write a one-line docstring on any default that is not obvious, such as why
total_centsis1000or why a status must be a particular string. - Review factory changes as carefully as model changes. A small edit to a default can change the meaning of hundreds of tests.
- Keep defaults boring. A default that is valid, ordinary, and unlikely to trigger special behavior is better than one that is realistic but unusual. For example, avoid a default
total_centsnear a discount threshold. - When a library such as factory_boy takes over, keep the same module layout and naming. The organization advice above applies equally to
UserFactoryclasses.
Exercise
Your make_order factory is in orders.py, and a teammate wants make_user to accept with_orders=3 so a user comes with three orders. Why is this a problem for the module layout, and where should the behavior go instead?
Show answer
users.py would need to import make_order from orders.py, which already imports make_user from users.py. That creates a circular import and reverses the one-way dependency from orders to users. Put the behavior in a scenario helper, such as make_user_with_orders(count) in scenarios.py. It creates the user with make_user(), then calls make_order(customer=user) the requested number of times.
Exercise
You add a required phone field to User, and 60 tests fail with TypeError: missing 1 required positional argument: 'phone'. What is the smallest change that fixes them, and what check would have caught this in one failure instead of sixty?
Show answer
Add a valid default for phone to the defaults dictionary in make_user, for example one derived from the counter so it stays unique if the model requires that. The smoke test that builds every public factory (test_factory_builds_an_object) would have failed once, on the factory itself, with a message pointing at the missing field.
Exercise
A test asserts assert make_user().id == 1. It passes when run alone and fails in the full suite. Why, and how should the test be rewritten?
Show answer
The id comes from a module-level counter shared by the whole test session. Earlier tests already advanced it, so the value depends on test order. Pass the value the test needs: user = make_user(id=1) and then assert user.id == 1, or better, drop the assertion if the specific id does not matter to what the test is checking.