Module 04 · Lesson 4.3
Golden Master and Approval Tests
On this page
- What you will learn
- What a golden master test is
- Worked scenario: sixty Tidewell orders in one file
- Step-by-step workflow: build and use a golden master
- When the output changes: reading the diff
- What a golden master cannot do
- Using an AI assistant with a golden master
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Have you ever played a spot-the-difference puzzle? You look at two pictures and find what changed. You do not need to know what each picture should look like. You only need to see where they differ.
A golden master test works the same way. You record the output of old code once. Every later run is compared with that recording. In this lesson you build a tiny one by hand for the Tidewell Wholesale price_order function. The company and data are invented.
What you will learn
- Explain what a golden master (approval) test is and when it beats single-case tests.
- Build a repeatable set of inputs, with no clock and no randomness.
- Write a comparison test that shows a clear diff when the output changes.
- Decide when to approve a change and when to reject it.
Before you start
- You have read Finding Seams in Legacy Code, or your code already runs in a test.
- You can run pytest and read a unified diff.
- A function in your repository that returns a lot of output, such as totals, reports or text.
What a golden master test is
In a normal test you write the expected answer by hand. That is fine for one order. It is too slow for sixty orders, or for a report with a thousand lines.
A golden master (also called an approval test) saves the full output of the code to a file the first time. That file is the master copy. On each later run, the test produces the output again and compares it with the file. Any difference is a failure.
- Golden master
- A saved copy of the output that you have looked at and accepted. Like the master recording a record is pressed from.
- Approved file
- The same thing, as a file in your repository. In approval tools it often has
approvedin its name. - Received output
- What the code produces on this run. It is compared with the approved file.
- Approving
- Deciding that a new output is correct, and saving it as the new master. It is a human decision.
| Single-case characterization test | Golden master test | |
|---|---|---|
| Best for | A few rules you can name | Many cases or large output |
| Expected value | Written in the test | Stored in a separate file |
| Failure message | One wrong value | A diff of every changed line |
| Weak spot | You may forget a case | Only covers the inputs you feed it |
Libraries exist for this. The ApprovalTests (opens in a new tab) project offers versions for many languages. In this lesson we build a tiny version by hand, so you can see every moving part.
Worked scenario: sixty Tidewell orders in one file
You have single-case tests for price_order. But the function has many paths: three bands, many quantities, many products. You want a wide net that catches a change in any of them.
So you build 60 synthetic orders. Six are chosen by hand to hit the odd spots: exactly £50.00, a lower-case band, a zero quantity, a half-penny rounding. The other 54 come from a tiny number machine that always gives the same numbers.
- Synthetic data
- Made-up data that looks real. It contains no customer information, so it is safe to commit and share.
- Deterministic
- Always giving the same result for the same input. A recipe is deterministic; a lucky dip is not.
import sys
from decimal import Decimal
from pathlib import Path
from invoicing.totals import price_order
PRICES = {
"NAP-100": Decimal("1.25"),
"CUP-250": Decimal("0.18"),
"LID-250": Decimal("0.07"),
"FOIL-30": Decimal("4.95"),
"STR-500": Decimal("0.50"),
}
DISCOUNTS = {"TC7-0042": Decimal("10"), "TC7-0107": Decimal("12.5")}
BANDS = ["Standard", "Standard", "Volume", "Contract", "standard", "Volume", "Standard"]
ACCOUNTS = ["TC7-0042", "TC7-0107"]
APPROVED = Path(__file__).parent / "golden" / "price_order.approved.txt"
HAND_PICKED = [
("Standard", "", [("NAP-100", 40)]),
("Standard", "", [("NAP-100", 39)]),
("standard", "", [("NAP-100", 39)]),
("Standard", "", [("NAP-100", 0), ("CUP-250", 10)]),
("Volume", "", [("STR-500", 23)]),
("Contract", "TC7-0042", [("NAP-100", 1)]),
]
def build_orders(count=60):
orders = list(HAND_PICKED)
seed = 12345
skus = sorted(PRICES)
while len(orders) < count:
n = len(orders)
band = BANDS[n % len(BANDS)]
account = ACCOUNTS[n % 2] if band == "Contract" else ""
lines = []
for _ in range(1 + n % 3):
seed = (seed * 1103515245 + 12345) % 2147483648
sku = skus[(seed >> 8) % len(skus)]
seed = (seed * 1103515245 + 12345) % 2147483648
lines.append((sku, (seed >> 8) % 45))
orders.append((band, account, lines))
return orders
def render(orders):
rows = []
for number, (band, account, lines) in enumerate(orders, start=1):
result = price_order(
lines,
band,
account,
get_list_price=PRICES.__getitem__,
get_discount=DISCOUNTS.__getitem__,
)
text = " ".join(f"{sku}x{qty}" for sku, qty in lines)
money = " ".join(f"{k}={result[k]}" for k in ("goods", "delivery", "vat", "total"))
rows.append(f"{number:02d} {band} {account or '-'} [{text}] {money}")
return "\n".join(rows) + "\n"
if __name__ == "__main__":
if "--approve" in sys.argv:
APPROVED.write_text(render(build_orders()), encoding="utf-8", newline="\n")
print(f"approved file written: {APPROVED.name}")
else:
sys.stdout.write(render(build_orders()))Builds the orders, renders the results as text, and can save the approved file.
What each part does:
HAND_PICKEDholds six orders written by hand for the tricky cases.build_ordersadds more orders. It uses a small formula (seed * 1103515245 + 12345) that works like a flip-book: the same start always gives the same pages. It does not use the clock or Python's random module, so every machine builds the same orders.BANDSrepeats a pattern, so every band appears, including the lower-casestandard.renderturns each order into one readable line. Readable lines make diffs easy to read.- Running the file with
--approvewrites the approved file. Running it without arguments prints the output.
The first six lines of the approved file look like this. Open yours and read it. Check a few lines by hand against the rules. A golden master is only as good as the review you gave it.
01 Standard - [NAP-100x40] goods=50.00 delivery=0.00 vat=10.00 total=60.00
02 Standard - [NAP-100x39] goods=48.75 delivery=7.50 vat=11.25 total=67.50
03 standard - [NAP-100x39] goods=48.75 delivery=0.00 vat=9.75 total=58.50
04 Standard - [NAP-100x0 CUP-250x10] goods=1.80 delivery=7.50 vat=1.86 total=11.16
05 Volume - [STR-500x23] goods=10.93 delivery=0.00 vat=2.19 total=13.12
06 Contract TC7-0042 [NAP-100x1] goods=1.13 delivery=0.00 vat=0.23 total=1.36Line 02 shows delivery=7.50: the goods are £48.75, below £50. Line 01 shows delivery=0.00: the goods are exactly £50.00. Line 03 shows delivery=0.00 for the lower-case band. Those three lines already tell the whole delivery story.
Step-by-step workflow: build and use a golden master
Step 1: Choose inputs that cover the paths
Include every band, both sides of each boundary, and the odd cases. Add some varied ordinary cases too. Aim for variety, not size.
What you should see: A list of inputs, hand-picked and generated.
Step 2: Remove anything that changes between runs
Dates, random numbers, ids, file paths and the order of dictionary keys can all change. Fix them or leave them out. If the output must hold one, replace it with a fixed word before saving. That is called scrubbing.
What you should see: Running the generator twice gives byte-identical output.
Step 3: Render the output as readable text
One line per case, with the inputs and the results together. You will read this file with your own eyes.
What you should see: A text format a person can review.
Step 4: Approve the first run, after reading it
Write the approved file once. Then read it. Check several lines by hand against what you know of the rules. Do not approve a file you have not read.
Bash python -m tests.golden_orders --approveWhat you should see: An approved file that you have looked at.
Step 5: Compare on every run
The test renders the output again and compares it with the file. If they differ, it fails and shows the diff.
What you should see: A test that fails on any change, in any of the 60 orders.
Step 6: Decide when something differs
Read the diff. If you did not mean to change behaviour, your change is wrong: fix your change. If you did mean it, approve the new output in its own commit, with a reason.
What you should see: A clear decision for each difference.
- Synthetic inputs
Same on every machine
- Run the code
Render as text
- Approve once
Read it first
- Compare each run
Received vs approved
- Decide on a diff
Fix code or re-approve
The only human step is the decision. The computer does the comparing.
Here is the comparison test and the result of running the generator command.
import difflib
import pytest
from tests.golden_orders import APPROVED, build_orders, render
def test_price_order_matches_the_approved_output():
approved = APPROVED.read_text(encoding="utf-8")
received = render(build_orders())
if received == approved:
return
diff = difflib.unified_diff(
approved.splitlines(),
received.splitlines(),
fromfile="approved",
tofile="received",
n=0,
lineterm="",
)
pytest.fail("price_order output no longer matches the approved file:\n" + "\n".join(diff), pytrace=False)What each part does:
APPROVED.read_textreads the saved master.render(build_orders())produces today's output.- If they match, the test ends and passes.
- If not,
difflib.unified_diffbuilds a diff.n=0leaves out unchanged lines, so only changed lines show. pytest.failreports the diff as the failure message.
approved file written: price_order.approved.txt
. [100%]
1 passed in 0.01sTimings vary. The approving message and the pass should not.
When the output changes: reading the diff
Now suppose someone changes how the Volume discount is rounded. The code uses round-half-up, and they switch to round-half-even (also called banker's rounding), which rounds an exact half to the nearest even digit. It looks harmless. The golden master disagrees.
F [100%]
================================== FAILURES ===================================
________________ test_price_order_matches_the_approved_output _________________
price_order output no longer matches the approved file:
--- approved
+++ received
@@ -5 +5 @@
-05 Volume - [STR-500x23] goods=10.93 delivery=0.00 vat=2.19 total=13.12
+05 Volume - [STR-500x23] goods=10.92 delivery=0.00 vat=2.18 total=13.10
=========================== short test summary info ===========================
FAILED tests/test_price_order_golden.py::test_price_order_matches_the_approved_output
1 failed in 0.01sHow to read it:
- Lines starting
-are from the approved file. Lines starting+are from this run. - Only order 05 changed. Its goods dropped from £10.93 to £10.92, because 23 units of a 50p product give an exact half-penny.
- The VAT and total changed too, because they are built from the goods.
- One line of change in a 60-line file is easy to review. A change in all 60 lines would suggest a bigger problem.
What a golden master cannot do
A golden master only checks the inputs you gave it. If a change affects an input you never fed in, the test stays green. Here is a real example.
Change the Volume rule from qty >= 20 to qty > 20. This affects only orders with exactly 20 units. None of the 60 orders has a line of exactly 20 units.
. [100%]
1 passed in 0.02s
.........F..... [100%]
================================== FAILURES ===================================
____________ test_volume_discount_starts_at_twenty_units[20-23.75] ____________
tests\test_price_order_characterization.py:58: in test_volume_discount_starts_at_twenty_units
assert str(price([("NAP-100", qty)], "Volume")["goods"]) == expected_goods
E AssertionError: assert '25.00' == '23.75'
E
E - 23.75
E + 25.00
=========================== short test summary info ===========================
FAILED tests/test_price_order_characterization.py::test_volume_discount_starts_at_twenty_units[20-23.75]
1 failed, 14 passed in 0.05sThe golden master passed. The single-case test for 20 units caught it. This is why the two layers belong together. Single-case tests guard the boundaries you know. The golden master guards the wide middle that you did not think of.
- Coverage gaps. Add inputs when you learn of a new rule, or when a bug is found.
- Rubber-stamp approvals. If people re-approve without reading, the file protects nothing.
- Noisy output. Dates, ids and ordering make every run differ. Scrub them or leave them out.
- Huge files. If nobody can read the diff, shrink the output or split it by area.
Using an AI assistant with a golden master
An assistant is useful here, in three jobs. It can draft the generator, suggest hand-picked edge cases, and write the comparison test. It must not approve anything.
- Ask it to suggest hand-picked inputs for each branch and boundary in the code you paste.
- Ask it to find sources of change between runs: clock, randomness, ordering, ids.
- Run the generator yourself and read the approved file. Check lines by hand.
- If an assistant offers to 'update the approved file to make the test pass', say no. A new approved file is a decision about behaviour.
Conclusion and your next step
A golden master records the output of many cases once and compares it on every run. Use synthetic, deterministic inputs; read the approved file; and treat every diff as a decision. Keep single-case tests for the boundaries, since the master covers only what you feed it.
Your next step: you now have two safety nets under price_order. It is time to use them. Continue with Small, Reversible Refactorings to improve the structure one small commit at a time.
Further reading: see the Practical Test Pyramid (opens in a new tab) for how different kinds of tests fit together, and the module overview Characterization Tests and Safe Refactoring.
Reusable prompt
Golden master input designer
Gets a deterministic set of inputs for an approval test, and a list of things that could make the output change between runs.
I am building a golden master (approval) test for a legacy Python function. I will approve the output myself after reading it. You must not approve or update any approved file.
Function (simplified, synthetic):
def price_order(lines, band, account="", get_list_price=..., get_discount=...): ...
Rules: bands are "Standard", "Volume", "Contract". Volume: 5% off lines with qty >= 20. Standard: delivery 7.50 when goods < 50.00. VAT 20% on goods + delivery.
Do these in order:
1. List 8 hand-picked orders that hit boundaries and odd cases (exact 50.00, qty 19/20/21, a lower-case band, qty 0, an empty order).
2. Describe a deterministic way to generate 50 more varied orders without using the clock or the random module.
3. List anything in a rendered output line that could change between runs (dates, ids, ordering, floating point) and how to remove it.
4. Say which rule you think no input covers yet.
Do not predict the outputs.Show the reusable template
Replace each {{placeholder}} with your own details.
I am building a golden master (approval) test for a legacy {{language}} function. I will approve the output myself after reading it. You must not approve or update any approved file.
Function (code I am allowed to share, with synthetic data):
{{function_code}}
Do these in order:
1. List {{hand_picked_count}} hand-picked inputs that hit boundaries and odd cases.
2. Describe a deterministic way to generate {{generated_count}} more varied inputs without using the clock or randomness.
3. List anything in a rendered output line that could change between runs and how to remove it.
4. Say which rule you think no input covers yet.
Do not predict the outputs.Expected output and limitations
A short list of hand-picked inputs that name each boundary, a repeatable way to generate more, a list of sources of change with fixes, and a note about uncovered rules. It should not contain predicted outputs or approved files.
1. Hand-picked
- Standard, NAP-100 x40 (goods exactly 50.00)
- Standard, NAP-100 x39 (just under 50.00)
- standard (lower case), NAP-100 x39
- Volume, NAP-100 x19, x20, x21
- Standard, NAP-100 x0 plus CUP-250 x10
- Standard, empty order
2. Generation
- Use a fixed seed and a small formula, such as a linear congruential generator.
3. Sources of change
- Dictionary order: sort the keys before rendering.
- Floats: this code uses Decimal, so write amounts as text.
4. Possible gap
- A Volume line whose 5% discount lands on an exact half penny.Limitations to keep in mind
- The assistant has not run your code. Treat every suggested input as a candidate.
- It may not see rules that are in other files, such as contract discounts.
- A generated set can still miss a boundary. Compare your inputs with the branches in the code.
- This sample is illustrative. Your assistant's answer will differ.
Common errors and how to fix them
The test fails on another machine or on a later day
Why it happens: The output contains something that changes: a date, an id, a random value, or dictionary order.
Fix: Find it by running the generator twice and comparing. Fix it or scrub it before saving.
The approved file was saved without being read
Why it happens: It was easy to run the approve command and move on.
Fix: Open the file. Check at least five lines by hand against the rules. Ask a colleague to look at the first approval.
A red test is turned green by re-approving
Why it happens: The diff was large or confusing, and re-approving was quick.
Fix: Do not re-approve until you understand each changed line. If you cannot explain it, revert your change.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Build a golden master for your own function
Take the function you characterized earlier, or another one with rich output. Build at least 30 synthetic cases, save an approved file, and prove that a deliberate change shows up as a readable diff.
You will need
- A function that returns text, totals or another output you can render as lines.
- A way to run it in a test, such as a seam.
- A short list of the boundaries in the code.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- If output is large, render one line per case and leave out anything that never changes.
- To find unstable output, run the generator twice and compare the two files.
- If an assistant helped, say which of its suggested inputs you kept.
Show a model answer
A good answer has a generator that is boring and repeatable, a readable approved file, and a log of the deliberate change with its diff. The gap check is the sign of understanding: you found an input the master misses, for example a boundary that no generated case reaches, and added a single-case test. A weak answer saves unreadable output, includes a timestamp so it fails the next day, or approves without looking.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The test did its job: it found a difference you did not intend. Re-approving is the tempting shortcut, but it records the accident as correct. Deleting the test removes the net.
Show the answer and explanation
Answer: B. A comparison needs the same output each time. Speed is not the issue. Tests may use them, but then you must fix a seed or scrub the output so the result is stable.
Show the answer and explanation
Answer: A. A golden master protects only the cases in it. That is why boundaries also need single-case tests. File size and number types are not the reason here.
Frequently asked questions
What is the difference between a golden master and an approval test?
They are two names for nearly the same idea. Both save an approved output and compare later runs with it. 'Approval test' is the name used by tools; 'golden master' is the older name for the saved file.
How many cases should a golden master have?
Enough to reach every branch and boundary, and no more than a person can review. Thirty to a few hundred short lines is common. Add a case whenever you find a rule it did not cover.
What if my output has dates or ids in it?
Replace them with fixed words before saving, or leave them out of the rendered text. This is called scrubbing. Without it, the test fails on every run.
Do I need a library to do this?
No. A small script and a diff, like the one here, is enough to start. Libraries add tidy diff tools, folders of approved files and helpers for many output types.
- 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.
- ApprovalTests(opens in a new tab)
ApprovalTests · Approval-testing libraries for many languages.
- difflib: Helpers for computing deltas(opens in a new tab)
Python Software Foundation · Official documentation · The standard library module used to show the diff.
- The Practical Test Pyramid(opens in a new tab)
Martin Fowler
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.