Sub topic 4
Choosing sensible, valid defaults
This chapter assumes you can write and run tests in Python, know what a dataclass is, and have seen the basic make_user factory from the previous chapter. Here we focus on one question: what should a factory return when the test says nothing?
Why defaults matter
A factory's defaults are what every test gets unless it overrides them. If the defaults are poor, every test inherits the problem. Good defaults follow three rules:
- Valid. The object should pass the same checks real code would apply. A user with an empty email teaches the test nothing and may crash code that was never meant to see that state.
- Ordinary. Pick the most common, least surprising case. A
memberwho isactiveis typical. An admin or a suspended account is a special case, and a test should ask for it by name. - Neutral. Defaults should not accidentally trigger the behavior under test. If a discount applies to orders over 5000 cents, a default total of 10000 would silently put every test in discount territory.
Start from the factory
Here is the factory from the spine again:
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})Each default was chosen on purpose:
| Field | Default | Reason |
|---|---|---|
| `id` | next number from a counter | Unique, so two users never collide |
| `email` | `user{n}@example.com` | Well-formed, and `example.com` is reserved for documentation so it never reaches a real mailbox |
| `role` | `"member"` | The most common role, with no special permissions |
| `active` | `True` | The normal state of an account |
Defaults describe the "happy path"
A useful test of your defaults is to call the factory with no arguments and ask, "Would the production code accept this?" The next example checks that directly.
def can_log_in(user):
return user.active
def test_default_user_is_valid_for_login():
user = make_user()
assert can_log_in(user) is TrueIf this fails, the default is wrong, not the test. Fix it in the factory, once, and every test benefits.
Keep defaults close to real rules
Defaults drift out of date when the rules change. Suppose the system later requires emails to contain @. The default [email protected] still passes, so no test breaks. Now suppose it requires roles to come from a fixed list. A default of "member" is fine only if "member" is in that list.
You can guard against this by adding a small test to the factory itself:
def test_make_user_defaults_are_valid():
user = make_user()
assert "@" in user.email
assert user.role in {"member", "admin"}
assert user.active is TrueThis test is cheap and fails in one obvious place when a rule changes.
Avoid these default mistakes
- Magic values with meaning. A default like
total_cents=0may look harmless, but code that treats zero as "free" or "missing" will behave differently. Prefer a small ordinary value such as1000. - Real-looking personal data. Use reserved domains such as
example.comrather than addresses that might belong to someone. - Shared mutable defaults. Never put a list or dict directly in a default that is reused. The factory above builds a fresh
defaultsdictionary on every call, so each user gets its own values. If you add a field such astags, create the list inside the function.
def make_user_with_tags(**overrides):
n = next(_user_ids)
defaults = {
"id": n,
"email": f"user{n}@example.com",
"role": "member",
"active": True,
"tags": [],
}
return {**defaults, **overrides}Because [] is created inside the function body, each call gets a new list. If tags lived at module level and was reused, one test could change it and break another.
How defaults fit the whole flow
Exercise
A teammate sets the default total_cents in make_order to 100000. Your shipping rule gives free shipping to orders of 50000 cents or more. Why is this default a problem, and what would you change it to?
Show answer
The default sits above the free-shipping threshold, so every test that uses the default order silently gets free shipping. Tests about shipping costs would pass or fail for reasons they never state. Change the default to a small ordinary value such as 1000, well below the boundary, and have the free-shipping test override total_cents explicitly.