Sub topic 12
Characterization tests for existing code
This chapter assumes you have worked through the red-green-refactor cycle in the earlier chapters. It also assumes you can read a pytest file and a Git diff, and that you have used a coding agent to edit files and run tests.
Why existing code needs a different first step
The earlier chapters started with a failing test and let the agent write the code. Legacy code is code that already exists, has no tests, and that you need to change. The test-first rule still applies, but you can't write a red test for behavior that already works.
Before you ask an agent to modify such code, you need a safety net. The net must describe what the code does today, not what it should do. A test that records current behavior is a characterization test. The name comes from Michael Feathers, who described tests that "characterize" a system as it actually behaves.
An agent makes this step more important. It edits quickly and with confidence, and it will happily "clean up" a function whose odd behavior some caller depends on. Without tests, you only find out in production.
How characterization tests differ from other tests
| Kind of test | Written when | Expected first result | Source of the expected value |
|---|---|---|---|
| TDD test | Before the code exists | Red | The requirement |
| Characterization test | After the code exists, before changing it | Green | What the code actually returns |
| Regression test | After a bug is fixed | Red before the fix, green after | The corrected requirement |
The key difference is the source of truth. In TDD, a human decides what the code should do. In characterization, the running code is the source of truth, even where it looks wrong. You are recording facts, not judging them.
The workflow
The sequence below keeps the agent honest. Each step has a check that doesn't depend on the agent's description of its own work.
A worked example
Here is a legacy shipping calculator. Nobody remembers why it works the way it does, and it has no tests.
# legacy_pricing.py
def shipping_cost(weight_kg, country, express=False):
if weight_kg <= 0:
return 0
base = 5
if weight_kg > 2:
base = base + (weight_kg - 2) * 1.5
if country != "US":
base = base * 2
if express:
base = base + 10
return round(base, 2)The task: country codes arrive in mixed case from a new client, and "us" should count as domestic. That is a change to untested code, so you characterize it first.
Step 1: Probe instead of predicting
Do not let the agent work out expected values by reading the code. Reading is where agents make arithmetic and logic mistakes, and a wrong expected value in a "green" test hides the mistake. Run the code and record what it returns.
# probe.py
from legacy_pricing import shipping_cost
cases = [
(1, "US", False),
(2, "US", False),
(2.5, "US", False),
(4, "US", False),
(4, "DE", False),
(1, "US", True),
(0, "US", True),
(-3, "US", False),
(1, "us", False),
]
for weight, country, express in cases:
print((weight, country, express), "->", shipping_cost(weight, country, express))Running python probe.py prints:
(1, 'US', False) -> 5
(2, 'US', False) -> 5
(2.5, 'US', False) -> 5.75
(4, 'US', False) -> 8.0
(4, 'DE', False) -> 16.0
(1, 'US', True) -> 15
(0, 'US', True) -> 0
(-3, 'US', False) -> 0
(1, 'us', False) -> 10Read the list for surprises. Three rows stand out:
- A zero weight with express shipping returns 0, so the express fee is silently dropped.
- A negative weight returns 0 instead of raising an error.
- Lowercase
"us"is treated as international and costs 10.
Characterization does not fix these. It records them so a later change can't alter them by accident.
Step 2: Pin the outputs
# test_legacy_pricing_characterization.py
import pytest
from legacy_pricing import shipping_cost
@pytest.mark.parametrize(
"weight_kg, country, express, expected",
[
(1, "US", False, 5),
(2, "US", False, 5), # boundary: exactly 2 kg is not surcharged
(2.5, "US", False, 5.75),
(4, "US", False, 8.0),
(4, "DE", False, 16.0),
(1, "US", True, 15),
(0, "US", True, 0), # quirk: express fee dropped for zero weight
(-3, "US", False, 0), # quirk: negative weight returns 0
(1, "us", False, 10), # quirk: country match is case-sensitive
],
)
def test_current_behavior(weight_kg, country, express, expected):
assert shipping_cost(weight_kg, country, express) == expectedRun it with python -m pytest -q. All nine cases must pass on the first run. Green on the first run is the correct result here, which is the reverse of TDD. If a case fails, your recorded value is wrong. Fix the test and leave legacy_pricing.py alone.
Step 3: Prove the tests can fail
A test that can't fail protects nothing. Temporarily change weight_kg > 2 to weight_kg >= 2 in the source and run the suite. The (2, "US", False, 5) case should fail. Then revert the edit.
You can ask the agent to do this, but check the result yourself. After the revert, run git status --short. Only the new test file should show as changed.
Step 4: Commit the tests alone
Commit the characterization tests in their own commit, before any behavior change. This gives you a clean restore point and makes the next diff easy to review. The commit message should say these tests record current behavior, including known quirks.
Step 5: Run a normal TDD cycle
Now the usual cycle applies. Write the red test for the new requirement first:
# added to test_legacy_pricing_characterization.py
from legacy_pricing import shipping_cost
def test_country_code_is_case_insensitive():
assert shipping_cost(1, "us") == 5Run it and read the failure. It should report assert 10 == 5, which is the intended reason: the behavior is missing. Then make the smallest change:
# legacy_pricing.py (changed line)
if country.upper() != "US":Run the suite again. The new test passes. One characterization case now fails: (1, "us", False, 10). That failure is correct, because it caught a behavior change. This particular change is intentional, so update that row to expect 5 in the same commit as the code change. Explain the reason in the commit message.
Nothing else fails. The zero-weight and negative-weight quirks are unchanged, which is what the safety net is for.
Instructing the agent
Give the agent explicit rules for this phase. It may default to fixing bugs it notices, because that looks helpful.
## Characterizing existing code
1. Do not modify any non-test file while writing characterization tests.
2. Get expected values by running the code, not by reading it and predicting. Show the probe output.
3. Every new characterization test must pass on the first run. If one fails, correct the test.
4. If you notice a bug or odd behavior, add a comment marking it as a quirk and tell me. Do not fix it.
5. Cover the function I plan to change: boundaries, empty or zero inputs, and each branch.
6. Stop after the tests pass. Do not start the requested change until I have reviewed and committed them.Rule 6 matters most. Without it, an agent often goes straight from the tests to the change and puts both in one diff.
Edge cases and limits
Coverage is a means, not the goal
You do not need to characterize the whole codebase. Cover the code your change touches and the code that calls it. A coverage report is useful for finding branches you missed, such as the express branch above. Chasing 100% coverage before a small change wastes effort.
Nondeterminism
Code that reads the clock, generates random values, calls the network, or reads files can't be pinned directly. Control the input instead: pass a fixed date, seed the random generator, or substitute a fake for the network call. If the code makes this impossible, make a minimal change that only exposes the input as a parameter. Verify it with whatever tests you can write first.
Larger outputs
For functions that return big structures, such as a rendered report, store a snapshot (a "golden master") and compare against it. The same rule applies. Produce the snapshot by running the code, and read it before committing. A snapshot nobody has read protects only against change, not against the bugs already in it.
Pinned bugs are not endorsements
Name quirks in comments, as in the test file above, so a future reader doesn't mistake -3 -> 0 for a requirement. When someone decides to fix a quirk, the fix goes through the TDD cycle. You write a red test for the correct behavior, then update or remove the matching characterization row.
Common errors
- Predicting values by reading the code. The agent computes
5.75in its head and gets6.25. Use probe output. - Fixing bugs while characterizing. The tests then describe code that doesn't exist yet, and the later diff mixes refactoring with new behavior.
- Weak assertions.
assert shipping_cost(1, "US") is not Nonepasses for nearly any change. Assert exact values. - One diff for tests and change. A reviewer can't tell whether an edited expectation was deliberate. Separate commits fix that.
- Skipping the break-it check. A mistyped import or an unused parametrize row can leave you with tests that never exercise the code.
Exercise
You ask an agent to add characterization tests for a function. The agent reports that all tests pass, but the diff also changes a line in the function itself, "to fix an obvious off-by-one bug." What is wrong, and what should you do?
Show answer
The agent broke the rule that characterization tests record current behavior and must pass against unmodified code. The tests now describe code that differs from what is in production, and the bugfix is hidden inside a test commit. Revert the source change, rerun the tests against the original code, and fix any test that fails. If the off-by-one is real, report it as a quirk and handle it later with a red test for the correct behavior in a separate TDD cycle.
Exercise
After characterizing shipping_cost, you change the code to treat lowercase country codes as domestic. Two characterization tests fail: (1, "us", False, 10) and (0, "US", True, 0). Which failure is expected, and what do you do about the other?
Show answer
The (1, "us", False, 10) failure is expected, because it pins the exact behavior you chose to change. Update its expected value to 5 in the same commit and say why. The (0, "US", True, 0) failure is not expected, because the change had nothing to do with zero weight or express fees. It means the change altered unrelated behavior, so inspect the diff, find the cause, and fix the code until that test passes again without editing the test.