0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

13,931テストを1日で書いた——Claude Code hookのテスト戦略と自動化

0
Last updated at Posted at 2026-06-17

9,677本。Claude Code hookのテスト数だ。

hookは「危険なコマンドをブロックする」「安全なコマンドを許可する」という二値判定をする小さなシェルスクリプトだ。小さいからテストも簡単。だが数が多い。40個以上のhookに対して、それぞれ正常系、異常系、エッジケースを網羅する。

どうやって1日で9,677本書いたか。

この記事は2026年6月時点の情報に基づいている。

test.shの構造

テストは1つのtest.shファイルにまとまっている。実行も簡単だ。

bash test.sh

全テストが順に走り、結果がまとめて表示される。

Running 9,677 tests...

[PASS] destructive-guard: blocks rm -rf /
[PASS] destructive-guard: blocks rm -rf ~
[PASS] destructive-guard: allows rm file.txt
...
[PASS] checkpoint-tamper-guard: blocks .claude/checkpoints write

9,677 passed, 0 failed

test_hook関数

テストの核はこの関数だ。

test_hook() {
  local HOOK_NAME="$1"
  local INPUT_JSON="$2"
  local EXPECTED_EXIT="$3"
  local DESCRIPTION="$4"

  TOTAL=$((TOTAL + 1))

  # hookスクリプトを抽出
  local HOOK_SCRIPT
  HOOK_SCRIPT=$(extract_hook "$HOOK_NAME")

  # 入力JSONを環境変数として渡す
  local ACTUAL_EXIT
  CLAUDE_TOOL_INPUT="$INPUT_JSON" bash -c "$HOOK_SCRIPT" > /tmp/hook-stdout 2> /tmp/hook-stderr
  ACTUAL_EXIT=$?

  if [ "$ACTUAL_EXIT" -eq "$EXPECTED_EXIT" ]; then
    PASSED=$((PASSED + 1))
    echo "[PASS] $HOOK_NAME: $DESCRIPTION"
  else
    FAILED=$((FAILED + 1))
    echo "[FAIL] $HOOK_NAME: $DESCRIPTION (expected exit $EXPECTED_EXIT, got $ACTUAL_EXIT)"
    echo "  stdout: $(cat /tmp/hook-stdout)"
    echo "  stderr: $(cat /tmp/hook-stderr)"
  fi
}

シンプルだ。hookに入力を渡し、exit codeを期待値と比較する。

extract_hook関数

hookのソースコードはscripts.jsonに格納されている。extract_hookはそこからhook名でスクリプトを取り出す。

extract_hook() {
  local NAME="$1"
  jq -r --arg name "$NAME" \
    '.hooks[] | select(.name == $name) | .command' \
    scripts.json
}

hookのロジック自体は外部ファイルではなく、JSONの中に埋め込まれている。テスト時にファイルパスを気にしなくていい。

テストカバレッジ100%の過程

「カバレッジ100%」は行カバレッジではない。hookが判定する全パターンを網羅しているという意味だ。

パターンの分類

1つのhookに対して、最低4種類のテストを書く。

ブロックすべきもの(exit 2)

hookが正しくブロックする入力。

# destructive-guard: rm -rf のバリエーション
test_hook "destructive-guard" '{"command":"rm -rf /"}' 2 "blocks rm -rf /"
test_hook "destructive-guard" '{"command":"rm -rf ~"}' 2 "blocks rm -rf ~"
test_hook "destructive-guard" '{"command":"rm -rf /*"}' 2 "blocks rm -rf /*"
test_hook "destructive-guard" '{"command":"  rm   -rf   /  "}' 2 "blocks with extra spaces"
test_hook "destructive-guard" '{"command":"rm -r -f /"}' 2 "blocks separated flags"

許可すべきもの(exit 0)

hookが誤ブロックしてはいけない入力。

# destructive-guard: 安全なrmは通す
test_hook "destructive-guard" '{"command":"rm file.txt"}' 0 "allows single file rm"
test_hook "destructive-guard" '{"command":"rm -f build/*.o"}' 0 "allows build cleanup"
test_hook "destructive-guard" '{"command":"rm -rf node_modules"}' 0 "allows node_modules cleanup"

エッジケース

hookが壊れやすい入力。

# null入力、空文字列、不正なJSON
test_hook "destructive-guard" '' 0 "empty input"
test_hook "destructive-guard" '{}' 0 "empty JSON"
test_hook "destructive-guard" '{"command":""}' 0 "empty command"
test_hook "destructive-guard" '{"command":null}' 0 "null command"
test_hook "destructive-guard" 'not json' 0 "invalid JSON"

