STAFFCHAPTER 30

AI agents in the test loop: generation, triage and what to verify

An agent writes tests fast and fixes red builds faster, and both jobs have a failure that looks like success: a suite that is green because nothing checks anything, and a fix that is green because the test was edited. Measure the first, and treat a changed expectation as a change to the specification

60 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-24
PREDICT

An agent writes ten tests for the checkout order code. They pass, and line coverage is 100%. A reviewer deletes the four tests that check nothing specific (one with soft assertions, two that compare the answer with itself, one that replaces the pricing with a canned answer), then runs the mutation tool on the module and its pricing code. Compared with the full ten, the mutation score of the remaining six is:

Testing AI features showed that a test file an assistant writes has high coverage and a mediocre mutation score, and that you close the gap by reading the survivors. That was one person, one file, one prompt. An agent changes the economics. It writes the file in a minute, so you now have far more tests to judge than you can read. It can also run, read a failure, change code and run again without you, which is useful and is also the first time in this course that the thing being judged can edit the judge. This chapter is about running that loop so the checks stay outside the agent’s reach.

Three jobs, three failures

An agent can sit in the test loop in three places. The failure in each is a result that looks like success.

Job The agent does The failure that looks like success What you verify
Generate Reads code, writes tests, runs them Green, high coverage, soft or circular assertions Mutation score and survivors; where each expected value came from
Triage Reads a red log, names a cause A confident narrative that is not the evidence Rerun rate, behaviour on the last green commit, the error type
Repair Edits until the build is green The test or the threshold is changed, not the fault The diff: which files, which assertions, what the specification says

The agent is good at the part of each job that is typing and pattern matching. It reads a stack trace quickly, it knows the library, it writes a parametrised test in seconds. It is weak where the job needs something it does not have: what the business meant, what is allowed to change, what a failure on Thursday at 02:00 would cost. Everything in the right-hand column of the table is a person supplying that.

There is a second reason to keep the checks outside. An agent told “make the build green” has a goal that the cheapest edit satisfies. Anyone who has watched an agent loop will have seen it: skip the test, widen the tolerance, add a retry, regenerate the snapshot. This is not malice. It is the shortest path to the stated goal. The AI Engineering chapter on agents explains the loop and why errors compound in it, and Anthropic’s note on building effective agents recommends testing them in sandboxes with guardrails for the same reason. In a test loop, the guardrails are the parts of the pipeline the agent cannot edit.

Generating: what the suite looks like

Run an agent over a module and the result has a recognisable shape. The lab ships one, written in the style agents produce (it is not captured from a tool, so yours will differ). It targets Ojaline’s checkout/orders.py, the order path that prices a cart, reserves stock, charges the provider and writes the order. Ten tests, all green, 100% line and branch coverage of orders.py. The flaws are the ones you will meet in real output:

  • Soft assertions. assert order["total_kobo"] > 0 and isinstance(order["id"], str). They say something came back.
  • The mirror. The charge amount equals the order total, and the total equals a quote computed by the same function. Neither compares with a number a person worked out, so any bug in pricing satisfies both.
  • Mocking the thing under test. The quote step is replaced by a canned answer, and the test asserts the canned number reaches the provider. It tests the mock.
  • The snapshot. A whole order dictionary pasted into the test, recorded from today’s output. It protects against change, which is not the same as protecting against being wrong, and when it breaks the usual fix is to paste the new output.
  • An unchecked side effect. The decline test checks that the error was raised and that the provider was called once. It never looks at stock. A declined order must put the stock back, and a paid one must keep it taken.
  • A drifted fake. The agent made an in-memory stand-in for the database, and its take_stock always succeeds. The real one refuses when there is not enough. No test can reach the out-of-stock path, because the fake cannot get there.

The last one is the mock-drift lesson again: a stand-in that does not behave like the real thing makes the tests that use it pass for the wrong reason.

▶ SIMULATION
CONSUMER UNIT TESTS
mock: amount: number
runs: —
REAL PROVIDER RESPONSE
id: "inv_101"
amount: 48200
status: "paid"
PRODUCTION CHECKOUT
last call: —
deploys blocked: 0
last—
✓ no production call fails while the consumer's unit tests are green
SCHEDULE
01[CONSUMER]unit tests run against the hand-written mock
02[PROVIDER]provider renames amount to total
03[PROVIDER]provider deploys (its own tests pass)
04[CONSUMER]unit tests run again: the mock has not changed
05[CONSUMER]production checkout calls the real API
06[CI]report
Start of break: the provider renames a field scenario. 6 steps.
// The consumer's test owns the mock. Nothing ties it to the provider.
const mockBilling = { id: 'inv_101', amount: 48200, status: 'paid' };

test('shows the amount', () => {
  const page = render(mockBilling);
  expect(page.total).toBe('₦482.00');   // green forever
});

Watch which side the drift is on. The real component changes, the fake does not, and every test stays green. An agent writing its own fake produces this on the first try, because it writes the fake to make its own tests pass.

