Sub topic 11
Using a Factory Library
This chapter assumes you can write Python tests, use dataclasses, and have read the earlier chapters on defaults, overrides, sequences, relationships, traits, and determinism. Hand-written factories work well. A library such as factory_boy gives you the same ideas in a declarative form, so you write less plumbing.
What a library gives you
Each idea you built by hand has a named equivalent in factory_boy.
| Hand-written idea | factory_boy feature |
|---|---|
| Counter for unique ids | `factory.Sequence` |
| Field computed from other fields | `factory.LazyAttribute` |
| Wrapper such as `make_admin` | `factory.Trait` |
| Calling another factory for a relationship | `factory.SubFactory` |
Install it with pip install factory_boy. The package imports as factory.
The same factories, declared
The examples reuse the User and Order dataclasses from earlier chapters.
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)
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)
customer = factory.SubFactory(UserFactory)
total_cents = 1000
status = "pending"
admin = UserFactory(admin=True)
order = OrderFactory(customer__email="[email protected]")
print(admin)
print(order)Plain values such as role = "member" are constant defaults. Meta.model tells the factory which class to construct. Calling the factory passes the resolved fields to that class as keyword arguments.
How each feature behaves
Sequence calls your function with an integer that increases on every call. Two users never share an id, which is the same job the count iterator did before.
LazyAttribute receives the object being built, so the email can depend on the id. It runs after the other fields are resolved. Use it when one field is derived from another.
Trait lives under Params. Its name becomes a boolean argument. UserFactory(admin=True) applies role="admin", and UserFactory() leaves the defaults alone. A trait is not passed to the model, so User never sees an admin argument.
SubFactory builds the related object for you. Double underscores reach into it: customer__email="[email protected]" overrides the email of the customer that OrderFactory creates. To share one customer across orders, pass the object itself with customer=alice.
alice = UserFactory(email="[email protected]")
first = OrderFactory(customer=alice)
second = OrderFactory(customer=alice, status="shipped")
assert first.customer is second.customerBuild versus create
factory.Factory builds plain Python objects in memory. For a database-backed model, you use a subclass such as DjangoModelFactory or SQLAlchemyModelFactory. These offer two strategies. UserFactory.build() makes an unsaved object, and UserFactory.create() saves it. Prefer build() when the test does not need the database, because it is faster.
Determinism
factory_boy uses Faker for fields such as factory.Faker("name"). Seed it so failures reproduce.
import factory.random
factory.random.reseed_random(12345)Call this once per test session, and print the seed when a run fails.
Common mistakes
- Using
LazyAttributewhere a constant would do. Keep it for derived values. - Forgetting that
Sequencenumbers are global to the factory. Do not assert on a specific id. - Putting a
TraitoutsideParams, where it is treated as an ordinary field. - Creating deep
SubFactorychains that save many rows for a test that needs one.
Exercise
Using the factories above, write one call that creates an admin user, and a second call that creates a pending order whose customer is that admin.
Show answer
admin = UserFactory(admin=True) and order = OrderFactory(customer=admin). You could also write OrderFactory(customer__admin=True), which passes the trait through the SubFactory and builds a new admin customer.