Files
DongHyeonka da9a2b03a4
frontend-quality-gates / merge / static checks (pull_request) Successful in 2m2s
frontend-quality-gates / merge / tests (pull_request) Successful in 15m54s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 5m59s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
frontend-quality-gates / main / self-tests and removal drills (pull_request) Skipped
fix(hooks): N5가 checkout 안의 다른 git repo 파일을 세지 않는다
Stop 훅 N5는 checkout 아래 경로면 어느 git repo의 파일이든 desktop
확인이 필요한 편집으로 센다. checkout 안 카드 저장소 사본에 파일만
써도 턴 끝을 막는데, 그 파일은 scripts/verify.sh가 보내는 트리에 없어
desktop 게이트가 볼 수 없다.

파일이 속한 repo의 git common dir가 checkout의 것과 다르고, verify.sh가
보내는 파일(추적 파일과 무시되지 않는 새 파일)에도 없을 때만 뺀다.
안쪽에 .git이 남은 폴더라도 git add -A가 담는 파일이면 센다. 같은
repo의 worktree는 common dir가 같아 다른 repo로 보지 않는다. git이
답하지 못하면(시간 초과, UTF-8이 아닌 답, 절대 경로가 아닌 옛 git의
답, 깨진 index) 센다. 느린 문서 검사가 훅 제한 시간에 걸려도 편집이
남도록 기록을 그 검사보다 먼저 한다.

무시되는 경로를 모두 빼는 안은 무시 폴더에 둔 worktree까지 빠져서,
사본 폴더 이름만 빼는 안은 다른 사본에서 다시 나서, index나 그 경로
하나만 묻는 안은 남은 .git 아래 새 파일이 빠져서 쓰지 않는다.

편집마다 git 호출이 두 번, 다른 repo의 파일이면 세 번이다(실제
checkout에서 약 10 ms). 다른 repo 파일에 대한 N2·N3·N6 알림과,
.claude/ 아래 worktree의 코드를 세지 않는 기존 규칙, checkout 밖
파일을 세지 않는 동작은 그대로다.

검증: 고치기 전 hooks.py에 다른 repo 시험 2개를 더하면 실패한다.
리뷰가 찾은 시간 초과·옛 git 답·추적 파일·새 파일·기록 순서 시험은
각 수정 전 판에서 실패한다. worktree·이름 접두어 시험은 동작을
고정하는 시험이고 변이로 확인했다. 고친 뒤 scripts/verify.sh hooks
105개와 docs가 통과하고, 변이 21개를 모두 시험이 잡는다.

Refs: REV-FE-0039
2026-11-22 20:57:34 +09:00

466 lines
24 KiB
Python

