Module 04 · Lesson 4.1
What Characterization Tests Are
On this page
- What you will learn
- What a characterization test is
- Worked scenario: the price_order function at Tidewell
- Step-by-step workflow: write characterization tests
- The first characterization tests, with pytest
- Pinning odd behaviour without fixing it
- Using an AI assistant to draft characterization tests
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Imagine you move into a flat the last tenant left in a mess. Before you move a single chair, you take photos of every room. If something looks wrong later, you can check the photos. You will know what was there before you touched it.
A characterization test is a photo of code. It records what the code does today, whether that is right or not. This lesson shows how to write these tests for a long function nobody dares to change, using the fictional Tidewell Wholesale order service. The people and data are invented.
What you will learn
- Explain what a characterization test is and how it differs from an ordinary unit test.
- Write pytest tests whose expected values come from running the code, not from guessing.
- Pin surprising behaviour with a clear name, without fixing it.
- Check that your tests would really fail if the behaviour changed.
Before you start
- You have read Fixing and Proving the Fix or know how to write a regression test.
- You can run pytest, or another test tool, on your own machine.
- You have a function with real logic and no tests, in a repository you may work in.
What a characterization test is
Most tests say what code should do. A characterization test says what code does. You run the code, see the answer, and write that answer into the test.
Why do this? Old code has users and money attached to it. Nobody remembers every rule. If you change it without a safety net, you may break a rule nobody wrote down.
- Legacy code
- Code that is in use, that you did not write, and that has no tests. Think of an old bridge: people cross it daily, but there are no drawings.
- Characterization test
- A test that records current behaviour. It is the photo of the room before you move the furniture.
- Pinning
- Fixing a behaviour in place with a test, so it cannot change by accident. Like pinning a note to a board.
| Ordinary unit test | Characterization test | |
|---|---|---|
| Question it asks | Is the code right? | Is the code the same as before? |
| Where the expected value comes from | A rule, a spec or a person | Running the code |
| If the code is wrong | The test fails | The test still passes |
| When you write it | While building | Before changing old code |
Worked scenario: the price_order function at Tidewell
Tidewell's order service calculates every order total in invoicing/totals.py, in a function called price_order. It is long and has no tests. In an earlier module you fixed contract rounding in legacy/pricing_v1.py. Now the team wants to add a minimum order value, and they want to tidy this function first.
Nobody wants to tidy a function that sets what customers pay without a safety net. So you write characterization tests first. The code below is a simplified version of the service's code, so you can run it without Django.
| Rule in the code | What it does |
|---|---|
| Band | Each customer has a price band: Standard, Volume or Contract. |
| Volume band | 5% off any line with 20 or more units. |
| Contract band | The unit price comes from contract_unit_price, using the customer's contract discount. |
| Delivery | £7.50 when the goods total is below £50.00, for the Standard band only. |
| VAT | 20% of goods plus delivery, rounded once at the end, half up. |
from decimal import Decimal, ROUND_HALF_UP
from catalogue.prices import contract_discount, list_price
from legacy.pricing_v1 import contract_unit_price
def price_order(lines, band, account="", get_list_price=list_price, get_discount=contract_discount):
g = Decimal("0.00")
for sku, q in lines:
p = get_list_price(sku)
if band == "Contract":
p = contract_unit_price(p, get_discount(account))
t = p * q
if band == "Volume" and q >= 20:
t = (t * Decimal("0.95")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
g = g + t
d = Decimal("0.00")
if band == "Standard" and g < Decimal("50.00"):
d = Decimal("7.50")
v = ((g + d) * Decimal("0.20")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
return {"goods": g, "delivery": d, "vat": v, "total": g + d + v}The function before any tests or refactoring. The one-letter names are the original style.
What each part does:
linesis a list of(sku, qty)pairs. A SKU is a product code, such asNAP-100for napkins.get_list_priceandget_discountfetch prices. In the real service they read the database. Here they are parameters, so tests can pass plain dictionaries. The next lesson shows how to make this change safely.- The loop prices each line. Contract customers get the contract unit price. Volume customers get 5% off big lines.
deliveryis added for small Standard orders.vis the VAT. The function returns four amounts, allDecimal.
Step-by-step workflow: write characterization tests
Step 1: Pick one function and say what you want to protect
Write one sentence, such as: 'Everything
price_orderreturns for any band.' A small target keeps the work short.What you should see: A one-line scope in your notes.
Step 2: Make it runnable in a test
If the function needs a database or the clock, find a seam first. A seam is a place where you can swap a part without editing the code around it. Finding Seams in Legacy Code covers this. Here the prices already arrive as parameters.
What you should see: You can call the function from a test with no database.
Step 3: Guess, then ask the code
For each case, write down what you think will happen. Then run the code and look. A short throwaway script is enough. Wrong guesses are useful: each one shows a rule you had not understood.
Pythonprobe.py from decimal import Decimal from invoicing.totals import price_order PRICES = {"NAP-100": Decimal("1.25"), "CUP-250": Decimal("0.18")} def show(label, lines, band): result = price_order(lines, band, get_list_price=PRICES.__getitem__) print(label, "->", {k: str(v) for k, v in result.items()}) show("small Standard order", [("NAP-100", 10)], "Standard") show("lower-case band ", [("NAP-100", 10)], "standard") show("zero-quantity line ", [("NAP-100", 0), ("CUP-250", 10)], "Standard")A throwaway script. You do not commit it.
What you should see: A list of real answers, one per case.
Step 4: Write the real answer into a test
Copy the value the code gave you into the test as the expected value. Do not 'correct' it. If it looks odd, keep it and read the next step.
What you should see: A test that passes on the untouched code.
Step 5: Cover normal, edge and surprising cases
Normal: typical orders. Edge: the exact boundary, such as £50.00 or 20 units. Surprising: input nobody planned for, such as a quantity of zero or a band written in lower case.
What you should see: At least one case in each group.
Step 6: Name the oddities
Put
CURRENT_BEHAVIOURin the name of any test that pins something odd. The name tells the next reader: this is what the code does, not necessarily what it should do.What you should see: Odd behaviour is labelled, not hidden.
Step 7: Break the code on purpose
Change one number in the function and run the tests. If nothing fails, the tests are not protecting that line. Put the number back afterwards.
What you should see: Proof that the tests can fail.
Step 8: Commit the tests on their own
The commit holds tests only, with no change to the function. Later, if a test fails, you know the code changed, not the test.
What you should see: A clean starting point in git history.
small Standard order -> {'goods': '12.50', 'delivery': '7.50', 'vat': '4.00', 'total': '24.00'}
lower-case band -> {'goods': '12.50', 'delivery': '0.00', 'vat': '2.50', 'total': '15.00'}
zero-quantity line -> {'goods': '1.80', 'delivery': '7.50', 'vat': '1.86', 'total': '11.16'}Look at the second line. A reader would guess that the lower-case band standard is the same as Standard and pays £7.50 delivery. The code gives 0.00. That is the first surprise. We come back to it below.
- Pick a function
One small target
- Make it runnable
Find a seam
- Guess, then run
Ask the code
- Write the answer
Expected = observed
- Add edges and surprises
Name the odd ones
- Break it on purpose
Tests must fail
The last step is the one people skip. Do not skip it.
The first characterization tests, with pytest
Here is the test file. It uses pytest.mark.parametrize. That is a way to run one test with many sets of inputs, like one recipe cooked with several shopping lists.
from decimal import Decimal
import pytest
from invoicing.totals import price_order
PRICES = {
"NAP-100": Decimal("1.25"),
"CUP-250": Decimal("0.18"),
"FOIL-30": Decimal("4.95"),
"STR-500": Decimal("0.50"),
}
DISCOUNTS = {"TC7-0042": Decimal("10")}
def price(lines, band, account=""):
return price_order(
lines,
band,
account,
get_list_price=PRICES.__getitem__,
get_discount=DISCOUNTS.__getitem__,
)
def money(result):
return tuple(str(result[k]) for k in ("goods", "delivery", "vat", "total"))
@pytest.mark.parametrize(
"lines, band, account, expected",
[
([("NAP-100", 10)], "Standard", "", ("12.50", "7.50", "4.00", "24.00")),
([("NAP-100", 40)], "Volume", "", ("47.50", "0.00", "9.50", "57.00")),
([("NAP-100", 40)], "Contract", "TC7-0042", ("45.20", "0.00", "9.04", "54.24")),
([("CUP-250", 3), ("FOIL-30", 1)], "Standard", "", ("5.49", "7.50", "2.60", "15.59")),
],
)
def test_normal_orders(lines, band, account, expected):
assert money(price(lines, band, account)) == expected
@pytest.mark.parametrize(
"qty, expected_goods",
[(39, "48.75"), (40, "50.00"), (41, "51.25")],
)
def test_standard_delivery_is_charged_only_below_fifty_pounds(qty, expected_goods):
result = price([("NAP-100", qty)], "Standard")
charged = result["delivery"] == Decimal("7.50")
assert (str(result["goods"]), charged) == (expected_goods, qty < 40)
@pytest.mark.parametrize(
"qty, expected_goods",
[(18, "22.50"), (19, "23.75"), (20, "23.75"), (21, "24.94")],
)
def test_volume_discount_starts_at_twenty_units(qty, expected_goods):
assert str(price([("NAP-100", qty)], "Volume")["goods"]) == expected_goods
def test_volume_line_total_rounds_half_up_to_the_penny():
assert str(price([("STR-500", 23)], "Volume")["goods"]) == "10.93"
def test_vat_is_rounded_once_on_goods_plus_delivery():
assert money(price([("CUP-250", 1)], "Standard")) == ("0.18", "7.50", "1.54", "9.22")
def test_lowercase_standard_band_gets_no_delivery_charge_CURRENT_BEHAVIOUR():
result = price([("NAP-100", 10)], "standard")
assert result["delivery"] == Decimal("0.00")
def test_zero_quantity_line_is_kept_and_priced_at_zero_CURRENT_BEHAVIOUR():
result = price([("NAP-100", 0), ("CUP-250", 10)], "Standard")
assert money(result) == ("1.80", "7.50", "1.86", "11.16")What each part does:
PRICESandDISCOUNTSare plain dictionaries that stand in for the database.PRICES.__getitem__is the dictionary's own lookup, used as a function. It makesget_list_price(sku)return the price for that SKU.moneyturns the four amounts into text, so the expected values are easy to read.test_normal_ordersruns four typical orders. One of them is the 40-pack napkin order from the Module 3 bug.- The
deliveryandvolumetests check each side of a boundary: 39, 40 and 41 packs; 18 to 21 units. - The two
CURRENT_BEHAVIOURtests pin the oddities.
............... [100%]
15 passed in 0.02sTimings such as 0.02s vary from run to run. The passing count should not.
A surprise that is not a bug
Look at the volume test. Nineteen units cost £23.75. Twenty units also cost £23.75. That follows from the rules: twenty units at £1.25 is £25.00, and 5% off gives £23.75. It is not a coding mistake. But the sales team may like to know. Pin it, and tell them.
Check that the tests can fail
Now change the delivery charge in the function from 7.50 to 7.00, run the tests, and put it back. The tests should notice.
F..FF.......F.F [100%]
=========================== short test summary info ===========================
FAILED tests/test_price_order_characterization.py::test_normal_orders[lines0-Standard--expected0]
FAILED tests/test_price_order_characterization.py::test_normal_orders[lines3-Standard--expected3]
FAILED tests/test_price_order_characterization.py::test_standard_delivery_is_charged_only_below_fifty_pounds[39-48.75]
FAILED tests/test_price_order_characterization.py::test_vat_is_rounded_once_on_goods_plus_delivery
FAILED tests/test_price_order_characterization.py::test_zero_quantity_line_is_kept_and_priced_at_zero_CURRENT_BEHAVIOUR
5 failed, 10 passed in 0.02sFive tests failed, so the delivery charge is well protected. This check is a hand-made version of mutation testing, where a tool makes small deliberate breaks for you. The blog post Mutation Testing Explained: Why Code Coverage Lies to You explains the idea.
Pinning odd behaviour without fixing it
Two things in price_order look wrong. You will be tempted to fix them. Do not, not yet.
- Lower-case band. Delivery is charged only when
band == "Standard". A few old customer records store the band asstandard. Those customers never pay delivery. - Zero quantity. A line with a quantity of zero is kept and priced at £0.00. It is not rejected.
============================= test session starts =============================
collecting ... collected 15 items / 13 deselected / 2 selected
tests/test_price_order_characterization.py::test_lowercase_standard_band_gets_no_delivery_charge_CURRENT_BEHAVIOUR PASSED [ 50%]
tests/test_price_order_characterization.py::test_zero_quantity_line_is_kept_and_priced_at_zero_CURRENT_BEHAVIOUR PASSED [100%]
====================== 2 passed, 13 deselected in 0.02s =======================Why not fix them now? There are three reasons.
- Callers may depend on them. An EDI customer might send zero-quantity lines as placeholders. Some customers may be getting free delivery by agreement.
- A fix mixed into a cleanup makes failures impossible to read. You would not know which change broke which test.
- The right answer is a business decision. It belongs to the finance systems contact, not to you.
Using an AI assistant to draft characterization tests
An assistant is good at listing test cases quickly. It is bad at knowing what your code does. It reads names and comments and guesses what the code should do. Then it writes that guess as the expected value. The test fails, or worse, you 'fix' the code to match.
So split the job. Let the assistant propose inputs. You run the code and record the outputs.
- Give it the function and ask for a table of inputs only: normal, edge and surprising.
- Run each input yourself and write down the real result.
- Ask it to turn your table into pytest code. Expected values come from your table.
- Run the break-it check from the workflow. Assistant-written tests often pass without testing anything.
The prompt library has a ready-made version: Characterisation Tests for Legacy Code.
Conclusion and your next step
A characterization test records what code does today. You take the expected value from running the code, cover normal, edge and surprising cases, name the odd ones, and prove the tests can fail. Pinned behaviour is not approved behaviour: it is just known.
Your next step: the function in this lesson was easy to test because prices arrive as parameters. Most legacy code is not so kind. Continue with Finding Seams in Legacy Code to learn how to make hard-to-test code testable with a tiny edit.
Further reading: the book *Working Effectively with Legacy Code* by Michael Feathers gave this field its vocabulary. On this site, see Golden Master Testing: Safely Refactoring Legacy Code Without Specs and the module overview Characterization Tests and Safe Refactoring.
Reusable prompt
Characterization test input planner
Gets a list of test inputs from an assistant while you keep control of the expected values by running the code yourself.
I need characterization tests for a legacy Python function. A characterization test records what the code DOES today, even if that looks wrong.
Task: propose test INPUTS only. Do not write expected outputs. I will run the code and record the real results.
Function (simplified, synthetic data):
def price_order(lines, band, account="", get_list_price=..., get_discount=...):
# lines are (sku, qty) pairs; bands are "Standard", "Volume", "Contract"
# Volume: 5% off lines with qty >= 20. Contract: unit price from contract_unit_price.
# Standard: delivery 7.50 when goods < 50.00. VAT 20% on goods + delivery.
Return a table with the columns: id, band, lines, why this case matters.
Include at least 4 normal cases, 4 edge cases (exact boundaries) and 3 surprising cases (unusual input such as zero quantity, different letter case, empty order).
Rules: do not say what the output "should" be; do not suggest changing the code; if you are unsure what a line of code does, say so instead of guessing.Show the reusable template
Replace each {{placeholder}} with your own details.
I need characterization tests for a legacy {{language}} function. A characterization test records what the code DOES today, even if that looks wrong.
Task: propose test INPUTS only. Do not write expected outputs. I will run the code and record the real results.
Function (code I am allowed to share, with synthetic data):
{{function_code}}
Return a table with the columns: id, inputs, why this case matters.
Include at least {{normal_count}} normal cases, {{edge_count}} edge cases (exact boundaries) and {{surprising_count}} surprising cases (unusual input).
Rules: do not say what the output "should" be; do not suggest changing the code; if you are unsure what a line of code does, say so instead of guessing.Expected output and limitations
A table of inputs with a reason for each, grouped into normal, edge and surprising cases. It should name boundaries from the code, such as 20 units and £50.00, and it should not predict results.
id band lines why this case matters
N1 Standard [("NAP-100", 10)] typical small order, pays delivery
E1 Standard [("NAP-100", 40)] goods exactly 50.00: boundary of the delivery rule
E2 Volume [("NAP-100", 20)] first quantity that gets the 5% discount
S1 standard [("NAP-100", 10)] band in lower case: not the same text as "Standard"
S2 Standard [("NAP-100", 0), ("CUP-250", 10)] a zero-quantity line next to a normal line
S3 Standard [] empty order (unsure what the code does here)Limitations to keep in mind
- The assistant has not run the code. Every row is only a suggestion until you run it.
- It may miss a rule that is easy to see only in the full code, such as how Contract prices are rounded.
- It may repeat the same kind of case many times. Check that the boundaries in your function are all covered.
- This sample is illustrative. Your assistant's wording and table will differ.
Common errors and how to fix them
The expected values come from a guess or from the assistant, not from running the code
Why it happens: It feels faster to write what 'should' happen.
Fix: Run the code first. Copy the real result. If you disagree with it, keep the test and write the question in a note.
The tests pass but would not notice a change
Why it happens: The assertions are too weak, such as 'the result is not None'.
Fix: Check exact values. Then break one number in the code on purpose and confirm that tests fail.
Odd behaviour is fixed during the same change
Why it happens: The bug looks obvious and the fix is one line.
Fix: Pin it with a CURRENT_BEHAVIOUR test, write it in a note, and ask the owner. Fix it later in its own commit.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Characterize one function in your own repository
Choose one function with real logic and no tests, in a repository you are allowed to work in. Write characterization tests for it and prove they can fail.
You will need
- A function with at least three branches (if, else or loops).
- A way to call it from a test. If it needs a database, use the next lesson to find a seam first.
- A notes file for odd behaviour.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- Start with the branches. One test per branch is a good first target.
- If you cannot choose, pick the function that people are most afraid to change.
- If an assistant helped, record which test cases you added, changed or dropped.
Show a model answer
A good answer has a short table of cases, a test file where each expected value is exact, and a notes file with one or two oddities. The proof of quality is the break-it log: three changes, each caught. A weak answer has one test per function that only checks that the result is not empty, or expected values copied from comments. Those pass even when the code is broken.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The aim is to record current behaviour, so you run the code and keep the answer. A rule or a name tells you what the code should do, which may differ. That is the tempting mistake, because it feels more careful.
Show the answer and explanation
Answer: B. These tests say 'same as before', not 'correct'. Deleting the test hides the behaviour. The bug is real, but it needs a separate decision and fix.
Show the answer and explanation
Answer: B. A change that no test notices shows a gap in your safety net. Calling the tests fine is the tempting answer because they are green, but green with no protection is false comfort.
Frequently asked questions
Is a characterization test the same as a unit test?
It is written like a unit test, but it has a different purpose. A unit test checks that code is right. A characterization test checks that code has not changed. The expected value comes from running the code.
What if the current behaviour is a bug?
Pin it anyway and name the test so people can see it is odd. Then decide with the owner whether to change it. Fix it in its own commit, so a failing test always has a clear cause.
How many characterization tests do I need?
Enough to cover each branch and each boundary of the code you plan to change. For a short function that may be 8 to 15 cases. For larger output, the next lessons add a golden master.
Can an AI assistant write these tests?
It can suggest inputs and write the boilerplate. It cannot know what your code does without running it. Take the expected values from real runs, and check that the tests fail when you break the code.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- How to parametrize fixtures and test functions(opens in a new tab)
pytest · Official documentation · The pytest feature used for the case tables.
- pytest documentation(opens in a new tab)
pytest · Official documentation
- decimal: Decimal fixed-point and floating-point arithmetic(opens in a new tab)
Python Software Foundation · Official documentation · Why money is stored as Decimal.
- Refactoring Catalog(opens in a new tab)
Martin Fowler · Names for the small refactorings you will use after these tests exist.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.