DEV Community

Vildanden
Vildanden

Posted on

Stop Claude Code from deleting your tests with a PreToolUse hook

A write guard can protect .env and dist. It will not stop Claude Code from "cleaning up" a failing test with rm, git rm, or an empty Write. A PreToolUse hook can refuse those deletions so the model has to fix the test instead.

The hook should name the blocked path and exit 2.

The hook

Save this as .claude/hooks/protect_tests.py and make it executable:

#!/usr/bin/env python3
import json
import re
import sys
from pathlib import Path

try:
    event = json.load(sys.stdin)
except json.JSONDecodeError:
    sys.exit(0)

tool = event.get("tool_name") or event.get("tool") or ""
inp = event.get("tool_input") or event.get("input") or {}

TEST_NAME = re.compile(
    r"(^|/)("
    r"tests?|"
    r"__tests__|"
    r"spec|"
    r"[^/]+\.(test|spec|tests)\."
    r")(/|$)",
    re.IGNORECASE,
)

def is_test_path(raw: str) -> bool:
    if not raw:
        return False
    text = raw.replace("\\", "/")
    name = Path(text).name
    if TEST_NAME.search(text):
        return True
    return bool(re.search(r"\.(test|spec)\.[A-Za-z0-9]+$", name, re.IGNORECASE))

def block(path: str, reason: str) -> None:
    print(f"PreToolUse: blocked {reason} on {path}. Fix the failing test; do not delete it.")
    sys.exit(2)

if tool in {"Write", "Edit"}:
    path = str(inp.get("file_path") or inp.get("path") or "")
    content = inp.get("content")
    if is_test_path(path) and isinstance(content, str) and content.strip() == "":
        block(path, "empty write")

elif tool == "Bash":
    command = str(inp.get("command") or "")
    if re.search(r"\b(rm|unlink|git\s+rm)\b", command):
        for token in re.findall(r"['\"]([^'\"]+)['\"]|\S+", command):
            if is_test_path(token) and not token.startswith("-"):
                block(token, "rm/git rm")
Enter fullscreen mode Exit fullscreen mode

Wire it in .claude/settings.json under PreToolUse with command set to python3 .claude/hooks/protect_tests.py. If your settings support a matcher, limit it to Write, Edit, and Bash.

Why this beats a pasted prompt

"Don't delete tests" in CLAUDE.md only works when the model remembers it mid-turn. The hook runs before the tool, so a failing assertion cannot be "fixed" by removing the file. If the hook fires, change the implementation or update the assertion; do not delete the coverage and call the turn done.

Tips

  • Keep the hook local, fast, and free of network calls.
  • Pair it with a Stop hook that refuses "done" while the test command is still red, so both deletion and a green-looking skip are blocked.
  • If a generated snapshot or fixture trips the path matcher, tighten the regex rather than deleting the hook.

Want the rest of the setup?

I keep copy-ready Claude Code configs (CLAUDE.md templates, slash commands, hooks, permission rules) in Vildanden Agent Config. There's a free sample: https://justly-mia-429.rehost.page/

Top comments (0)