Sub topic 7
Building related objects
This chapter assumes you can write Python tests with a runner such as pytest. It also assumes you have read the earlier chapters on factory functions, defaults, overrides, and unique values. The examples reuse User, make_user, and the counter-based ids from those chapters.
Why relationships complicate factories
Real objects point at other objects. An order has a customer, an invoice has line items, and a comment has an author and a post. A test for a single order still needs a valid customer, or the order is not valid.
Without help, every test has to build the whole chain by hand:
- Create the user.
- Pass the user to the order.
- Repeat for every other dependency.
That is the copy-pasted setup factories are meant to remove. The rule for this chapter is that a factory should build the objects it depends on, and the test should only mention a related object when it cares about it.
One factory calling another
Start with an Order that holds a User. 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
_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})
@dataclass
class Order:
id: int
customer: User
total_cents: int
status: str
_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})A test that only cares about the order status can now ignore the customer:
def test_new_order_is_pending():
order = make_order()
assert order.status == "pending"
assert order.customer.active is Truemake_order() calls make_user(), so the customer gets a unique id and email from the user sequence. Two calls to make_order() produce two orders with two different customers.
Sharing one related object
Sometimes the relationship is the thing under test. A customer's lifetime spend depends on several orders belonging to the same person. Build the customer once and pass it to each order.
def total_spent(orders):
return sum(o.total_cents for o in orders if o.status != "cancelled")
def test_total_spent_ignores_cancelled_orders():
alice = make_user(email="[email protected]")
orders = [
make_order(customer=alice, total_cents=2500),
make_order(customer=alice, total_cents=1500, status="shipped"),
make_order(customer=alice, total_cents=9900, status="cancelled"),
]
assert all(o.customer is alice for o in orders)
assert total_spent(orders) == 4000Every order points at the same User object. The test names alice because the shared customer matters here. It does not set ids or other fields, because nothing depends on them.
For many children of the same parent, a small helper keeps the test short:
def make_orders_for(customer, how_many, **overrides):
return [make_order(customer=customer, **overrides) for _ in range(how_many)]Overriding a nested field
Sometimes a test needs a specific value on a related object but does not need to hold a reference to it. With plain functions, build the related object and pass it in:
order = make_order(customer=make_user(email="[email protected]"))That is readable for one level. At three or four levels of nesting it gets noisy, which is one reason libraries offer a shorthand. The last section shows factoryboy's `customer_email="[email protected]"` form.
The flow of a call differs depending on whether the caller supplies the related object:
Pitfalls with default related objects
Do not build the default in the signature
It is tempting to write the default directly in the function signature:
def make_order_buggy(customer=make_user(), **overrides):
...Python evaluates default argument values once, when the function is defined. Every call that omits customer would receive the same User object. Tests would silently share a customer, and a test that mutates it would affect the others. This is why the factory above uses customer=None and builds the user inside the function body.
Be careful when None is a legitimate value
If None can mean "no customer" (for example a guest checkout), customer=None cannot also mean "build a default". Use a sentinel object that no caller would pass by accident:
_UNSET = object()
def make_guest_capable_order(customer=_UNSET, **overrides):
if customer is _UNSET:
customer = make_user()
return make_order(customer=customer, **overrides)Now make_guest_capable_order() builds a customer, while make_guest_capable_order(customer=None) really passes None. Note that the call to make_order passes a non-None customer in the default case. For the explicit None case you would need make_order to accept None too, so decide on one convention across your factories and apply it everywhere.
Hidden objects hide cost
Each default related object is extra work. A factory that builds an order, which builds a customer, which builds a company, which builds an address, creates four objects for a test that wanted one. In memory this is cheap. Once objects are persisted to a database, it slows the suite and fills tables with rows no one asked for. The next chapter covers building versus persisting. For now, keep the default chain short and include a related object only when the parent is invalid without it.
Keep relationships consistent
When two related objects both carry the same fact, defaults must agree. If an order stores customer_id as well as customer, the factory must derive one from the other instead of generating both independently. Otherwise you get an order whose customer_id does not match its customer. Derive the dependent field from the related object after it exists.
@dataclass
class Shipment:
id: int
order: Order
recipient_email: str
_shipment_ids = count(1)
def make_shipment(order=None, **overrides):
if order is None:
order = make_order()
defaults = {
"id": next(_shipment_ids),
"order": order,
"recipient_email": order.customer.email,
}
return Shipment(**{**defaults, **overrides})Here recipient_email defaults to the customer's email, so a shipment built from make_order(customer=alice) is addressed to Alice without extra code. A caller can still override the recipient when a test needs a different one.
Choosing how to supply a relationship
| Test situation | What to write | Why |
|---|---|---|
| The related object does not matter | `make_order()` | The default customer keeps the order valid. |
| One detail of the related object matters | `make_order(customer=make_user(active=False))` | The test shows only the field that drives the outcome. |
| Several objects must share a parent | Build `alice`, pass `customer=alice` to each | Identity is the point, so name it. |
| The relationship is optional | Pass `None` with a sentinel-aware factory | Distinguishes "none" from "use the default". |
The same idea in factory_boy
The factory_boy library expresses relationships with SubFactory. It also lets callers reach into the related object's fields with a double underscore.
import factory
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 OrderFactory(factory.Factory):
class Meta:
model = Order
id = factory.Sequence(lambda n: n)
customer = factory.SubFactory(UserFactory)
total_cents = 1000
status = "pending"
order = OrderFactory(customer__email="[email protected]")
alice = UserFactory(email="[email protected]")
shared = [OrderFactory(customer=alice) for _ in range(3)]customer__email is passed through to UserFactory, so the default customer is built with that email. Passing customer=alice replaces the sub-factory entirely, which is the sharing pattern from earlier. The behavior matches the hand-written version, and it avoids the default-argument bug because the sub-factory runs on each call.
Summary of practices
- Have a factory build any required related object when the caller does not supply one.
- Use
Noneor a sentinel as the default marker, never a pre-built object in the signature. - Pass one object to several factories when the test is about the shared relationship.
- Derive fields that duplicate related data from the related object.
- Keep the default chain as short as validity allows.
- Make defaults flow in one direction to avoid recursion.
Exercise
A teammate writes def make_comment(author=make_user(), body="hi"): return Comment(author=author, body=body). Two tests each call make_comment() and one of them sets comment.author.active = False. The other test then fails unexpectedly. What is the cause, and how do you fix the factory?
Show answer
The default make_user() runs once, when the function is defined, so every call without an author shares the same User object. The first test mutates that shared user, which affects the second. Fix it by using author=None and building the user inside the function body: if author is None: author = make_user(). Each call then gets a fresh user.
Exercise
Using the make_user and make_order functions from this chapter, write a test that creates two orders for one customer, one with total 3000 and one with total 2000, and asserts the sum of their totals is 5000 and that both orders share the same customer.
Show answer
def testtwoordersshareacustomer(): alice = makeuser(email="[email protected]") first = makeorder(customer=alice, totalcents=3000) second = makeorder(customer=alice, totalcents=2000) assert first.customer is second.customer assert first.totalcents + second.totalcents == 5000