Sub topic 12
Characterization Tests for Existing Code
This chapter assumes you can write pytest tests, read Git diffs, and have used the red-green-refactor cycle from earlier chapters. It covers what to do when the code already exists and has no tests.
Why existing code breaks the usual cycle
Normal TDD starts with a failing test for a behavior that does not exist yet. Legacy code is different. The behavior exists, nobody wrote it down, and you do not want to change it by accident.
If you ask an agent to "clean up" or "add a feature to" untested code, nothing tells you whether it broke something. The agent runs the suite, sees green, and reports success. An empty suite is always green.
A characterization test records what the code does today. It does not say what the code should do. Its job is to pin current behavior, bugs included, so that any later change shows up as a failing test.
The workflow
- Pick one small unit of code you are about to change.
- Call it with realistic inputs and observe the actual outputs.
- Write tests that assert those observed outputs.
- Run the tests and confirm they pass against the unchanged code.
- Commit the tests on their own.
- Only then ask the agent to change the code, using the normal red-green-refactor cycle.
Notice that step 4 reverses the usual rule. Here the tests should pass the first time. A failure means your recorded expectation does not match reality, so fix the test.
A worked example
Suppose a repository contains this function. It has no tests.
# pricing.py
def shipping_cost(weight_kg, country):
if weight_kg <= 0:
return 0
base = 5 if country == "US" else 12
if weight_kg > 10:
base += (weight_kg - 10) * 2
return round(base, 2)First, observe the behavior. You can run it yourself or ask the agent to print results for chosen inputs without editing any file.
from pricing import shipping_cost
for args in [(0, "US"), (-1, "US"), (1, "US"), (10, "US"), (11, "US"), (1, "DE"), (12.5, "DE")]:
print(args, shipping_cost(*args))Then record those results as tests.
# test_pricing_characterization.py
import pytest
from pricing import shipping_cost
@pytest.mark.parametrize(
"weight, country, expected",
[
(0, "US", 0),
(-1, "US", 0),
(1, "US", 5),
(10, "US", 5),
(11, "US", 7),
(1, "DE", 12),
(12.5, "DE", 17.0),
],
)
def test_shipping_cost_current_behavior(weight, country, expected):
assert shipping_cost(weight, country) == expectedThe cases cover the boundaries: zero, a negative weight, exactly 10 kg, just above 10 kg, and both country branches. Boundaries are where a careless rewrite usually changes behavior.
Run the suite.
python -m pytest -qAll tests pass, and you commit them. Now the agent can safely refactor shipping_cost, because a change in behavior will turn a test red.
Working with the agent
An agent can speed up the observation step, but give it firm limits. Add rules like these to your instruction file:
## Characterization tests
- Do not change production code while writing characterization tests.
- Assert only values you observed by running the code. Never infer them from reading it.
- Cover boundaries and every branch you can find.
- If current behavior looks like a bug, keep the test and add a comment. Do not fix it in this step.The last rule matters. Fixing a bug while characterizing hides the original behavior and mixes two changes in one commit. Record it first, then fix it later in a normal red-green-refactor cycle by changing the test deliberately.
Limits of characterization tests
- They only cover the inputs you chose. Untested branches stay unprotected.
- They lock in bugs. A passing test means "unchanged," not "correct."
- Tests tied to current output can be brittle. Keep them at the level of a function's public result, not its internals.
When a characterization test later fails because you intended the change, update that one test in the same commit as the change, and say so in the commit message.
Exercise
You ask an agent to refactor an untested function. The suite is green afterward. Why is that not enough evidence that behavior is preserved, and what should you do first?
Show answer
A suite with no tests covering the function is green regardless of what the agent changes. Before the refactor, write characterization tests: run the function with representative and boundary inputs, assert the observed outputs, confirm they pass on the unchanged code, and commit them. Then refactor and re-run the suite.
Exercise
While characterizing a function, you find that it returns 0 for a negative weight, which looks like a bug. Should the characterization test assert 0, and when do you fix it?
Show answer
Yes, assert 0 with a comment noting it looks wrong. The test records current behavior. Fix the bug later in a separate red-green cycle, where you change the test to the correct expectation first and then change the code.