Characterization tests
A characterization test records what the code does, not what it should do. It is a safety net for change, not a specification.
Steps
- Pick the seam. The narrowest public entry point that exercises the code you will change: a function, a CLI command, an HTTP endpoint, a report generator.
- Generate inputs that cover the branches: read the code and list conditions; create inputs for each side of each condition, plus real-world samples (anonymized production payloads, fixtures from bug reports). For combinatorial inputs, generate the cross product of a few values per parameter.
- Capture outputs. Call the code with each input and record the output (return value, written file, HTTP response, SQL emitted). Normalize unstable parts first: timestamps, random IDs, ordering of sets/maps, absolute paths.
- Write the tests asserting outputs equal the recorded ones. Options:
- Snapshot/approval tools in the existing stack (Jest/Vitest snapshots, pytest snapshot plugins, approval-test libraries).
- Plain golden files:
tests/golden/<case>.jsonplus a test that compares, and anUPDATE_GOLDEN=1switch to regenerate.
- Check they bite. Make a small deliberate change in the code and confirm at least one test fails.
- Mark surprises. When recorded behavior looks wrong, keep the test as-is (it documents reality) and add a comment
# characterization: looks like a bug, see <issue>. Fixing it is a separate, explicit change.
Then change the code
Refactor with the tests green after every step. When you intentionally change behavior, update only the affected golden outputs and explain each change in the commit.
Clean up later
Once real, intention-revealing unit tests exist for the area, delete characterization tests that duplicate them; golden files rot if nobody understands them.