Sub topic 5
Overriding Only What the Test Cares About
This chapter assumes you can write and run tests in Python, know what a dataclass is, and have seen a basic factory function that returns a valid object with defaults. Here you will learn how to override fields so each test shows only the detail it depends on.
The idea
A factory gives every field a safe default. A test then replaces only the fields that matter for the behavior under test. Anything the test does not mention is, by implication, irrelevant to the result. That is what makes the test easy to read: the setup holds the one difference that explains the assertion.
Here is the factory from the previous chapter.
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 User(**{**defaults, **overrides}). In a dict merge, later keys win. Putting overrides after defaults means a caller's value replaces the default with the same name.
A test that shows its intent
Compare two tests for the same function.
def can_log_in(user):
return user.active
def test_inactive_user_cannot_log_in():
user = make_user(active=False)
assert can_log_in(user) is False
def test_active_user_can_log_in():
user = make_user()
assert can_log_in(user) is TrueThe first test passes active=False, and nothing else. A reader sees at once that active is the cause of the result. The second test passes nothing, which tells the reader the defaults already describe a user who can log in.
Without a factory, each test would list all four fields. The one field that matters would hide among three that do not.
Rules for good overrides
- Override the field the assertion depends on. If the test checks login for inactive users, override
active. - Do not restate defaults. Writing
make_user(role="member")suggests the role matters when it does not. Readers will look for a reason that is not there. - Use a named value when the number or string is meaningful.
make_user(email="[email protected]")is fine when the test asserts on that address. - Keep the setup short. If you need to override five fields in most tests, the defaults are probably wrong. Change them.
Handling mistakes in overrides
The **overrides approach has one weakness. A misspelled field such as make_user(actvie=False) fails with a TypeError from the dataclass constructor, which is helpful. But with a plain dict or a class that accepts any keyword, the typo could be silently ignored and the test would pass for the wrong reason.
Prefer constructors that reject unknown names. Dataclasses do this for you.
try:
make_user(actvie=False)
except TypeError as error:
print(error)Overrides on related objects
The same rule applies when one object holds another. The order factory accepts a customer and creates a default one when none is given. This lets a test share one customer across several orders.
@dataclass
class Order:
id: int
customer: User
total_cents: int
status: str
_order_ids = count(1)
def make_order(customer=None, **overrides):
if customer is None:
customer = make_user()
defaults = {
"id": next(_order_ids),
"customer": customer,
"total_cents": 1000,
"status": "pending",
}
return Order(**{**defaults, **overrides})
alice = make_user(email="[email protected]")
first = make_order(customer=alice)
second = make_order(customer=alice, status="shipped")Both orders belong to alice. The second also overrides status. Everything else comes from defaults.
Common errors
| Error | Result | Fix |
|---|---|---|
| Overriding fields the test does not use | Noisy setup, unclear intent | Remove them |
| Changing a default to suit one test | Other tests break or change meaning | Override in that test instead |
| Mutating the object after creation | Setup is split across lines | Pass the value as an override |
| Misspelled keyword on a loose factory | Test passes without testing | Use a typed constructor |
Exercise
Using makeuser and canlog_in, a test needs a user who is an admin but inactive, and asserts that this user cannot log in. Which overrides should it pass, and why is passing email or id unnecessary?
Show answer
It should call make_user(role="admin", active=False). The assertion depends on active, and role="admin" is included because the scenario describes an admin. The id and email come from defaults, and the counter makes them unique, so the test does not need to mention them.