Sub topic 7
Building related objects
This chapter assumes you can write a basic factory function with defaults and keyword overrides, and that you know Python dataclasses. Real domain objects refer to each other: an order belongs to a customer. A factory has to build that customer too, without making each test do it by hand.
The problem with relationships
Without help, a test that needs an order must first build a user and then pass it in. Repeated across hundreds of tests, this brings back the noisy setup that factories were meant to remove. The test only cares about the order's status, so the customer should be an implementation detail.
One factory calls another
The order factory builds a default customer when the caller does not supply one.
from dataclasses import dataclass
from itertools import count
@dataclass
class User:
id: int
email: str
role: str
active: bool
@dataclass
class Order:
id: int
customer: User
total_cents: int
status: str
_user_ids = count(1)
_order_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_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})
order = make_order(status="shipped")
assert order.customer.email.endswith("@example.com")The test above never mentions a user. It still gets a valid one, with a unique id and email from the user factory's counter.
Sharing one related object
Sometimes the relationship is what the test is about, for example "an order history lists only this customer's orders". Create the customer once and pass it to each order.
alice = make_user(email="[email protected]")
first = make_order(customer=alice)
second = make_order(customer=alice, status="shipped")
assert first.customer is second.customerBoth orders now point to the same object. Each call without customer creates a separate user, so tests that need different customers get them for free.
Common errors
Three mistakes show up repeatedly with related objects.
- Default argument evaluated once. Writing
def make_order(customer=make_user())runsmake_user()when the function is defined. Every order then shares one customer, and tests affect each other. UseNoneas the default and create the object inside the function, as shown above. - Eager defaults. Putting
"customer": make_user()inside thedefaultsdictionary creates a user on every call, even when the caller passedcustomer. The extra user is wasted. It also advances the id counter, which makes ids harder to predict. Resolve the customer first, asmake_orderdoes. - Overriding the relationship through
overrides.make_order(customer=alice)works becausecustomeris a named parameter. If it were only in**overrides, the default user would still be built before the override replaced it.
Choosing what to build by default
A relationship that is required for the object to be valid should get a default. An optional relationship, such as an order's coupon, should default to None. Tests that care can pass one in. This keeps default objects small and makes each test's setup show what is actually involved.
Exercise
A teammate writes def make_order(customer=make_user(), **overrides). Two tests each call make_order() and each modify order.customer.active. Why can one test break the other, and how do you fix the signature?
Show answer
The default make_user() runs once, when the function is defined, so every order built without an explicit customer shares the same User object. A change made in one test is visible in the next. Fix it by using customer=None and calling make_user() inside the function when customer is None, so each call creates a fresh customer.