Sub topic 1
Why Test Data Becomes a Problem
Prerequisites
Assume you can write and run automated tests, understand basic Python classes or dataclasses, and have used test fixtures or setup code.
Why Test Data Becomes a Problem
Tests need data that represents realistic cases. A user may need an ID, email address, role, and active status. An order may need a customer, amount, and status.
Copying this setup into every test creates maintenance problems:
- A changed required field breaks many tests.
- The important difference between tests becomes hard to see.
- Shared mutable data can let one test affect another.
- Invalid or incomplete objects can make failures unrelated to the behavior under test.
A test should make its relevant condition obvious. Data setup should provide everything else quietly.
Static Fixtures Versus Factories
A static fixture is a predefined object or data record. It is simple, but every test receives the same values unless you copy and modify the fixture.
A factory is a function or class that creates a new test object. It centralizes defaults while allowing each test to request the variation it needs.
flowchart TD
A[Test asks for data] --> B[Factory applies valid defaults]
B --> C[Factory returns a new object]
C --> D[Test exercises behavior]Your First Test Data Factory
Here, User is a dataclass, a class whose fields and basic initialization Python generates for you. make_user is the factory.
from dataclasses import dataclass
@dataclass
class User:
email: str
role: str
active: bool
def make_user():
return User(
email="[email protected]",
role="member",
active=True,
)
def can_log_in(user):
return user.active
user = make_user()
assert can_log_in(user) is TrueThe test does not construct every field itself. It asks for a normal user and can focus on login behavior.
Choosing Sensible, Valid Defaults
Defaults should satisfy the object's ordinary invariants. An invariant is a rule that should always be true, such as requiring a non-empty email or a valid role.
Good defaults are:
- Valid for the domain.
- Common in ordinary application behavior.
- Independent between factory calls.
- Stable across test runs.
- Easy to understand.
Avoid defaults that hide unusual states. An inactive user or cancelled order should be requested explicitly by a test that needs that state.
Exercise
What should a factory default represent?
Show answer
A valid, common object state, while leaving unusual or behavior-specific states for the test to request explicitly.