-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_all_hooks.py
More file actions
executable file
·287 lines (238 loc) · 9.33 KB
/
test_all_hooks.py
File metadata and controls
executable file
·287 lines (238 loc) · 9.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/env python3
"""
Test script to verify all Claude Code hook logging is working.
This script generates unique identifiers for each tool call and
then verifies the logs contain those identifiers.
"""
import json
import random
import sys
from datetime import datetime
from pathlib import Path
# Generate unique test identifier
TEST_ID = f"zebra-{random.randint(1000, 9999)}-flamingo-{random.randint(1000, 9999)}"
print(f"Test ID: {TEST_ID}")
# Tools to test with their expected hook types
TOOLS_TO_TEST = {
"Bash": {
"hooks": ["PreToolUse", "PostToolUse"],
"test_command": f'echo "Hook test {TEST_ID}"',
},
"Read": {"hooks": ["PreToolUse", "PostToolUse"], "test_file": "/tmp/hook_test.txt"},
"Write": {
"hooks": ["PreToolUse", "PostToolUse"],
"test_file": "/tmp/hook_test_write.txt",
"content": f"Test content {TEST_ID}",
},
"Edit": {
"hooks": ["PreToolUse", "PostToolUse"],
"test_file": "/tmp/hook_test_edit.txt",
"old_string": "original",
"new_string": f"edited {TEST_ID}",
},
"MultiEdit": {
"hooks": ["PreToolUse", "PostToolUse"],
"test_file": "/tmp/hook_test_multiedit.txt",
},
"Grep": {"hooks": ["PreToolUse", "PostToolUse"], "pattern": TEST_ID},
"Glob": {"hooks": ["PreToolUse", "PostToolUse"], "pattern": "*.py"},
"LS": {"hooks": ["PreToolUse", "PostToolUse"], "path": "/tmp"},
"TodoWrite": {
"hooks": ["PreToolUse", "PostToolUse"],
"todos": [
{
"content": f"Test todo {TEST_ID}",
"status": "pending",
"priority": "low",
"id": "test1",
}
],
},
"WebSearch": {
"hooks": ["PreToolUse", "PostToolUse"],
"query": f"test search {TEST_ID}",
},
"WebFetch": {
"hooks": ["PreToolUse", "PostToolUse"],
"url": "https://example.com",
"prompt": f"Find {TEST_ID}",
},
}
# Other hook types to test
OTHER_HOOKS = {
"UserPromptSubmit": {"description": "Triggered when user submits a prompt"},
"Notification": {"description": "Triggered for notifications"},
"Stop": {"description": "Triggered when stopping"},
"SubagentStop": {"description": "Triggered when subagent stops"},
"PreCompact": {"description": "Triggered before compacting context"},
}
def find_logs_with_test_id(base_dir, start_time, test_id):
"""Find all log files created after start_time containing test_id."""
found_logs = {}
base_path = Path(base_dir)
if not base_path.exists():
return found_logs
for log_file in base_path.rglob("*.json"):
# Skip files created before our test
if log_file.stat().st_mtime < start_time.timestamp():
continue
try:
with open(log_file) as f:
content = f.read()
data = json.loads(content)
# Check if our test ID appears anywhere in the log
if test_id in content:
hook_type = data.get("hook_type", "unknown")
tool_name = data.get("tool_name", "unknown")
key = f"{hook_type}:{tool_name}"
if key not in found_logs:
found_logs[key] = []
found_logs[key].append(
{
"file": str(log_file),
"timestamp": data.get("timestamp"),
"tool_input": data.get("input_data", {}).get(
"tool_input", {}
),
"status": data.get("execution", {}).get("status"),
}
)
except Exception as e:
print(f"Error reading {log_file}: {e}")
return found_logs
def print_test_plan():
"""Print the test plan."""
print("\n=== HOOK TESTING PLAN ===")
print(f"Test ID: {TEST_ID}")
print(f"Start Time: {datetime.now()}")
print("\nTools to test:")
for tool, config in TOOLS_TO_TEST.items():
print(f" - {tool}: {', '.join(config['hooks'])}")
print("\nOther hooks to observe:")
for hook, config in OTHER_HOOKS.items():
print(f" - {hook}: {config['description']}")
print("\n=== INSTRUCTIONS ===")
print("1. This script has created test files and printed test commands")
print("2. Please execute each of the following tool calls:")
print("3. After execution, verify the results with:")
print(f" mise run test-hooks-verify {TEST_ID}")
def generate_test_commands():
"""Generate the commands for testing each tool."""
print("\n=== TEST COMMANDS TO EXECUTE ===\n")
# Create test files first
Path("/tmp/hook_test.txt").write_text(f"Test file content {TEST_ID}")
Path("/tmp/hook_test_edit.txt").write_text("original content")
Path("/tmp/hook_test_multiedit.txt").write_text("line1\nline2\nline3")
commands = []
# Bash
commands.append("# Bash tool test")
commands.append(f"Run bash command: echo 'Hook test {TEST_ID}'")
# Read
commands.append("\n# Read tool test")
commands.append("Read file: /tmp/hook_test.txt")
# Write
commands.append("\n# Write tool test")
commands.append(
f"Write to file /tmp/hook_test_write.txt with content: Test content {TEST_ID}"
)
# Edit
commands.append("\n# Edit tool test")
commands.append(
f"Edit file /tmp/hook_test_edit.txt, replace 'original' with 'edited {TEST_ID}'"
)
# MultiEdit
commands.append("\n# MultiEdit tool test")
commands.append(
f"MultiEdit file /tmp/hook_test_multiedit.txt, replace 'line2' with 'modified {TEST_ID}'"
)
# Grep
commands.append("\n# Grep tool test")
commands.append(f"Search for pattern '{TEST_ID}' in /tmp/")
# Glob
commands.append("\n# Glob tool test")
commands.append(f"Find files matching '*{TEST_ID}*.txt' in /tmp/")
# LS
commands.append("\n# LS tool test")
commands.append("List files in /tmp/")
# TodoWrite
commands.append("\n# TodoWrite tool test")
commands.append(f"Add todo: 'Test todo {TEST_ID}'")
# WebSearch
commands.append("\n# WebSearch tool test")
commands.append(f"Search web for: 'test search {TEST_ID}'")
# WebFetch
commands.append("\n# WebFetch tool test")
commands.append(f"Fetch https://example.com with prompt 'Find {TEST_ID}'")
for cmd in commands:
print(cmd)
# Save timestamp for verification
timestamp_file = Path("/tmp/hook_test_timestamp.txt")
timestamp_file.write_text(str(datetime.now().timestamp()))
def verify_logs(test_id):
"""Verify that all expected logs were created."""
print(f"\n=== VERIFYING LOGS FOR TEST ID: {test_id} ===")
# Read the timestamp
timestamp_file = Path("/tmp/hook_test_timestamp.txt")
if not timestamp_file.exists():
print("ERROR: No timestamp file found. Did you run the test first?")
return False
start_time = datetime.fromtimestamp(float(timestamp_file.read_text()))
print(f"Searching for logs created after: {start_time}")
# Find all logs with our test ID
# Use the central eyelet data directory for testing
from src.eyelet.utils.paths import get_eyelet_data_dir
base_dir = get_eyelet_data_dir() / "hooks"
found_logs = find_logs_with_test_id(base_dir, start_time, test_id)
print(f"\nFound {len(found_logs)} unique tool/hook combinations")
# Check expected vs found
expected_count = 0
found_count = 0
print("\n=== DETAILED RESULTS ===")
for tool, config in TOOLS_TO_TEST.items():
print(f"\n{tool}:")
for hook in config["hooks"]:
expected_count += 1
key = f"{hook}:{tool}"
if key in found_logs:
found_count += 1
print(f" ✓ {hook} - {len(found_logs[key])} log(s)")
for log in found_logs[key]:
print(f" - {log['file']}")
else:
print(f" ✗ {hook} - NOT FOUND")
# Check for other hooks
print("\n=== OTHER HOOKS ===")
for hook in OTHER_HOOKS:
found_any = False
for key in found_logs:
if key.startswith(f"{hook}:"):
print(f" ✓ {hook} - Found in {key}")
found_any = True
if not found_any:
print(f" - {hook} - Not triggered during test")
# Summary
print("\n=== SUMMARY ===")
print(f"Expected tool hooks: {expected_count}")
print(f"Found tool hooks: {found_count}")
print(
f"Coverage: {found_count}/{expected_count} ({found_count / expected_count * 100:.1f}%)"
)
# List any unexpected logs
unexpected = []
for key in found_logs:
hook_type, tool_name = key.split(":", 1)
if tool_name not in TOOLS_TO_TEST and hook_type not in OTHER_HOOKS:
unexpected.append(key)
if unexpected:
print(f"\nUnexpected logs found: {', '.join(unexpected)}")
return found_count == expected_count
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "--verify":
test_id = sys.argv[2] if len(sys.argv) > 2 else TEST_ID
success = verify_logs(test_id)
sys.exit(0 if success else 1)
else:
print_test_plan()
generate_test_commands()
print("\n\nAfter executing all commands above, run:")
print(f"mise run test-hooks-verify {TEST_ID}")