Why coverage cannot see any of it

All six flaws are invisible to coverage, because every one of those tests runs the lines. This is the gap in the lesson below, and the same measurement closes it.

▶ SIMULATION
SUITE
calls every path, asserts fee >= 0
line coverage: —
CODE UNDER TEST
if (subtotal >= 5000) return 0;
let fee = 499;
if (member) fee -= 250;
return Math.max(fee, 0);
MUTANTS (build result)
—
last—
✓ the build is red whenever the code is wrong
SCHEDULE
01[TEAM]suite: calls every path, asserts fee >= 0
02[CI]run the suite on the real code, with coverage
03[MUTATOR]flip >= to >
04[MUTATOR]off by one: 5000 to 4999
05[MUTATOR]base fee 499 to 500
06[MUTATOR]member discount adds instead of subtracts
07[MUTATOR]drop the member line
08[CI]report
Start of break: 100% coverage, no assertions scenario. 8 steps.
// Every line runs, so coverage says 100%. Nothing checks the answer.
test('shippingFee runs', () => {
  expect(shippingFee(1000, false)).toBeGreaterThanOrEqual(0);
  expect(shippingFee(1000, true)).toBeGreaterThanOrEqual(0);
  expect(shippingFee(9000, false)).toBeGreaterThanOrEqual(0);
});

The measurement is the mutation score from Coverage and mutation testing. It changes the code in small ways and counts the changes the tests notice. In the lab it is 116 of 169 mutants killed, 69%, against 100% line coverage of the order code. The survivors are the useful part. One of them changes paid = True to paid = False in place_order. With that change every successful order puts its stock back, as if it had been declined, so the shelf never empties. All ten agent tests pass. That is a real bug class, and the file never looks at stock after a sale.

Closing the loop with the survivors

You can hand the survivors back to the agent. This is the design Meta described: generate tests aimed at mutants the existing tests miss, and keep a test only if it kills one. Foster and colleagues reported engineers accepting 73% of the tests in their test-a-thons, over 10,795 Kotlin classes; those tests were aimed at privacy hardening, so the figure is for that task. The mutant is a specification the agent can act on: here is a fault, write a test that fails with it.

A loop like that needs four limits, or it produces a different kind of mess.

  1. A budget. A number of rounds and a cap on tests added. Without one the loop buys score with test count.
  2. The mutation tool runs where the agent cannot edit it. If the agent can change pyproject.toml, it can shrink paths_to_mutate. Pin the configuration and the files it measures.
  3. Equivalent mutants are a person’s call. Some survivors cannot change any output. An agent asked to kill every survivor will write a contorted test for one, or declare one equivalent when it is not. A reader decides.
  4. A reading step. Each accepted test is read by someone who can say where its expected value came from. The score tells you which tests kill mutants. Only a person can tell you whether a kill means anything.

Liu and colleagues show the same effect from the other side. Their EvalPlus work added about eighty times as many tests to a popular code-generation benchmark, and the pass rates of the models fell by up to 19.3 to 28.9 percent: the old tests were too weak to notice wrong programs. Weak tests are the ordinary state of things, and an agent writes more of them, faster, unless you measure.

Triage: reading a red build

A red build has three kinds of cause, and each leaves a different trace.

Cause What it looks like The test that tells you
Flaky Fails on some runs of the same code Rerun 20 times on the last green commit. A rate above 0 and below 100% is the signature
A real bug Fails every run on the new code, passes on the old Run the same test on the last green commit. The difference between the two runs is the change
Environment Fails before test logic runs, or on one machine type Read the error type: a missing file, a missing time zone database, a version mismatch, a full disk

An agent is a good first reader. Give it a log and it will name the failing assertion and the likely cause in seconds, and for the environment class it is often right on the first try. Its failure is the story. A log is evidence, and a model reading it produces a plausible account that can be wrong while sounding certain. So the agent triages, and it must attach the evidence for its class: the rerun count for flaky, the result on the base commit for a real bug, the exact error line for environment. A claim without that is a guess.

Rerun counts need a little arithmetic. A test that fails on 40% of runs passes three reruns in a row about one time in five (0.6 to the third power is 0.22). So “it passed when I reran it” is weak evidence, and “it passed three times, so it is flaky and safe to ignore” is worse, because a real bug that shows only under some orders of events looks the same. The lesson on retries shows how a retry turns a visible bug into an invisible one.

The repair is where it goes wrong

Triage leads to a fix, and the fix is where an agent’s shortcut does damage. In the lab you triage three red runs on the lab code: A fails one test and a rerun passes, B fails one test on every run, C fails at collection before any test runs. Suppose an agent proposes one change for each.

  • Run A (flaky): wrap the test body in a loop that retries three times.
  • Run B (real bug): change the expected discount in the failing test from 50,000 kobo to 0.
  • Run C (environment): add the tzdata package to requirements.txt.

