-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathtest_payload.py
More file actions
432 lines (322 loc) · 16.2 KB
/
test_payload.py
File metadata and controls
432 lines (322 loc) · 16.2 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
"""Tests for AI hook payload normalization."""
import pytest
from pytest_mock import MockerFixture
from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload
from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType
def test_from_cursor_payload_prompt_event() -> None:
"""Test conversion of Cursor beforeSubmitPrompt payload."""
cursor_payload = {
'hook_event_name': 'beforeSubmitPrompt',
'conversation_id': 'conv-123',
'generation_id': 'gen-456',
'user_email': 'user@example.com',
'model': 'gpt-4',
'cursor_version': '0.42.0',
'prompt': 'Test prompt',
}
unified = AIHookPayload.from_cursor_payload(cursor_payload)
assert unified.event_name == AiHookEventType.PROMPT
assert unified.conversation_id == 'conv-123'
assert unified.generation_id == 'gen-456'
assert unified.ide_user_email == 'user@example.com'
assert unified.model == 'gpt-4'
assert unified.ide_provider == 'cursor'
assert unified.ide_version == '0.42.0'
assert unified.prompt == 'Test prompt'
assert type(unified.ide_provider) is str
def test_from_cursor_payload_file_read_event() -> None:
"""Test conversion of Cursor beforeReadFile payload."""
cursor_payload = {
'hook_event_name': 'beforeReadFile',
'conversation_id': 'conv-123',
'file_path': '/path/to/secret.env',
}
unified = AIHookPayload.from_cursor_payload(cursor_payload)
assert unified.event_name == AiHookEventType.FILE_READ
assert unified.file_path == '/path/to/secret.env'
assert unified.ide_provider == 'cursor'
def test_from_cursor_payload_mcp_execution_event() -> None:
"""Test conversion of Cursor beforeMCPExecution payload."""
cursor_payload = {
'hook_event_name': 'beforeMCPExecution',
'conversation_id': 'conv-123',
'command': 'GitLab',
'tool_name': 'discussion_list',
'arguments': {'resource_type': 'merge_request', 'parent_id': 'organization/repo', 'resource_id': '4'},
}
unified = AIHookPayload.from_cursor_payload(cursor_payload)
assert unified.event_name == AiHookEventType.MCP_EXECUTION
assert unified.mcp_server_name == 'GitLab'
assert unified.mcp_tool_name == 'discussion_list'
assert unified.mcp_arguments == {
'resource_type': 'merge_request',
'parent_id': 'organization/repo',
'resource_id': '4',
}
def test_from_cursor_payload_with_alternative_field_names() -> None:
"""Test that alternative field names are handled (path vs file_path, etc.)."""
cursor_payload = {
'hook_event_name': 'beforeReadFile',
'path': '/alternative/path.txt', # Alternative to file_path
}
unified = AIHookPayload.from_cursor_payload(cursor_payload)
assert unified.file_path == '/alternative/path.txt'
cursor_payload = {
'hook_event_name': 'beforeMCPExecution',
'tool': 'my_tool', # Alternative to tool_name
'tool_input': {'key': 'value'}, # Alternative to arguments
}
unified = AIHookPayload.from_cursor_payload(cursor_payload)
assert unified.mcp_tool_name == 'my_tool'
assert unified.mcp_arguments == {'key': 'value'}
def test_from_cursor_payload_unknown_event() -> None:
"""Test that unknown event names are passed through as-is."""
cursor_payload = {
'hook_event_name': 'unknownEvent',
'conversation_id': 'conv-123',
}
unified = AIHookPayload.from_cursor_payload(cursor_payload)
# Unknown events fall back to original name
assert unified.event_name == 'unknownEvent'
def test_from_payload_cursor() -> None:
"""Test from_payload dispatcher with Cursor tool."""
cursor_payload = {
'hook_event_name': 'beforeSubmitPrompt',
'prompt': 'test',
}
unified = AIHookPayload.from_payload(cursor_payload, tool='cursor')
assert unified.event_name == AiHookEventType.PROMPT
assert unified.ide_provider == 'cursor'
def test_from_payload_unsupported_tool() -> None:
"""Test from_payload raises ValueError for unsupported tools."""
payload = {'hook_event_name': 'someEvent'}
with pytest.raises(ValueError, match='Unsupported IDE/tool: unsupported'):
AIHookPayload.from_payload(payload, tool='unsupported')
def test_from_cursor_payload_empty_fields() -> None:
"""Test handling of empty/missing fields."""
cursor_payload = {
'hook_event_name': 'beforeSubmitPrompt',
# Most fields missing
}
unified = AIHookPayload.from_cursor_payload(cursor_payload)
assert unified.event_name == AiHookEventType.PROMPT
assert unified.conversation_id is None
assert unified.prompt == '' # Default to empty string
assert unified.ide_provider == 'cursor'
# Claude Code payload tests
def test_from_claude_code_payload_prompt_event() -> None:
"""Test conversion of Claude Code UserPromptSubmit payload."""
claude_payload = {
'hook_event_name': 'UserPromptSubmit',
'session_id': 'session-123',
'prompt': 'Test prompt for Claude Code',
}
unified = AIHookPayload.from_claude_code_payload(claude_payload)
assert unified.event_name == AiHookEventType.PROMPT
assert unified.conversation_id == 'session-123'
assert unified.ide_provider == 'claude-code'
assert unified.prompt == 'Test prompt for Claude Code'
assert type(unified.ide_provider) is str
def test_from_claude_code_payload_file_read_event() -> None:
"""Test conversion of Claude Code PreToolUse with Read tool."""
claude_payload = {
'hook_event_name': 'PreToolUse',
'session_id': 'session-456',
'tool_name': 'Read',
'tool_input': {'file_path': '/path/to/secret.env'},
}
unified = AIHookPayload.from_claude_code_payload(claude_payload)
assert unified.event_name == AiHookEventType.FILE_READ
assert unified.file_path == '/path/to/secret.env'
assert unified.ide_provider == 'claude-code'
assert unified.mcp_tool_name is None
def test_from_claude_code_payload_mcp_execution_event() -> None:
"""Test conversion of Claude Code PreToolUse with MCP tool."""
claude_payload = {
'hook_event_name': 'PreToolUse',
'session_id': 'session-789',
'tool_name': 'mcp__gitlab__discussion_list',
'tool_input': {'resource_type': 'merge_request', 'parent_id': 'org/repo', 'resource_id': '4'},
}
unified = AIHookPayload.from_payload(claude_payload, tool='claude-code')
assert unified.event_name == AiHookEventType.MCP_EXECUTION
assert unified.mcp_server_name == 'gitlab'
assert unified.mcp_tool_name == 'discussion_list'
assert unified.mcp_arguments == {'resource_type': 'merge_request', 'parent_id': 'org/repo', 'resource_id': '4'}
assert unified.ide_provider == 'claude-code'
def test_from_claude_code_payload_empty_fields() -> None:
"""Test handling of empty/missing fields for Claude Code."""
claude_payload = {
'hook_event_name': 'UserPromptSubmit',
# Most fields missing
}
unified = AIHookPayload.from_claude_code_payload(claude_payload)
assert unified.event_name == AiHookEventType.PROMPT
assert unified.conversation_id is None
assert unified.prompt == '' # Default to empty string
assert unified.ide_provider == 'claude-code'
# Claude Code transcript extraction tests
def test_from_claude_code_payload_extracts_from_transcript(mocker: MockerFixture) -> None:
"""Test that version, model, and generation_id are extracted from transcript file."""
transcript_content = (
b'{"type":"user","version":"2.1.20","uuid":"user-uuid-1","message":{"role":"user","content":"hello"}}\n'
b'{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","role":"assistant",'
b'"content":[{"type":"text","text":"Hi!"}]},"uuid":"assistant-uuid-1"}\n'
b'{"type":"user","version":"2.1.20","uuid":"user-uuid-2","message":{"role":"user","content":"test prompt"}}\n'
)
mock_path = mocker.patch('cycode.cli.apps.ai_guardrails.scan.payload.Path')
mock_path.return_value.exists.return_value = True
mock_path.return_value.open.return_value.__enter__.return_value.seek = mocker.Mock()
mock_path.return_value.open.return_value.__enter__.return_value.tell.return_value = len(transcript_content)
mock_path.return_value.open.return_value.__enter__.return_value.read.return_value = transcript_content
claude_payload = {
'hook_event_name': 'UserPromptSubmit',
'session_id': 'session-123',
'prompt': 'test prompt',
'transcript_path': '/mock/transcript.jsonl',
}
unified = AIHookPayload.from_claude_code_payload(claude_payload)
assert unified.ide_version == '2.1.20'
assert unified.model == 'claude-opus-4-5-20251101'
assert unified.generation_id == 'user-uuid-2'
def test_from_claude_code_payload_handles_missing_transcript(mocker: MockerFixture) -> None:
"""Test that missing transcript file doesn't break payload parsing."""
mock_path = mocker.patch('cycode.cli.apps.ai_guardrails.scan.payload.Path')
mock_path.return_value.exists.return_value = False
claude_payload = {
'hook_event_name': 'UserPromptSubmit',
'session_id': 'session-123',
'prompt': 'test',
'transcript_path': '/nonexistent/path/transcript.jsonl',
}
unified = AIHookPayload.from_claude_code_payload(claude_payload)
assert unified.ide_version is None
assert unified.model is None
assert unified.generation_id is None
assert unified.conversation_id == 'session-123'
assert unified.prompt == 'test'
def test_from_claude_code_payload_handles_no_transcript_path() -> None:
"""Test that absent transcript_path doesn't break payload parsing."""
claude_payload = {
'hook_event_name': 'UserPromptSubmit',
'session_id': 'session-123',
'prompt': 'test',
}
unified = AIHookPayload.from_claude_code_payload(claude_payload)
assert unified.ide_version is None
assert unified.model is None
assert unified.generation_id is None
def test_from_claude_code_payload_extracts_model_from_nested_message(mocker: MockerFixture) -> None:
"""Test that model is extracted from nested message.model field."""
transcript_content = (
b'{"type":"assistant","message":{"model":"claude-sonnet-4-20250514",'
b'"role":"assistant","content":[]},"uuid":"uuid-1"}\n'
)
mock_path = mocker.patch('cycode.cli.apps.ai_guardrails.scan.payload.Path')
mock_path.return_value.exists.return_value = True
mock_path.return_value.open.return_value.__enter__.return_value.seek = mocker.Mock()
mock_path.return_value.open.return_value.__enter__.return_value.tell.return_value = len(transcript_content)
mock_path.return_value.open.return_value.__enter__.return_value.read.return_value = transcript_content
claude_payload = {
'hook_event_name': 'UserPromptSubmit',
'prompt': 'test',
'transcript_path': '/mock/transcript.jsonl',
}
unified = AIHookPayload.from_claude_code_payload(claude_payload)
assert unified.model == 'claude-sonnet-4-20250514'
def test_from_claude_code_payload_gets_latest_user_uuid(mocker: MockerFixture) -> None:
"""Test that generation_id is the UUID of the latest user message."""
transcript_content = b"""{"type":"user","uuid":"old-user-uuid","message":{"role":"user","content":"first"}}
{"type":"assistant","uuid":"assistant-uuid","message":{"role":"assistant","content":[]}}
{"type":"user","uuid":"latest-user-uuid","message":{"role":"user","content":"second"}}
{"type":"assistant","uuid":"last-assistant-uuid","message":{"role":"assistant","content":[]}}
"""
mock_path = mocker.patch('cycode.cli.apps.ai_guardrails.scan.payload.Path')
mock_path.return_value.exists.return_value = True
mock_path.return_value.open.return_value.__enter__.return_value.seek = mocker.Mock()
mock_path.return_value.open.return_value.__enter__.return_value.tell.return_value = len(transcript_content)
mock_path.return_value.open.return_value.__enter__.return_value.read.return_value = transcript_content
claude_payload = {
'hook_event_name': 'UserPromptSubmit',
'prompt': 'test',
'transcript_path': '/mock/transcript.jsonl',
}
unified = AIHookPayload.from_claude_code_payload(claude_payload)
assert unified.generation_id == 'latest-user-uuid'
# Claude Code email extraction tests
def test_from_claude_code_payload_extracts_email_from_config(mocker: MockerFixture) -> None:
"""Test that ide_user_email is populated from ~/.claude.json."""
mocker.patch(
'cycode.cli.apps.ai_guardrails.scan.payload.load_claude_config',
return_value={'oauthAccount': {'emailAddress': 'user@example.com'}},
)
claude_payload = {
'hook_event_name': 'UserPromptSubmit',
'session_id': 'session-123',
'prompt': 'test',
}
unified = AIHookPayload.from_claude_code_payload(claude_payload)
assert unified.ide_user_email == 'user@example.com'
def test_from_claude_code_payload_email_none_when_config_missing(mocker: MockerFixture) -> None:
"""Test that ide_user_email is None when ~/.claude.json is missing."""
mocker.patch(
'cycode.cli.apps.ai_guardrails.scan.payload.load_claude_config',
return_value=None,
)
claude_payload = {
'hook_event_name': 'UserPromptSubmit',
'session_id': 'session-123',
'prompt': 'test',
}
unified = AIHookPayload.from_claude_code_payload(claude_payload)
assert unified.ide_user_email is None
def test_from_claude_code_payload_email_none_when_no_oauth(mocker: MockerFixture) -> None:
"""Test that ide_user_email is None when oauthAccount is missing from config."""
mocker.patch(
'cycode.cli.apps.ai_guardrails.scan.payload.load_claude_config',
return_value={'someOtherKey': 'value'},
)
claude_payload = {
'hook_event_name': 'UserPromptSubmit',
'session_id': 'session-123',
'prompt': 'test',
}
unified = AIHookPayload.from_claude_code_payload(claude_payload)
assert unified.ide_user_email is None
# IDE detection tests
def test_is_payload_for_ide_claude_code_matches_claude_code() -> None:
"""Test that Claude Code events match when expected IDE is claude-code."""
payload = {'hook_event_name': 'UserPromptSubmit'}
assert AIHookPayload.is_payload_for_ide(payload, 'claude-code') is True
payload = {'hook_event_name': 'PreToolUse'}
assert AIHookPayload.is_payload_for_ide(payload, 'claude-code') is True
def test_is_payload_for_ide_cursor_matches_cursor() -> None:
"""Test that Cursor events match when expected IDE is cursor."""
payload = {'hook_event_name': 'beforeSubmitPrompt'}
assert AIHookPayload.is_payload_for_ide(payload, 'cursor') is True
payload = {'hook_event_name': 'beforeReadFile'}
assert AIHookPayload.is_payload_for_ide(payload, 'cursor') is True
payload = {'hook_event_name': 'beforeMCPExecution'}
assert AIHookPayload.is_payload_for_ide(payload, 'cursor') is True
def test_is_payload_for_ide_claude_code_does_not_match_cursor() -> None:
"""Test that Claude Code events don't match when expected IDE is cursor.
This prevents double-processing when Cursor reads Claude Code hooks.
"""
payload = {'hook_event_name': 'UserPromptSubmit'}
assert AIHookPayload.is_payload_for_ide(payload, 'cursor') is False
payload = {'hook_event_name': 'PreToolUse'}
assert AIHookPayload.is_payload_for_ide(payload, 'cursor') is False
def test_is_payload_for_ide_cursor_does_not_match_claude_code() -> None:
"""Test that Cursor events don't match when expected IDE is claude-code."""
payload = {'hook_event_name': 'beforeSubmitPrompt'}
assert AIHookPayload.is_payload_for_ide(payload, 'claude-code') is False
payload = {'hook_event_name': 'beforeReadFile'}
assert AIHookPayload.is_payload_for_ide(payload, 'claude-code') is False
def test_is_payload_for_ide_empty_event_name() -> None:
"""Test handling of empty or missing hook_event_name."""
payload = {'hook_event_name': ''}
assert AIHookPayload.is_payload_for_ide(payload, 'cursor') is False
assert AIHookPayload.is_payload_for_ide(payload, 'claude-code') is False
payload = {}
assert AIHookPayload.is_payload_for_ide(payload, 'cursor') is False
assert AIHookPayload.is_payload_for_ide(payload, 'claude-code') is False