Sub topic 4
Choosing sensible, valid defaults
This chapter assumes you can write and run tests with pytest, you know Python dataclasses, and you have seen a basic factory function like make_user. The chapter is about the values a factory fills in when a test says nothing. Those values decide whether your factory stays pleasant to use or becomes a source of confusing failures.
What "valid" means
A default is valid when the object it produces could exist in your running system. That is a stricter rule than "the constructor accepts it". A User with role="member" and email="x" may construct without error and still be impossible in production, because signup rejects such emails.
Check validity against every rule that applies to the object:
- Type and format rules, such as an email containing
@. - Allowed value sets, such as roles being
memberoradmin. - Rules between fields, such as an end date that is later than the start date.
- Rules between objects, such as an order pointing at a customer that exists.
The test data should not be able to reach states the application can never reach. If it does, a test can pass or fail because of a situation that never happens in production.
Make invalid objects fail loudly
The best protection is to let the model reject bad data itself. If your class validates its input, a factory with a bad default fails immediately instead of producing a quiet lie.
from dataclasses import dataclass
from itertools import count
VALID_ROLES = {"member", "admin"}
@dataclass
class User:
id: int
email: str
role: str
active: bool
def __post_init__(self):
if "@" not in self.email:
raise ValueError(f"invalid email: {self.email!r}")
if self.role not in VALID_ROLES:
raise ValueError(f"invalid role: {self.role!r}")
_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})Validation in __post_init__ also catches mistakes in tests. If someone writes make_user(role="admn"), the test fails at setup with a clear message. Without validation, the typo travels into the code under test and fails somewhere far from its cause.
Not every model validates. Plain records and database rows often accept anything. In that case, add a test for the factory itself, covered below.
Pick the most ordinary value
A default should describe the most common, least surprising object. Ask what a typical row in production looks like, then use that.
def test_default_user_is_ordinary():
user = make_user()
assert user.role == "member"
assert user.active is TrueOrdinary defaults have two benefits. Tests that don't care about a field get the behavior that most code paths expect. And a reader who sees make_user() can guess what comes back without opening the factory.
The decision flow for each field looks like this:
Defaults by kind of field
| Kind of field | Good default | Why |
|---|---|---|
| Status or enum | The common starting state, such as `"pending"` | Matches how objects begin life. |
| Boolean flag | The value that does not trigger special behavior | Tests for the special case set the flag themselves. |
| Money | A small positive whole number of cents | Avoids zero, negatives, and rounding questions. |
| Text that is not unique | A fixed readable string | Fixed values make failures easy to read. |
| Unique text or id | A sequence-based value | Prevents collisions between objects. |
| Optional field | `None` or empty, unless the code under test needs it | Keeps the object minimal. |
| Date or time | A fixed moment | Avoids tests that depend on when they run. |
| Collection | A new empty or one-item collection per call | Avoids shared state. |
The boolean row deserves attention. Take is_banned. The default should be False, because a test that cares about banned users will say make_user(is_banned=True). If the default were True, nearly every other test would trip over special handling.
Avoid defaults that hide meaning
Two kinds of default cause trouble.
The first is the surprising default. If make_order() returns an order with total_cents=0, any test of discount or tax logic may pass for the wrong reason, because zero times anything is zero. Pick a value that makes arithmetic observable, such as 1000.
The second is the overly specific default. A factory that defaults email to "[email protected]" invites tests to depend on that name. Later, someone changes the default and twenty tests break, none of which cared about Alice. Generated values like [email protected] signal that the exact value is not a promise.
Derived defaults stay consistent
Some fields depend on others. If a test overrides one, the dependent field should follow it, or the object becomes invalid. The factory below derives ends_at from starts_at.
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
@dataclass
class Subscription:
user: User
starts_at: datetime
ends_at: datetime
def make_subscription(user=None, starts_at=None, **overrides):
if user is None:
user = make_user()
if starts_at is None:
starts_at = datetime(2024, 1, 1, tzinfo=timezone.utc)
defaults = {
"user": user,
"starts_at": starts_at,
"ends_at": starts_at + timedelta(days=30),
}
return Subscription(**{**defaults, **overrides})
late = make_subscription(starts_at=datetime(2024, 6, 1, tzinfo=timezone.utc))
print(late.ends_at)The output is 2024-07-01 00:00:00+00:00. If starts_at were an ordinary entry in the defaults dictionary, overriding it would leave ends_at in January, before the start. Promoting starts_at to a named parameter lets the other defaults read it.
The timestamp is a fixed constant on purpose. A default of datetime.now() means each test run sees different data, and a test that crosses midnight or a month boundary may fail only once a day. Reserve "now" for tests about time itself, and pass it explicitly there.
Never share mutable defaults
The most common bug in factory defaults is a shared mutable value. Python builds the defaults dictionary each time the function runs, but a list defined outside it is created once.
from dataclasses import dataclass, field
SHARED_TAGS = ["new"]
@dataclass
class Account:
name: str
tags: list = field(default_factory=list)
def make_account_broken(**overrides):
defaults = {"name": "acme", "tags": SHARED_TAGS}
return Account(**{**defaults, **overrides})
def make_account(**overrides):
defaults = {"name": "acme", "tags": ["new"]}
return Account(**{**defaults, **overrides})
first = make_account_broken()
first.tags.append("vip")
second = make_account_broken()
print(second.tags)
third = make_account()
third.tags.append("vip")
print(make_account().tags)The first print shows ['new', 'vip'], because both accounts hold the same list. A test that mutated its account has changed data for every later test in the process. The second print shows ['new'], because the literal inside the function builds a fresh list on each call.
The rule: write list, dict, and set literals inside the factory body, or build them with a function. The same applies to nested objects. Do not create a module-level DEFAULT_USER and reuse it.
Test the factory itself
Factories are code, so they can be wrong. A short set of tests protects every test that depends on them.
import pytest
def test_default_user_passes_validation():
make_user()
def test_each_user_is_unique():
first = make_user()
second = make_user()
assert first.id != second.id
assert first.email != second.email
def test_defaults_are_not_shared():
first = make_account()
first.tags.append("vip")
assert make_account().tags == ["new"]
def test_override_can_make_user_invalid():
with pytest.raises(ValueError):
make_user(role="owner")The last test confirms an important property. Overrides are not defaults, so they should be able to reach invalid states when a test wants to check how the code handles bad data. With validation in the model, those tests need pytest.raises, which is the right behavior.
Keep defaults minimal but complete
A default should supply every field that validity requires, and nothing the object does not need. Two failure modes pull in opposite directions.
- Too little: the factory leaves required fields as
None, and every test must fill them in. The factory no longer saves work. - Too much: the factory attaches a profile, three addresses, and a payment method to every user. Each
make_user()becomes slow and each test inherits data it never asked for.
When a related object is optional in the model, default it to absent. A user with no orders is a valid user. Tests that need orders create them with make_order(customer=user), which the next chapters cover.
Summary of the working model
- A default is valid if the object could exist in production, not merely if it constructs.
- Pick the most ordinary, least surprising value.
- Generate unique values and derive dependent ones, so overrides keep the object consistent.
- Use fixed constants for dates and text, and build mutable values fresh on each call.
- Test the factory so a broken default is caught in one place.
Exercise
A teammate writes this factory, and a test that calls make_invoice(issued_on=date(2024, 3, 1)) fails validation with "due date before issue date". What is wrong with the factory, and how would you fix it?
from dataclasses import dataclass
from datetime import date
@dataclass
class Invoice:
issuedon: date
dueon: date
def makeinvoice(**overrides):
defaults = {
"issuedon": date(2024, 1, 1),
"due_on": date(2024, 1, 31),
}
return Invoice({defaults, **overrides})
Show answer
The due_on default is a fixed date that does not depend on issued_on. When a test overrides issued_on to a later date, due_on stays in January, so the invoice breaks the rule that the due date must not precede the issue date. Fix it by making issued_on a named parameter with a fixed default and computing due_on from it, for example due_on = issued_on + timedelta(days=30), then passing both through the defaults dictionary so that overrides still work.
Exercise
Why is defaults = {"name": "acme", "tags": SHARED_TAGS} with a module-level SHARED_TAGS = ["new"] risky, and what is the one-line change that removes the risk?
Show answer
Every call returns an object that holds the same list, so a test that appends to tags changes the data seen by all later calls in the process. Replace the reference with a literal inside the factory body, "tags": ["new"], so each call builds a new list.