Sub topic 8
Traits for named variants
This chapter assumes you can write Python tests, know dataclasses, and have read the earlier chapters on factory defaults, overrides, and relationships. It builds on make_user and make_order.
The problem traits solve
Some variants of an object come up in many tests. An admin user, a cancelled order, and an inactive account each need the same overrides every time. If each test repeats make_user(role="admin"), the meaning of that override is spread across the test suite. If the definition of an admin changes, for example by also needing a permissions field, you edit every call site.
A trait is a named set of overrides for a factory. The name says what the variant means, and the definition lives in one place.
A trait as a thin wrapper
In plain Python, a trait is a small function that applies its overrides and then passes the caller's overrides on.
def make_admin(**overrides):
return make_user(**{"role": "admin", **overrides})
def make_cancelled_order(**overrides):
return make_order(**{"status": "cancelled", **overrides})The order of the merged dictionaries matters. The trait's values come first and **overrides comes last. The caller's values therefore win, and a test can still adjust a single field:
admin = make_admin(email="[email protected]")
assert admin.role == "admin"
assert admin.email == "[email protected]"A test that uses make_cancelled_order() reads as a statement of intent. It tells the reader the order is cancelled and says nothing about how cancellation is stored.
Combining traits
Because each trait is a function that accepts overrides, you can combine two by passing one's values into the other. Here is an inactive admin:
def make_inactive_admin(**overrides):
return make_admin(**{"active": False, **overrides})This works for two or three traits. Beyond that, the number of wrapper functions grows quickly. Factory libraries handle combinations better, as shown below.
Traits in factory_boy
The factory_boy library has traits built in. A trait is declared inside Params and switched on with a boolean argument.
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")
inactive = factory.Trait(active=False)
admin = UserFactory(admin=True)
inactive_admin = UserFactory(admin=True, inactive=True)Traits combine by listing them, so you do not write a function for each pair. Explicit keyword arguments still override a trait, as in UserFactory(admin=True, role="superuser"). The User dataclass from the earlier chapters is assumed to be in scope.
Choosing good traits
- Name the business meaning, not the field values.
cancelledis better thanstatus_x. The name should survive a change in how the data is stored. - Keep each trait small. One trait should describe one idea. Combine small traits instead of building one that does everything.
- Add a trait when a variant repeats. One test with
active=Falsedoes not need a trait. When several tests repeat the same override, name it.
Common errors
- Putting the trait's values after the overrides. Writing
{**overrides, "role": "admin"}makes the trait win, so a test cannot change those fields. Keep overrides last. - Hiding too much in a trait. A trait that sets ten fields makes it hard to see which one a test depends on. If a test relies on a single field, override that field directly so it is visible.
- Traits that conflict. If two traits set the same field, the result depends on merge order. Avoid overlapping traits, or document which one wins.
Exercise
Write make_shipped_order(**overrides) using the make_order function. It should set status to "shipped" and let the caller override any field, including status. Which side of the merged dictionary should **overrides go on, and why?
Show answer
def makeshippedorder(overrides): return make_order({"status": "shipped", overrides}) `overrides` goes last in the dictionary. Later keys replace earlier ones, so the caller's values win over the trait's values.
Exercise
In factory_boy, how would you create an inactive admin from UserFactory, and why is this easier than with wrapper functions once you have many traits?
Show answer
Call UserFactory(admin=True, inactive=True). Traits are switched on by name, so any combination works without writing a new function for each pair.