-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_hook.py
More file actions
243 lines (184 loc) · 9.03 KB
/
test_hook.py
File metadata and controls
243 lines (184 loc) · 9.03 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
"""Unit tests for the bits of logic that actually branch.
Run with:
python3 -m unittest test_hook.py -v
"""
from __future__ import annotations
import json
import os
import tempfile
import unittest
from pathlib import Path
import claude_hook
class DelayForDurationTests(unittest.TestCase):
"""Each band boundary maps to its expected delay."""
def test_short_turn(self):
self.assertEqual(claude_hook._delay_for_duration(10), 20)
def test_medium_turn(self):
self.assertEqual(claude_hook._delay_for_duration(90), 15)
def test_long_turn(self):
self.assertEqual(claude_hook._delay_for_duration(200), 10)
def test_very_long_turn_no_delay(self):
self.assertEqual(claude_hook._delay_for_duration(600), 0)
def test_band_boundaries(self):
# < 60 → 20, [60, 120) → 15, [120, 300) → 10, >= 300 → 0
self.assertEqual(claude_hook._delay_for_duration(59.9), 20)
self.assertEqual(claude_hook._delay_for_duration(60), 15)
self.assertEqual(claude_hook._delay_for_duration(120), 10)
self.assertEqual(claude_hook._delay_for_duration(300), 0)
class ToolErroredTests(unittest.TestCase):
def test_is_error_true(self):
self.assertTrue(claude_hook.tool_errored({"tool_response": {"is_error": True}}))
def test_nonzero_exit_code_camel(self):
self.assertTrue(claude_hook.tool_errored({"tool_response": {"exitCode": 1}}))
def test_nonzero_exit_code_snake(self):
self.assertTrue(claude_hook.tool_errored({"tool_response": {"exit_code": 2}}))
def test_zero_exit_code_is_clean(self):
self.assertFalse(claude_hook.tool_errored({"tool_response": {"exitCode": 0}}))
def test_is_error_false(self):
self.assertFalse(claude_hook.tool_errored({"tool_response": {"is_error": False}}))
def test_error_string(self):
self.assertTrue(claude_hook.tool_errored({"tool_response": {"error": "boom"}}))
def test_status_failed(self):
self.assertTrue(claude_hook.tool_errored({"tool_response": {"status": "FAILED"}}))
def test_empty_response_is_clean(self):
self.assertFalse(claude_hook.tool_errored({"tool_response": {}}))
def test_non_dict_response_is_clean(self):
self.assertFalse(claude_hook.tool_errored({"tool_response": "ok"}))
class ResponseIndicatesErrorTests(unittest.TestCase):
def _msg(self, text):
return {"last_assistant_message": text}
def test_plain_error_phrase(self):
self.assertTrue(claude_hook.response_indicates_error(
self._msg("I encountered an error while reading the file.")))
def test_failed_to_phrase(self):
self.assertTrue(claude_hook.response_indicates_error(
self._msg("Failed to connect to the database.")))
def test_negation_overrides_phrase(self):
self.assertFalse(claude_hook.response_indicates_error(
self._msg("Ran the test suite - no errors found.")))
def test_mid_sentence_phrase_does_not_match(self):
# "could not have gone better" should NOT be treated as an error,
# because "could not" only counts at sentence start.
self.assertFalse(claude_hook.response_indicates_error(
self._msg("It could not have gone better.")))
def test_sentence_boundary_phrase_matches(self):
# After a sentence break, "Failed to ..." still counts.
self.assertTrue(claude_hook.response_indicates_error(
self._msg("Did the build. Failed to push the artifact.")))
def test_successfully_overrides(self):
self.assertFalse(claude_hook.response_indicates_error(
self._msg("Successfully deployed; could not have gone better.")))
def test_empty_message_is_clean(self):
self.assertFalse(claude_hook.response_indicates_error(self._msg("")))
def test_case_insensitive(self):
self.assertTrue(claude_hook.response_indicates_error(
self._msg("UNABLE TO open the connection.")))
class CleanTests(unittest.TestCase):
def test_strips_bold_and_backticks(self):
self.assertEqual(claude_hook.clean("**bold** and `code`"), "bold and code")
def test_collapses_whitespace(self):
self.assertEqual(claude_hook.clean("a b\n\nc\td"), "a b c d")
def test_empty(self):
self.assertEqual(claude_hook.clean(""), "")
class TruncateTests(unittest.TestCase):
def test_under_limit_unchanged(self):
self.assertEqual(claude_hook.truncate("hello", 10), "hello")
def test_exactly_limit_unchanged(self):
self.assertEqual(claude_hook.truncate("abcde", 5), "abcde")
def test_over_limit_ellipsized(self):
out = claude_hook.truncate("abcdefghij", 5)
self.assertEqual(len(out), 5)
self.assertTrue(out.endswith("..."))
def test_truncate_runs_clean_first(self):
# Markdown should be stripped before length check.
self.assertEqual(claude_hook.truncate("**bold**", 10), "bold")
class FormatToolHintTests(unittest.TestCase):
def test_bash_takes_first_line_only(self):
out = claude_hook.format_tool_hint(
"Bash", {"command": "ls -la\nrm -rf /"})
self.assertEqual(out, "ls -la")
def test_edit_uses_basename(self):
self.assertEqual(
claude_hook.format_tool_hint("Edit", {"file_path": "/long/path/to/foo.py"}),
"foo.py")
def test_read_uses_basename(self):
self.assertEqual(
claude_hook.format_tool_hint("Read", {"file_path": "/a/b/c.txt"}),
"c.txt")
def test_webfetch_uses_url(self):
self.assertEqual(
claude_hook.format_tool_hint("WebFetch", {"url": "https://example.com/x"}),
"https://example.com/x")
def test_grep_uses_pattern(self):
self.assertEqual(
claude_hook.format_tool_hint("Grep", {"pattern": "TODO"}),
"TODO")
def test_fallback_picks_longest_string(self):
# Unknown tool: longest stringy value wins.
out = claude_hook.format_tool_hint(
"MysteryTool", {"short": "x", "long": "the longer description"})
self.assertEqual(out, "the longer description")
def test_fallback_skips_none_values(self):
# None must not win against shorter strings via json.dumps(None) == "null".
out = claude_hook.format_tool_hint(
"MysteryTool", {"meta": None, "x": "abc"})
self.assertEqual(out, "abc")
def test_max_len_caps_output(self):
long_cmd = "a" * 500
out = claude_hook.format_tool_hint("Bash", {"command": long_cmd}, max_len=50)
self.assertEqual(len(out), 50)
class ParsePendingToolTests(unittest.TestCase):
def test_empty_path_returns_none(self):
self.assertIsNone(claude_hook.parse_pending_tool(""))
def test_missing_file_returns_none(self):
self.assertIsNone(claude_hook.parse_pending_tool("/nonexistent/path"))
def test_finds_most_recent_tool_use(self):
# JSONL transcript, scanned bottom-up: last tool_use wins.
lines = [
{"message": {"content": [{"type": "tool_use", "name": "OldTool",
"input": {"x": 1}}]}},
{"message": {"content": [{"type": "text", "text": "hi"}]}},
{"message": {"content": [{"type": "tool_use", "name": "Bash",
"input": {"command": "ls"}}]}},
]
with tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False) as f:
for line in lines:
f.write(json.dumps(line) + "\n")
path = f.name
try:
result = claude_hook.parse_pending_tool(path)
self.assertIsNotNone(result)
name, inp = result
self.assertEqual(name, "Bash")
self.assertEqual(inp, {"command": "ls"})
finally:
os.unlink(path)
def test_no_tool_use_returns_none(self):
with tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False) as f:
f.write(json.dumps({"message": {"content": [{"type": "text"}]}}) + "\n")
path = f.name
try:
self.assertIsNone(claude_hook.parse_pending_tool(path))
finally:
os.unlink(path)
def test_skips_malformed_lines(self):
with tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False) as f:
f.write("not json at all\n")
f.write(json.dumps({"message": {"content": [{"type": "tool_use",
"name": "Read", "input": {"file_path": "/x"}}]}}) + "\n")
path = f.name
try:
result = claude_hook.parse_pending_tool(path)
self.assertEqual(result[0], "Read")
finally:
os.unlink(path)
class OptedOutTests(unittest.TestCase):
def test_marker_present_opts_out(self):
with tempfile.TemporaryDirectory() as d:
(Path(d) / claude_hook.OPT_OUT_MARKER).touch()
self.assertTrue(claude_hook.opted_out({"cwd": d}))
def test_marker_absent_does_not_opt_out(self):
with tempfile.TemporaryDirectory() as d:
self.assertFalse(claude_hook.opted_out({"cwd": d}))
if __name__ == "__main__":
unittest.main()