Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 3

Lab: Ship an Endpoint with an Agent, Tests First

Lab: commit acceptance tests for a status filter, brief a coding agent with a spec and an instructions file, review its plan, approve the edit and review the diff like a pull request.

Contentsand lesson path

What you will learn

  • Delegate a scoped change to a coding agent with a written spec, acceptance tests committed first and project context (an instructions file, reusable skills, MCP tools), reviewing its plan before it edits code.
  • Review AI-generated changes, refactors and documentation as you would a colleague's pull request: run the tests, check every new dependency and API call against official documentation, and reject changes that pass only by weakening or deleting tests.

Prerequisites: Software Testing Fundamentals

01. Goal and preparation

You will ship one real change end to end the way a careful team does: write the acceptance tests, commit them, brief an agent, review its plan, approve the edit, then review the diff as if a colleague had sent it. The feature is a status filter on the reading-list service from the briefing lesson, so the spec style and the instructions file should already feel familiar. By the end you will have a three-commit history in which the tests always preceded the code that satisfies them.

This course verifies its examples without paid APIs, so the agent here is mock_agent.py, a scripted stand-in printed in full in step 1, which prints a plan, waits for approval and applies one scripted edit before running your real test suite. Every step around it — the commits, the pytest runs, the plan review, the diff review — is exactly what you would do with a live agent. Swap the mock for your tool of choice and nothing else in the lab changes.

Versions used when this lab was run: Python 3.12.13, FastAPI 0.163.1, Pydantic 2.14.3, pytest 9.2.0 and httpx2 2.16.2 — the HTTP client FastAPI's TestClient is built on in current releases. Verify current versions at run time, as the endpoint test lab shows. You need uv for the virtual environment and git for the commits.

Project layout
lab/
  AGENTS.md              standing rules for the agent
  app.py                 the whole service
  mock_agent.py          scripted stand-in for a coding agent
  specs/status-filter.md the one-page spec
  tests/test_api.py      acceptance tests, committed first

02. Step 1: create the project, spec and instructions file

Make the folder, create the virtual environment with uv and install FastAPI, pytest and httpx2 (Pydantic comes with FastAPI):

Terminal
mkdir lab && cd lab
uv venv --python 3.12 .venv
uv pip install --python .venv fastapi pytest httpx2
Illustrative output (excerpt; the install time and versions vary)
Installed 20 packages in 4.63s
 + fastapi==0.163.1
 + httpx2==2.16.2
 + pydantic==2.14.3
 + pytest==9.2.0

Save the starting service as app.py. It is the same three-entry service as before, and the whole application fits in one file on purpose — the point of this lab is the workflow, not the architecture:

Python · app.py (starting point)
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="Reading list")


class Entry(BaseModel):
    id: int
    title: str
    status: str


ENTRIES: dict[int, Entry] = {
    1: Entry(id=1, title="Refactoring HTTP clients", status="unread"),
    2: Entry(id=2, title="Async Python patterns", status="unread"),
    3: Entry(id=3, title="Postgres indexes deep dive", status="done"),
}


@app.get("/reading-list")
def list_entries() -> list[Entry]:
    return list(ENTRIES.values())

Write the spec with the four sections you know — Context, Change, Non-goals, Acceptance — and make the acceptance concrete enough to test:

Markdown · specs/status-filter.md
# Feature: filter the reading list by status

## Context

`GET /reading-list` returns every entry. Readers want to see only what
is still unread, or only what they have finished.

## Change

`GET /reading-list` accepts an optional `status` query parameter.

- Omitted: behaves exactly as today (all entries, same order).
- `status=unread` or `status=done`: only entries with that status.
- Any other value: the endpoint returns FastAPI's 422 error.

## Non-goals

No new endpoints, no database, no pagination, no changes to anything
other than `app.py`.

## Acceptance

The tests in `tests/test_api.py` (already committed) define done. Do
not edit them.

Copy AGENTS.md exactly as printed in step 3 of the briefing lesson — Commands, Conventions, Boundaries — so that the commit below matches.

Save the scripted agent as mock_agent.py. It is deliberately simple: plan prints a canned plan for a spec, run refuses to touch a file without --approved, and run --approved makes one scripted edit to app.py, runs your real test suite and lists the files that changed. It also holds the plans used in the briefing lesson. Nothing in it is clever, which is the point: every judgement in this lab is yours.

Python · mock_agent.py
"""A scripted stand-in for a coding agent. For this course's labs only.

`plan` prints a canned plan for a spec. `run --approved` applies one scripted
edit to app.py (the status filter), runs the real test suite and lists the
files that changed. Without --approved it refuses, like a permission prompt.
"""
import subprocess
import sys
from pathlib import Path

