Sub topic 2
Overriding Only What the Test Cares About
Assume you can write and run Python tests, use dataclasses, and understand basic test fixtures. This chapter uses a factory: a function that creates test objects with valid defaults.
Override Only the Important Field
A test should make its reason clear. If the test checks inactive users, set only active=False. The factory supplies the email, role, and ID.
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):
user_id = next(_user_ids)
defaults = {
"id": user_id,
"email": f"user{user_id}@example.com",
"role": "member",
"active": True,
}
return User(**{**defaults, **overrides})
def can_log_in(user):
return user.active
inactive_user = make_user(active=False)
active_user = make_user()
assert can_log_in(inactive_user) is False
assert can_log_in(active_user) is True**overrides collects keyword arguments. Merging it after defaults means an override wins. This keeps setup short and prevents unrelated changes to the User class from forcing edits in every test.
Generate Unique Values with Sequences
A sequence produces a new value each time the factory runs. The counter above gives each user a different ID and email. This prevents collisions when a test creates several objects.
A sequence is usually unique only within the current process. If the value must be unique in a database, the database constraint still provides the final guarantee.
Build Related Objects
Factories can call other factories. An order factory can create a default customer, while allowing a test to pass a specific customer.
@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]")
order = make_order(customer=alice, status="shipped")
assert order.customer is alice
assert order.status == "shipped"Passing alice makes the relationship explicit. Omitting customer creates a valid default automatically.
Exercise
What should you override when testing that a shipped order belongs to a particular customer?
Show answer
Override both customer with that customer and status with "shipped" if the status is part of the behavior being tested.