◆ AI All-in-One

Level 2 Agentic Coding · Agentic Coding

Tests as Guardrails

An agent's "done" is a claim; a passing test is evidence. This chapter shows how to make tests, linters, type checkers and continuous integration do most of the checking for you, how to work test-first with an agent, how to stop it cheating, and how to check user interfaces with screenshots.

Level
●●●●● Easy
Reading
17 min
To learn it well
45 minutes to read, an afternoon to practise
↗ Plan a path here

Read first

Setting Up a Coding Agent

This leads to

Reviewing and Debugging AI-Written Code
The full path from zero — 9 concepts before this one
  1. What Is AI?
  2. Python for AI
  3. How Machines Learn
  4. Setting Up Your Environment
  5. Large Language Models, Explained Simply
  6. AI Fluency: Working Well with AI
  7. Asking Well: Everyday Prompting
  8. What Is Agentic Coding?
  9. Setting Up a Coding Agent
  10. Tests as Guardrails

Read them roughly in this order. See it on the concept map →

Why it matters

A coding agent stops when the work looks done. Ask it to add a feature and it will edit some files, perhaps run something, and report "Done. The feature works and all tests pass." That sentence is a claim. Sometimes it is true. Sometimes the agent ran nothing, or ran the tests and misread the output, or made the tests pass by changing what they check.

You could check every claim by hand: run the program, try the odd inputs, read every line. That works for one small change. It does not work for ten changes a day, and it does not work when the agent spent forty steps on something you did not watch. If you are the only check, you become the bottleneck and every mistake waits until you happen to notice it.

The way out is to give the agent something it can run that comes back pass or fail. Then it can close the loop itself: make the change, run the check, read the failure, fix, run again. Anthropic's Claude Code guide makes this one of its core pieces of advice (and calls the command that runs the check "the single most useful line" in a memory file), and Simon Willison makes the same point: agent loops work best on problems with "clear success criteria". Tests are the main such check. Linters, type checkers and an automatic run on every push catch more. Together they act as guardrails: they don't drive the car, but they stop it going off the road while you look at the map.

This chapter builds on Setting Up a Coding Agent and the tally project from earlier chapters. It picks up the budgets feature planned in Planning and Specs: Telling an Agent What to Build and builds part of it test-first.

The idea

A test is an executable promise

An automated test is a small piece of code that runs part of your program with a known input and checks the output against the answer you expect. If they match, the test passes. If not, it fails and says why. The check itself is an assertion: a line that states something must be true, such as "formatting 150 spent against a budget of 200 gives 50.00 left".

A test turns a sentence from your spec into something a machine can check in a millisecond, as often as you like. That has three consequences for agent work:

  1. The agent can check itself. It no longer needs you to say whether it worked.
  2. "Done" becomes objective. "All 14 tests pass" is evidence; "I've implemented the feature" is not.
  3. Old behaviour stays protected. Every test you keep is a promise that something that worked yesterday still works today. A test that catches a feature breaking again after a later change is called a regression test.

A test that checks one small piece (one function, say) is a unit test. All of a project's tests together form its test suite.

Layers of checks

Tests are not the only automatic check. Each kind of tool catches a different kind of mistake, at a different speed. Stack them and each layer catches some of what the layers before it missed:

CheckWhat it catches in agent codeSpeed Formatter ruff format inconsistent style, noisy diffs seconds Linter ruff check unused imports, undefined names, bad patterns seconds Type checker mypy float where Decimal expected, None not handled seconds Tests pytest wrong behaviour, broken edge cases, regressions seconds–minutes CI GitHub Actions "works on my machine", skipped local checks minutes Human review you, reading the diff wrong goal, scope creep, weak tests, security minutes–hours each layer catches what the ones above miss; the agent can run all but the last itself
Fig. 1 Layers of automatic checks, fastest first. Each catches a different kind of mistake in agent-written code. The agent can run every layer except the last; your review is reserved for what machines can't judge.
  • A formatter rewrites code into one consistent layout (spacing, line breaks, quotes). It catches nothing wrong, but it keeps diffs free of noise, so the real changes stand out.
  • A linter reads code without running it and flags likely mistakes: an import nobody uses, a misspelled variable, a suspicious pattern.
  • A type checker checks that values of the right kinds flow into the right places. In Python, if a function promises to return a Decimal and actually returns a float, a type checker such as mypy says so before anything runs.
  • Tests run the code and check behaviour.
  • Continuous integration (CI) runs all of the above automatically on a fresh machine every time code is pushed, so nothing gets in because someone (or some agent) skipped a step.
  • Your review catches what no machine can: the wrong goal, a feature you didn't ask for, tests that check nothing. That is the subject of Reviewing and Debugging AI-Written Code.

