Sub topic 11
Using a factory library
This chapter assumes you can write a hand-rolled factory function, as in the earlier chapters on defaults, overrides, sequences, relationships, and traits. It also assumes you have used pytest or a similar runner. The examples use Python and the factory_boy library, which you can install with pip install factory_boy.
Why move from functions to a library
A hand-written make_user works well for a few small types. As the suite grows, you repeat the same mechanics in every factory: a counter for unique ids, a dictionary merge for overrides, a wrapper function for each trait, and glue code for related objects. A factory library packages those mechanics as declarations, so each factory states what the object looks like and the library decides how to build it.
A library also gives you things that are tedious to write yourself:
- Lazy fields that are computed from other fields after overrides are applied.
- Dotted override syntax for related objects, such as
customer__email. - A switch between building in memory and persisting, without changing the factory.
- Integration with fake-data generators and a shared random seed.
The cost is another dependency and some library-specific vocabulary. For a project with two or three simple types, a plain function is still a reasonable choice.
The same factories, declared
Here is the earlier make_user and make_order rewritten with factory_boy. The code is self-contained and runs as shown.
from dataclasses import dataclass
import factory
@dataclass
class User:
id: int
email: str
role: str
active: bool
@dataclass
class Order:
id: int
customer: User
total_cents: int
status: str
class UserFactory(factory.Factory):
class Meta:
model = User
id = factory.Sequence(lambda n: n + 1)
email = factory.LazyAttribute(lambda obj: f"user{obj.id}@example.com")
role = "member"
active = True
class Params:
admin = factory.Trait(role="admin")
class OrderFactory(factory.Factory):
class Meta:
model = Order
id = factory.Sequence(lambda n: n + 1)
customer = factory.SubFactory(UserFactory)
total_cents = 1000
status = "pending"
admin = UserFactory(admin=True)
order = OrderFactory(customer__email="[email protected]", status="shipped")
print(admin)
print(order)Meta.model names the class the factory produces. Calling UserFactory(...) collects the declarations, applies your keyword arguments, and calls User(**fields). A plain value such as role = "member" is a static default. Everything else uses a declaration class, covered next.
The declarations you will use most
| Declaration | What it does | Hand-rolled equivalent |
|---|---|---|
| `Sequence(fn)` | Calls `fn(n)` with a counter that increases on each call | `next(_user_ids)` |
| `LazyAttribute(fn)` | Computes a value from the partly built object, after overrides | A line after the merge, using other fields |
| `LazyFunction(fn)` | Calls `fn()` for each object, with no arguments | A call inside the defaults dictionary |
| `SubFactory(F)` | Builds a related object with another factory | `customer = make_user()` |
| `SelfAttribute("field")` | Copies another field of the same object | Reusing a local variable |
| `Trait(...)` | Applies a named set of overrides when its flag is true | `make_admin` wrapper |
| `Faker("name")` | Draws a realistic fake value | `random` plus string formatting |
Sequences
Sequence starts at 0 by default. The n + 1 above keeps ids starting at 1, to match the earlier hand-rolled version. The counter belongs to the factory class and is not reset between tests. Do not write assertions that depend on a specific id. If you really need a fresh start, call UserFactory.reset_sequence(), but treat that as a smell.
Lazy attributes
A plain default cannot read other fields. LazyAttribute can, and it runs after overrides are applied. If a test passes id=99, the email becomes [email protected] without extra work. If a test passes email="[email protected]", the lambda never runs for that field.
Traits
A Trait is declared inside Params. The name (admin) is a boolean flag you pass to the factory, not a field on the model. The model never receives an admin argument, so a dataclass without that field works. Explicit overrides win over the trait, so UserFactory(admin=True, role="auditor") produces role auditor.
Relationships and dotted overrides
SubFactory builds the related object each time the parent is built. The double underscore reaches into it: customer__email="[email protected]" is passed to UserFactory as email=.... To share one customer across several orders, build it once and pass the object, which replaces the sub-factory call:
alice = UserFactory(email="[email protected]")
first = OrderFactory(customer=alice)
second = OrderFactory(customer=alice, status="shipped")
assert first.customer is second.customerHow a call is resolved
The order of steps explains most surprises. Overrides take priority over declarations, and lazy declarations see the final values.
Build versus create
Every factory exposes both strategies:
in_memory = OrderFactory.build()
saved = OrderFactory.create()With the base factory.Factory, both just call the class constructor, so they behave the same. The difference appears with database-aware base classes: DjangoModelFactory calls the manager's create, and SQLAlchemyModelFactory adds the object to a session you configure in Meta. Related objects follow the strategy of the parent. OrderFactory.build() also builds the customer in memory, and OrderFactory.create() saves both.
Calling the factory directly, as in UserFactory(), means create. On a database-backed factory, that writes rows. If a test does not need the database, use .build() explicitly so the cost is visible and the test stays fast.
Fake data and determinism
factory.Faker draws realistic values from the Faker library, which installs with factory_boy. It makes names, emails, and addresses look plausible, which helps when you read failing output or demo data. It also introduces randomness, so seed it.
import factory
class SeededUserFactory(UserFactory):
email = factory.Faker("email")
class SeededOrderFactory(OrderFactory):
customer = factory.SubFactory(SeededUserFactory)
total_cents = factory.Faker("pyint", min_value=100, max_value=50_000)
SEED = 12345
factory.random.reseed_random(SEED)
order = SeededOrderFactory()
print(f"seed={SEED} total={order.total_cents} email={order.customer.email}")factory.random.reseed_random(seed) resets the random state used by Faker and by the fuzzy helpers in factory.fuzzy. Running this script twice gives the same totals and emails. Subclassing UserFactory here reuses its model, sequence, and traits and replaces only the fields that change.
In a test suite, reseed in a fixture that runs before each test, and print or log the seed when a test fails. That keeps the earlier rule intact: a failure must be reproducible. Do not reseed with the clock and then forget to record the value.
import random
import factory
import pytest
@pytest.fixture(autouse=True)
def seed_factories():
seed = random.SystemRandom().randrange(1_000_000)
factory.random.reseed_random(seed)
print(f"factory seed={seed}")
yieldpytest shows captured output for failed tests, so the seed appears exactly when you need it. To replay, hardcode the seed temporarily.
Common gotchas
- Shared mutable defaults.
tags = []as a static default gives every object the same list. Usefactory.LazyFunction(list). - Evaluation at import time.
created_at = datetime.now()runs once, when the module loads. Usefactory.LazyFunction(datetime.now)instead. - Faker randomness without a seed. A test that passes 99 times in 100 usually has an unseeded random value behind it.
- Sequence assumptions. Do not hardcode
id == 1in assertions. Another test, or another factory subclass sharing the counter, may have used it. - Unknown override names. A typo like
UserFactory(rolle="admin")is passed to the model constructor. A dataclass raisesTypeError, but some ORMs silently ignore unknown arguments, so check what your model does. - Hidden database writes. Switching a factory to a model base class can turn every
Factory()call into an insert. Review test runtime after you do.
Choosing between a library and your own functions
Use a library when you have many model types, relationships that must follow build or create strategies, or a need for realistic fake data. It also helps when a team wants one shared way to declare factories. Stay with plain functions when you have few types, no database, and a team that does not know the library. In both cases the design rules are the same: valid defaults, overrides for what the test cares about, unique values, and reproducible randomness.
Exercise
Using the UserFactory and OrderFactory from this chapter, add a cancelled trait to OrderFactory. Then write the call that builds, in memory, a cancelled order for an admin customer whose email is "[email protected]". Which parts of the call set the role and the email?
Show answer
Inside OrderFactory, add class Params: containing cancelled = factory.Trait(status="cancelled"). The call is OrderFactory.build(cancelled=True, customer__admin=True, customer__email="[email protected]"). The customer__admin=True argument passes the admin trait flag to UserFactory, which sets the role to "admin". The customer__email argument overrides the email on that same customer. Using .build() keeps both objects in memory.
Exercise
A test uses OrderFactory(total_cents=factory.Faker("pyint"))-style random totals, and it fails once in a while on CI. What two steps make the failure reproducible?
Show answer
First, seed the random state before each test with factory.random.reseed_random(seed), choosing the seed in a fixture. Second, print or log that seed so a failed run shows it. To replay the failure, set the same seed value by hand and rerun the test.