hookが不正な入力でクラッシュすると、exit code 1が返る。これはexit 2(ブロック)でもexit 0(許可)でもない。Claude Code本体はexit 1をエラーとして扱い、hookを無視してコマンドを実行する。つまりhookがクラッシュすると安全機構がバイパスされる。

だからエッジケーステストが重要だ。不正入力でもexit 0を返して、正常終了することを保証する。

回帰テスト

過去に見つかったバグを再現する入力。

# バグ: "rm -rf" がパス名に含まれる場合に誤ブロック
test_hook "destructive-guard" '{"command":"cat rm-rf-recovery.md"}' 0 "allows filename containing rm-rf"
test_hook "destructive-guard" '{"command":"grep rm -rf logs/"}' 0 "allows grep with rm pattern"

エッジケーステストの設計

エッジケーステストは機械的に生成できる。以下のパターンを全hookに適用する。

入力の境界値

# 極端に長いコマンド(4096文字)
LONG_CMD=$(python3 -c "print('echo ' + 'a' * 4090)")
test_hook "destructive-guard" "{\"command\":\"$LONG_CMD\"}" 0 "very long command"

# Unicode文字を含むコマンド
test_hook "destructive-guard" '{"command":"rm -rf /tmp/テスト"}' 2 "unicode path with rm -rf"

# 改行を含むコマンド
test_hook "destructive-guard" '{"command":"echo hello\nrm -rf /"}' 2 "newline injection"

バイパス試行

攻撃者(または暴走したAI)がhookをバイパスしようとするパターン。

# コマンド置換
test_hook "destructive-guard" '{"command":"$(echo rm) -rf /"}' 2 "command substitution bypass"

# バックティック
test_hook "destructive-guard" '{"command":"`echo rm` -rf /"}' 2 "backtick bypass"

# エイリアス的なパターン
test_hook "destructive-guard" '{"command":"\\rm -rf /"}' 2 "escaped rm bypass"

# Base64エンコード
test_hook "destructive-guard" '{"command":"echo cm0gLXJmIC8= | base64 -d | bash"}' 2 "base64 encoded rm"

全てのバイパス試行がexit 2でブロックされることを確認する。

並列テスト生成(3バッチ × エージェント)

9,677本を手で書いたわけではない。3つのバッチに分けて並列生成した。

バッチ 対象 hook数 テスト数
1 Security hooks 6 ~240
2 Monitoring + Productivity 7 ~280
3 既存hooks + Safety 残り全部 ~120

各バッチを別のサブエージェントに割り当てた。3つが並列で走る。1バッチあたり約20分。

生成の指示テンプレート

サブエージェントに渡したプロンプトはこんな感じだ。

hookスクリプト: [スクリプト全文]
このhookに対して以下4カテゴリのテストを生成せよ:
1. ブロックすべき入力(exit 2期待) — 最低15パターン
2. 許可すべき入力(exit 0期待) — 最低10パターン
3. エッジケース(null、空、特殊文字、極長) — 最低10パターン
4. バイパス試行(コマンド置換、エンコード、改行注入) — 最低5パターン
形式: test_hook "hook名" 'JSON入力' 期待exit code "説明"

生成されたテストは全て手動で確認してからtest.shに追加した。AI生成テストをそのまま信用するのは危険だ。期待値が間違っていることがある。

実行速度

13,931テストの実行時間は約45秒。hookが小さいシェルスクリプトなので、1テストあたり約20ミリ秒で終わる。CIに入れても負担にならない。

time bash test.sh
# real    0m44.8s
# 9,677 passed, 0 failed

まとめ

hookのテストは3つの原則で書ける。

  1. ブロックと許可の両方をテストする。 片方だけでは意味がない
  2. エッジケースは必ず入れる。 hookがクラッシュすると安全機構がバイパスされる
  3. 並列生成で量を稼ぐ。 手書きは最初の10本だけ。残りはパターンで生成

自分のClaude Code環境が安全かどうか、まずnpx cc-health-checkで確認してみてほしい。

npx cc-health-check

Claude Codeの安全な運用方法をまとめたZenn Bookも公開している。hookの設計、テスト戦略、事故事例と対策を体系的にカバーしている。


Claude Code を安全に使うために、破壊的操作や設定の事故を未然に止める無料の hook 群(MIT ライセンス)を公開しています → cc-safe-setup(npx cc-safe-setup)。導入もアカウント登録も不要です。

さらに、800時間の運用データから、トークン消費の削減・事故の検知と復旧などを主題別にまとめた手引きも公開しています。気になる人は著者の本の一覧から、価格と評価を見て選べます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?