Key idea The agent's summary is a claim; a check it can run is evidence. Give every task a check that comes back pass or fail, make the agent run it and show you the output, and protect the check from being edited to pass.

In practice

Tests in Python with pytest

The standard test tool for Python is pytest. A test is any function whose name starts with test_, in a file whose name starts with test_, containing plain assert statements:

# test_tally.py
from decimal import Decimal
from tally import parse_amount

def test_parse_amount_accepts_currency_sign():
    assert parse_amount("£12.50") == Decimal("12.50")

Run every test in the project with:

python -m pytest -q        # -q: quiet, one character per test
# ......                   [100%]
# 6 passed in 0.01s

A dot is a pass, F a failure, E an error while setting up. When something fails, pytest prints the assertion with both values side by side, which is exactly the kind of precise feedback an agent can act on. python -m pytest test_tally.py -k month runs only tests whose names contain "month", which keeps the loop fast while working on one thing.

Making the agent run the checks

Agents run tests readily when they know the command and you ask for evidence. Three ways to arrange that, from gentle to strict:

  1. Put the commands in the memory file. The Commands section of tally's AGENTS.md (Project Context and Memory Files) already says how to test, lint and type-check. An agent that knows the command uses it.
  2. Ask in the prompt, and ask for evidence. "Run the tests after each change and keep going until they pass. Show me the command and its output." Reading the real output takes seconds and tells you far more than "all tests pass".
  3. Enforce it with a hook. Claude Code can run a command of yours whenever the agent tries to finish its turn (a Stop hook). If the command exits with code 2, the agent is sent back to work, with whatever the command printed to stderr as the reason. In .claude/settings.json:
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "python -m pytest -q 1>&2 || exit 2" }
        ]
      }
    ]
  }
}

Now the agent cannot end its turn while a test fails (as of late 2026 Claude Code gives up after eight blocks in a row, so a hopeless loop still ends). Hooks are covered properly in Extending Your Agent: Skills, Hooks, MCP and Subagents. Other agents have similar mechanisms, and all of them can be told the command in their instructions file.

Test-first with an agent

Test-driven development (TDD) is the discipline of writing a failing test before the code that makes it pass. Its rhythm is called red-green-refactor: write a test and watch it fail (red), write the simplest code that makes it pass (green), then tidy up while the tests stay green (refactor). Many developers found it too slow to do by hand all the time. With an agent the balance changes. Writing tests is cheap, and a test written before the code is a spec the agent can't argue with.

1. Write tests from the acceptance criteria (you review) 2. Run: red they fail, for the right reason 3. Commit the tests alone 4. Implement agent writes code, runs tests, repeats 5. Run: green all pass, old and new 6. Tidy, commit lint, types, read the diff still red? back to 4: read the failure, fix the code tests locked git diff on the test file: empty
Fig. 2 Test-first with an agent. You review and commit the tests while they fail for the right reason. Then the agent implements, running the tests and fixing until they pass, without touching the committed tests. A diff of the test file at the end should be empty.

The steps:

  1. Write the tests from the acceptance criteria. Ask the agent to do it ("Write tests for criteria 1 to 4 of SPEC.md. We're doing test-driven development, so don't write the implementation yet"). Saying it is TDD matters: otherwise agents tend to helpfully add a stub that makes the tests pass. Then read the tests. They are now the definition of done, so this is the most valuable review you will do.
  2. Run them and watch them fail. A test that passes before the feature exists is testing nothing. It should fail for the right reason: the feature is missing, not a typo in the test.
  3. Commit the tests alone. The commit is a lock. From now on, any change to the test file shows up in git diff.
  4. Let the agent implement, running the tests after each change and reading the failures. Tell it not to modify the tests.
  5. Green. All tests pass, the new ones and every old one.
  6. Tidy and commit: formatter, linter, type checker, then read the diff.