Only the third is a fix. The first hides the flake and leaves the suite slower to find the next one. The second is the worst, and the most tempting, because it turns the build green in one line and passes review: the diff is small and the test name matches. But the failing test was the one that checks an order of exactly ₦10,000 gets 5% off, which is the rule in pricing.py. The agent’s change records the bug as the specification. It is now a bug protected by a test.

The rule that follows is easy to state and has to be enforced by the pipeline, not by hope: a change to an expected value needs a reason that comes from the specification, and a person approves it. An agent that changes code and tests in the same pull request is marking its own homework. The checks that catch it are mechanical:

  • A diff that edits a test and the code that test covers is routed to a human.
  • A diff that adds skip, xfail, a retry or a wider tolerance, or deletes an assertion, fails a check by itself.
  • Thresholds, mutation config and the CI file are not writable by the agent’s credentials. The Security track’s chapter, Security review when AI agents write the code, covers what an agent’s credentials and tools should be allowed to touch. The Software Engineer track’s Working with AI coding agents covers the everyday habits of reviewing what one produces. Both are in the career tracks, not in this course.

What to verify, in order

Arrange the checks from cheap to expensive, and run the cheap ones on every agent pull request.

  1. A structural audit (seconds). A script that finds tests with no assertion, tests with mostly soft assertions, and tests that patch a name inside the module they claim to test. It cannot see a mirror. In the lab you write it in under sixty lines.
  2. Does the test fail for the right reason? Revert the change the test is meant to protect and check that the test goes red. A test never seen red has not been shown to test anything.
  3. Mutation score and survivors (a minute on a module). Compare with the same measure on the human-written suite. Read the survivors that matter.
  4. Where each expected value came from. For every number in an assertion, a person can say: the specification, a worked example, or “the code returned it”. The last is a snapshot, and it is acceptable where you have chosen to pin behaviour, as in a characterisation test of legacy code.
  5. The diff rules above, enforced.
  6. Keep it deterministic. Agent-written tests that touch the clock, the network or a random source go through the seams the suite already has. A test that sleeps is a future flake, and an agent writes them readily.

Two notes on the lab’s tooling. The mutation tool forks one child process per mutant. On macOS a forked child that opens a SQLite file crashes (a segfault) if the parent process used SQLite earlier, which the tool’s own first test run does. The lab README’s authors’ notes record this. That is why the agent’s file here uses an in-memory fake rather than the real database, and it is a reason to expect that a mutation run over database tests may need Linux. And the score belongs to a module and a test set: a suite of 20 tests can score better than one of 200.

Where it goes wrong

  • Reporting test count and coverage. Both rise for free with an agent. Report the mutation score and the survivors.
  • Letting the agent mark its own work. The agent that wrote the tests runs the mutation tool, reads the result and declares success. Run the measurement in a job it cannot edit.
  • Regenerating snapshots on red. The update flag exists for intended change. An agent uses it on every red.
  • Retries as a fix. A rerun that turns red into green is a decision to stop looking.
  • Triage without evidence. A paragraph of cause and no rerun count. Ask for the numbers.
  • An agent with write access to the tests and the thresholds. Every shortcut above becomes available at once.
  • Calling a model in the blocking build. The lab never does. Keep a real-model agent in its own job with a budget, and run the deterministic checks above in the build.
LAB Measure an agent's test file, triage three red builds, and decide what the agent may change ~60 MIN
YOU NEEDlabs/testing set up (README, 'Set up'), Python 3.9+no Docker, no servers, no network, no model: everything runs offlinea scratch database path: export CHECKOUT_DB=/tmp/agent-lab.sqlitelabs/testing/scripts/seed_bugs.py, used once in step 5 (the bugs were revealed in the seeded-bugs project)

You will run a test file an agent wrote, measure it with the mutation tool, audit it, triage three red builds, and then add the tests the survivors ask for. Work from labs/testing with the venv from the README. You create a test folder, one test file and one script, and you edit pyproject.toml temporarily. If you have a coding agent, you can also generate your own file in step 7. No paid account is needed for any step.

1. Add the agent’s file and run it. Make the folder and create tests/agent/test_orders_agent.py with the content below. It is a file in the style a coding agent produces for checkout/orders.py. It carries six flaws, and it ships its own in-memory stand-in for the database so the mutation tool can run it on macOS.

cd labs/testing
export CHECKOUT_DB=/tmp/agent-lab.sqlite
mkdir -p tests/agent && touch tests/agent/__init__.py
"""Tests for checkout.orders, in the style a coding agent produces when asked to
'add thorough tests for place_order'. Written for this chapter, not captured from a tool."""

from datetime import datetime, timezone
from unittest.mock import patch

import pytest

from checkout.clock import FakeClock
from checkout.orders import PaymentDeclined, UnknownProduct, place_order, quote_lines
from checkout.payments_client import ChargeResult
from checkout.pricing import Quote

ITEMS = [{"product_id": 2, "qty": 2}]