"""scripts/hooks/hooks.py의 시험. 고장 낸 입력에서 알림이 나오고, 맞는 입력에서 조용한지 본다.
python3 -m unittest discover -s scripts/tests
"""
from __future__ import annotations
import importlib.util
import io
import json
import os
import shutil
import subprocess
import sys
import tempfile
import textwrap
import unittest
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
from unittest import mock
SCRIPTS = Path(__file__).resolve().parent.parent
REPO = SCRIPTS.parent
_spec = importlib.util.spec_from_file_location("hooks", SCRIPTS / "hooks/hooks.py")
hooks = importlib.util.module_from_spec(_spec)
sys.modules["hooks"] = hooks
_spec.loader.exec_module(hooks)
GIT_ENV = {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.com", "GIT_COMMITTER_NAME": "t",
"GIT_COMMITTER_EMAIL": "t@example.com", "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.hooksPath",
"GIT_CONFIG_VALUE_0": "/dev/null"}
FILES = {
"src/adapters/http/index.ts": "export * from './client.ts';\n",
"src/adapters/http/client.ts": "export const client = 1;\n",
"src/adapters/auth/index.ts": "export const auth = 1;\n",
"src/adapters/auth/session.ts": "export const session = 1;\n",
"src/adapters/platform/locks.ts": "export const locks = 1;\n",
"src/bootstrap/compose.ts": "export {};\n",
"src/presentation/pages/home-page.tsx": "export {};\n",
"src/domain/order.ts": "export {};\n",
}
class Repository:
"""A throwaway git checkout with the real import rules and a few adapter groups."""
def __init__(self) -> None:
self._directory = tempfile.TemporaryDirectory()
self.root = Path(self._directory.name).resolve()
shutil.copy(REPO / hooks.RULES, self.root / hooks.RULES)
for path, text in FILES.items():
self.write(path, text)
self.git("init", "-q")
self.git("add", "-A")
self.git("commit", "-q", "-m", "base")
def git(self, *args: str) -> None:
subprocess.run(["git", *args], cwd=self.root, check=True, capture_output=True, env={**os.environ, **GIT_ENV})
def write(self, path: str, text: str) -> Path:
target = self.root / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text, encoding="utf-8")
return target
def payload(self, path: str, tool: str = "Edit", **extra) -> dict:
return {"session_id": "s1", "cwd": str(self.root), "tool_name": tool,
"tool_input": {"file_path": str(self.root / path)}, **extra}
def close(self) -> None:
self._directory.cleanup()
def run_event(event: str, payload: dict) -> tuple[int, str, str]:
out, err = io.StringIO(), io.StringIO()
with mock.patch.dict(os.environ, {}, clear=False), \
mock.patch.object(sys, "stdin", io.StringIO(json.dumps(payload))), redirect_stdout(out), redirect_stderr(err):
os.environ.pop("CLAUDE_PROJECT_DIR", None)
code = hooks.main([event])
return code, out.getvalue(), err.getvalue()
def added_context(stdout: str) -> str:
return json.loads(stdout)["hookSpecificOutput"]["additionalContext"] if stdout else ""
class RepositoryTestCase(unittest.TestCase):
def setUp(self) -> None:
self.repo = Repository()
self.addCleanup(self.repo.close)
def edit(self, path: str, text: str) -> str:
self.repo.write(path, text)
code, out, _ = run_event("post-edit", self.repo.payload(path))
self.assertEqual(code, 0)
return added_context(out)
class BoundaryNudgeTest(RepositoryTestCase):
def test_a_deep_import_past_the_barrel_is_item_1(self) -> None:
text = self.edit("src/bootstrap/compose.ts", 'import { client } from "../adapters/http/client.ts";\n')
self.assertIn("경계 알림(N3) src/bootstrap/compose.ts", text)
self.assertIn("꼭 지킬 것 1 의심: `adapter-groups-are-reached-through-their-barrel`", text)
self.assertIn("src/adapters/http/client.ts", text)
def test_the_barrel_is_quiet(self) -> None:
self.assertEqual(self.edit("src/bootstrap/compose.ts", 'import { client } from "../adapters/http/index.ts";\n'), "")
def test_another_adapter_is_item_2_and_the_kernel_is_allowed(self) -> None:
text = self.edit("src/adapters/http/client.ts", textwrap.dedent("""\
import { session } from "../auth/session.ts";
import { locks } from "../platform/locks.ts";
"""))
self.assertIn("꼭 지킬 것 2 의심: `adapters-do-not-know-other-concrete-adapters`", text)
self.assertNotIn("platform/locks", text)
def test_a_package_import_is_checked_by_its_name(self) -> None:
text = self.edit("src/domain/order.ts", 'import { useState } from "react";\n')
self.assertIn("꼭 지킬 것 3 의심: `domain-is-framework-neutral` — `react`", text)
def test_type_only_reexports_and_dynamic_imports_count(self) -> None:
for source in ('export type { Client } from "../../adapters/http/client.ts";\n',
'const page = () => import("../../adapters/http/client.ts");\n',
'import type {\n Client,\n} from "../../adapters/http/client";\n'):
with self.subTest(source=source):
self.assertIn("presentation-does-not-know-adapters",
self.edit("src/presentation/pages/home-page.tsx", source))
def test_findings_are_capped_and_keep_the_gate_line(self) -> None:
text = self.edit("src/presentation/pages/home-page.tsx",
'import { client } from "../../adapters/http/client.ts";\nimport z from "zod";\n')
lines = text.splitlines()
self.assertLessEqual(len(lines), hooks.MAX_LINES)
self.assertRegex(lines[-2], r"^- 외 \d+개$")
self.assertIn("FE-GATE-010", lines[-1])
def test_files_outside_src_and_declarations_are_not_checked(self) -> None:
self.assertEqual(self.edit("tests/unit/x.test.ts", 'import { c } from "../../src/adapters/http/client.ts";\n'), "")
self.assertEqual(self.edit("src/bootstrap/env.d.ts", 'import { c } from "../adapters/http/client.ts";\n'), "")
def test_the_real_rules_find_nothing_in_the_real_sources(self) -> None:
# A nudge the gate would not raise is noise. The repository passes check:architecture, so every
# source file here must be quiet; a new false positive fails this test before it reaches a session.
noisy = []
for path in sorted((REPO / "src").rglob("*")):
if path.suffix in (".ts", ".tsx") and path.is_file():
relative = path.relative_to(REPO).as_posix()
if hooks.boundary_findings(REPO, relative, path.read_text(encoding="utf-8")):
noisy.append(relative)
self.assertEqual(noisy, [])
class StandardNudgeTest(RepositoryTestCase):
TEST = "tests/unit/orders.test.ts"
def setUp(self) -> None:
super().setUp()
self.repo.write(self.TEST, 'it.skip("a", () => {});\nit("b", () => {});\n')
self.repo.git("add", "-A")
self.repo.git("commit", "-q", "-m", "test")
def test_skips_and_only_added_since_the_last_commit_are_reported(self) -> None:
text = self.edit(self.TEST, 'it.skip("a", () => {});\nit.skip("b", () => {});\ndescribe.only("c", () => {});\n')
self.assertIn("게이트 기준 알림(N6) tests/unit/orders.test.ts", text)
self.assertIn("`.only` 0→1", text)
self.assertIn("`.skip` 1→2", text)
self.assertIn("꼭 지킬 것 4", text)
def test_an_unchanged_or_smaller_count_is_quiet(self) -> None:
self.assertEqual(self.edit(self.TEST, 'it.skip("a", () => { expect(1).toBe(1); });\n'), "")
self.assertEqual(self.edit(self.TEST, 'it("a", () => {});\n'), "")
def test_a_new_test_file_counts_from_zero_and_playwright_fixme_counts(self) -> None:
text = self.edit("tests/e2e/new.spec.ts", 'test.fixme("x", async () => {});\n')
self.assertIn("`.fixme` 0→1", text)
def test_a_gate_standard_file_edit_is_reported(self) -> None:
for path in ("config/performance/budgets.json", "config/ci/ungated-tests.json",
"config/scale/feature-shape-ceilings.json", "vitest.config.ts",
"tests/unit/__snapshots__/x.test.ts.snap"):
with self.subTest(path=path):
self.assertIn("게이트의 기준 파일", self.edit(path, "{}\n"))
def test_source_text_that_looks_like_a_skip_is_not_counted(self) -> None:
self.assertEqual(self.edit("src/domain/order.ts", 'export const note = "use it.only when";\n'), "")
class DocumentNudgeTest(RepositoryTestCase):
def checker(self, code: int, stderr_lines: list[str]) -> None:
body = "import sys\n" + "".join(f"print({line!r}, file=sys.stderr)\n" for line in stderr_lines)
self.repo.write(hooks.DOC_CHECK[0], body + f"sys.exit({code})\n")
def test_failures_naming_the_edited_document_come_back_first(self) -> None:
self.checker(1, ["", "FAILED: 2 problem(s)", " docs/work/improve.md:3: history ID '1103/11-07'",
" docs/work/README.md:9: broken relative link 'x.md'"])
text = self.edit("docs/work/improve.md", "# x\n")
self.assertIn("문서 검사 알림(N2) docs/work/improve.md", text)
self.assertIn("1103/11-07", text)
self.assertNotIn("broken relative link", text)
def test_failures_elsewhere_are_shown_when_none_names_the_document(self) -> None:
self.checker(1, [" AGENTS.md: 41 lines, limit 40"])
self.assertIn("AGENTS.md: 41 lines", self.edit("docs/manual/README.md", "# x\n"))
def test_a_passing_check_adds_nothing(self) -> None:
self.checker(0, [])
self.assertEqual(self.edit("docs/work/improve.md", "# x\n"), "")
class TurnEndNudgeTest(RepositoryTestCase):
def stop(self, **extra) -> dict | None:
_, out, _ = run_event("stop", {"session_id": "s1", "cwd": str(self.repo.root), **extra})
return json.loads(out) if out else None
def bash(self, command: str) -> None:
run_event("post-bash", {"session_id": "s1", "cwd": str(self.repo.root), "tool_name": "Bash",
"tool_input": {"command": command}})
def test_an_edit_blocks_the_turn_end_once_with_the_reason(self) -> None:
self.edit("src/domain/order.ts", "export const a = 1;\n")
first = self.stop()
self.assertEqual(first["decision"], "block")
self.assertIn("src/domain/order.ts", first["reason"])
self.assertIn("scripts/verify.sh", first["reason"])
self.assertIsNone(self.stop())
def test_a_desktop_run_clears_the_pending_edits(self) -> None:
for command in ("ssh desktop 'cd ~/workspace/x && corepack pnpm -s lint'",
"scripts/verify.sh merge --log fe-x",
"./scripts/verify.sh gate FE-GATE-005",
"cd /w && scripts/verify.sh script verify:documentation 2>&1 | tail"):
with self.subTest(command=command):
self.edit("src/domain/order.ts", "export const a = 2;\n")
self.bash(command)
self.assertIsNone(self.stop())
def test_reading_verify_sh_or_a_dry_run_does_not_count(self) -> None:
# 1112/08-09. Only a command that runs a desktop step clears the reminder.
for command in ("scripts/verify.sh merge --dry-run",
"sed -n 1,80p scripts/verify.sh && ls",
"grep -n foo scripts/verify.sh config/ci/gates.json",
"git log -- scripts/verify.sh docs/work",
"ssh desktop 'cat /tmp/claude-gates/x/FE-GATE-005.log | grep vitest'"):
with self.subTest(command=command):
self.edit("src/domain/order.ts", "export const a = 5;\n")
self.bash(command)
self.assertIsNotNone(self.stop())
def test_a_wrapped_desktop_step_counts(self) -> None:
for command in ("timeout 900 scripts/verify.sh exec --log x -- node scripts/run-vitest.ts run tests/unit/a.test.ts",
"VERIFY_SNAPSHOT=1 scripts/verify.sh merge --log r9",
# round9 confirm review: a shell that runs the script, and ssh options with a value.
"bash scripts/verify.sh merge --log r9",
"ssh -o BatchMode=yes desktop 'cd ~/workspace/x && corepack pnpm -s lint'",
"ssh -p 22 desktop 'corepack pnpm -s lint'"):
with self.subTest(command=command):
self.edit("src/domain/order.ts", "export const a = 6;\n")
self.bash(command)
self.assertIsNone(self.stop())
def test_laptop_commands_and_other_hosts_do_not_count(self) -> None:
for command in ("corepack pnpm lint", "ssh build-box 'corepack pnpm lint'", "scripts/verify.sh docs",
"scripts/verify.sh hooks", "scripts/verify.sh gate FE-GATE-005 --on here",
"ssh desktop uptime"):
with self.subTest(command=command):
self.edit("src/domain/order.ts", "export const a = 3;\n")
self.bash(command)
self.assertIsNotNone(self.stop())
def test_files_the_laptop_checks_do_not_need_the_desktop(self) -> None:
for path in (".claude/settings.json", "scripts/hooks/hooks.py", "scripts/tests/test_x.py",
"docs/ledger/estimates.jsonl", "scripts/check-work-docs.py"):
self.repo.write(path, "x\n")
run_event("post-edit", self.repo.payload(path))
self.assertIsNone(self.stop())
def test_living_instruction_documents_need_the_desktop(self) -> None:
# 1112/08-04. verify:documentation, a desktop gate, checks these documents too.
for path in (".claude/rules/x.md", ".claude/skills/fe-x/SKILL.md", "CLAUDE.md",
"src/adapters/AGENTS.md", "src/features/CLAUDE.md",
# round9 confirm review: living module READMEs beside laptop-checked files.
"scripts/hooks/README.md", "docs/ledger/README.md"):
with self.subTest(path=path):
self.edit(path, "x\n")
self.assertIsNotNone(self.stop())
def test_a_file_of_another_repository_inside_the_checkout_does_not_need_the_desktop(self) -> None:
# The desktop gates never see a nested clone (a project-docs copy): verify.sh sends this repository's tree.
path = "cards-copy/projects/x/card.md"
self.repo.write(path, "# card\n")
self.repo.git("init", "-q", "cards-copy")
run_event("post-edit", self.repo.payload(path))
self.assertIsNone(self.stop())
def test_another_repository_does_not_hide_an_edit_of_this_one(self) -> None:
self.repo.write("cards-copy/card.md", "# card\n")
self.repo.git("init", "-q", "cards-copy")
run_event("post-edit", self.repo.payload("cards-copy/card.md"))
self.edit("src/domain/order.ts", "export const a = 7;\n")
reason = self.stop()["reason"]
self.assertIn("src/domain/order.ts", reason)
self.assertNotIn("cards-copy", reason)
def test_an_ignored_worktree_of_this_repository_still_needs_the_desktop(self) -> None:
self.repo.write(".git/info/exclude", "lanes/\n")
self.repo.git("worktree", "add", "-q", "--detach", "lanes/wt")
self.edit("lanes/wt/src/domain/order.ts", "export const a = 8;\n")
self.assertIsNotNone(self.stop())
def test_a_folder_git_cannot_read_still_needs_the_desktop(self) -> None:
self.repo.write("broken/.git", "gitdir: /nonexistent/gitdir\n")
self.edit("broken/note.md", "# note\n")
self.assertIsNotNone(self.stop())
def test_a_root_git_cannot_read_still_needs_the_desktop(self) -> None:
self.repo.git("init", "-q", "cards-copy")
(self.repo.root / ".git").rename(self.repo.root / "git-moved-away")
# A TMPDIR inside some checkout must not answer for the root.
with mock.patch.dict(os.environ, {"GIT_CEILING_DIRECTORIES": str(self.repo.root.parent)}):
self.edit("cards-copy/card.md", "# card\n")
self.assertIsNotNone(self.stop())
def test_a_tracked_file_below_a_stray_git_directory_still_needs_the_desktop(self) -> None:
# `git add -A` in verify.sh still sends it: this repository's index has the path.
self.repo.git("init", "-q", "src/domain")
self.edit("src/domain/order.ts", "export const a = 10;\n")
self.assertIsNotNone(self.stop())
def test_a_new_file_below_a_stray_git_directory_still_needs_the_desktop(self) -> None:
# verify.sh's `git add -A` goes on into a folder that has tracked files, stray .git or not.
self.repo.git("init", "-q", "src")
for path in ("src/domain/new.ts", "src/features/a/index.ts", "src/*.md"):
with self.subTest(path=path):
self.edit(path, "export const a = 10;\n")
self.assertIsNotNone(self.stop())
def test_an_ignored_file_is_not_taken_for_the_tracked_one_its_name_starts(self) -> None:
self.repo.write("cards-copy/card.md", "# tracked before the copy\n")
self.repo.git("add", "cards-copy/card.md")
self.repo.git("init", "-q", "cards-copy")
self.repo.write(".git/info/exclude", "card.m\n")
self.edit("cards-copy/card.m", "ignored\n")
self.assertIsNone(self.stop())
def test_an_index_git_cannot_read_still_needs_the_desktop(self) -> None:
self.repo.git("init", "-q", "cards-copy")
self.repo.write(".git/index", "not an index\n")
self.edit("cards-copy/card.md", "# card\n")
self.assertIsNotNone(self.stop())
def test_an_answer_that_is_not_an_absolute_path_still_needs_the_desktop(self) -> None:
# Before git 2.31 rev-parse echoes the option it does not know, exits 0 and answers relative to the folder.
run = subprocess.run
def older_git(command, **options):
return run([word.replace("--path-format=", "--unknown-format=") for word in command], **options)
# An ignored file: only the comparison of the two git dirs can keep it counted.
self.repo.write(".git/info/exclude", "*.local\n")
with mock.patch.object(hooks.subprocess, "run", side_effect=older_git):
self.edit("src/domain/new.local", "export const a = 11;\n")
self.assertIsNotNone(self.stop())
def test_an_answer_git_cannot_give_in_time_or_in_utf8_still_needs_the_desktop(self) -> None:
run = subprocess.run
timeout = subprocess.TimeoutExpired("git", 5)
undecodable = UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid start byte")
for name, failing_call, error in (("root timeout", 1, timeout), ("file timeout", 2, timeout),
("index timeout", 3, timeout), ("root not utf-8", 1, undecodable),
("file not utf-8", 2, undecodable)):
with self.subTest(name):
copy = f"copy-{failing_call}-{type(error).__name__}"
self.repo.git("init", "-q", copy)
waits = []
def failing_git(command, **options):
waits.append(options.get("timeout"))
if len(waits) == failing_call:
raise error
return run(command, **options)
self.repo.write(f"{copy}/card.txt", "card\n")
with mock.patch.object(hooks.subprocess, "run", side_effect=failing_git):
run_event("post-edit", self.repo.payload(f"{copy}/card.txt"))
# No further git call once one has not answered, each within the hook's own limit.
self.assertEqual(waits, [5] * failing_call)
self.assertIsNotNone(self.stop())
def test_the_edit_is_recorded_before_the_slower_document_check(self) -> None:
pending = []
def document_check(root, path):
pending.extend(hooks.load_state(root, "s1")["pending"])
return []
with mock.patch.object(hooks, "doc_findings", side_effect=document_check):
self.edit("docs/work/improve.md", "# x\n")
self.assertEqual(pending, ["docs/work/improve.md"])
def test_a_worktree_under_dot_claude_follows_that_folders_rule(self) -> None:
self.repo.git("worktree", "add", "-q", "--detach", ".claude/worktrees/wt")
self.edit(".claude/worktrees/wt/src/domain/order.ts", "export const a = 12;\n")
self.assertIsNone(self.stop())
self.edit(".claude/worktrees/wt/README.md", "# x\n")
self.assertIsNotNone(self.stop())
def test_without_a_git_command_an_edit_still_needs_the_desktop(self) -> None:
with mock.patch.object(hooks.subprocess, "run", side_effect=FileNotFoundError("git")):
self.edit("src/domain/order.ts", "export const a = 9;\n")
self.assertIsNotNone(self.stop())
def test_a_new_edit_after_the_reminder_reminds_again(self) -> None:
self.edit("src/domain/order.ts", "export const a = 4;\n")
self.stop()
self.edit("docs/work/README.md", "# x\n")
self.assertIsNotNone(self.stop())
def test_an_active_stop_hook_never_blocks_again(self) -> None:
self.edit("src/domain/order.ts", "export const a = 5;\n")
self.assertIsNone(self.stop(stop_hook_active=True))
class SettingsWiringTest(unittest.TestCase):
SETTINGS = REPO / ".claude/settings.json"
def setUp(self) -> None:
self.settings = json.loads(self.SETTINGS.read_text(encoding="utf-8"))
def commands(self, event: str, matcher: str | None) -> list[str]:
return [hook["command"] for entry in self.settings["hooks"].get(event, [])
if entry.get("matcher") == matcher for hook in entry["hooks"]]
def test_every_event_calls_its_hook(self) -> None:
self.assertEqual(self.commands("PostToolUse", "Edit|Write|MultiEdit"),
['python3 "$CLAUDE_PROJECT_DIR"/scripts/hooks/hooks.py post-edit'])
self.assertEqual(self.commands("PostToolUse", "Bash"),
['python3 "$CLAUDE_PROJECT_DIR"/scripts/hooks/hooks.py post-bash'])
self.assertEqual(self.commands("Stop", None), ['python3 "$CLAUDE_PROJECT_DIR"/scripts/hooks/hooks.py stop'])
self.assertNotIn("PreToolUse", self.settings["hooks"])
def test_real_env_files_are_denied_and_the_example_is_not(self) -> None:
deny = self.settings["permissions"]["deny"]
for tool in ("Read", "Edit"):
self.assertIn(f"{tool}(**/.env)", deny)
self.assertIn(f"{tool}(**/.env.local)", deny)
self.assertFalse([rule for rule in deny if "example" in rule or rule in ("Read(**/.env.*)", "Edit(**/.env.*)")])
def test_the_harness_plugin_is_enabled_from_its_marketplace(self) -> None:
self.assertEqual(self.settings["enabledPlugins"], {"harness@claude-harness": True})
source = self.settings["extraKnownMarketplaces"]["claude-harness"]["source"]
self.assertEqual(source, {"source": "git",
"url": "https://git.learn.hyeonworks.com/donghyeon.kang/claude-harness.git"})
def test_the_hook_script_runs_from_the_command_line(self) -> None:
for event in hooks.EVENTS:
result = subprocess.run([sys.executable, str(SCRIPTS / "hooks/hooks.py"), event], input="{}",
capture_output=True, text=True, timeout=10, cwd=tempfile.gettempdir())
self.assertEqual(result.returncode, 0, event + result.stderr)
result = subprocess.run([sys.executable, str(SCRIPTS / "hooks/hooks.py"), "nope"], input="{}",
capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 1)
if __name__ == "__main__":
unittest.main()