Test data and fixtures

Testing backends Junior Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Predict the output

What does the factory produce?

Python 3.13
from dataclasses import dataclass


@dataclass
class Order:
    id: int
    status: str = "new"
    total: int = 100


def make_order(id: int = 1, **kw: str) -> Order:
    return Order(id=id, **kw)  # type: ignore[arg-type]


print(make_order(7, status="shipped"))

Options
Hint 1 of 1

Which fields are overridden?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Order(id=7, status='shipped', total=100)

Correct. Only status is overridden; total keeps its default.

A factory supplies sensible defaults so each test sets only the fields it cares about. Here id is 7, status is overridden and total keeps its default of 100.

Why not the others?
  • B Order(id=1, status='shipped', total=100). id=7 is passed positionally.
  • C Order(id=7, status='new', total=100). status is overridden.
  • D A TypeError. status is a valid field.

30-second answer

Each test should build the minimum data it needs, explicitly, using small factory functions with sensible defaults that tests override only where it matters: make_order(status="shipped"). Avoid one giant shared fixture file that every test depends on, because changing it breaks unrelated tests and hides what each test is about. Use unique values so tests can run in parallel.

Practise saying it · 25 s. No recording, just a timer

Test data.

Say your answer out loud, then check which of these points you covered:

  • Factories with defaults
  • Minimal and explicit
  • Unique values
  • No shared mega-fixtures

Deep dive

Factories keep tests readable: only relevant fields appear.

Builders can create related rows (user → order → items).

Snapshot real production data only after anonymising it.

Reset state by transaction rollback or truncation.

Common mistakes

  • A shared seed file of hundreds of rows.
  • Tests relying on ids like 1 and 2.
  • Copying production data with personal information.

Senior take & follow-ups

Minimal explicit data via factories, unique values, no shared mega-fixtures.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why not one big seed?

    Show hint

    Hidden coupling between tests.

  2. How do you keep tests parallel-safe?

    Show hint

    Unique values and isolated transactions or schemas.

Suggest a fix if something here is wrong or out of date.