Sub topic 8
Traits for named variants
This chapter assumes you can write pytest tests, you know Python dataclasses, and you have read the earlier chapters on defaults, overrides, unique values, and relationships. It builds on the make_user and make_order factories from those chapters.
The problem traits solve
Overrides work well for one-off differences. Suppose a test needs a cancelled order:
order = make_order(status="cancelled")This is readable the first time. Now suppose twenty tests need cancelled orders. Each one repeats the string "cancelled". If the status value is renamed to "canceled", you edit twenty places. Worse, some variants need more than one field. An administrator might need role="admin" and also a particular flag. The knowledge of what makes an admin is then spread across the test suite.
A trait is a named, reusable set of overrides that describes one variant of an object. The name carries the meaning (admin, cancelled), and the factory owns the field values behind it. Tests ask for the variant by name.
The setup used in this chapter
The examples below share one set of definitions. This block is complete and runs as shown.
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})A trait as a thin wrapper
In plain Python, the simplest trait is a function that calls the base factory with a fixed set of overrides.
def make_admin(**overrides):
return make_user(**{"role": "admin", **overrides})
def make_cancelled_order(**overrides):
return make_order(**{"status": "cancelled", **overrides})The wrapper does not copy the base factory's logic. It still gets unique ids, unique emails, and every other default from make_user and make_order. It only changes the fields that define the variant.
Using it in a test reads like a sentence:
def can_delete_any_post(user):
return user.role == "admin" and user.active
def test_admin_can_delete_any_post():
admin = make_admin()
assert can_delete_any_post(admin) is TrueCompare this with make_user(role="admin"). Both work. The trait version hides the field name, so a test reader sees the concept (an admin) instead of the mechanism (a string in a column).
Order of precedence
Look closely at how the wrapper merges its dictionaries:
{"role": "admin", **overrides}In a dictionary literal, later keys win. The trait's values come first, and the caller's overrides come after them. So a caller can still replace anything the trait set. Combined with the base factory's {**defaults, **overrides}, the full order is:
- Base defaults are applied first.
- The trait's values replace defaults.
- The caller's explicit keyword arguments replace everything else.
This lets you describe an inactive admin without a new trait:
def test_inactive_admin_cannot_delete_posts():
admin = make_admin(active=False)
assert can_delete_any_post(admin) is FalseThe test names the variant (make_admin) and then states the one extra difference that matters (active=False). The reader sees both.
If you reversed the merge, as in {**overrides, "role": "admin"}, the trait would silently win over the caller. A call such as make_admin(role="member") would still return an admin. That is a hard bug to spot, so keep the caller last.
Traits that touch several fields
Traits earn their keep when a variant means more than one field. Imagine that a "high-value order" must have a large total and start in a review status. Without a trait, every test repeats both values and must remember that they go together.
def make_high_value_order(**overrides):
return make_order(**{
"total_cents": 500_000,
"status": "needs_review",
**overrides,
})
def test_high_value_order_needs_review():
order = make_high_value_order()
assert order.total_cents >= 100_000
assert order.status == "needs_review"If the business rule changes, you change the trait in one place. All tests that ask for a high-value order follow along.
Passing related objects through a trait
Traits do not interfere with relationships. Because make_cancelled_order forwards its keyword arguments to make_order, a customer keyword reaches the customer parameter of the base factory.
alice = make_user(email="[email protected]")
cancelled = make_cancelled_order(customer=alice)
other = make_order(customer=alice)
assert cancelled.customer is other.customer
assert cancelled.status == "cancelled"Combining traits
Sometimes a test needs two variants at once, such as an admin who is also suspended. You have two simple options.
The first is to nest wrappers or use an override, as shown with make_admin(active=False). This is enough when one variant is a named concept and the other is a single field.
The second is to store each trait as a dictionary and merge several of them with one helper:
ADMIN = {"role": "admin"}
SUSPENDED = {"active": False}
def make_user_with(*traits, **overrides):
merged = {}
for trait in traits:
merged.update(trait)
merged.update(overrides)
return make_user(**merged)
user = make_user_with(ADMIN, SUSPENDED)
assert user.role == "admin"
assert user.active is FalseIf two traits set the same field, the later trait in the argument list wins. Traits that overlap are a sign that they are not independent variants. Prefer traits that each control different fields, so the order never matters.
Traits in factory_boy
Libraries support traits directly. In factory_boy, you declare them in an inner Params class, and each one becomes a boolean argument you can pass when you call the factory.
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 Params:
admin = factory.Trait(role="admin")
suspended = factory.Trait(active=False)
admin = UserFactory(admin=True)
suspended_admin = UserFactory(admin=True, suspended=True)
custom = UserFactory(admin=True, email="[email protected]")
assert admin.role == "admin"
assert suspended_admin.active is False
assert custom.email == "[email protected]"Two things are worth noting. First, the trait names live in Params, so they are not passed to User as constructor arguments. Without that, User(admin=True) would raise a TypeError. Second, explicit keyword arguments, such as email="[email protected]", still override trait values, which matches the precedence of the hand-written version.
The two traits here touch different fields (role and active), so combining them is unambiguous.
When to write a trait
Not every difference deserves a name. Use this table as a guide.
| Situation | Better choice |
|---|---|
| One field differs, and the value is the point of the test | Inline override: `make_user(active=False)` |
| The same override appears in many tests | Trait |
| The variant sets several fields that must stay consistent | Trait |
| The variant has a domain name that your team uses (admin, cancelled) | Trait |
| A one-off value no other test shares | Inline override |
Failure modes
- Trait explosion. Creating a function for every combination (
make_inactive_admin_with_big_order) leads to dozens of helpers that nobody can find. Keep traits small and independent, then combine them or add an override. - Traits that drift from reality. A trait's field values can become invalid when the model changes, for example if
"cancelled"is no longer a legal status. Because the trait is in one place, the fix is also in one place, but you still need a test or validation that would catch it. - Traits that encode test-specific assumptions. A trait named
make_user_for_checkout_testties the factory to one test file. Name traits after domain concepts instead. - Reversed precedence. As covered above, putting caller overrides before trait values makes the trait win. Check the merge order in every wrapper.
Exercise
Write a trait function make_shipped_order(**overrides) that returns an order with status "shipped". Then write a call that creates a shipped order with a total of 2500 cents for an existing customer named alice. Finally, say what make_shipped_order(status="pending").status returns with your implementation.
Show answer
Implementation: def make_shipped_order(**overrides): return make_order(**{"status": "shipped", **overrides}). The call is make_shipped_order(customer=alice, total_cents=2500). The last expression returns "pending", because the caller's overrides come after the trait values in the merged dictionary, so the caller wins.
Exercise
A teammate writes def make_admin(**overrides): return make_user(**{**overrides, "role": "admin"}). What goes wrong, and how do you fix it?
Show answer
The trait's "role" key is placed after the caller's overrides, so it always wins. A call like make_admin(role="member") still returns an admin, and the caller cannot override the trait. Fix it by putting the trait first: make_user(**{"role": "admin", **overrides}).
Exercise
With factory_boy, you declare admin = factory.Trait(role="admin") directly as a class attribute of UserFactory, outside Params. Why is Params the right place?
Show answer
Fields declared in Params are available to the factory's declarations but are not passed to the model's constructor. A trait declared as a normal attribute would be passed to User(...) as an unexpected argument and raise a TypeError. Params keeps the trait as a factory option only.