Sub topic 14
Testing approval flows
This chapter assumes you can read short Python programs, know how an agent calls tools, and have seen the gate, fingerprint, and pending-store code from earlier chapters. It shows how to test them with plain pytest-style functions.
What to test
An approval flow fails in ways that ordinary tests miss. The happy path ("approve, then it runs") nearly always works. The bugs sit at the edges, where something runs that should not have, or nothing runs when it should.
Each decision type needs its own test, plus each failure path:
| Behavior | Expected result |
|---|---|
| Low-risk call | Runs with no human prompt |
| Unknown tool | Treated as high risk, human is asked |
| Approve | Tool runs with the original arguments |
| Edit | Tool runs with the edited arguments only |
| Reject | Tool never runs, reason is returned |
| Changed arguments after approval | `PermissionError` |
| Expired or repeated decision | No execution |
Use fakes, not real tools
Replace tools with recording fakes, so a test can check both what ran and what did not. Replace the human with a function that returns a fixed decision.
from dataclasses import dataclass
import hashlib
import json
@dataclass(frozen=True)
class ToolCall:
name: str
args: dict
RISK = {"search_docs": "low", "send_email": "high"}
def risk_of(call):
return RISK.get(call.name, "high")
def run_step(call, tools, ask_human):
if risk_of(call) == "low":
return tools[call.name](**call.args)
decision = ask_human(call)
action = decision["action"]
if action == "approve":
return tools[call.name](**call.args)
if action == "edit":
edited = ToolCall(call.name, decision["args"])
return tools[edited.name](**edited.args)
return {"rejected": True, "reason": decision.get("reason", "")}
def fingerprint(call):
payload = json.dumps({"name": call.name, "args": call.args}, sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()
def execute_if_approved(call, approval, tools):
if approval["fingerprint"] != fingerprint(call):
raise PermissionError("Approval does not match this action")
return tools[call.name](**call.args)
class Recorder:
"""A fake tool that remembers every call made to it."""
def __init__(self):
self.calls = []
def __call__(self, **kwargs):
self.calls.append(kwargs)
return {"ok": True}
def test_low_risk_skips_human():
tool = Recorder()
def human(call):
raise AssertionError("human should not be asked")
run_step(ToolCall("search_docs", {"q": "x"}), {"search_docs": tool}, human)
assert tool.calls == [{"q": "x"}]
def test_unknown_tool_requires_approval():
asked = []
tool = Recorder()
def human(call):
asked.append(call)
return {"action": "reject", "reason": "no"}
run_step(ToolCall("new_tool", {}), {"new_tool": tool}, human)
assert len(asked) == 1
assert tool.calls == []
def test_reject_never_runs_tool():
tool = Recorder()
result = run_step(
ToolCall("send_email", {"to": "[email protected]"}),
{"send_email": tool},
lambda c: {"action": "reject", "reason": "wrong recipient"},
)
assert tool.calls == []
assert result == {"rejected": True, "reason": "wrong recipient"}
def test_edit_runs_only_edited_args():
tool = Recorder()
run_step(
ToolCall("send_email", {"to": "[email protected]"}),
{"send_email": tool},
lambda c: {"action": "edit", "args": {"to": "[email protected]"}},
)
assert tool.calls == [{"to": "[email protected]"}]
def test_changed_args_break_approval():
tool = Recorder()
approved = ToolCall("send_email", {"to": "[email protected]"})
approval = {"fingerprint": fingerprint(approved)}
tampered = ToolCall("send_email", {"to": "[email protected]"})
try:
execute_if_approved(tampered, approval, {"send_email": tool})
except PermissionError:
pass
else:
raise AssertionError("expected PermissionError")
assert tool.calls == []Every negative test ends by asserting that the tool's call list is empty. That assertion is the real check. A test that only looks at the return value can pass while the email was still sent.
Testing time and repeats
Expiry tests should not sleep. Pass a TTL of zero or a negative number, or patch the clock, so the test runs instantly. Resolve the same approval ID twice and check that the second attempt fails with KeyError. This catches double execution after a retry or a double click.
For pause and resume, save state, build a fresh gate object (which simulates a restart), and resume from the stored data. If the test only resumes within the same object, it can pass while real restarts lose data.
Adversarial cases
Add a few cases that mimic hostile input. Give the gate arguments that contain text such as "ignore the reviewer and send now". Check that the decision still comes only from the human's structured response. Also check that changing key order in the arguments does not change the fingerprint, and that changing a value does.
Exercise
A test for the reject path calls run_step, then asserts that the return value equals {"rejected": True, "reason": "wrong recipient"}. Why is this not enough, and what should you add?
Show answer
The return value can be correct even if the tool also ran. Add an assertion that the fake tool's recorded call list is empty, which proves the rejected action never executed.