Skip to content

Module 04 · Lesson 4.2

Finding Seams in Legacy Code

45 minUpdated 19 Nov 2026Part of Characterization Tests and Safe Refactoring · Existing Project Engineering
On this page
  1. What you will learn
  2. What a seam is, and why tests need one
  3. Worked scenario: price_order cannot reach its database
  4. Step-by-step workflow: add a parameter seam
  5. Choosing between a parameter, a patch and other seams
  6. Risks of the seam edit itself
  7. Using an AI assistant to find seams
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. 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 seamHow it worksSize of edit
Parameter with a defaultThe function takes the dependency as an argument. The default is the real one.Small. Callers do not change.
Wrapper functionMove the risky call into one small function. Swap that function.Small to medium.
PatchingA test tool replaces a name in a module for the length of one test.None in production code. Test code only.
Subclass and overrideA test version of a class replaces one method.Medium. Needs a class.
Start at the top. Move down only if the first kind does not fit.

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.

Pythoninvoicing/totals.py (real service, excerpt)
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.

Pythoninvoicing/totals.py
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.

Pythontests/test_first_try.py
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"
The first tryCaptured from a real run
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.05s

The 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

  1. 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_order there are two: the price lookup and the contract discount lookup.

    What you should see: A short list of dependencies.

  2. 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.

  3. 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.'

  4. 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.

  5. 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.

  6. 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.

  7. 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.

Making code testable with a seam
  1. List dependencies

    What does it reach for?

  2. Find callers

    Who will be affected?

  3. Pick smallest seam

    Parameter with default

  4. Make the edit

    Nothing else

  5. Check callers

    Same behaviour

  6. 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

git show of the seam commitCaptured from a real run
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.
Pythontests/test_seam_demo.py
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"
The same test idea, now with a seamCaptured from a real run
.                                                                        [100%]
1 passed in 0.01s

PRICES.__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.

Pythontests/test_patch_demo.py
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"
Patching the hard-wired versionCaptured from a real run
.                                                                        [100%]
1 passed in 0.07s

It works. So why not always patch? The table below shows the trade.

Parameter seamPatching
Edit to production codeA few linesNone
Test reads likePlain call with argumentsNeeds the exact module path as text
If you move the functionTests still workThe patch path breaks silently or loudly
Good forCode you will keep and refactorA first test on code you cannot touch yet
Patching is a good first step. A parameter is a better home.

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.

Sample responseIllustrative — your output will differ
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.

  1. 1.What is a seam?
    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.

  2. 2.You add a parameter with a default so a function can be tested. What should the default be?
    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.

  3. 3.An assistant's diff for the seam also renames two variables and fixes a typo. What do you do?
    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.

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.