"""The commit hook (.claude/hooks/pre-commit-tests.sh) blocks exactly the commits whose
tests fail, judged on what the commit will contain. Each test builds a throwaway git
repo with one test file and feeds the hook a Bash command the way Claude Code does."""
from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
import pytest
HOOK = Path(__file__).resolve().parents[1] / ".claude" / "hooks" / "pre-commit-tests.sh"
PASSING = "def test_ok():\n assert True\n"
FAILING = "def test_broken():\n assert False\n"
@pytest.fixture
def repo(tmp_path):
def git(*args):
subprocess.run(["git", *args], cwd=tmp_path, check=True, capture_output=True)
git("init", "-q")
(tmp_path / "tests").mkdir()
(tmp_path / "tests" / "test_a.py").write_text(PASSING)
git("add", "tests/test_a.py")
return tmp_path, git
def run_hook(repo_dir: Path, command: str) -> tuple[int, str]:
env = {**os.environ, "CLAUDE_PROJECT_DIR": str(repo_dir),
"PATH": f"{Path(sys.executable).parent}{os.pathsep}{os.environ['PATH']}"}
result = subprocess.run(["bash", str(HOOK)], input=json.dumps({"tool_input": {"command": command}}),
text=True, capture_output=True, env=env)
return result.returncode, result.stderr
@pytest.mark.parametrize("command", ["git status", 'rg "git commit" docs', "git log --grep 'git commit'"])
def test_commands_that_do_not_commit_pass_through(repo, command):
repo_dir, git = repo
(repo_dir / "tests" / "test_a.py").write_text(FAILING)
git("add", "-A")
assert run_hook(repo_dir, command)[0] == 0
def test_a_commit_is_judged_on_the_staged_files(repo):
repo_dir, git = repo
assert run_hook(repo_dir, "git commit -m ok")[0] == 0
(repo_dir / "tests" / "test_a.py").write_text(FAILING)
assert run_hook(repo_dir, "git commit -m 'broken but not staged'")[0] == 0
git("add", "tests/test_a.py")
code, err = run_hook(repo_dir, "cd somewhere && git commit -m staged")
assert code == 2 and "test_broken" in err
def test_commit_a_adds_changes_to_tracked_files_but_not_untracked_ones(repo):
repo_dir, _ = repo
(repo_dir / "tests" / "test_new.py").write_text(FAILING)
assert run_hook(repo_dir, "git commit -a -m x")[0] == 0
(repo_dir / "tests" / "test_a.py").write_text(FAILING)
assert run_hook(repo_dir, "git commit -am x")[0] == 2
def test_staging_and_committing_in_one_command_is_refused(repo):
code, err = run_hook(repo[0], "git add -A && git commit -m x")
assert code == 2 and "separate commands" in err