Sub topic 12
Organizing and maintaining factories
This chapter assumes you can write pytest tests and that you have built the make_user, make_order, and trait functions from the earlier chapters. Once a project has a dozen models, factories need a home and some upkeep, or they become the next mess to maintain.
Give factories one home
Put all factories in one package that tests import from. Without this, each test file grows its own private make_user, and you are back to copy-pasted setup.
tests/
factories/
__init__.py
users.py
orders.py
test_login.py
test_orders.pyUse one module per domain area. Re-export the public functions from __init__.py, so tests import from a single place and you can move code between modules without touching any test.
# tests/factories/__init__.py
from .orders import make_cancelled_order, make_order
from .users import make_admin, make_user
__all__ = ["make_user", "make_admin", "make_order", "make_cancelled_order"]This arrangement is the main maintenance benefit. When User gains a required field, you add a default in one factory and every test keeps working.
Keep each factory small and predictable
A few conventions keep a growing set of factories readable:
- Name factories
make_<thing>for plain builders andmake_<trait>_<thing>for traits, such asmake_cancelled_order. - Give every factory the same signature shape: optional related objects first, then
**overrides. - Keep defaults minimal. Set a field only if the model needs it to be valid.
- Keep logic out of factories. A factory that sends emails or calls a service is hiding behavior from the test.
- Build traits on the base factory, never by copying its defaults, so a change to the base reaches every variant.
Share counters and handle cleanup
Sequence counters such as _user_ids live at module level. That works because ids only need to be unique, not predictable. If a test asserts on a specific id, set the id explicitly with an override instead of relying on the counter. Otherwise the test breaks whenever another test runs first.
For persisted factories, keep cleanup out of the factories. Put it in a pytest fixture, or run each test in a rolled-back transaction. Factories create data, and fixtures own its lifetime.
# tests/conftest.py
import pytest
from tests.factories import make_user
@pytest.fixture
def user():
return make_user()Add a fixture like this only when many tests need the same object. A test that needs a special user should call make_user(...) itself, so its setup stays visible.
Test the factories themselves
Factories are code, and a broken default fails many tests at once with confusing errors. A small test file catches this early. It checks that every factory runs with no arguments and that repeated calls give unique ids.
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_with_no_arguments(factory):
first = factory()
second = factory()
assert first.id != second.id
def test_traits_apply_their_overrides():
assert make_admin().role == "admin"
assert make_cancelled_order().status == "cancelled"Add each new factory to the parametrized list. If the model later validates its fields, such as requiring a well-formed email, extend this test to check them.
Maintain factories over time
- Change defaults in one place. If a new rule makes
role="member"invalid, fix the factory and leave the tests alone. - Delete unused traits. A trait that no test calls is dead code that still has to track model changes.
- Promote repeated overrides. If five tests pass
status="shipped", addmake_shipped_order. If only one test needs it, leave the override inline. - Watch the diff size. A model change that forces edits in many test files means some tests build objects by hand instead of using the factories.
Exercise
A new required field country is added to User. Where should you change the code, and why does this show the value of keeping factories in one package?
Show answer
Add a default for country (for example "US") in make_user in the users module. Every test that builds users through the factories, including make_admin and make_order through its default customer, picks up the new field with no edits. Tests that need a specific country override it explicitly.