Sub topic 11
Testing a Hook with Sample Events
This chapter assumes you can write a small Python script, use a shell pipe, and read JSON. It also assumes you have a pre-action hook like the ones from earlier chapters: it reads a tool-call event from stdin and signals its decision with an exit code and a stderr message.
Why test hooks outside the agent
A hook is a plain program. It takes JSON in and gives an exit code and text out. That makes it easy to test without starting an agent at all.
Testing through the agent is a poor way to find bugs, for three reasons:
- The model decides which commands to run, so you cannot make it produce a specific edge case on demand.
- A blocked call only shows up as a message in a chat. You cannot easily tell whether the hook, the permission system, or the model caused it.
- A hook that fails open (allows everything because it crashed) looks the same as a hook that works, until something risky gets through.
Local tests are fast and repeatable. They also work as a regression suite. Each time you find a bypass, you add one more sample event and the bug stays fixed.
The test loop
The loop has three steps:
- Build a sample event, the same JSON the agent would send.
- Pipe it into the hook.
- Check the exit code and the stderr text.
The diagram shows what you control and what you replace.
A first manual check
The quickest test is a shell pipe. Save the hook from the earlier chapter as guard.py, then run:
echo '{"tool_name":"shell","tool_input":{"command":"rm -rf /"}}' | python3 guard.py
echo "exit code: $?"
echo '{"tool_name":"shell","tool_input":{"command":"ls -la"}}' | python3 guard.py
echo "exit code: $?"The first command should print a "Blocked" message on stderr and report exit code: 2. The second should print nothing and report exit code: 0.
$? holds the exit code of the last command in the pipeline, which is the hook. Read it immediately. Any other command, even echo, overwrites it.
The field names in these events (tool_name, tool_input, command) follow a common convention. Your agent may use different names, so check its documentation and copy a real event before you rely on a sample.
Capture a real event first
Hand-written events drift away from reality. Before you write tests, log one real event from your agent. A throwaway hook can do it:
#!/usr/bin/env python3
import sys
with open("/tmp/last_event.json", "w") as f:
f.write(sys.stdin.read())
sys.exit(0)Run the agent once, trigger a shell command, and open /tmp/last_event.json. Use that file as the template for your samples. Remove the logging hook afterwards, because event data can contain secrets.
An automated test suite
Typing pipes by hand does not scale past four or five cases. A table of cases and a loop is easy to maintain. This script uses only the Python standard library and runs the hook as a subprocess, exactly as the agent would.
#!/usr/bin/env python3
import json
import subprocess
import sys
HOOK = ["python3", "guard.py"]
# (name, raw stdin text, expected exit code, text expected in stderr)
CASES = [
("harmless listing",
json.dumps({"tool_name": "shell", "tool_input": {"command": "ls -la"}}),
0, ""),
("recursive delete of root",
json.dumps({"tool_name": "shell", "tool_input": {"command": "rm -rf /"}}),
2, "Blocked"),
("force push",
json.dumps({"tool_name": "shell", "tool_input": {"command": "git push origin main --force"}}),
2, "Blocked"),
("uppercase SQL",
json.dumps({"tool_name": "shell", "tool_input": {"command": "psql -c 'DROP TABLE users'"}}),
2, "Blocked"),
("rm in a subfolder is allowed",
json.dumps({"tool_name": "shell", "tool_input": {"command": "rm -rf build/cache"}}),
0, ""),
]
def run_case(stdin_text):
result = subprocess.run(
HOOK,
input=stdin_text,
capture_output=True,
text=True,
timeout=5,
)
return result.returncode, result.stderr
failures = 0
for name, stdin_text, want_code, want_text in CASES:
code, err = run_case(stdin_text)
ok = code == want_code and want_text in err
print(f"{'PASS' if ok else 'FAIL'}: {name} (exit {code})")
if not ok:
failures += 1
print(f" expected exit {want_code} with {want_text!r} in stderr, got: {err!r}")
sys.exit(1 if failures else 0)Three details matter here:
- The
timeout=5argument makes a hanging hook fail the test instead of freezing your terminal. - The script checks both the exit code and the message. A hook that exits 2 with an empty message gives the agent nothing to recover with.
- The suite itself exits non-zero on failure, so you can run it in continuous integration.
What to put in the cases
Good coverage comes from several categories, not from many similar cases.
| Category | Example | Why it matters |
|---|---|---|
| Clearly dangerous | `rm -rf /` | Confirms the basic rule works |
| Clearly safe | `ls -la`, `npm test` | Catches false positives that would make the hook unusable |
| Near misses | `rm -rf build/cache`, `git push origin main` | Checks that patterns are not too broad |
| Variations | `RM -RF /`, `git push --force origin main`, extra spaces | Checks case and ordering |
| Other tools | A file-edit event | Confirms the hook ignores or handles tools it was not written for |
| Malformed input | Empty stdin, invalid JSON, missing fields | Confirms the hook fails closed |
False positives deserve as much attention as misses. A hook that blocks git push because the pattern matches too loosely will train people to disable it.
Testing fail-closed behavior
A hook that crashes should block the action. The fail-closed check from the earlier chapter looks like this:
import json
import sys
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: hook could not read the tool call, so it was not allowed.", file=sys.stderr)
sys.exit(2)Add cases that feed it broken input. Each should end in exit code 2:
BROKEN_CASES = [
("empty input", "", 2, "Blocked"),
("not json", "this is not json", 2, "Blocked"),
("json but a list", "[]", 2, "Blocked"),
("missing tool_input", json.dumps({"tool_name": "shell"}), 2, "Blocked"),
("command is null", json.dumps({"tool_name": "shell", "tool_input": {"command": None}}), 2, "Blocked"),
]The "[]" case is a common surprise. json.load parses it without error, then event["tool_input"] raises TypeError, which is why that exception is in the except clause. The None command is subtler: re.search would raise TypeError on None later in the script, outside the try block. Python then exits with code 1, and many agents treat any exit code other than 2 as a non-blocking error. That means the action goes ahead. Your test will catch this only if you run the case, so run it.
Testing path protection
Functions such as is_protected can be tested directly, without a subprocess. Use a temporary directory so that symlink cases are real:
import os
import tempfile
PROTECTED = [".env", ".git", "infra/prod"]
def is_protected(path, project_root):
full = os.path.realpath(os.path.join(project_root, path))
root = os.path.realpath(project_root)
if os.path.commonpath([full, root]) != root:
return True
relative = os.path.relpath(full, root)
parts = relative.split(os.sep)
return any(
relative == p or relative.startswith(p + os.sep) or p in parts
for p in PROTECTED
)
with tempfile.TemporaryDirectory() as root:
os.makedirs(os.path.join(root, "src"))
os.makedirs(os.path.join(root, "infra", "prod"))
os.symlink(os.path.join(root, ".env"), os.path.join(root, "src", "link"))
checks = [
(".env", True),
("src/../.env", True),
("src/link", True),
("infra/prod/main.tf", True),
("../outside.txt", True),
("src/app.py", False),
("environment.md", False),
]
for path, expected in checks:
actual = is_protected(path, root)
status = "PASS" if actual == expected else "FAIL"
print(f"{status}: {path} -> {actual}")The cases that matter most are src/../.env and src/link. Without realpath, both would look harmless. The environment.md case checks that a name which only starts with .env-like text is not caught by a sloppy prefix match.
Testing the decision flow, not only the pattern
A passing pattern test does not prove the whole hook works. Run at least a few end-to-end events through the real script, including the exact JSON shape your agent sends. Also test with a non-trivial working directory, because hooks usually run from the project root and relative paths depend on it. In subprocess.run, set cwd= to match.
Common errors
- Reading
$?too late. Another command ran in between. Save it withcode=$?right away. - Testing only the blocked path. Every blocking test should have a nearby allowed test.
- Hand-written events with wrong field names. The hook sees no command, matches nothing, and exits 0. The test passes while the hook protects nothing. Always check one sample against a real captured event.
- Asserting the full stderr text. Exact message matches break whenever you improve the wording. Check a stable keyword.
- Skipping stdout. Some agents read stdout for JSON decisions. If your hook prints debug text there, it may be misread. Keep debugging output on stderr, or in a log file.
Exercise
Your hook has this test: it sends {"tool_name":"shell","tool_input":{"cmd":"rm -rf /"}} and expects exit code 2, but the hook exits 0. The agent's real events use the field command, not cmd. What has gone wrong, and how would you fix both the test and the hook?
Show answer
The sample event uses the wrong field name, so the hook found no command (get("command", "") returns an empty string), matched no pattern, and allowed the call. The test failure is correct, and it shows a real weakness. Fix the test by using command, copied from a captured real event. Fix the hook by failing closed: if the shell tool's event has no string command field, exit 2 with a message instead of treating it as empty. Then add a test for the missing-field case that expects exit code 2.
Exercise
Write down five test cases (input and expected exit code) for a hook that blocks git push --force. Include at least one case that guards against a false positive and one malformed input.
Show answer
Example set: (1) git push --force origin main expects 2. (2) git push origin main --force expects 2, which checks argument order. (3) git push origin main expects 0, a near miss and false-positive guard. (4) git log --oneline expects 0, an unrelated safe command. (5) Stdin of not json expects 2, which checks fail-closed behavior. Other valid answers include git push -f (expects 2 if the hook covers short flags) and an uppercase GIT PUSH --FORCE.