Sub topic 3
Traits for Named Variants
This chapter assumes you can write and run automated Python tests, define basic classes or dataclasses, and use test fixtures. A trait is a named group of factory overrides. It represents a meaningful variant, such as an administrator or a cancelled order.
Traits for Named Variants
Traits keep tests readable without hiding the important difference:
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})
def make_admin(**overrides):
return make_user(role="admin", **overrides)
admin = make_admin(active=False)make_admin() communicates the test's intent. The caller can still override another field. In larger projects, use a dictionary merge when several defaults must remain overridable.
Building Versus Persisting
A build creates an object in memory. It is fast and does not need a database. Use it for validation, formatting, and business-rule tests.
A create builds an object and saves it through a database or repository. Use it when the behavior under test queries stored data.
flowchart TD
A[Test needs data] --> B{Does the code query storage?}
B -->|No| C[Build in memory]
B -->|Yes| D[Create and persist]Keeping Generated Data Deterministic
Factories may use sequences for unique values. Avoid unseeded randomness. If random data is useful, use a local seeded generator and report its seed when a test fails.
import random
rng = random.Random(12345)
total_cents = rng.randint(100, 50_000)
print(total_cents)The same seed produces the same value, so the failure can be reproduced.
Using a Factory Library
Libraries such as factory_boy provide Sequence, SubFactory, and Trait:
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"
class Params:
admin = factory.Trait(role="admin")Use a library when relationships, persistence, or many variants make hand-written functions repetitive. Keep simple factories simple if a library would add more concepts than value.
Organizing and Maintaining Factories
Keep factories near the test support code, not inside production modules. Group them by domain. Give defaults valid values, make relationships explicit, and update factories when domain rules change. A factory should describe data setup, not business behavior.
Anti-Patterns to Avoid
- Creating invalid defaults and fixing them in every test.
- Adding many hidden side effects to a factory call.
- Using global random state.
- Persisting every object automatically.
- Creating a large “god factory” with unrelated options.
- Using a trait when a direct override would be clearer.
Exercise
A test only checks whether an inactive user is rejected. Which setup is clearer: make_user(active=False) or make_inactive_admin_with_expired_email()?
Show answer
make_user(active=False), because it changes only the field the test depends on.