FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

Lock down a client's legacy code before anyone touches it

Pin real output to a golden master, scrub out the noise, then break the code on purpose to prove the safety net catches failures.

ShareLinkedInFacebookX

In brief

  • Characterization tests record what code does, even when that looks wrong, so that every later change shows up.
  • If your tests pass before you have touched the code, the tests are probably the problem. Break the code yourself to make sure they catch failures.
  • A test suite that locks down behavior gives an agent a clear pass/fail signal when it changes a client's legacy code.
Diagram of five steps along a horizontal line: pick the boundary, write a failing test first, cover combinations, filter out noise, break the code yourself. Step 5 is shaded orange and labelled \"Must go red\". A dashed arrow loops from step 5 back to step 3, labelled \"Still green? Add edge cases\".
The final step checks the previous four: plant a small bug in the code. If the test suite stays green, go back and add boundary values to the list of combinations, and only then revert the bug.

Mark Seemann offers a warning that sounds backwards: if your tests pass before you have changed a single line of production code, the tests themselves are probably the problem. The warning comes from his writing on characterization tests, the kind the Stack Overflow blog calls “the regression tests nobody writes”.

For a forward deployed engineer, they are the tests most worth writing. You often arrive at a client to find a module that has run for years, that nobody dares to touch, and that you now have to change to integrate a new system. If you hand the change to an agent, you need even more urgently something that tells you what it just broke.

The guide below works through the steps in Python. The method is simple: run the code, see what it returns, and pin exactly that result in a test.

What you will build and what you need

Take a hypothetical client, a delivery company with a function shipping_fee(zone, weight) written long ago and full of nested if statements. You need to extract it so it can be called through an API. The goal is to lock down every current output of the function before you change a single line.

You need Python, pytest, the ApprovalTests library and coverage.py. ApprovalTests compares a test’s result with a golden master. If no golden master exists yet, it captures the current result as the golden master, which is what legacy code calls for.

pip install approvaltests
pip install coverage

Step 1: pick the smallest boundary that still means something

Hugo Teijiz, in a tutorial on freeCodeCamp, advises choosing the smallest test boundary that still captures meaningful behavior. In this example the boundary is the shipping_fee function, not the whole service and the database behind it.

If the function reads configuration or calls the network, find the nearest cut point where inputs and outputs are still clear. Too wide a boundary makes tests slow and noisy. Too narrow, and you lock down a few trivial details while missing the behavior the client actually relies on.

Step 2: write a test you know will fail

Seemann quotes Michael Feathers’ recipe: put the code in a test harness, then write an assertion you know will fail, so the failure message shows you the real behavior. ApprovalTests does this for you. A new test always fails on its first run because there is no .approved file yet.

# Import path shortened per the ApprovalTests.Python README;
# check it against the version you install.
from approvaltests import verify
from legacy.shipping import shipping_fee

def test_shipping_fee_inner_city():
    verify(shipping_fee("inner_city", 2.5))

Run pytest and the test goes red, producing a received file. Read that file, see the number the function actually returns, and copy it to the approved file. Run again and the test is green. From now on, any change to the function’s output turns the test red.

Step 3: cover many combinations, not a few hand-picked cases

A single case locks down very little. ApprovalTests.Python has verify_all_combinations, which generates every combination of the input lists you give it and writes them all to one golden master. The library’s documentation uses the example verify_all_combinations(is_awake, [["Monday", "Sunday"], ["7:00", "9:00", "11:00"]]). Applied to the shipping fee function:

# Import shortened; see the docs page "How to Test Combinations of Inputs".
from approvaltests.combination_approvals import verify_all_combinations

def test_shipping_fee_all_combinations():
    verify_all_combinations(
        shipping_fee,
        [["inner_city", "outer_city", "remote_province"],
         [0, 0.5, 2.5, 30, 31]],
    )

Three zones times five weights gives 15 combinations, all in a single approved file. To know whether that is enough, measure branch coverage: with the --branch flag, coverage.py measures branches taken, not just individual lines. The documentation gives the command as coverage run --branch myprog.py. To run it through pytest, use this variant:

coverage run --branch -m pytest

For any branch the report shows as untaken, add values to the input lists. When there are too many combinations to run them all, J. B. Rainsberger samples them. If the system has a random element, he seeds the generator with the same seed string every time, so the sample is repeatable between runs.

Step 4: scrub the noise before it hides the signal

Suppose the function also returns a receipt with a creation time and a generated order ID. The Stack Overflow blog warns about exactly this: timestamps and auto-generated IDs change on every run, and unless they are handled separately they drown out the real signal. The tests go red constantly, and the whole team learns to ignore red.

ApprovalTests.Python has a built-in scrubber for dates and times that replaces time values with a placeholder:

# Import shortened per the docs page "How to Scrub Dates".
from approvaltests import verify, Options
from approvaltests.scrubbers.date_scrubber import DateScrubber

def test_receipt():
    verify(
        create_receipt("inner_city", 2.5),
        options=Options().with_scrubber(
            DateScrubber.get_scrubber_for("00:00:00")),
    )

The string "00:00:00" is taken verbatim from the example in the library’s docs. The same principle applies to generated IDs: replace them with fixed values before comparing, and do not delete the field altogether.

Step 5: break the code to test the net

This is the step most often skipped. Seemann deliberately breaks the code under test, watches the assertion fail, then reverts. Nicolas Carlo, author of Understand Legacy Code, does the same: he plants a deliberate bug to confirm that at least one test fails.

With shipping_fee, change a > to >= at a weight threshold, or add 1 to one of the fees. If the suite stays green, your inputs never reached that threshold. Go back to step 3, add boundary values, and only then revert the bug.

Should you fix strange behavior when you find it?

This is the most common mistake. Reading the golden master, you will find things that look like bugs, such as a 0 kg parcel still being charged a fee. An engineer’s reflex is to fix it on the spot. Resist it.

Teijiz writes that characterization tests do not prove that the old behavior is correct, only that it exists. Suspicious behavior should be recorded as it is and investigated later. At a client, some reconciliation process may well depend on exactly that “wrong” number.

The safe approach is to flag the odd behavior in the test’s name and take it to whoever owns the business process. Fixing it is a separate change, with its own test and the client’s agreement.

At the client, the suite becomes the agent’s signal

The Claude Code best practices documentation advises giving an agent something it can run that returns pass or fail, such as a test file or a script that compares output with a fixture.

The golden master suite you have just built meets that requirement. Give the agent the job of extracting shipping_fee, with the condition that every approval test must stay green. It will know for itself when it has broken the old behavior.

The skill is also easy to demonstrate when job hunting. On a CV or in a portfolio, do not just write “refactored legacy code”. Describe how many input combinations you used to lock down behavior, how far branch coverage rose, and how you planted bugs to verify the net.

When an FDE job posting mentions a client’s existing systems or integration with legacy code, that is the moment to tell this story.

A client’s legacy code does not need you to believe it is correct. It needs you to know exactly what it does before you let anyone, human or agent, touch it.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
11 sources
Read next on the roadmap · Stage 2: Broad engineeringYour old secret may stop working the moment you click rotateStripe keeps old keys alive for up to seven days and OpenAI revokes them at once by default, so code must accept both secrets before anyone rotates.