class FakeDb:
    """An in-memory stand-in for checkout.db.Database."""

    def __init__(self):
        self.products = {
            1: {"id": 1, "name": "Ankara fabric", "price_kobo": 1_200_000, "status": "published"},
            2: {"id": 2, "name": "Shea butter", "price_kobo": 350_000, "status": "published"},
            3: {"id": 3, "name": "Aso-oke cap", "price_kobo": 650_000, "status": "published"},
            4: {"id": 4, "name": "Prototype tote bag", "price_kobo": 900_000, "status": "draft"},
            5: {"id": 5, "name": "Test item", "price_kobo": 1_000_000, "status": "published"},
        }
        self.stock = {1: 50, 2: 100, 3: 5, 4: 10, 5: 5}
        self.orders = {}

    def get_product(self, product_id):
        return self.products.get(product_id)

    def take_stock(self, product_id, qty):
        self.stock[product_id] -= qty
        return True

    def give_stock(self, product_id, qty):
        self.stock[product_id] += qty

    def find_order_by_key(self, key):
        return self.orders.get(key)

    def save_order(self, key, total_kobo, charge_id, created_at, lines):
        order = {
            "id": "ord_%012d" % (len(self.orders) + 1),
            "idempotency_key": key,
            "status": "paid",
            "total_kobo": total_kobo,
            "charge_id": charge_id,
            "created_at": created_at.isoformat(),
            "lines": lines,
        }
        self.orders[key] = order
        return order

class StubPayments:
    def __init__(self, result=ChargeResult("ch_stub", "succeeded")):
        self.result = result
        self.calls = []

    def charge(self, reference, amount_kobo, idempotency_key):
        self.calls.append((reference, amount_kobo, idempotency_key))
        return self.result

@pytest.fixture
def db():
    return FakeDb()

@pytest.fixture
def payments():
    return StubPayments()

@pytest.fixture
def clock():
    return FakeClock(datetime(2026, 11, 23, 9, 0, tzinfo=timezone.utc))

def test_place_order_creates_an_order(db, payments, clock):
    order, created = place_order(db, payments, clock, ITEMS, "key-1", distance_km=3)
    assert created is True
    assert order is not None
    assert order["total_kobo"] > 0
    assert isinstance(order["id"], str)

def test_charge_amount_matches_order_total(db, payments, clock):
    order, _ = place_order(db, payments, clock, ITEMS, "key-2", distance_km=3)
    assert payments.calls[0][1] == order["total_kobo"]

def test_total_matches_the_quote(db, payments, clock):
    quote, _ = quote_lines(db, ITEMS, 3, clock, None)
    order, _ = place_order(db, payments, clock, ITEMS, "key-3", distance_km=3)
    assert order["total_kobo"] == quote.total

def test_total_comes_from_the_quote(db, payments, clock):
    fake = (
        Quote(900_000, 0, 0, 900_000, 67_500, 150_000, 1_117_500),
        [{"product_id": 2, "qty": 2, "unit_price_kobo": 350_000}],
    )
    with patch("checkout.orders.quote_lines", return_value=fake):
        order, _ = place_order(db, payments, clock, ITEMS, "key-4", distance_km=3)
    assert payments.calls[0][1] == 1_117_500
    assert order["total_kobo"] == 1_117_500

def test_order_snapshot(db, payments, clock):
    order, _ = place_order(db, payments, clock, ITEMS, "key-5", distance_km=3)
    snapshot = {k: v for k, v in order.items() if k != "id"}
    assert snapshot == {
        "idempotency_key": "key-5",
        "status": "paid",
        "total_kobo": 902_500,
        "charge_id": "ch_stub",
        "created_at": "2026-11-23T09:00:00+00:00",
        "lines": [{"product_id": 2, "qty": 2, "unit_price_kobo": 350_000}],
    }

def test_declined_payment_raises(db, clock):
    declining = StubPayments(ChargeResult("", "declined", "insufficient_funds"))
    with pytest.raises(PaymentDeclined):
        place_order(db, declining, clock, ITEMS, "key-6", distance_km=3)
    assert len(declining.calls) == 1

def test_unknown_product_raises(db, payments, clock):
    with pytest.raises(UnknownProduct):
        place_order(db, payments, clock, [{"product_id": 999, "qty": 1}], "key-7")

def test_draft_product_cannot_be_bought(db, payments, clock):
    with pytest.raises(UnknownProduct):
        place_order(db, payments, clock, [{"product_id": 4, "qty": 1}], "key-8")

def test_retry_with_the_same_key_returns_the_first_order(db, payments, clock):
    first, created_first = place_order(db, payments, clock, ITEMS, "key-9", distance_km=3)
    second, created_second = place_order(db, payments, clock, ITEMS, "key-9", distance_km=3)
    assert created_first is True
    assert created_second is False
    assert second["id"] == first["id"]
    assert len(payments.calls) == 1

def test_order_of_exactly_ten_thousand_naira_gets_five_percent_off(db, clock):
    quote, _ = quote_lines(db, [{"product_id": 5, "qty": 1}], 3, clock, None)
    assert quote.tier_discount == 50_000
