Module 04 · Lesson 4.2
Finding Seams in Legacy Code
On this page
- What you will learn
- What a seam is, and why tests need one
- Worked scenario: price_order cannot reach its database
- Step-by-step workflow: add a parameter seam
- Choosing between a parameter, a patch and other seams
- Risks of the seam edit itself
- Using an AI assistant to find seams
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Think of the plug socket on your wall. You can plug in a lamp, a kettle or a tester. You do not rewire the house to do it. The socket is a place where one part can be swapped for another.
Code has such places too. We call them seams. In this lesson you will find a seam in a Tidewell Wholesale function that reads from a database, make one tiny edit, and write your first test. The company and data are invented.
What you will learn
- Explain what a seam is, using plain words and an example.
- List what a function reaches out to, such as a database, the clock or a network.
- Add a parameter seam with the smallest edit that keeps the old behaviour.
- Choose between a parameter, a patch and other seams, and explain your choice.
Before you start
- You have read What Characterization Tests Are.
- You know how to read a git diff and run pytest.
- You have a function in your own repository that is hard to test, and you may change it.
What a seam is, and why tests need one
A seam is a place where you can change what the code uses without editing the code at that place. The word comes from sewing: a seam is where two pieces of cloth join, and you can open it without cutting the cloth.
Why do tests need seams? A test must run fast, on any machine, and give the same answer every time. Code that talks to a database, the clock or the internet does not do that. You need a way to swap those parts for simple stand-ins.
- Dependency
- Something your code needs from outside itself, such as a database, a file, the current time or another service. Like the ingredients a recipe needs from the shop.
- Test double (stand-in)
- A simple replacement for a real dependency, used in tests. A crash-test dummy is a stand-in for a person. A dictionary of prices is a stand-in for a price table.
- Seam
- A place where you can swap a dependency for a stand-in without changing the surrounding logic.
| Kind of seam | How it works | Size of edit |
|---|---|---|
| Parameter with a default | The function takes the dependency as an argument. The default is the real one. | Small. Callers do not change. |
| Wrapper function | Move the risky call into one small function. Swap that function. | Small to medium. |
| Patching | A test tool replaces a name in a module for the length of one test. | None in production code. Test code only. |
| Subclass and override | A test version of a class replaces one method. | Medium. Needs a class. |
Worked scenario: price_order cannot reach its database
In the real service, price_order looks up each product's price in the database. In outline, the Django code looks like this. It is an excerpt, so there is no output.
from catalogue.models import Product
def price_order(lines, band):
for sku, q in lines:
p = Product.objects.get(sku=sku).list_price # reads the database
...In this lesson we use a simplified version, so you can run it without Django. A file called catalogue/prices.py stands in for the database. It always fails, like a database that is not switched on.
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=""):
g = Decimal("0.00")
for sku, q in lines:
p = list_price(sku)
if band == "Contract":
p = contract_unit_price(p, contract_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 hard-wired version. The function calls list_price and contract_discount directly.
Now try the obvious first test. It calls price_order and checks that a small Standard order pays delivery.
from invoicing.totals import price_order
def test_small_standard_order_pays_delivery():
result = price_order([("NAP-100", 10)], "Standard")
assert str(result["delivery"]) == "7.50"F [100%]
================================== FAILURES ===================================
___________________ test_small_standard_order_pays_delivery ___________________
tests\test_first_try.py:5: in test_small_standard_order_pays_delivery
result = price_order([("NAP-100", 10)], "Standard")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
invoicing\totals.py:10: in price_order
p = list_price(sku)
^^^^^^^^^^^^^^^
catalogue\prices.py:2: in list_price
raise RuntimeError("cannot connect to the database")
E RuntimeError: cannot connect to the database
=========================== short test summary info ===========================
FAILED tests/test_first_try.py::test_small_standard_order_pays_delivery - Run...
1 failed in 0.05sThe test is fine. The function reached for the database inside its own body, and there is nothing to swap. Timings vary between runs.
Step-by-step workflow: add a parameter seam
Step 1: List what the function reaches out to
Read the function and write down every outside thing it touches: database calls, the clock, files, the network, global settings. In
price_orderthere are two: the price lookup and the contract discount lookup.What you should see: A short list of dependencies.
Step 2: Find every caller
Search for the function name, so you know who will be affected. In the real service the callers are the portal view, the EDI importer and the replay command.
Bash git grep -n "price_order("What you should see: A list of call sites. You will check each one after the edit.
Step 3: Choose the smallest seam
Prefer a parameter with a default. If the default is the real function, every existing caller keeps working without a change.
What you should see: One sentence: 'Add get_list_price and get_discount parameters, defaulting to the real lookups.'
Step 4: Make the edit, and nothing else
Add the parameters. Use them where the function called the real lookups. Do not rename, reformat or fix anything in the same commit.
What you should see: A diff of a few lines.
Step 5: Check that old callers behave the same
Read each call site: it passes no new arguments, so it gets the default, which is the old lookup. If you can, run one real path, such as placing a test order in a development copy.
What you should see: Evidence that production behaviour is unchanged.
Step 6: Write the test with stand-ins
Pass dictionaries instead of the database, as in What Characterization Tests Are.
What you should see: A passing test with no database.
Step 7: Commit the seam edit alone
Use a message that says what it is, such as 'Add get_list_price and get_discount parameters to price_order'. If anything goes wrong, one revert removes it.
What you should see: A one-purpose commit.
- List dependencies
What does it reach for?
- Find callers
Who will be affected?
- Pick smallest seam
Parameter with default
- Make the edit
Nothing else
- Check callers
Same behaviour
- Test with stand-ins
No database
The edit is small on purpose. It is the only untested change in the whole process.
The seam edit, as a real git diff
diff --git a/invoicing/totals.py b/invoicing/totals.py
index cc1996d..195e4f0 100644
--- a/invoicing/totals.py
+++ b/invoicing/totals.py
@@ -4,12 +4,12 @@ from catalogue.prices import contract_discount, list_price
from legacy.pricing_v1 import contract_unit_price
-def price_order(lines, band, account=""):
+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 = list_price(sku)
+ p = get_list_price(sku)
if band == "Contract":
- p = contract_unit_price(p, contract_discount(account))
+ 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)What each part does:
- Lines starting with
-were removed. Lines starting with+were added. - The signature gets two new parameters. Their defaults are the real lookups, so
price_order(lines, band, account)still works. - The two calls inside the function now go through the parameters. The logic around them did not change.
from decimal import Decimal
from invoicing.totals import price_order
PRICES = {"NAP-100": Decimal("1.25")}
def test_small_standard_order_pays_delivery():
result = price_order([("NAP-100", 10)], "Standard", get_list_price=PRICES.__getitem__)
assert str(result["delivery"]) == "7.50". [100%]
1 passed in 0.01sPRICES.__getitem__ is a dictionary's own lookup used as a function. It answers get_list_price("NAP-100") with Decimal("1.25").
Choosing between a parameter, a patch and other seams
A parameter is not the only way in. Python's unittest.mock.patch can swap a name inside a module just for one test. Here it is on the hard-wired version, with no edit to production code.
from decimal import Decimal
from unittest.mock import patch
from invoicing.totals import price_order
def test_small_standard_order_pays_delivery():
with patch("invoicing.totals.list_price", return_value=Decimal("1.25")):
result = price_order([("NAP-100", 10)], "Standard")
assert str(result["delivery"]) == "7.50". [100%]
1 passed in 0.07sIt works. So why not always patch? The table below shows the trade.
| Parameter seam | Patching | |
|---|---|---|
| Edit to production code | A few lines | None |
| Test reads like | Plain call with arguments | Needs the exact module path as text |
| If you move the function | Tests still work | The patch path breaks silently or loudly |
| Good for | Code you will keep and refactor | A first test on code you cannot touch yet |
Risks of the seam edit itself
There is an irony here. The edit that lets you add tests is made before the tests exist. So it is the riskiest edit in the whole job. Keep it so small that you can check it by eye.
- Keep behaviour identical. The default must be the old call, not a copy of it.
- Change nothing else. No renames, no tidy-ups, no fixes in the same commit.
- Do not add a second code path just for tests. A test-only branch such as
if TESTING:means tests no longer run the real code. - Read every caller. A caller that passes arguments by position may now send a value into the wrong slot.
- Ask a second person to read the diff. Four lines are easy to review.
Using an AI assistant to find seams
An assistant can read a long function and list its dependencies quickly. It can also suggest the smallest edit. But it cannot see your callers, so it cannot tell you what the edit will break.
- Ask it to list dependencies and propose seams. Do not ask it to rewrite the function.
- Ask for the smallest edit and a diff only.
- Make the edit yourself, or apply its diff, then read every line.
- Do the caller check with your own search. Do not rely on its list.
The prompt library has a related prompt: Safe Extract-Function Refactoring.
Conclusion and your next step
A seam is a place where you can swap a dependency without editing the logic around it. List what the code reaches for, find its callers, add the smallest seam, check the callers, and commit the edit alone. Then write tests with stand-ins.
Your next step: you now have tests for single cases. Continue with Golden Master and Approval Tests to capture the output of many orders at once, so you can detect any change, even in cases you did not think of.
Further reading: the book *Working Effectively with Legacy Code* by Michael Feathers is the classic source for seams. On this site, see Legacy Modernization with AI: The Strangler Fig Pattern and Characterization Tests and Safe Refactoring.
Reusable prompt
Seam finder
Gets a list of a function's outside dependencies and the smallest possible seam edits, without letting the assistant rewrite the code.
I want to write tests for a legacy Python function that is hard to test. Help me find seams. Do NOT rewrite the function.
Function (simplified, synthetic):
def price_order(lines, band, account=""):
g = Decimal("0.00")
for sku, q in lines:
p = list_price(sku) # reads the database
if band == "Contract":
p = contract_unit_price(p, contract_discount(account)) # reads the database
...
Answer in this order:
1. A list of everything the function reaches out to (database, clock, files, network, settings), each with the line it is on.
2. For each one, the SMALLEST seam that would let a test replace it, and why. Prefer a parameter with a default that is the current behaviour.
3. For the best option, a diff only. Change nothing else: no renames, no formatting, no fixes.
4. What I must check before I trust the edit (callers, positional arguments, default values).
If you cannot see something, say so instead of guessing.Show the reusable template
Replace each {{placeholder}} with your own details.
I want to write tests for a legacy {{language}} function that is hard to test. Help me find seams. Do NOT rewrite the function.
Function (code I am allowed to share):
{{function_code}}
Answer in this order:
1. A list of everything the function reaches out to (database, clock, files, network, settings), each with the line it is on.
2. For each one, the SMALLEST seam that would let a test replace it, and why. Prefer a parameter with a default that is the current behaviour.
3. For the best option, a diff only. Change nothing else: no renames, no formatting, no fixes.
4. What I must check before I trust the edit (callers, positional arguments, default values).
If you cannot see something, say so instead of guessing.Expected output and limitations
A numbered answer: a list of dependencies with line references, one small seam per dependency, a short diff for the best option, and a list of checks. There should be no rewritten function and no unrelated changes.
1. Dependencies
- list_price(sku): database read, once per line
- contract_discount(account): database read, Contract band only
2. Smallest seams
- Add get_list_price=list_price and get_discount=contract_discount parameters.
Defaults keep today's behaviour, so callers do not change.
3. Diff
-def price_order(lines, band, account=""):
+def price_order(lines, band, account="", get_list_price=list_price, get_discount=contract_discount):
... (two call lines change to use the parameters)
4. Check before trusting
- Every caller passes lines, band and account in that order.
- No caller passes more than three positional arguments.
(I cannot see the callers. Please search for them.)Limitations to keep in mind
- The assistant can only see what you pasted. It cannot tell you who calls the function.
- It may suggest a bigger change than you need, such as a class. Choose the smallest.
- Its diff may include bonus edits. Remove any that are not the seam.
- This sample is illustrative. Your assistant's answer will be worded differently.
Common errors and how to fix them
The seam edit also changes logic
Why it happens: While in the function, a small fix or rename looks free.
Fix: Revert everything except the seam. Do the other change in its own commit, after the tests exist.
The default is a copy of the real lookup, not the real lookup
Why it happens: The author wanted a version that is easier to test.
Fix: Make the default the same object production already used, so production behaviour cannot drift from tests.
Tests patch so much that they no longer test the real code
Why it happens: Every dependency was replaced, including ones that are safe and fast.
Fix: Replace only what is slow, random or outside your control. Let the real logic run.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Add a seam to one function in your own repository
Pick a function that cannot be tested because of one outside dependency. Add the smallest seam, check its callers, and write one passing test with a stand-in.
You will need
- A function that reads a database, a file, the clock or a network service.
- Your repository's search tool, such as
git grep. - Permission to make a small change.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- If the dependency is the clock, pass the time in as a parameter with a default that reads the real clock.
- If the function is inside a class, a wrapper method on the class may be the smallest seam.
- If you used an assistant, note which parts of its diff you removed.
Show a model answer
A good answer shows a tiny diff: one new parameter, one changed call, and a default that equals the old behaviour. The caller list proves nobody is affected. The test uses a dictionary or a lambda as a stand-in. A weak answer rewrites half the function, adds a test-only branch, or never checks the callers. If you cannot make the function testable with a few lines, consider patching for a first test and plan a larger change later with the team.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. A seam is about substitution: you change what the code uses, not the logic around it. It is not a bug, and it is not a test. A seam only makes tests possible.
Show the answer and explanation
Answer: B. The default keeps every existing caller behaving as before. A fake default would quietly change production. Forcing every caller to pass a value means editing all callers, which is a bigger and riskier change.
Show the answer and explanation
Answer: B. The seam edit is the one change made without tests, so it must be tiny and checkable. Extra edits make it hard to review. An explanation of the renames does not reduce the review burden.
Frequently asked questions
Do I need a seam for every dependency?
No. Only for the ones that make tests slow, random or hard to set up, such as a database or the clock. Fast, plain code can run for real in a test.
Is adding a parameter safe?
It is usually safe when the new parameters have defaults equal to the old behaviour, and you checked every caller. Keep the edit tiny and commit it alone, so you can undo it with one revert.
What is the difference between a seam and a mock?
A seam is the place where a swap is possible. A mock is one kind of stand-in you can put there. You need the seam first. Then a dictionary, a simple function or a mock can fill it.
What if I cannot change the code at all?
Then patch from the test, as shown above, to write your first tests. Once those tests exist, you can add a proper seam with more confidence.
- 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.
- unittest.mock: mock object library(opens in a new tab)
Python Software Foundation · Official documentation · How patch works.
- git-grep Documentation(opens in a new tab)
Git project · Official documentation · Finding callers.
- How to use fixtures(opens in a new tab)
pytest · Official documentation · Another way to supply stand-ins in pytest.
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.