QA and Test Automation · Lab 35 of 35
Build an AI Agent That Writes and Runs API Tests, With a Gate
Build a small agent loop: a local model writes a pytest file for one ShopRung requirement, the loop runs it, feeds the errors back, and a gate keeps the test only if it passes on the normal shop and fails with the matching planted bug. Measured with llama3.2:3b: 0 of 6 tests accepted. The gate rejected every one, and accepts a correct hand-written test.
⏱ 60 minAdvanced💸 Free6 steps
Python 3.12pytesthttpxOllama (optional)llama3.2:3bShopRung bug switch
Overview video
What you will build
A folder api-test-agent with an agent you can trust because of what it refuses:
- agent.py: write, run, read the errors, retry (up to 3 attempts), then the gate: pass on the normal shop, fail with the planted bug, or be rejected.
- rules.json: three requirements (CART-2, PRICE-3, ORD-7), each paired with the ShopRung bug that breaks it.
- conftest.py: the fixtures the model must use:
api,aliceandbob, with a data reset before every test. - Four example tests to prove the gate: two good ones (accepted), a weak one that cannot catch its bug, and the real llama3.2:3b output (both rejected).
Before you start
- The episodes behind it: Coding agents on a test repo and Testing AI-written code.
- pytest and httpx fixtures, as in lab 11, and the bug switch, as in lab 3. ShopRung installed, as in lab 1 setup.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start and leave it running. The gate switches its planted bugs on and off through /api/test/bugs.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"status":"UP","app":"ShopRung","version":"1.0.0"} S2Make the project
Python 3.12 or newer (py on Windows). Create requirements.txt and .gitignore with the contents below, then make the virtual environment and install. Run the activate line again in every new terminal. For step 5 you also need Ollama with ollama pull llama3.2:3b; every other step works without it.
mkdir -p api-test-agent/tests/examples
cd api-test-agent
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtmkdir -p api-test-agent/tests/examples
cd api-test-agent
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtmkdir api-test-agent\tests\examples
cd api-test-agent
py -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt Successfully installed ... httpx-0.28.1 ... pytest-8.3.4
Rules, each with its bug
The agent's work list, and how to prove each test.
Save rules.json. Each entry is a requirement from ShopRung's list and the name of the planted bug that breaks it. That pairing is what makes generated tests checkable: a test for CART-2 is only useful if it fails when quantity-limit is on.
Then save tests/conftest.py. These fixtures are the contract with the model: it must use api, alice and bob as test arguments, never create its own clients. Data resets before every test.
[
{"id": "CART-2", "bug": "quantity-limit",
"requirement": "Each cart line has a quantity from 1 to 10. Adding more of a product that is already in the cart adds to that line, and the line still cannot go above 10."},
{"id": "PRICE-3", "bug": "coupon-boundary",
"requirement": "SAVE10 takes 10% off the subtotal when the subtotal is $50.00 or more."},
{"id": "ORD-7", "bug": "order-leak",
"requirement": "A customer sees only their own orders. Opening another customer's order shows \"not found\"."}
] - The bug that must turn this rule's test red.line 2
"""Fixtures the generated tests may use: api (no login), alice and bob (logged in). Data is reset before each test."""
import os
import httpx
import pytest
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
def client(email=None, password=None):
c = httpx.Client(base_url=BASE_URL, timeout=10)
if email:
token = c.post("/api/auth/login", json={"email": email, "password": password}).json()["token"]
c.headers["Authorization"] = f"Bearer {token}"
return c
@pytest.fixture(autouse=True)
def reset():
httpx.post(f"{BASE_URL}/api/test/reset")
@pytest.fixture
def api():
c = client()
yield c
c.close()
@pytest.fixture
def alice():
c = client("alice@shoprung.test", "Alice123!")
yield c
c.close()
@pytest.fixture
def bob():
c = client("bob@shoprung.test", "Bob12345!")
yield c
c.close() - A fresh shop before every test.line 18
- A logged-in client; the test receives it as an argument.line 31
The agent loop and the gate
Write, run, read errors, retry; then prove it.
Create agent.py. For one rule it sends the model the requirement, the API facts it needs and the fixture rules. It saves the answer as a test file and runs pytest. If the run fails, the full pytest output goes back to the model with "fix the test", up to three attempts: the same loop coding agents use.
Then the gate, in gate(): a test that never passed is rejected; a test that passes is run again with its bug switched on, and must now fail. A test that still passes with the bug on is rejected too: it cannot catch what it is for. --check puts any existing file through the same gate.
"""An agent that writes an API test for one requirement, runs it, fixes it from the errors, and only keeps it
if it passes on the normal shop AND fails when the matching ShopRung bug is switched on.
python agent.py CART-2 # one rule
python agent.py --all # every rule in rules.json
python agent.py --check tests/examples/good_cart_2.py CART-2 # put an existing test through the same gate
"""
import argparse
import json
import os
import re
import subprocess
import sys
import urllib.request
from pathlib import Path
OLLAMA = os.environ.get("OLLAMA_URL", "http://localhost:11434")
MODEL = os.environ.get("MODEL", "llama3.2:3b")
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
MAX_ATTEMPTS = 3
RULES = {r["id"]: r for r in json.loads(Path("rules.json").read_text())}
CONTEXT = """ShopRung JSON API (base URL from the fixtures; use relative paths like "/api/cart"):
- POST /api/cart/items {"productId": int, "quantity": int} -> 200 with the cart {"items": [{"productId", "name", "quantity"}], "subtotalCents", "discountCents", ...}
- POST /api/cart/coupon {"code": "SAVE10"} -> 200 with the cart, or 400 {"error": "coupon_not_applicable", "message": "..."}
- GET /api/cart -> the cart. POST /api/orders -> 201 with the order {"id", "status", ...}
- GET /api/orders/<id> -> 200 with the order, or 404 {"error": "not_found", "message": "No order with id <id>"}
- Errors: 400 invalid_quantity "Quantity must be between 1 and 10"; 409 out_of_stock.
Products: 1 "Clean Code Notebook" $12.50 (stock 40), 4 "Green Build Mug" $15.00 (stock 60), 6 "Ship It T-Shirt" $20.00 (stock 30).
Alice already has order 2 (SHIPPED). Bob has no orders.
Fixtures in conftest.py (do not redefine them): api (not logged in), alice, bob (logged-in httpx.Client objects). Data is reset before every test."""
FIRST = """Write a pytest file that tests exactly this requirement of ShopRung:
{rid}: {requirement}
{context}
Test the boundaries exactly. Use only the fixtures and endpoints above. Return one Python file in a ```python block, nothing else."""
RETRY = """Your test file failed. Here is the pytest output:
{output}
If a test is wrong about the requirement or the API, fix the test. Return the whole corrected file in a ```python block."""
def ask(messages: list[dict]) -> str:
body = {"model": MODEL, "messages": messages, "stream": False, "options": {"temperature": 0.7, "num_predict": 1500}}
req = urllib.request.Request(f"{OLLAMA}/api/chat", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=300) as r:
return json.load(r)["message"]["content"]
def code_from(answer: str) -> str:
blocks = re.findall(r"```(?:python)?\n(.*?)```", answer, re.S)
return max(blocks, key=len) if blocks else answer
def run_tests(path: Path) -> tuple[bool, str]:
r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(path)],
capture_output=True, text=True, timeout=120, env={**os.environ, "BASE_URL": BASE_URL})
return r.returncode == 0, (r.stdout + r.stderr)[-3000:]
def set_bugs(bugs: list[str]) -> None:
req = urllib.request.Request(f"{BASE_URL}/api/test/bugs", data=json.dumps({"enabled": bugs}).encode(),
headers={"Content-Type": "application/json"})
urllib.request.urlopen(req, timeout=10).read()
def gate(rule: dict, path: Path, passed: bool) -> dict:
"""Keep a test only if it passes on the normal shop and fails with the rule's bug switched on."""
if not passed:
return {"verdict": "rejected: does not pass on the normal shop"}
set_bugs([rule["bug"]])
try:
still_passes, output = run_tests(path)
finally:
set_bugs([])
bug_run = output.strip().splitlines()[-1] if output.strip() else ""
if still_passes:
return {"bug_run": bug_run, "verdict": f"rejected: still passes with {rule['bug']} on"}
return {"bug_run": bug_run, "verdict": "accepted: passes, and fails with " + rule["bug"]}
def work_on(rule: dict) -> dict:
path = Path(f"tests/test_{rule['id'].lower().replace('-', '_')}.py")
messages = [{"role": "user", "content": FIRST.format(rid=rule["id"], requirement=rule["requirement"], context=CONTEXT)}]
report = {"rule": rule["id"], "attempts": []}
for attempt in range(1, MAX_ATTEMPTS + 1):
answer = ask(messages)
path.write_text(code_from(answer))
passed, output = run_tests(path)
report["attempts"].append({"attempt": attempt, "passed": passed, "summary": output.strip().splitlines()[-1] if output.strip() else ""})
print(f"{rule['id']} attempt {attempt}: {'passed' if passed else 'failed'} {report['attempts'][-1]['summary']}", flush=True)
if passed:
break
messages += [{"role": "assistant", "content": answer}, {"role": "user", "content": RETRY.format(output=output)}]
if passed:
report.update(gate(rule, path, passed))
else:
report["verdict"] = f"rejected: still failing after {MAX_ATTEMPTS} attempts"
report["file"] = path.read_text()
print(f"{rule['id']}: {report['verdict']}", flush=True)
return report
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("rule", nargs="?")
parser.add_argument("--all", action="store_true")
parser.add_argument("--check", metavar="FILE", help="gate an existing test file instead of asking the model")
parser.add_argument("--report", default="report.json")
args = parser.parse_args()
if args.check:
rule, path = RULES[args.rule], Path(args.check)
passed, output = run_tests(path)
print("normal shop:", output.strip().splitlines()[-1] if output.strip() else "")
result = gate(rule, path, passed)
if "bug_run" in result:
print(f"with {rule['bug']}:", result["bug_run"])
print(f"{rule['id']}: {result['verdict']}")
return
rules = list(RULES.values()) if args.all else [RULES[args.rule]]
reports = [work_on(r) for r in rules]
Path(args.report).write_text(json.dumps(reports, indent=2))
accepted = sum(r["verdict"].startswith("accepted") for r in reports)
print(f"accepted {accepted} of {len(reports)}")
if __name__ == "__main__":
main() - Only the API facts the rule needs: endpoints, errors, seed data.line 23
- The real pytest output goes back to the model.line 41
- Pass on the normal shop, then fail with the bug.line 72
- Green with the bug on means the test checks nothing that matters.line 82
Prove the gate before trusting it
One test it must accept, one it must reject.
A gate is a test of tests, so test it first. Save two hand-written CART-2 tests. The good one checks 10 is allowed, 11 is refused, and 6 + 5 on one line is refused. The weak one only adds 2 items: it passes, but it never goes near the limit.
Put both through the gate. The good test passes, then fails twice with quantity-limit on: accepted. The weak test passes with the bug on too: rejected. The file names do not start with test_, so pytest tests never runs these examples by accident.
"""CART-2, written by hand: the reference answer for the gate."""
def add(client, product_id, quantity):
return client.post("/api/cart/items", json={"productId": product_id, "quantity": quantity})
def test_ten_is_allowed(alice):
r = add(alice, 4, 10)
assert r.status_code == 200
assert r.json()["items"][0]["quantity"] == 10
def test_eleven_is_refused(alice):
r = add(alice, 4, 11)
assert r.status_code == 400
assert r.json()["error"] == "invalid_quantity"
def test_adding_to_a_line_cannot_pass_ten(alice):
assert add(alice, 4, 6).status_code == 200
r = add(alice, 4, 5)
assert r.status_code == 400, "6 + 5 = 11 must be refused"
assert alice.get("/api/cart").json()["items"][0]["quantity"] == 6 - One past the limit.line 15
- The second half of CART-2: adding to an existing line.line 23
"""CART-2, a weak test: it passes, but it only tries numbers inside the limit."""
def test_add_items(alice):
r = alice.post("/api/cart/items", json={"productId": 4, "quantity": 2})
assert r.status_code == 200
assert r.json()["items"][0]["quantity"] == 2 python agent.py --check tests/examples/good_cart_2.py CART-2
python agent.py --check tests/examples/weak_cart_2.py CART-2python agent.py --check tests/examples/good_cart_2.py CART-2
python agent.py --check tests/examples/weak_cart_2.py CART-2python agent.py --check tests/examples/good_cart_2.py CART-2
python agent.py --check tests/examples/weak_cart_2.py CART-2 normal shop: 3 passed in 0.28s with quantity-limit: 2 failed, 1 passed in 0.35s CART-2: accepted: passes, and fails with quantity-limit normal shop: 1 passed in 0.11s with quantity-limit: 1 passed in 0.11s CART-2: rejected: still passes with quantity-limit on
What a small model wrote
Real output, through the gate.
This is the ORD-7 file llama3.2:3b produced after its third attempt in our second round, unedited. It reads well: test names from the requirement, the right order number, even the exact error message. But line 2 imports the fixtures from conftest instead of taking them as arguments, so alice is a function, not a logged-in client, and every test fails with AttributeError.
The retry loop showed the model that error three times and it never fixed it. Save the file and gate it.
import pytest
from conftest import api, alice, bob
def test_customer_sees_only_own_orders():
# Get order from Alice's perspective
response = alice.get("/api/orders/2")
assert "id" in response.json()
def test_opening_other_customer_order_shows_not_found():
# Bob tries to open Alice's order 2 (SHIPPED)
response = bob.get("/api/orders/2")
assert response.status_code == 404
assert response.json()["error"] == "not_found"
assert response.json()["message"] == "No order with id 2"
def test_customer_sees_only_own_orders_with_coupon():
# Bob tries to open Alice's order with saved coupon
response = alice.get("/api/cart/coupon", json={"code": "SAVE10"}, headers={"Authorization": "Bearer ALICE_TOKEN"})
assert response.status_code == 200
response = bob.get("/api/orders/2")
assert response.status_code == 404
assert response.json()["error"] == "not_found"
assert response.json()["message"] == "No order with id 2"
def test_customer_sees_only_own_orders_after_new_order():
# Bob adds new item to cart (quantity out of bounds)
response = bob.post("/api/cart/items", json={"productId": 1, "quantity": 0}, headers={"Authorization": "Bearer BOB_TOKEN"})
assert response.status_code == 400
assert response.json()["error"] == "invalid_quantity"
assert response.json()["message"] == "Quantity must be between 1 and 10"
# Bob adds new item to cart (out of stock)
response = bob.post("/api/cart/items", json={"productId": 3, "quantity": 100}, headers={"Authorization": "Bearer BOB_TOKEN"})
assert response.status_code == 409
assert response.json()["error"] == "out_of_stock"
assert response.json()["message"] == "Product out of stock"
# Bob creates new order and adds item to cart
bob.post("/api/orders", json={"status": "PENDING"}, headers={"Authorization": "Bearer BOB_TOKEN"})
response = bob.post("/api/cart/items", json={"productId": 1, "quantity": 5}, headers={"Authorization": "Bearer BOB_TOKEN"})
# Bob tries to open Alice's order
response = alice.get("/api/orders/3")
assert response.status_code == 200
assert "id" in response.json() - The mistake: fixtures are not imported, pytest passes them in.line 2
- The right idea, which never ran.line 12
python agent.py --check tests/examples/llama_ord_7.py ORD-7python agent.py --check tests/examples/llama_ord_7.py ORD-7python agent.py --check tests/examples/llama_ord_7.py ORD-7 normal shop: 4 failed in 0.29s ORD-7: rejected: does not pass on the normal shop
Run the agent (with Ollama)
Measure it instead of believing a demo.
With Ollama running, let the agent work through all three rules and save a report. We ran it twice on a laptop: 18 attempts, 0 of 6 tests accepted. Four of the six final files imported the fixtures from conftest; both PRICE-3 files built their own HTTP clients that never logged in, one pointing at an invented address; one file added a Django marker to a project with no Django.
Your numbers will differ: the temperature is 0.7. Try a larger model with MODEL=..., or improve the prompt (an example test with fixture arguments is a good start), and measure again. Whatever the model, the gate decides what is kept.
python agent.py --all --report report.jsonpython agent.py --all --report report.jsonpython agent.py --all --report report.json CART-2 attempt 1: failed 1 error in 0.04s CART-2 attempt 2: failed 1 error in 0.04s CART-2 attempt 3: failed 1 error in 0.05s CART-2: rejected: still failing after 3 attempts PRICE-3 attempt 1: failed 1 error in 0.06s PRICE-3 attempt 2: failed 6 failed in 0.58s PRICE-3 attempt 3: failed 6 failed in 0.42s PRICE-3: rejected: still failing after 3 attempts ORD-7 attempt 1: failed 1 error in 0.05s ORD-7 attempt 2: failed 6 failed in 0.21s ORD-7 attempt 3: failed 6 failed in 0.18s ORD-7: rejected: still failing after 3 attempts accepted 0 of 3
Write what the agent could not
A test for ORD-7 that the gate accepts.
Write the ORD-7 test yourself, using the model's good ideas (order 2, a 404, the not_found error) with fixtures as arguments. Gate it: it passes, then fails with order-leak on, where Bob can open Alice's order. Accepted. Move accepted tests into tests/ with a test_ name and they join your suite.
"""ORD-7, written by hand: what the model's draft should have been."""
def test_alice_sees_her_own_order(alice):
r = alice.get("/api/orders/2")
assert r.status_code == 200
assert r.json()["id"] == 2
def test_bob_gets_not_found_for_alices_order(bob):
r = bob.get("/api/orders/2")
assert r.status_code == 404
assert r.json()["error"] == "not_found" - The fixture arrives as an argument.line 10
python agent.py --check tests/examples/good_ord_7.py ORD-7python agent.py --check tests/examples/good_ord_7.py ORD-7python agent.py --check tests/examples/good_ord_7.py ORD-7 normal shop: 2 passed in 0.22s with order-leak: 1 failed, 1 passed in 0.21s ORD-7: accepted: passes, and fails with order-leak
Check it works
The gate accepts good_cart_2.py and good_ord_7.py, and rejects weak_cart_2.py and llama_ord_7.py.
After every run, all bugs are off again: curl http://localhost:8080/api/test/bugs shows an empty list.
python agent.py --check tests/examples/good_ord_7.py ORD-7
python agent.py --check tests/examples/weak_cart_2.py CART-2python agent.py --check tests/examples/good_ord_7.py ORD-7
python agent.py --check tests/examples/weak_cart_2.py CART-2python agent.py --check tests/examples/good_ord_7.py ORD-7
python agent.py --check tests/examples/weak_cart_2.py CART-2 ORD-7: accepted: passes, and fails with order-leak ... CART-2: rejected: still passes with quantity-limit on
Troubleshooting
ConnectionRefusedError or Connection refused from the gate.
ShopRung is not running at BASE_URL (default http://localhost:8080). Start it, or set BASE_URL.
urllib.error.URLError when running the agent.
Ollama is not running or the model is not pulled: ollama pull llama3.2:3b, then ollama list.
Everything fails after you stopped the agent halfway.
A bug may still be on. Turn all bugs off: POST {"enabled":[]} to /api/test/bugs, as in lab 3.
A test you believe is right is rejected with "still passes".
It does not test the boundary or user the bug breaks. Read the bug's description in ShopRung's requirements and test exactly there.
What changes in production
- Teams that let agents write tests keep them behind proof: the test must fail on a known bad version (a planted bug, a mutant, or the commit before the fix).
- Agent output arrives as a pull request with the gate result attached; nothing is merged because it is green.
- Agent runs are measured like any tool: accepted tests per attempt, time and cost, per model and prompt version.
- Fixtures and API facts are given to the agent as a contract, and checked: a file that builds its own client is rejected early.
Interview angle
“How would you let an AI agent write tests safely?”
Behind a gate that proves each test. Our agent loop writes a pytest file, runs it, feeds errors back and retries; then the test must pass on the normal shop and fail with the planted bug for its requirement, or it is rejected. With a small local model, 0 of 6 tests passed the gate: it imported fixtures instead of using them and invented clients. The gate also rejected a hand-written test that passed but could never catch its bug, and accepted the correct ones.
Clean up
Practice
These run in your browser and check your answer.
The gate decision
Write verdict(passes_normal, passes_with_bug) that returns "accepted" only when the test passes on the normal shop and fails with the bug on; otherwise "rejected".
def verdict(passes_normal, passes_with_bug):
return "accepted" if passes_normal else "rejected"
Hint
Both conditions must hold: passes normally, and does not pass with the bug.
The full project
Every file from this lab, as it is after the last step.