.venv/bin/pytest tests/agent -q -p no:randomly -W ignore --cov=checkout.orders --cov=checkout.pricing --cov-branch

10 passed, and a coverage table that reads checkout/orders.py 40 0 10 0 100% and checkout/pricing.py 61 7 14 5 84%. The suite is green and the order code is fully covered. That is the report the pilot got.

2. Score it with the mutation tool. The lab’s config targets pricing.py and tests/unit/. Point it at the order code, the pricing code and the agent’s file, and keep a copy to restore afterwards. The edit is written in Python because sed -i differs between macOS and Linux.

cp pyproject.toml pyproject.toml.orig
python3 - <<'EOF'
s = open("pyproject.toml").read()
s = s.replace('paths_to_mutate = ["checkout/pricing.py"]', 'paths_to_mutate = ["checkout/orders.py", "checkout/pricing.py"]')
s = s.replace('tests_dir = ["tests/unit/"]', 'tests_dir = ["tests/agent/"]')
s = s.replace('"checkout/search_index.py"]', '"checkout/search_index.py", "checkout/inventory.py"]')
open("pyproject.toml", "w").write(s)
EOF
rm -rf mutants .mutmut-cache
.venv/bin/python scripts/mutate.py run 2>&1 | tr '\r' '\n' | grep "169/169" | tail -1
The last progress line reads 169/169 🎉 116 🫥 4 ⏰ 0 🤔 0 🙁 49 🔇 0: 116 killed of 169, a score of 69%, with 49 survivors and 4 mutants no test reached. Full line coverage of orders.py, and a third of the faults it was shown get through.

3. Read the survivors. Count them by function, then look at the one that matters most.

.venv/bin/python scripts/mutate.py results | sed 's/checkout\.//; s/__mutmut_[0-9]*:.*//' | sort | uniq -c
.venv/bin/python scripts/mutate.py show checkout.orders.x_place_order__mutmut_35

The first command lists 53 lines (the survivors plus the four unreached): 10 orders.x_place_order, 5 orders.x_quote_lines, 21 pricing.x_price_cart, 6 pricing.x_delivery_fee, 4 pricing.x_promo_applies, 3 pricing.x_line_total and four small ones in the two exception classes. The second prints a diff that changes paid = True to paid = False. With it, every paid order releases its stock again. The suite is green.

4. Audit the file. Create scripts/audit_agent_tests.py. It is the cheap first filter: it flags tests with no assertion, tests whose assertions are mostly soft, and tests that patch a name inside the module under test.

"""A cheap first filter for machine-written tests. It finds three shapes a reader should look at.

  .venv/bin/python scripts/audit_agent_tests.py tests/agent/test_orders_agent.py --module checkout.orders

NO-ASSERT    the test makes no assertion and no pytest.raises
SOFT         half or more of its assertions only say 'something came back' (> 0, is not None, isinstance)
MOCKS-OWN    it patches a name inside the module it claims to test

It cannot see a test whose expected value was computed by the code under test. That needs a person.
"""

import argparse
import ast
import sys

def is_soft(node):
    test = node.test
    if isinstance(test, ast.Call) and getattr(test.func, "id", "") == "isinstance":
        return True
    if isinstance(test, ast.Compare) and len(test.ops) == 1:
        op, right = test.ops[0], test.comparators[0]
        if isinstance(op, ast.IsNot) and isinstance(right, ast.Constant) and right.value is None:
            return True
        if isinstance(op, (ast.Gt, ast.GtE)) and isinstance(right, ast.Constant) and right.value in (0, 1):
            return True
    return False

def patches_module(call, module):
    name = getattr(call.func, "id", getattr(call.func, "attr", ""))
    if name != "patch" or not call.args:
        return False
    arg = call.args[0]
    return isinstance(arg, ast.Constant) and isinstance(arg.value, str) and arg.value.startswith(module + ".")

def audit(path, module):
    tree = ast.parse(open(path).read())
    findings = []
    for fn in [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name.startswith("test_")]:
        asserts = [n for n in ast.walk(fn) if isinstance(n, ast.Assert)]
        raises = [n for n in ast.walk(fn) if isinstance(n, ast.Attribute) and n.attr == "raises"]
        soft = [a for a in asserts if is_soft(a)]
        if not asserts and not raises:
            findings.append((fn.name, "NO-ASSERT", "no assertion"))
        elif asserts and len(soft) * 2 >= len(asserts):
            findings.append((fn.name, "SOFT", "%d of %d assertions are soft" % (len(soft), len(asserts))))
        if any(isinstance(n, ast.Call) and patches_module(n, module) for n in ast.walk(fn)):
            findings.append((fn.name, "MOCKS-OWN", "patches a name inside " + module))
    return findings

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("file")
    parser.add_argument("--module", required=True, help="dotted name of the module under test")
    args = parser.parse_args()
    findings = audit(args.file, args.module)
    for name, kind, why in findings:
        print("%-10s %s: %s" % (kind, name, why))
    print("%d finding(s)" % len(findings))
    sys.exit(1 if findings else 0)