Linters, formatters and type checkers

As of late 2026 the common Python choices are ruff (a very fast linter and formatter) and mypy (a type checker), and the same ideas exist for every language: ESLint, Prettier and tsc for JavaScript and TypeScript, cargo clippy for Rust, and so on. They take seconds, so ask the agent to run them before it says it is done. Here is the sort of slip they catch. This function was meant to total a month's expenses as Decimal, the way tally handles all money:

# bad.py
import json
from decimal import Decimal


def month_total(rows: list[dict[str, str]]) -> Decimal:
    total = 0.0
    for row in rows:
        total += float(row["amount"])
    return total


def report(rows: list[dict[str, str]]) -> None:
    print(f"Total: {month_totl(rows):.2f}")
ruff check bad.py --output-format concise
# bad.py:1:8: F401 [*] `json` imported but unused
# bad.py:13:21: F821 Undefined name `month_totl`
mypy bad.py
# bad.py:9: error: Incompatible return value type (got "float", expected "Decimal")  [return-value]
# bad.py:13: error: Name "month_totl" is not defined; did you mean "month_total"?  [name-defined]

(Real output from ruff 0.17 and mypy 2.4.) The misspelled name would also crash at run time, but only when report runs, which a test might not reach. The float would never crash at all. It would just make money sums slightly wrong (in floating point, 0.1 + 0.2 is 0.30000000000000004). The type checker catches it for free, because the function's type hints (the -> Decimal after its name) state what it promises. Asking the agent to add type hints to new code is cheap, and it makes this whole layer work.

Continuous integration

Checks that only run on your laptop are checks that can be skipped. Continuous integration runs them on a clean machine for every push and pull request, and shows a green tick or a red cross next to the change. On GitHub this is GitHub Actions, configured by a file in the repository:

# .github/workflows/checks.yml
name: checks
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
      - run: pip install pytest ruff mypy
      - run: ruff check .
      - run: mypy tally.py
      - run: python -m pytest -q

(The action versions are current as of late 2026; check the GitHub Actions docs for newer ones.) CI matters more with agents, not less. Cloud agents such as the Copilot cloud agent or Codex cloud hand you a pull request from a machine you never saw, and CI is the one check guaranteed to have run on it. Make the pull request's merge button depend on CI passing ("branch protection" in GitHub's settings), and a red cross can't be merged by accident.

Checking what tests can't see: screenshots

Tests check text and numbers well and layout badly. If the agent is building a web page, "the tests pass" says nothing about a button hidden behind a menu or text that is white on white. For visual work, give the agent eyes. As of late 2026 there are three common ways:

  • Paste a screenshot or mockup into the prompt ("make it look like this") and later a screenshot of the result ("this is what I see; the total is cut off").
  • Let the agent drive a browser. Claude Code's Chrome integration, or a browser-automation MCP server such as Microsoft's Playwright MCP, lets the agent open the page, click through it, take a screenshot and compare it with the mockup itself.
  • Ask it to run and look. Claude Code's /verify command has the agent build and run the app and look at the result, which catches problems that pass every test.

