Module 03 · Lesson 3.5
Fixing and Proving the Fix
On this page
- What you will learn
- Why the regression test comes before the fix
- Worked scenario: red, fix, green
- Step-by-step workflow: from confirmed cause to closed ticket
- Check how far the bug reaches
- Write the root-cause note
- Using an AI assistant to write the test and the note
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
A plumber who mops up a puddle has not fixed the leak. A good plumber finds the pipe, repairs it, then turns the water on and watches. In software, the watching is a test. It must fail while the leak exists and pass once the pipe is mended.
This lesson finishes the investigation. You write a regression test that fails before the fix, repair the real cause, show the same test passing, and write a short root-cause note that anyone can read. The example is the napkin invoice bug from the fictional Tidewell Wholesale, using a simplified copy of its code.
What you will learn
- Write a regression test that fails for the right reason before the fix.
- Fix the cause rather than the symptom, with the smallest safe change.
- Show a failing run and a passing run as proof, and check what else is affected.
- Write a root-cause note that separates trigger, cause and fix, and names who decides about past invoices.
Before you start
- Finish Debugging with an AI Assistant. You need a confirmed cause, not just a suspicion.
- pytest installed, and the practice repository or a repository of your own where you can run tests.
- Your reproduction card and your hypothesis log.
Why the regression test comes before the fix
A regression test is a test that guards against a bug coming back. You write it from the bug itself. If the bug ever returns, the test fails and tells you.
Order matters. Write the test first and run it against the broken code. If it fails, you have shown that the test can detect the problem. If you write the test after the fix, it passes from the start, and you never learn whether it would have caught anything.
- Red and green
- People call a failing test 'red' and a passing test 'green'. The aim is red before the fix and green after, with the same test.
- Symptom
- What people notice. Here: an invoice that is 40p too low.
- Trigger
- The kind of input that makes the problem appear. Here: a contract price whose exact value ends in a half penny.
- Root cause
- The reason in the code that makes the symptom happen. Here: float arithmetic and the built-in
round()in the contract price function. - Fix and workaround
- A fix removes the cause. A workaround only hides the symptom, such as adding a penny to invoices by hand.
Worked scenario: red, fix, green
You know the cause from the last three lessons. Contract prices use floats and the built-in round(). Finance wants each contract unit price rounded half up to the penny. You will write a test that states that rule.
Step 1: write the regression test
The test below lives in the same file as the old 'flaky' test. It checks four prices. Three are in the group that goes wrong, and one is a control: a price that needs no rounding, which should pass before and after the fix.
from decimal import Decimal
import pytest
from legacy.pricing_v1 import contract_unit_price
def test_contract_price_rounding():
assert contract_unit_price("1.25", 10) == Decimal("1.13")
@pytest.mark.parametrize(
"list_price, discount, expected",
[
("1.25", 10, "1.13"), # exact half penny: must round up
("1.15", 10, "1.04"), # float stores this just below the half
("1.50", 15, "1.28"), # same problem with another discount
("2.00", 10, "1.80"), # control: no rounding needed
],
)
def test_contract_unit_price_rounds_half_up(list_price, discount, expected):
result = contract_unit_price(list_price, discount)
assert Decimal(str(result)) == Decimal(expected)
def test_contract_unit_price_refuses_float_prices():
with pytest.raises(TypeError):
contract_unit_price(1.25, 10)The whole test file after the fix. The 'flaky' comment is gone.
What each part does
@pytest.mark.parametrize(...)runs one test function once for each row of data. It is like a recipe tried with four different ingredients.- Each row has a list price, a discount in percent and the expected unit price. Prices are strings, so no float error enters before the code under test.
Decimal(str(result))turns the answer into aDecimalfirst, so the test checks the value and not whether it is a float or a Decimal.- The first row is the original defect: 1.25 less 10% is exactly 1.125 and must be 1.13.
- The second and third rows are prices that floats store just below a half: 1.035 and 1.275.
- The fourth row, 2.00 less 10%, is the control. It is 1.80 with no rounding.
test_contract_unit_price_refuses_float_priceschecks the new rule that a float price is refused. The fix adds that rule.
A second test checks the original report at order level. It lives in tests/test_price_order.py, next to the other order tests.
def test_order_58213_contract_total():
total = price_order([("NAP-100", 40)], "Contract", PRICES, contract_discount=10)
assert total == Decimal("45.20")Added at the end of the file. Order 58213 in miniature.
Step 2: watch it fail
Run only the new test against the broken code. The -k option selects tests by part of their name.
python -m pytest -q --tb=short -k rounds_half_upFFF. [100%]
================================== FAILURES ===================================
____________ test_contract_unit_price_rounds_half_up[1.25-10-1.13] ____________
tests\test_contract_pricing.py:23: in test_contract_unit_price_rounds_half_up
assert Decimal(str(result)) == Decimal(expected)
E AssertionError: assert Decimal('1.12') == Decimal('1.13')
E + where Decimal('1.12') = Decimal('1.12')
E + where '1.12' = str(1.12)
E + and Decimal('1.13') = Decimal('1.13')
____________ test_contract_unit_price_rounds_half_up[1.15-10-1.04] ____________
tests\test_contract_pricing.py:23: in test_contract_unit_price_rounds_half_up
assert Decimal(str(result)) == Decimal(expected)
E AssertionError: assert Decimal('1.03') == Decimal('1.04')
E + where Decimal('1.03') = Decimal('1.03')
E + where '1.03' = str(1.03)
E + and Decimal('1.04') = Decimal('1.04')
____________ test_contract_unit_price_rounds_half_up[1.50-15-1.28] ____________
tests\test_contract_pricing.py:23: in test_contract_unit_price_rounds_half_up
assert Decimal(str(result)) == Decimal(expected)
E AssertionError: assert Decimal('1.27') == Decimal('1.28')
E + where Decimal('1.27') = Decimal('1.27')
E + where '1.27' = str(1.27)
E + and Decimal('1.28') = Decimal('1.28')
=========================== short test summary info ===========================
FAILED tests/test_contract_pricing.py::test_contract_unit_price_rounds_half_up[1.25-10-1.13]
FAILED tests/test_contract_pricing.py::test_contract_unit_price_rounds_half_up[1.15-10-1.04]
FAILED tests/test_contract_pricing.py::test_contract_unit_price_rounds_half_up[1.50-15-1.28]
3 failed, 1 passed, 8 deselected in 0.09s- '3 failed, 1 passed' is the line to read. The three rows in the group that goes wrong fail.
- Each failure says it got 1.12, 1.03 or 1.27, and wanted 1.13, 1.04 or 1.28. It fails for the right reason: a penny too low.
- The control row passes, which shows that the test does not simply fail for every input.
- '8 deselected' means that the other tests were not run this time.
Step 3: fix the cause
The cause is in contract_unit_price. The fix is to do the sum in Decimal and to round half up. A Decimal is Python's exact decimal type. ROUND_HALF_UP is the rule that sends a half upwards, as finance wants.
"""Contract pricing, kept from the original pricing service."""
from decimal import Decimal, ROUND_HALF_UP
PENNY = Decimal("0.01")
def _to_decimal(value):
"""Accept strings, ints and Decimals. Refuse floats."""
if isinstance(value, float):
raise TypeError("pass prices and discounts as str or Decimal, not float")
return Decimal(str(value))
def contract_unit_price(list_price, discount_percent):
"""Unit price for a contract customer, rounded half up to the penny."""
price = _to_decimal(list_price)
discount = _to_decimal(discount_percent)
unit = price * (Decimal(100) - discount) / Decimal(100)
return unit.quantize(PENNY, rounding=ROUND_HALF_UP)The function after the fix.
What each part does
PENNY = Decimal("0.01")is the size of the rounding step._to_decimalturns strings, whole numbers and Decimals intoDecimal. It refuses floats on purpose, with a clear message. A float may already carry the error you are removing.Decimal(str(value))converts through text, so '1.25' stays exactly 1.25.- The sum is price times (100 minus the discount) divided by 100. In
Decimal, 1.25 × 90 ÷ 100 is exactly 1.125. quantize(PENNY, rounding=ROUND_HALF_UP)rounds to the penny, with a half going up. 1.125 becomes 1.13.
This is the smallest change that removes the cause. price_order in the other file still wraps the result in Decimal(str(...)). That wrapper is now unnecessary but harmless. Leave it for a separate, tidy-up change. Keeping this diff small makes it easy to review.
Step 4: watch it pass
python -m pytest -q -k rounds_half_up
python -m pytest -q.... [100%]
4 passed, 8 deselected in 0.06s............ [100%]
12 passed in 0.03sThe same test went from red to green. The full run passes too. That includes test_contract_price_rounding, the old test that everyone ignored as 'flaky'. It was never flaky. It was describing this bug.
You can also run the reproduction from the first lesson again. It now shows what finance expects.
qty 1: expected 1.13, got 1.13 OK
qty 40: expected 45.20, got 45.20 OKStep-by-step workflow: from confirmed cause to closed ticket
Step 1: Name the behaviour you want
Say it in one sentence, with its source: 'Each contract unit price is rounded half up to the penny (finance policy).'
What you should see: A sentence the test will state.
Step 2: Write the regression test
Test at the smallest level that shows the defect, here one function. Include a control that should pass both before and after. Give the test a name that describes the behaviour.
What you should see: A test file change, not yet committed.
Step 3: Run it and see red for the right reason
Read the failure message. It should show the symptom you reproduced, not a typing mistake or a missing import.
What you should see: A saved failing run.
Step 4: Make the smallest fix at the cause
Change only what the cause needs. Do not tidy nearby code in the same change.
What you should see: A small diff.
Step 5: Run it again and see green
Run the new test, then the whole suite. Run your original reproduction too.
What you should see: A saved passing run, and no new failures.
Step 6: Check what else is affected
Search for other callers of the function, and estimate how many cases the bug touched. See the next section.
What you should see: A short scope note.
Step 7: Write the root-cause note and commit
Record trigger, cause, fix and open questions. Put the ticket number and the reason in the commit message.
What you should see: A commit and a note that a reviewer can follow.
- Confirmed cause
Float and round()
- Regression test
Written first
- Red
Fails for the right reason
- Smallest fix
Decimal, half up
- Green
Test and suite pass
- Write-up
Trigger, cause, fix
The same test is red before and green after.
Check how far the bug reaches
A fixed function is not the end. Ask who else the bug touched. In the real service you would list every caller of contract_unit_price and look at recent contract invoices. In this practice copy, you can at least estimate how common the problem is.
"""How wide is the problem? Count wrong contract prices."""
from decimal import Decimal, ROUND_HALF_UP
wrong = total = 0
for pence in range(50, 501): # list prices 0.50 to 5.00
for disc in (5, 10, 15, 20): # common contract discounts
price = Decimal(pence) / 100
exact = price * (100 - disc) / 100
correct = exact.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
as_float = round(float(price) * (1 - disc / 100), 2)
total += 1
wrong += Decimal(str(as_float)) != correct
print(f"{wrong} of {total} price and discount pairs come out one penny low")54 of 1804 price and discount pairs come out one penny low- The loops try every list price from 0.50 to 5.00, in steps of one penny, with four common discounts.
correctis the half-up answer inDecimal.as_floatis what the old code gave.wrong += ...counts one each time the two differ.- The result is a small share of cases, about three in a hundred. It is an estimate from a sweep. It is not the number of wrong invoices.
Whether to correct past invoices is not a developer's decision. It touches contracts, customer relations and accounting rules. Give the finance systems contact the facts: the date range from the culprit commit to the fix, and a list of the orders priced by the old code. They decide whether to issue credit notes or invoices.
Write the root-cause note
The note is for the next person, and for the reviewer today. Keep it to one page. Three words matter most: trigger, cause and fix. Keep them apart.
| Part | Question it answers | In this case |
|---|---|---|
| Symptom | What did people notice? | Invoice for 40 packs of NAP-100 was £44.80, not £45.20. |
| Trigger | Which inputs make it appear? | A contract unit price that is exactly a half penny, or that a float stores just below one. |
| Cause | What in the code does it, and since when? | Float arithmetic and built-in round() in contract_unit_price, introduced by 'Simplify contract pricing (drop Decimal)'. |
| Fix | What removes the cause? | Decimal arithmetic with ROUND_HALF_UP, floats refused, regression test added. |
# Contract prices were 1p low on some products (TC7-0042)
## Symptom
Order 58213 (40 packs of NAP-100, account TC7-0042) was invoiced at 44.80.
The accounts system expected 45.20. One pack was 1.12, expected 1.13.
## Trigger
A contract unit price whose exact value ends in a half penny
(1.25 less 10% = 1.125), or one that a float stores just below a half
(1.15 less 10%, 1.50 less 15%).
## Cause
contract_unit_price in legacy/pricing_v1.py used float arithmetic and the
built-in round(). round() sends an exact half to the even digit, and some
float products sit just below a half, so both lose a penny. Finance policy
is to round each contract unit price half up. The change came in with commit
4ad78b0, "Simplify contract pricing (drop Decimal)", dated 2025-06-02.
## Fix
Decimal arithmetic with ROUND_HALF_UP. Float inputs are refused.
Regression test: test_contract_unit_price_rounds_half_up (fails before the
fix, passes after). The older test_contract_price_rounding now passes too.
## Why it was not caught earlier
test_contract_price_rounding failed from 2025-06-02 and was marked "flaky"
on 2025-07-14. It was never flaky. Failing tests need an owner.
## Scope
About 3 in 100 price and discount pairs in a sweep of 0.50-5.00 with
discounts of 5, 10, 15 and 20 percent. This is an estimate, not a count
of invoices.
## Open questions (not for the developer to decide)
- Do past invoices from 2025-06-02 need correcting? Ask the finance
systems contact.
- Is the redundant Decimal(str(...)) wrapper in price_order worth a
tidy-up change? Ask the platform team lead.A short root-cause note. Roles are used instead of names.
Write it without blame. The aim is to explain how the bug happened and how to stop a repeat, not to find someone at fault. Google's guide to postmortem culture, listed in the references, describes this habit well.
Using an AI assistant to write the test and the note
An assistant is useful here. It can draft test cases and edge cases, and it can turn your facts into a clear write-up. It also brings two special risks.
- A test that never fails. A generated test may pass on the broken code. Always run it red first.
- A weakened test. If a generated fix does not make the test pass, an assistant may change the expected value in the test. Never accept a change to a test you wrote from policy.
- A wider fix than asked for. It may rewrite nearby code. Reject changes that the cause does not need.
- Invented facts in the note. Give it your evidence and ask it to mark anything it added.
Conclusion and your next step
You wrote a test that failed on the broken code, fixed the cause with the smallest change, and watched the same test pass. You checked how far the bug reaches and wrote a note that keeps trigger, cause and fix apart. Questions about past invoices went to the finance systems contact, where they belong.
Your next step: complete the module assignment on a defect in your own repository, with a reproduction, a hypothesis log, a failing-then-passing test and a root-cause note. Then start Characterization Tests and Safe Refactoring, where you protect untested code before you improve it.
To go further, read Golden Master Testing: Safely Refactoring Legacy Code Without Specs and Mutation Testing Explained: Why Code Coverage Lies to You. The module overview, Debugging and Root-Cause Analysis, lists the assignment.
Reusable prompt
Regression test and root-cause note drafter
Drafts a regression test from the stated rule, and a root-cause note from your evidence, while forbidding changes to the test's expected values.
Help me prove a fix. I will run every test myself.
Rule (source: finance policy): each contract unit price is rounded half up to the penny.
Defect: contract_unit_price("1.25", 10) returns 1.12 but must return 1.13. Also wrong: 1.15 with 10% (should be 1.04) and 1.50 with 15% (should be 1.28).
Cause (confirmed by experiments): float arithmetic and the built-in round() in legacy/pricing_v1.py, introduced by the commit "Simplify contract pricing (drop Decimal)".
Planned fix: Decimal arithmetic with ROUND_HALF_UP, floats refused with TypeError.
Test style: pytest, plain functions, parametrize for data.
Please give me:
1. A pytest regression test named test_contract_unit_price_rounds_half_up that includes the three failing prices and one control price that needs no rounding.
2. A reminder of how I should show that it fails before the fix.
3. A root-cause note with the headings Symptom, Trigger, Cause, Fix, Why it was not caught, Scope and Open questions. Keep trigger, cause and fix separate.
Rules: do not change the expected values to make a test pass; mark anything you added that is not in my facts; do not decide whether past invoices should be corrected, because that is a question for the finance systems contact.Show the reusable template
Replace each {{placeholder}} with your own details.
Help me prove a fix. I will run every test myself.
Rule (source: {{rule_source}}): {{behaviour_rule}}
Defect: {{defect_with_examples}}
Cause (confirmed by experiments): {{confirmed_cause}}
Planned fix: {{planned_fix}}
Test style: {{test_framework_and_style}}
Please give me:
1. A regression test named {{test_name}} that includes the failing examples and one control example that should pass before and after.
2. A reminder of how I should show that it fails before the fix.
3. A root-cause note with the headings Symptom, Trigger, Cause, Fix, Why it was not caught, Scope and Open questions. Keep trigger, cause and fix separate.
Rules: do not change the expected values to make a test pass; mark anything you added that is not in my facts; do not decide questions that belong to {{decision_owner_role}}.Expected output and limitations
A parametrised test with three failing rows and a control row, a reminder to run it red first, and a note with the seven headings. Trigger, cause and fix should be separate, anything added by the assistant should be marked, and open questions should go to a role, not be decided.
import pytest
from decimal import Decimal
from legacy.pricing_v1 import contract_unit_price
@pytest.mark.parametrize("price, discount, expected", [
("1.25", 10, "1.13"),
("1.15", 10, "1.04"),
("1.50", 15, "1.28"),
("2.00", 10, "1.80"), # control
])
def test_contract_unit_price_rounds_half_up(price, discount, expected):
assert Decimal(str(contract_unit_price(price, discount))) == Decimal(expected)
Run it before the fix: expect three failures and one pass.
Trigger: an exact half penny, or a float stored just below one.
Cause: float arithmetic and round() in contract_unit_price.
Open questions: past invoices (finance systems contact). [Added by me: none]Limitations to keep in mind
- The sample is illustrative. The assistant has not run the test, so you must show red and green yourself.
- It may produce a test that passes on the broken code. Run it before the fix every time.
- It may add facts about the scope or history that you did not give it. Delete or verify them.
- It cannot decide what to do about past invoices. That belongs to finance.
Common errors and how to fix them
Writing the test after the fix
Why it happens: The fix felt obvious, so the test seemed like a formality.
Fix: Stash the fix, run the test red, then restore the fix and run it green. Save both outputs.
Fixing the symptom
Why it happens: Adding a penny to the total, or rounding at the invoice level, makes the one reported case pass.
Fix: Fix the cause that the experiments confirmed, and test several prices, including a control.
Mixing cleanup into the fix
Why it happens: While in the file, you rename things and tidy the code.
Fix: Keep the fix diff small. Do the tidy-up as a separate change that has its own review.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Prove a fix on your own defect
Using the defect from your earlier exercises, write a regression test that fails first, fix the cause, show the test passing, and write a root-cause note.
You will need
- Your reproduction card, hypothesis log and the culprit commit if you found one.
- A test framework for the repository.
- The note layout from this lesson.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- To see red after you already wrote the fix, use
git stashon the fix or check out the commit before it. - If the test fails for a different reason, such as an import error, fix the test before you judge the code.
- If you cannot decide the expected value, that is a question for the owner of the rule. Ask before coding.
Show a model answer
A strong answer shows two pytest runs of the same test, red then green, and a diff of a few lines. The test has a control row and values beyond the reported one. The note reads easily: the symptom in the reporter's words, the trigger as a kind of input, the cause as a place in the code with the commit that introduced it, and the fix as the change plus the test. It ends with open questions for roles. A weak answer shows only a green run, fixes the single reported value and calls the cause 'a rounding bug'.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: A. A test that never failed has not been shown to detect the problem. 'Always start red' is a slogan, not the reason. It does not speed anything up.
Show the answer and explanation
Answer: B. Other failing rows show that the same cause is still active. Loosening the test hides it. Only checking the reported case is how the same bug returns under a different price.
Show the answer and explanation
Answer: B. Correcting invoices has money, contract and legal effects, so it is a business decision. The developer supplies the facts: dates and the list of affected orders. An assistant has no authority and no knowledge of the contracts.
Frequently asked questions
What is a regression test?
It is a test written from a bug that was found and fixed. If the bug ever comes back, the test fails and warns you. It keeps old mistakes from returning.
Why must the test fail before I fix the code?
A failing run proves that the test can detect the problem. If the test passes on broken code, it would also pass if the bug returned. Then it protects you from nothing.
What is the difference between cause and trigger?
The cause is the faulty place in the code, such as float arithmetic with round(). The trigger is the kind of input that makes it show, such as a price that ends in a half penny. Writing them apart helps reviewers see how wide the problem is.
Should I use Decimal for money in Python?
Yes, in most cases. Decimal does exact decimal sums and lets you choose the rounding rule, such as half up. Pass values as strings or Decimals, never as floats. Check your own organisation's rules for rounding.
- 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.
- decimal — Decimal fixed-point and floating-point arithmetic(opens in a new tab)
Python Software Foundation · Official documentation · Rounding modes and exact decimal arithmetic.
- How to parametrize fixtures and test functions - pytest documentation(opens in a new tab)
pytest · Official documentation
- git-revert Documentation(opens in a new tab)
Git project · Official documentation
- Google SRE - Blameless Postmortem for System Resilience(opens in a new tab)
Google · A blame-free way to write up what went wrong.
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.