if __name__ == "__main__":
    main()
.venv/bin/python scripts/audit_agent_tests.py tests/agent/test_orders_agent.py --module checkout.orders; echo "exit $?"

It prints SOFT test_place_order_creates_an_order: 3 of 4 assertions are soft, MOCKS-OWN test_total_comes_from_the_quote: patches a name inside checkout.orders, 2 finding(s) and exit 1. Two of the six flaws. Find the other four by reading, and note the test name for each: the two mirrors, the snapshot, the decline test that never looks at stock, and the fake whose take_stock cannot refuse. The script cannot see them, which is why step 6 needs a person.

5. Triage three red builds. Here are three excerpts from CI runs on a pull request for this service. They are trimmed from real runs on the lab code.

Run A:

.........s.............F..........                                      [100%]
______________ test_new_product_is_searchable_after_a_short_wait _______________
tests/test_flaky_example.py:19: in test_new_product_is_searchable_after_a_short_wait
    assert [d["id"] for d in index.search("shea")] == [7]
E   assert [] == [7]
FAILED tests/test_flaky_example.py::test_new_product_is_searchable_after_a_short_wait
1 failed, 33 passed, 1 skipped in 0.76s

Run B:

.........Fs.......................                                       [100%]
________ test_order_of_exactly_ten_thousand_naira_gets_five_percent_off ________
tests/agent/test_orders_agent.py:154: in test_order_of_exactly_ten_thousand_naira_gets_five_percent_off
    assert quote.tier_discount == 50_000
E   assert 0 == 50000
E    +  where 0 = Quote(subtotal=1000000, tier_discount=0, promo_discount=0, net=1000000, vat=75000, delivery_fee=150000, total=1225000).tier_discount
FAILED tests/agent/test_orders_agent.py::test_order_of_exactly_ten_thousand_naira_gets_five_percent_off
1 failed, 32 passed, 1 skipped, 1 deselected in 0.73s

Run C:

checkout/pricing.py:10: in <module>
    LAGOS = ZoneInfo("Africa/Lagos")
E   zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key Africa/Lagos'
ERROR tests/agent/test_orders_agent.py - zoneinfo._common.ZoneInfoNotFoundErr...
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
1 error in 0.17s

Run B uses one of the lab’s ten seeded bugs, number 01, a discount boundary. You met all ten in Project: catch ten seeded bugs, which revealed them and their answer key, so using one here gives nothing away. If you skipped that project, do it first. Decide each cause on evidence, not on the log alone. For A, rerun the quarantined test twenty times. For B, reproduce the change the pull request made (the lab’s patch 01-discount-boundary does exactly that) and run the suite. For C, hide the time zone database from Python, the way a slim CI image would.

fails=0; for i in $(seq 20); do .venv/bin/pytest -m "" -q -p no:randomly -W ignore tests/test_flaky_example.py >/dev/null 2>&1 || fails=$((fails+1)); done; echo "A: failed $fails of 20"

.venv/bin/python scripts/seed_bugs.py apply 01-discount-boundary
.venv/bin/pytest -q -p no:randomly -W ignore 2>&1 | tail -3

PYTHONTZPATH=/nonexistent .venv/bin/python -c "
import sys
sys.modules['tzdata'] = None
import pytest
sys.exit(pytest.main(['-q', '-p', 'no:randomly', '-W', 'ignore', '--tb=line']))" 2>&1 | tail -3 | cut -c1-120

A prints a count somewhere between 5 and 15 of 20 (12 when this was written): it fails on some runs of unchanged code, so it is flaky, and a retry loop would hide it. B prints FAILED tests/agent/test_orders_agent.py::test_order_of_exactly_ten_thousand_naira_gets_five_percent_off and 1 failed, 32 passed: with the patch in, the exact-₦10,000 order is priced with no discount, and the test the agent wrote is the only one that notices. The starter suite does not. C prints ERROR tests/... lines naming ZoneInfoNotFoundError and 5 errors during collection: an environment fault, and the right fix is the pinned tzdata in the requirements.

Now let the agent “fix” run B the way the proposal above did, and see what you have bought. The bug is still applied.

sed -i.bak 's/assert quote.tier_discount == 50_000/assert quote.tier_discount == 0/' tests/agent/test_orders_agent.py
.venv/bin/pytest -q -p no:randomly -W ignore 2>&1 | tail -1
mv tests/agent/test_orders_agent.py.bak tests/agent/test_orders_agent.py
.venv/bin/python scripts/seed_bugs.py revert 01-discount-boundary
.venv/bin/pytest -q -p no:randomly -W ignore 2>&1 | tail -1

The first run prints 33 passed, 1 skipped, 1 deselected: green, with the bug in. A one-line edit to a test turned a caught fault into a protected one. The restore and the revert put everything back, and the last line is 33 passed, 1 skipped, 1 deselected on the clean code.