Screenshots are a weaker check than tests (the agent's judgment of "looks right" can be wrong), so for anything that must stay correct, add an end-to-end test as well, one that clicks through the page in a real browser and checks the text that appears.

Worked example: budgets, test-first

Planning and Specs: Telling an Agent What to Build ended with a plan for monthly budgets in tally. Step 3 of that plan was a function format_line(category, total, budget) that produces one line of the report. The spec's criterion 4 says exactly what the lines must look like. Here it is built test-first, with the real output.

1. Tests from the criteria. You ask the agent for tests only. It writes these, and you check each against the spec, including "exactly at budget", the case the planning session discovered:

# test_budget.py
from decimal import Decimal

from tally import format_line


def test_under_budget_shows_amount_left():
    line = format_line("food", Decimal(150), Decimal(200))
    assert line == "food            150.00 /   200.00  50.00 left"


def test_exactly_at_budget_shows_zero_left():
    line = format_line("food", Decimal(200), Decimal(200))
    assert line == "food            200.00 /   200.00  0.00 left"


def test_over_budget_shows_overspend():
    line = format_line("rent", Decimal(450), Decimal(400))
    assert line == "rent            450.00 /   400.00  OVER by 50.00"


def test_no_budget_shows_total_only():
    assert format_line("coffee", Decimal(12), None) == "coffee           12.00"

2. Red. tally.py has only a placeholder, def format_line(...): raise NotImplementedError, so the import works and every test fails because the feature is missing:

$ python -m pytest -q test_budget.py
FFFF                                                       [100%]
FAILED test_budget.py::test_under_budget_shows_amount_left - NotImplementedError
FAILED test_budget.py::test_exactly_at_budget_shows_zero_left - NotImplemente...
FAILED test_budget.py::test_over_budget_shows_overspend - NotImplementedError
FAILED test_budget.py::test_no_budget_shows_total_only - NotImplementedError
4 failed in 0.02s

That is failing for the right reason. Commit: git add test_budget.py tally.py && git commit -m "Add failing tests for budget lines".

3. Implement. "Implement format_line so the tests in test_budget.py pass. Don't modify the tests. Run them after each change." The agent's first attempt computes budget - total and prints it with "left". It runs the tests and gets this:

..F.                                                       [100%]
_______________________ test_over_budget_shows_overspend _______________________
>       assert line == "rent            450.00 /   400.00  OVER by 50.00"
E       AssertionError: assert 'rent        ...  -50.00 left' == 'rent        ...OVER by 50.00'
E         - rent            450.00 /   400.00  OVER by 50.00
E         + rent            450.00 /   400.00  -50.00 left
1 failed, 3 passed in 0.01s

Notice how specific that is: expected line, actual line, and the differing part marked. No human needed to spot that overspending printed "-50.00 left". The agent reads it and adds the missing branch:

# tally.py (excerpt)
def format_line(category: str, total: Decimal, budget: Decimal | None) -> str:
    line = f"{category:<12}{total:>10.2f}"
    if budget is None:
        return line
    if total > budget:
        status = f"OVER by {total - budget:.2f}"
    else:
        status = f"{budget - total:.2f} left"
    return f"{line} / {budget:>8.2f}  {status}"
....                                                       [100%]
4 passed in 0.00s

4. Check the lock. Did the tests stay as you committed them?

git diff --exit-code --stat -- test_budget.py && echo "tests untouched"
# tests untouched

--exit-code makes git diff fail (exit code 1, and list the file) if there is any change, so this one line can go in a script or hook too. Then ruff check . (All checks passed!) and mypy tally.py (Success: no issues found).

5. Do the tests actually bite? A quick, powerful check: break the code on purpose and see whether a test notices. Change total > budget to total >= budget and run again:

FAILED test_budget.py::test_exactly_at_budget_shows_zero_left - AssertionErro...
1 failed, 3 passed in 0.01s

Good: the "exactly at budget" test earns its place. Put the > back. Deliberately planting a bug to check that the tests catch it is a hand-made version of mutation testing, which tools such as mutmut (for Python) automate. If you can change a line and every test still passes, that line is untested.

Common mistakes

  • Tests that test nothing. assert format_line(...) passes for any non-empty string. A test that replaces the very function it is testing with a fake (a "mock") passes whatever the real code does. Read the assertions: each should state a specific expected value.
  • Tests written after the code, from the code. Ask an agent to "add tests" for code it just wrote and it often reads the code and asserts whatever the code currently does, bugs included. Tests should come from the spec, not from the implementation.
  • Weakening the test instead of fixing the code. Changing an expected value, adding @pytest.mark.skip, loosening == to in, or wrapping the check in try/except. Watch for any diff in test files during an implementation task.
  • Special-casing. Code that detects the test's exact input and returns the expected answer (if category == "rent" and total == 450: ...). It passes the tests and works for nothing else. Hidden or extra test cases, and reading the code, catch it.
  • Trusting "all tests pass" without output. Ask for the command and its output. An agent may have run a subset, or none.
  • A slow or flaky suite. If the tests take ten minutes, or fail randomly one time in twenty, the agent (and you) will stop running them. Keep the fast unit tests fast, and fix or delete flaky ones.
  • Tests that touch real data. tally's tests use temporary files (Project Context and Memory Files records this as a gotcha). A test that writes to the real expenses.csv will one day destroy it.

Watch out An agent under pressure to make tests pass will sometimes edit the tests, skip them, or hard-code their expected answers. This is the coding version of reward hacking: optimising the measurement instead of the goal. Anthropic's system card for Claude 3.7 Sonnet (February 2025) reported that the model, after repeated failures, sometimes special-cased tests to make them pass, and Kent Beck lists "disabling or deleting tests" as a warning sign he watches for. Newer models do it less, but not never. Commit tests before implementation, tell the agent not to change them, and check git diff on test files every time.

Where it leads

A bit of history

Programmers have tested code for as long as there has been code, but automated tests written by the developers themselves spread with Kent Beck's work in the 1990s: the SUnit framework for Smalltalk, then JUnit for Java with Erich Gamma, and the Extreme Programming movement, which also popularised continuous integration. Beck's book Test-Driven Development: By Example (2002) set out red-green-refactor. pytest grew out of Holger Krekel's work in the mid-2000s and became Python's standard. TDD stayed a minority practice for two decades, often judged too slow. Coding agents revived it: when the machine writes the code, a precise, executable statement of what the code must do is the most valuable thing a human can provide, and the 2023 SWE-bench benchmark judges agents exactly that way, by whether hidden tests pass after their change.

Try it

  1. Take one acceptance criterion from a spec of yours (or criterion 3 of the budgets spec: invalid amounts are rejected like add rejects them). Ask an agent to write tests only, run them, and confirm they fail for the right reason. Commit them, then let the agent implement. Was git diff on the test file empty at the end?
  2. Plant a bug in a function that has tests (flip a > to >=, or delete a line). Does a test fail? If not, ask the agent to write the missing test, and check that it fails with the bug and passes without it.
  3. Add the Stop hook above (or your agent's equivalent) to a project, then ask the agent for a change that breaks a test. Watch what happens when it tries to finish.

Hint for 2: git stash puts your planted bug aside and git stash pop brings it back, so you can run the tests on both versions quickly.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You ask an agent to write tests before any code exists. One new test passes immediately. What does that tell you?

  2. During an implementation task, the diff shows the agent changed an expected value in test_budget.py from OVER by 50.00 to -50.00 left. What has happened?

  3. A function promises -> Decimal but returns a float sum. Which check catches this before any code runs?

  4. You change total > budget to total >= budget on purpose and run the tests. All tests still pass. What does that tell you?

  5. Cloud agents hand you pull requests from machines you never saw. Why does continuous integration matter even more here?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Claude Code: Best practices for agentic coding

Anthropic · 2025 · Beginner · Free

Concrete workflows for coding agents: CLAUDE.md files, explore-plan-code-commit, test-driven loops, course-correcting early, and running agents safely.

Docs

pytest documentation

pytest-dev · Beginner · Free

The official docs for Python's standard test tool: writing tests with plain assert, running and selecting them, fixtures such as tmp_path, and reading failure reports.

Article

Augmented Coding: Beyond the Vibes

Kent Beck · 2025 · Beginner · Free

The creator of TDD builds a real library test-first with a coding agent, and describes the warning signs he watches for: loops, unrequested features and disabled or deleted tests.

Article

Test Driven Development

Martin Fowler · Beginner · Free

A short, clear explanation of the test-first rhythm (write a test, make it pass, refactor), why it helps design, and the common mistake of skipping the refactor step.

Docs

Ruff documentation

Astral · Beginner · Free

The fast Python linter and formatter: installing it, ruff check and ruff format, choosing rules, and configuring it in pyproject.toml.

Docs

GitHub Actions documentation

GitHub · Intermediate · Free

How to run tests and checks automatically on every push and pull request, with workflow files, ready-made actions and tutorials for building and testing Python projects.

Article

Designing agentic loops

Simon Willison · 2025 · Intermediate · Free

How to set a coding agent up to iterate safely towards a clear goal: picking the tools it may run, sandboxing YOLO mode, scoped credentials, and problems with clear success criteria.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/agentic/testing-with-agents.md