PLANS = {
    'specs/status-filter.md': [
        "1. In app.py, narrow Entry.status to Literal['unread', 'done'].",
        '2. Add an optional status query parameter of the same type to',
        '   GET /reading-list; filter the returned list when given.',
        '3. Run .venv/bin/python -m pytest -q. No other files change.',
    ],
    'specs/stats-endpoint.md': [
        '1. Add a Stats model (total, unread, done) in app.py.',
        '2. Add GET /reading-list/stats returning Stats.',
        '3. Replace the ENTRIES dict with a SQLite database, so counts',
        '   stay correct as the list grows.',
        '4. Add POST /reading-list/reset so tests can start clean.',
        '5. Run .venv/bin/python -m pytest -q.',
    ],
    'specs/stats-endpoint.md --revise': [
        '1. Add a Stats model (total, unread, done) in app.py.',
        '2. Add GET /reading-list/stats returning Stats, computed from',
        '   the existing ENTRIES dict.',
        '3. Run .venv/bin/python -m pytest -q. No other files change.',
    ],
}
STATUS = 'Literal["unread", "done"]'
EDITS = [  # (old, new) text replacements in app.py, applied in order
    ('from fastapi import FastAPI\n',
     'from typing import Literal\n\nfrom fastapi import FastAPI\n'),
    ('    status: str\n', f'    status: {STATUS}\n'),
    ('def list_entries() -> list[Entry]:\n    return list(ENTRIES.values())\n',
     f'def list_entries(status: {STATUS} | None = None) -> list[Entry]:\n'
     '    entries = list(ENTRIES.values())\n'
     '    if status is not None:\n'
     '        entries = [e for e in entries if e.status == status]\n'
     '    return entries\n'),
]


def plan(spec: str, revise: bool) -> int:
    print(f'agent: plan for {spec}' + (' (revised)' if revise else ''))
    for line in PLANS[spec + (' --revise' if revise else '')]:
        print('  ' + line)
    print('agent: waiting for approval before editing any file')
    return 0


def run(approved: bool) -> int:
    if not approved:
        print('agent: refusing to edit files without --approved')
        return 1
    app = Path('app.py')
    source = app.read_text()
    for old, new in EDITS:
        if old not in source:
            print('agent: app.py is not the starting point; nothing edited')
            return 1
        source = source.replace(old, new)
    app.write_text(source)
    print('agent: edited app.py (status type narrowed, query parameter added)')
    tests = subprocess.run([sys.executable, '-m', 'pytest', '-q'],
                           capture_output=True, text=True)
    print(f'agent: pytest exit code {tests.returncode}')
    print(tests.stdout.strip())
    changed = subprocess.run(['git', 'diff', '--name-only'],
                             capture_output=True, text=True)
    print('agent: changed files:', ', '.join(changed.stdout.split()))
    return tests.returncode


if __name__ == '__main__':
    args = sys.argv[1:]
    if args[:1] == ['plan']:
        specs = [a for a in args[1:] if not a.startswith('--')]
        sys.exit(plan(specs[0] if specs else 'specs/status-filter.md',
                      '--revise' in args))
    if args[:1] == ['run']:
        sys.exit(run('--approved' in args))
    print('usage: mock_agent.py plan [SPEC] [--revise] | run --approved')
    sys.exit(2)

Keep the virtual environment and Python's caches out of Git with a .gitignore (otherwise git add tests/ in step 2 also commits __pycache__ files), then start the history with one commit, so the agent's later change has a clean baseline to diff against:

Terminal
printf '.venv/\n__pycache__/\n.pytest_cache/\n' > .gitignore
git init -b main && git add app.py AGENTS.md specs/ .gitignore mock_agent.py
git commit -m "reading-list service, agent instructions, spec"
Expected output (excerpt; commit hashes vary)
[main (root-commit) 2f1a4b4] reading-list service, agent instructions, spec
 5 files changed, 156 insertions(+)

03. Step 2: write and commit the acceptance tests first

Three tests pin the spec: the no-filter contract, the filter itself, and the 422 for unknown values. Each line maps to a bullet in the spec's Change section, which is what makes the spec checkable:

Python · tests/test_api.py
from fastapi.testclient import TestClient

from app import app

client = TestClient(app)


def test_lists_all_entries_without_filter() -> None:
    response = client.get("/reading-list")

    assert response.status_code == 200
    assert [entry["id"] for entry in response.json()] == [1, 2, 3]


def test_filters_entries_by_status() -> None:
    response = client.get("/reading-list", params={"status": "unread"})

    assert response.status_code == 200
    assert [entry["id"] for entry in response.json()] == [1, 2]


def test_rejects_unknown_status_with_422() -> None:
    response = client.get("/reading-list", params={"status": "skimming"})

    assert response.status_code == 422