6. Add what the survivors ask for, and delete what earned nothing. First keep the agent’s original for the break at the end: mkdir tests/agent_v1 && touch tests/agent_v1/__init__.py && cp tests/agent/test_orders_agent.py tests/agent_v1/. Then make two edits in tests/agent/test_orders_agent.py. Make the fake honest: add from checkout.inventory import OutOfStock under the other imports, and replace FakeDb.take_stock with this:

    def take_stock(self, product_id, qty):
        if self.stock[product_id] < qty:
            return False  # the real Database refuses, in one atomic UPDATE
        self.stock[product_id] -= qty
        return True

Then append the tests below to the end of the file. They pin stock after a paid and after a declined order, the out-of-stock path, hand-worked totals at the ₦10,000 edge, the promo at the Lagos midnights written as UTC instants, and every delivery-band edge. Each total is worked out from the rules, not from the code: a ₦10,000 item gets 5% off, which is 50,000 kobo, leaving 950,000; VAT at 7.5% is 71,250; delivery for 3 km is 150,000.

# --- added by a person, after reading the surviving mutants ---

def test_a_paid_order_keeps_its_stock_taken(db, payments, clock):
    place_order(db, payments, clock, ITEMS, "key-10", distance_km=3)
    assert db.stock[2] == 98

def test_a_declined_order_puts_the_stock_back_and_saves_nothing(db, clock):
    declining = StubPayments(ChargeResult("", "declined", "insufficient_funds"))
    with pytest.raises(PaymentDeclined) as caught:
        place_order(db, declining, clock, ITEMS, "key-11", distance_km=3)
    assert caught.value.code == "insufficient_funds"
    assert db.stock[2] == 100
    assert db.orders == {}

def test_an_order_for_more_than_is_in_stock_is_refused_before_charging(db, payments, clock):
    with pytest.raises(OutOfStock):
        place_order(db, payments, clock, [{"product_id": 3, "qty": 6}], "key-12")
    assert payments.calls == []
    assert db.stock[3] == 5

def test_exactly_ten_thousand_naira_is_charged_with_five_percent_off(db, payments, clock):
    # 1_000_000 - 50_000 discount = 950_000 net; VAT 71_250; delivery 150_000 for 3 km
    order, _ = place_order(db, payments, clock, [{"product_id": 5, "qty": 1}], "key-13", distance_km=3)
    assert order["total_kobo"] == 1_171_250
    assert payments.calls == [("key-13", 1_171_250, "key-13")]

def test_one_kobo_under_ten_thousand_naira_gets_no_discount(db, clock):
    db.products[5]["price_kobo"] = 999_999
    quote, _ = quote_lines(db, [{"product_id": 5, "qty": 1}], 3, clock, None)
    assert quote.tier_discount == 0

@pytest.mark.parametrize(
    "when, live",
    [
        (datetime(2026, 11, 30, 22, 59, tzinfo=timezone.utc), False),  # 23:59 in Lagos on 30 November
        (datetime(2026, 11, 30, 23, 0, tzinfo=timezone.utc), True),  # midnight in Lagos: 1 December
        (datetime(2026, 12, 31, 22, 59, tzinfo=timezone.utc), True),  # 23:59 in Lagos on 31 December
        (datetime(2026, 12, 31, 23, 0, tzinfo=timezone.utc), False),  # midnight in Lagos: 1 January
    ],
)
def test_harmattan_promo_follows_the_lagos_day(db, when, live):
    quote, _ = quote_lines(db, [{"product_id": 1, "qty": 1}], 3, FakeClock(when), "HARMATTAN")
    assert (quote.promo_discount > 0) is live

@pytest.mark.parametrize("km, fee", [(5, 150_000), (6, 300_000), (15, 300_000), (16, 500_000), (40, 500_000), (41, 900_000)])
def test_delivery_fee_bands_are_charged_at_their_edges(db, payments, clock, km, fee):
    order, _ = place_order(db, payments, clock, [{"product_id": 2, "qty": 1}], "key-km-%d" % km, distance_km=km)
    assert order["total_kobo"] == 350_000 + 26_250 + fee
.venv/bin/pytest tests/agent -q -p no:randomly -W ignore 2>&1 | tail -1
rm -rf mutants .mutmut-cache
.venv/bin/python scripts/mutate.py run 2>&1 | tr '\r' '\n' | grep "169/169" | tail -1

Now delete the four tests the audit and your reading marked as worth nothing: test_place_order_creates_an_order, test_charge_amount_matches_order_total, test_total_matches_the_quote and test_total_comes_from_the_quote. Run the same two commands again, then run the audit.

The first pass prints 25 passed and 169/169 🎉 148 🫥 0 ⏰ 0 🤔 0 🙁 21 🔇 0: 148 killed, 88%, up from 116. The survivors left are exception messages and a few small pricing mutants. After deleting the four tests you see 21 passed and the same 148: they were worth nothing to the score. The audit prints 0 finding(s) and exit 0. The paid = False mutant is now killed by test_a_paid_order_keeps_its_stock_taken.

