Sub topic 6
Pinning down current behavior with characterization tests
This chapter assumes you can read Python and run pytest. It also assumes you know basic Git, and that you have used a coding agent on a small task. Earlier chapters covered scoping a task and using commits as checkpoints. This chapter covers the safety net that sits under both.
What a characterization test is
A characterization test records what code does today. It does not check what the code should do. You run the existing code, observe its output, and write that output into an assertion.
This differs from a normal unit test. A unit test comes from a specification: "prices are shown with two decimals and a thousands separator." A characterization test comes from observation: "format_price(1234.5) returns "$1,234.50"." If the code has a bug, the test records the bug too.
That is the point. In a refactoring, the goal is to change the structure of the code while the observable behavior stays the same. You cannot check that without a record of the current behavior. When an agent edits your code, the record becomes your main way to detect behavior drift, which is a change in output that nobody asked for.
Why this matters more with an agent
An agent can rewrite many lines quickly and report success. Several things make that risky on code without tests:
- The agent reads the code and infers its intent. Where the code is odd, the agent may "fix" the oddity.
- The agent may run the existing tests, see them pass, and stop. If the tests do not cover the changed lines, a passing run proves little.
- Edge cases such as empty input, zero, negative numbers, and
Noneare the first things to change in a rewrite.
A characterization test suite gives the agent and you the same fixed target. The instruction "keep these tests green" is concrete and checkable.
The workflow
The order matters. Tests are written and committed first, on unchanged code, so that a later failure can only come from the refactoring.
A worked example
Here is the code to be refactored. It lives in pricing.py.
# pricing.py
def format_price(amount):
if amount is None:
return "n/a"
return "${:,.2f}".format(amount)First, choose inputs. Cover the normal case, the boundaries, and anything that looks surprising. Then run the code to see the real outputs. A quick script does this:
# explore.py
from pricing import format_price
for value in [1234.5, 0, -5, 0.005, 1e6, None]:
print(repr(value), "->", repr(format_price(value)))Running python explore.py prints:
1234.5 -> '$1,234.50'
0 -> '$0.00'
-5 -> '$-5.00'
0.005 -> '$0.01'
1000000.0 -> '$1,000,000.00'
None -> 'n/a'Two of these are worth a pause. A negative price renders as $-5.00, not -$5.00. The value 0.005 rounds to $0.01, but that depends on floating-point representation. You may think both are bugs. Record them anyway. Fixing a bug is a separate change from refactoring, and mixing the two makes failures hard to diagnose.
Now write the test file:
# tests/test_pricing.py
import pytest
from pricing import format_price
@pytest.mark.parametrize(
"value, expected",
[
(1234.5, "$1,234.50"),
(0, "$0.00"),
(-5, "$-5.00"), # looks wrong, but it is current behavior
(1e6, "$1,000,000.00"),
(None, "n/a"),
],
)
def test_format_price_current_behavior(value, expected):
# Expected values were recorded by running the existing code,
# not derived from a specification.
assert format_price(value) == expectedThe 0.005 case is left out on purpose. Its result depends on how the float is stored. A test that depends on it could fail on a different platform for reasons unrelated to your change. Leave out cases you cannot make stable, and say so in a comment or in your task description.
Run the tests on the unchanged code:
pytest tests/test_pricing.pyAll tests must pass before any refactoring starts. Then commit:
git add tests/test_pricing.py
git commit -m "Add characterization tests for format_price"Choosing what to record
You cannot test every input. Choose inputs that exercise each branch and each boundary of the code you will touch.
| Category | Examples | Why it matters |
|---|---|---|
| Typical values | `1234.5` | Confirms the main path |
| Boundaries | `0`, empty list, one-element list | Rewrites often break the edges |
| Odd values | negative numbers, very large numbers | Reveals formatting and overflow quirks |
| Missing data | `None`, empty string | Error handling is easy to alter by accident |
| Errors | inputs that raise exceptions | The exception type and message are behavior |
Test the code at the level where it will be used. If you refactor the inside of format_invoice but callers only see its return value, assert on the return value. Tests tied to internal helper functions will break when the refactoring legitimately moves those helpers.
Characterizing a function that returns structure
The same method works for richer results. Here is the invoice function from the extract-function example:
# invoice.py
def format_invoice(items):
subtotal = sum(i["price"] * i["qty"] for i in items)
tax = round(subtotal * 0.2, 2)
return {"subtotal": subtotal, "tax": tax, "total": subtotal + tax}# tests/test_invoice.py
from invoice import format_invoice
def test_format_invoice_typical():
items = [{"price": 10.0, "qty": 2}, {"price": 5.0, "qty": 1}]
assert format_invoice(items) == {"subtotal": 25.0, "tax": 5.0, "total": 30.0}
def test_format_invoice_empty():
assert format_invoice([]) == {"subtotal": 0, "tax": 0, "total": 0}
def test_format_invoice_rounds_tax():
items = [{"price": 0.333, "qty": 1}]
result = format_invoice(items)
assert result["tax"] == 0.07The empty-list case is a good catch. sum([]) returns the integer 0, so subtotal is 0, not 0.0. In Python 0 == 0.0 is true, so the assertion passes either way, but a type-sensitive caller could notice the difference. If the type matters to your callers, assert on it explicitly with isinstance.
Asking the agent to help
The agent is good at the tedious part: generating many inputs and recording outputs. Keep one rule. The agent must record outputs by running the code, not by reasoning about what the code should return. A model that predicts outputs can write a plausible value that is wrong, and the test then fails on unchanged code or, worse, encodes a false expectation.
A prompt that enforces this:
Write characterization tests for format_price in pricing.py.
Rules:
- Do not edit pricing.py.
- Create tests/test_pricing.py only.
- Choose inputs that cover each branch plus 0, negative, very large, and None.
- Get each expected value by running the function, then paste the actual output into the assertion.
- Mark any case that looks like a bug with a comment, but do not change the expected value.
- Run `pytest tests/test_pricing.py` and report the result.When the agent finishes, review the test file as carefully as you would review code. Check three things:
- The expected values match what you saw when running the code yourself on a few inputs.
- The tests did not call mocks that replace the code under test.
- The pre-existing source files have no changes in
git diff.
Common problems
- Tests that pass for the wrong reason. A test that asserts nothing, or asserts something always true, protects nothing. Check that your suite can fail. Make a deliberate change to the code, such as altering
0.2to0.3, and confirm a test goes red. Then revert it. This quick check is a small form of mutation testing. - Non-deterministic output. Timestamps, random values, dictionary ordering in old Python versions, and floating-point rounding all make recorded values unstable. Freeze the clock, seed the random generator, or leave those fields out of the assertion.
- Over-specified tests. Asserting the exact text of a long log message or a full HTML page makes the test fail on harmless changes. Assert the parts that callers depend on.
- Snapshots approved without looking. Snapshot tools write the current output to a file for you. They are convenient, but running them with an "update all" flag silently accepts any change. Never let the agent regenerate snapshots during a refactoring.
- Deleting a failing test. If the agent's change breaks a characterization test, the correct response is to fix the code or discard the step. Editing the expected value is acceptable only when you have decided the behavior should change, and that decision belongs in a separate commit.
When the behavior should change
Sometimes a characterization test exposes a real bug, such as the $-5.00 format. You have two good options:
- Keep the test as is, finish the refactoring, then make a separate commit that fixes the bug and updates the one assertion.
- Mark the test with
pytest.mark.xfailand a reason, so the suite stays green while the bug is tracked.
Either way, the refactoring commits stay pure. A reviewer can then trust that a green test run means no behavior changed.
Exercises
Exercise
You run an existing function and it returns "$-5.00" for an input of -5. A teammate says the correct format is "-$5.00". Should the characterization test assert "$-5.00" or "-$5.00" during the refactoring, and why?
Show answer
It should assert "$-5.00". A characterization test records current behavior. Changing the format is a behavior change, so it belongs in a separate commit after the refactoring. That keeps a failing test during the refactoring a reliable sign that the refactoring itself changed behavior.
Exercise
An agent writes characterization tests and reports they all pass. Name two checks you can do to confirm the tests are worth trusting.
Show answer
Any two of: confirm git diff shows no edits to the source files; spot-check a few expected values by running the code yourself; deliberately change the source (for example a constant) and confirm at least one test fails, then revert; check that no mocks replace the code under test.