Terminal
.venv/bin/python -m pytest -q
Illustrative output (excerpt; the run time varies)
FAILED tests/test_api.py::test_filters_entries_by_status - assert [1, 2, 3] =...
FAILED tests/test_api.py::test_rejects_unknown_status_with_422 - assert 200 =...
2 failed, 1 passed in 0.51s

Read the failure report like a reviewer. The two new-behaviour tests fail for the right reason — the endpoint ignores the parameter, so the filtered list is everything and an unknown value gets 200 instead of 422. The one passing test is the regression guard: the unfiltered list must not change. A suite that cannot fail cannot accept anything, so keep this red output as evidence, then commit:

Terminal
git add tests/ && git commit -m "tests: acceptance for status filter (written first)"

04. Step 3: ask the agent to plan, and read the plan

Now — and only now — bring in the agent, and ask for a plan before any edit:

Terminal
.venv/bin/python mock_agent.py plan
Expected output
agent: plan for specs/status-filter.md
  1. In app.py, narrow Entry.status to Literal['unread', 'done'].
  2. Add an optional status query parameter of the same type to
     GET /reading-list; filter the returned list when given.
  3. Run .venv/bin/python -m pytest -q. No other files change.
agent: waiting for approval before editing any file

Check the plan against the spec line by line. Step 1 narrows the model, which is how FastAPI produces the 422 the spec asks for rather than an if block — that also satisfies the Conventions section of AGENTS.md. Step 2 is the filter. Step 3 touches nothing else, which honours the Non-goals. Nothing here proposes a database or an extra endpoint; when a plan does, you reject it before the edit, as the scripted SQLite plan in the briefing lesson showed.

05. Step 4: approve, then let the agent edit and test

The mock refuses to run without --approved; with a live agent it stands for your approval of the reviewed plan, which you give at the permission prompt your tool shows before file edits. Try it once without the flag:

Terminal
.venv/bin/python mock_agent.py run
Expected output
agent: refusing to edit files without --approved

Nothing changed on disk. Now approve, and the agent applies its change and runs your committed suite itself:

Terminal
.venv/bin/python mock_agent.py run --approved
Illustrative output (the run time varies)
agent: edited app.py (status type narrowed, query parameter added)
agent: pytest exit code 0
...                                                                      [100%]
3 passed in 0.47s
agent: changed files: app.py

06. Step 5: review the diff like a pull request

A green suite is the floor, not the review. Commit the agent's work as its own commit, so it can be reverted or discussed as one unit, then look at what actually changed — first which files, then the diff itself:

Terminal
git add app.py && git commit -m "agent: status filter for the reading list"
Expected output (the commit hash varies)
[main 17b4a5b] agent: status filter for the reading list
 1 file changed, 8 insertions(+), 3 deletions(-)

One file changed: app.py. The tests you committed in step 2 are byte-for-byte what they were, which is the whole point of committing them first. The diff itself is small and idiomatic — Literal["unread", "done"] on the model and the same type on an optional query parameter, a plain filter, no new dependency, no invented API. The next lesson in this skill, refactors, docs and code review, trains the harder half of review: catching the change that passes its tests by weakening them.

Excerpt of git show HEAD -- app.py (the last hunk)
@@ -18,5 +20,8 @@ ENTRIES: dict[int, Entry] = {
 
 
 @app.get("/reading-list")
-def list_entries() -> list[Entry]:
-    return list(ENTRIES.values())
+def list_entries(status: Literal["unread", "done"] | None = None) -> list[Entry]:
+    entries = list(ENTRIES.values())
+    if status is not None:
+        entries = [e for e in entries if e.status == status]
+    return entries

07. Check your understanding

Practice check · 3 questions

The tests-first contract

Reason about the order of operations in this lab.

Q1. Why does the lab commit the failing tests before the agent is allowed to edit anything?
Q2. The mock agent refuses to edit without --approved. In a live session, what does that flag stand in for?
Q3. Before the agent starts, two tests fail and one passes. Is the suite ready to hand over?
Practice only: not graded, not saved, not evidence.

08. Apply it

Extend the lab on your own:

  1. Add a fourth acceptance test for status=done and one for an empty result, commit them red, then let the agent (mock or real) make them pass without touching the others.
  2. Add pagination to the spec's Non-goals, then ask your agent for a plan anyway and check whether the plan tries to add it — practising rejection is part of the skill.
  3. If you have access to a real coding agent, repeat the whole flow with it in a sandbox folder with no credentials, and keep the session log next to your git history as the practice asks.

09. Review prompt

Without looking back: list the commits in the order this lab creates them and what each protects. Say what you check when you read an agent's plan, and what you check in its diff that the test run cannot tell you. Finish by explaining, to a colleague, why the red pytest output in step 2 is evidence worth keeping.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check