Restore the lab’s config when you are done: mv pyproject.toml.orig pyproject.toml; rm -rf mutants .mutmut-cache.

7. (Optional) Do it with your own agent. If you have a coding agent, give it checkout/orders.py and this prompt, then run steps 1 to 4 on the file it writes (change the path and the test name in the commands):

Write pytest tests for checkout/orders.py in tests/agent/. Do not touch checkout/.
Use hand-worked expected values from these rules: discount 5% from 1_000_000 kobo,
10% from 5_000_000, VAT 7.5% on net goods rounded half up, delivery 150_000 up to 5 km.
For every test, name the rule it checks in the test name. Report nothing about coverage.
Your numbers will differ. Compare the mutation score with the 69% of the shipped file and the 88% of the checked one, and see which of the six flaws your agent made. Expect fewer soft assertions with a prompt that supplies expected values, and the same blind spot on side effects.

Break it: make the change from the survivor by hand. In checkout/orders.py change paid = True to paid = False. Run .venv/bin/pytest tests/agent_v1 -q -p no:randomly -W ignore: the agent’s original ten tests still pass. Run .venv/bin/pytest tests/agent -q -p no:randomly -W ignore: test_a_paid_order_keeps_its_stock_taken fails with assert 100 == 98. Revert the edit. The agent’s file would have shipped a bug that refills the shelf on every sale. Then add a mirror of your own to the checked file (assert the charge amount equals the order total) and run the audit: it still reports nothing. What check would you add to the pipeline for that one?

8. Put the lab back. Confirm the orders.py edit is reverted, then remove what you added. pyproject.toml was restored in step 6, so the git check below should show nothing.

git checkout checkout/orders.py pyproject.toml
rm -rf tests/agent tests/agent_v1 scripts/audit_agent_tests.py pyproject.toml.orig pyproject.toml.bak mutants .mutmut-cache
.venv/bin/python scripts/seed_bugs.py status | grep -c clean
git status --short .
unset CHECKOUT_DB
.venv/bin/pytest -q 2>&1 | tail -1
The count prints 10: every seeded bug is reverted. git status --short . prints nothing and the suite ends 23 passed, 1 skipped, 1 deselected.
DECIDE

Larkhollow's test-writing agent opens pull requests of new tests for a customer's service every night. In the first month it opens 60 pull requests with 900 tests. Xiomara's team can review perhaps 10 pull requests a week. The customer wants the coverage number on their dashboard to rise. You decide what the pipeline requires before an agent pull request can merge.

READING
  1. PAPER
    Mutation-Guided LLM-based Test Generation at Meta Foster, Gulati, Harman, Harper, Mao, Ritchey, Robert and Sengupta, 2025

    The closest published account of the loop in this chapter: mutants as the instruction to the generator, 9,095 mutants over 10,795 classes, 73% of tests accepted by engineers. Read it for the design of the loop; skip the privacy-specific detail. Read: Abstract and the sections on how mutants guide generation and on engineers' acceptance of the tests.

  2. PAPER
    An Empirical Evaluation of Using Large Language Models for Automated Unit Test Generation Schäfer, Nadi, Eghbali and Tip, 2023

    A careful measurement of what a model-written suite achieves on 25 npm packages: median statement coverage 70.2%. Read it for how they validate generated tests and the limits they report; skip the JavaScript-specific prompt details. It is an arXiv preprint. Read: Abstract; the sections on the TestPilot design and on the coverage results.

  3. PAPER
    Is Your Code Generated by ChatGPT Really Correct? Rigorous Evaluation of Large Language Models for Code Generation Liu, Xia, Wang and Zhang, 2023

    Shows what weak tests cost: about eighty times more tests cut measured pass rates by up to 19.3 to 28.9 percent. Read it to see generated tests used as a measuring tool; skip the model-ranking tables. Read: Abstract; the sections on test augmentation and the results.

  4. PAPER
    SWE-bench: Can Language Models Resolve Real-World GitHub Issues? Jimenez, Yang, Wettig, Yao, Pei, Press and Narasimhan, 2024

    Defines how a repair agent is judged: the project's own tests, run on the result. Read it for why a fix is graded by tests the agent did not write, which is the rule of this chapter; skip the model results, which date quickly. Read: Sections 1 to 3.

  5. PAPER
    Test-Driven Development for Code Generation Mathews and Nagappan, 2024

    Gives a model the tests first and reports higher success on MBPP and HumanEval. Read it as the case for writing the tests yourself and letting the agent write the code, the reverse of the loop in this chapter. Read: Abstract and the experiment sections.

  6. POST
    Building effective agents Anthropic, 2024

    The plain statement of the evaluator-optimizer pattern and the advice to test agents in sandboxes with guardrails. Read the sections on workflows against agents and on the evaluator-optimizer loop; skip the product examples.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Project: the test strategy for a payments product →