Sub topic 5
Overriding only what the test cares about
This chapter assumes you can write pytest-style tests, you know Python dataclasses and keyword arguments, and you have already written a basic factory with defaults. We start from the make_user factory shown below and look at how overrides work and why they make tests readable.
The rule: say only what matters
A test has a cause and an effect. The cause is the data that makes the behavior happen, and the effect is what you assert. Everything else in the setup is noise. A user needs an id, an email, and a role before it can exist, but a test about login does not care about any of them.
The rule is simple: a test names a field only when the test's outcome depends on that field. The factory fills in the rest with valid defaults. When you read such a test, every value you see is a clue to what is being tested.
Here is the factory from the previous chapters, which we will use throughout:
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})The key line is the last one. {**defaults, **overrides} builds a new dictionary. Keys from overrides come later, so they replace keys from defaults. Keys that are not overridden keep their default.
Reading a test that overrides one field
Compare two versions of a test for the same rule.
def can_log_in(user):
return user.active
def test_inactive_user_cannot_log_in_verbose():
user = User(id=1, email="[email protected]", role="member", active=False)
assert can_log_in(user) is False
def test_inactive_user_cannot_log_in():
user = make_user(active=False)
assert can_log_in(user) is FalseIn the verbose version, the reader has to compare four values against what they expect. Is role="member" significant? Does the email format matter? You cannot tell without reading can_log_in. In the second version, active=False is the only thing mentioned, so it must be the only thing that matters.
This is the main payoff of overrides. The setup becomes a statement of the difference between the normal case and the case under test.
Pass overrides explicitly, even when they equal the default
There is one case where you should override a field with the value it already has by default. That case is when your assertion depends on the value.
def display_name(user):
return user.email.split("@")[0].title()
def test_display_name_uses_the_part_before_the_at_sign():
user = make_user(email="[email protected]")
assert display_name(user) == "Alice"Suppose the test instead relied on the default and asserted == "User1". It would pass only while the default email starts with user and the counter happens to be at 1. Changing the default, or running another test first, would break it, and the failure would point away from the real cause.
A useful check: if your assertion mentions a literal value, that value should appear in the setup too. If the assertion compares against a field read from the object (assert result.email == user.email), no override is needed.
Why `{**defaults, **overrides}` and not `.get()`
Some factories are written like this:
def make_user_fragile(email=None, role=None, active=None):
return User(
id=next(_user_ids),
email=email or "[email protected]",
role=role or "member",
active=active or True,
)This looks friendly, but it has a bug that overrides should never have. active=False is falsy, so active or True returns True. The test asks for an inactive user and silently gets an active one. The test for "inactive users cannot log in" would then fail for a confusing reason, or worse, a test that expects a user to be active would pass by accident.
The dictionary merge has no such problem. It checks whether a key was passed, not whether its value is truthy. This also means you can pass None on purpose, for example to test how code handles a missing value:
def test_none_override_is_kept():
user = make_user(email=None)
assert user.email is NoneIf a field is allowed to be empty, None, 0, "", and False must all survive as overrides. The merge handles this without special code.
Misspelled fields fail loudly
Because the merged dictionary is passed to the constructor with **, an unknown key reaches User(...) and raises an error.
import pytest
def test_unknown_override_is_rejected():
with pytest.raises(TypeError):
make_user(activ=False)This is a feature. A typo like activ=False would otherwise be ignored, and the test would run against an active user and report a confusing result. Do not "make the factory more forgiving" by filtering out unknown keys. Strictness is what makes overrides trustworthy.
If you write the factory with a plain dict-like object instead of a dataclass, you lose this check. In that case, validate the keys yourself:
def make_settings(**overrides):
defaults = {"theme": "light", "language": "en"}
unknown = set(overrides) - set(defaults)
if unknown:
raise TypeError(f"Unknown fields: {sorted(unknown)}")
return {**defaults, **overrides}Defaults are rebuilt on every call
The defaults dictionary inside make_user is created each time the function runs. That is deliberate, and it matters for mutable values such as lists and dictionaries.
Consider a version that keeps defaults at module level:
from dataclasses import dataclass
@dataclass
class Profile:
name: str
settings: dict
SHARED_SETTINGS = {"theme": "light"}
def make_profile_shared(**overrides):
defaults = {"name": "Sam", "settings": SHARED_SETTINGS}
return Profile(**{**defaults, **overrides})
def make_profile(**overrides):
defaults = {"name": "Sam", "settings": {"theme": "light"}}
return Profile(**{**defaults, **overrides})
first = make_profile_shared()
first.settings["theme"] = "dark"
second = make_profile_shared()
print(second.settings["theme"]) # dark: the change leaked
third = make_profile()
third.settings["theme"] = "dark"
fourth = make_profile()
print(fourth.settings["theme"]) # light: each call gets a fresh dictWith the shared version, one test mutates the default and every later test sees the change. Tests then pass or fail depending on run order. Build mutable defaults inside the function so every object gets its own copy.
Overrides do not recompute derived defaults
In make_user, the default email is built from the same counter value as the id. If a test overrides id, the email does not change:
user = make_user(id=500)
print(user.id) # 500
print(user.email) # [email protected] (the number comes from the counter, not from 500)This is fine for most tests, but it can surprise you if you expect the email to follow the id. Two options:
- Override both fields when the relationship matters to the test.
- Accept that defaults are independent, which is usually the safer choice. A default that depends on another override is harder to reason about.
The factory library covered later in this tutorial has a way to express derived fields, so the relationship can be written once. For a hand-written factory, keep defaults independent unless you have a real need.
When many overrides are a warning sign
Overrides work best when there are one or two. If a test passes five fields, ask which one of these is true:
- The behavior really depends on five fields. This happens in rules such as pricing, and it is fine. Keep all five visible.
- Several fields always travel together, such as
role="admin"plus a set of permissions. A named variant would express that better. The chapter on traits covers this. - The test is checking too much. Splitting it into smaller tests, each with one override, often makes failures easier to diagnose.
A quick test of your own tests: remove one override at a time. If the test still passes and the assertion is still meaningful, that override was noise. Delete it.
Common mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| Using `value or default` to apply overrides | Falsy overrides such as `False`, `0`, or `""` are replaced by the default | Merge dictionaries: `{**defaults, **overrides}` |
| Asserting on a default value without overriding it | The test breaks when the default changes | Pass the value explicitly and assert on it |
| Ignoring unknown keyword arguments | Typos pass silently and the test checks the wrong data | Let the constructor raise `TypeError` |
| Sharing mutable defaults at module level | Mutations leak between tests | Build defaults inside the function |
| Overriding fields the test does not use | The reader wonders why each value matters | Remove overrides that do not change the outcome |
Putting it together
Here is a short group of tests that follow the rule. Each one states only its difference.
def is_admin(user):
return user.role == "admin"
def test_admin_role_is_recognized():
user = make_user(role="admin")
assert is_admin(user) is True
def test_member_role_is_not_admin():
user = make_user(role="member")
assert is_admin(user) is False
def test_inactive_admin_is_still_an_admin():
user = make_user(role="admin", active=False)
assert is_admin(user) is TrueThe second test passes role="member", which equals the default. That is intentional, because the assertion depends on the role. The third test overrides two fields to show that active does not affect is_admin. Both choices communicate intent.
Exercise
A teammate writes make_user with the line active=active if active else True to apply an active override. A test calls make_user(active=False) and asserts that can_log_in(user) is False. What happens, and how do you fix the factory?
Show answer
The test fails because the user ends up active. False is falsy, so the expression picks True, and the override is lost. Fix it by using User(**{**defaults, **overrides}), which keeps any key the caller passed regardless of its value, or by checking "active" in overrides.
Exercise
This test depends on a hidden default. Rewrite it so its intent is visible. def testgreeting(): user = makeuser() assert greet(user) == "Hello, [email protected]"
Show answer
The assertion hard-codes the counter-based email, so it breaks when the order of tests or the default format changes. Pass the value that the assertion depends on: user = make_user(email="[email protected]") and assert greet(user) == "Hello, [email protected]".
Exercise
Why is it a mistake to define DEFAULTS = {"tags": []} at module level and use {**DEFAULTS, **overrides} in a factory?
Show answer
The list object is created once and shared by every object the factory builds. A test that appends to tags changes the default for all later objects, so results depend on test order. Build the dictionary, including the list, inside the factory function so each call creates a new list.