-
Notifications
You must be signed in to change notification settings - Fork 955
Expand file tree
/
Copy pathtest_types.py
More file actions
621 lines (524 loc) · 22.7 KB
/
test_types.py
File metadata and controls
621 lines (524 loc) · 22.7 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
"""Tests for Claude SDK type definitions."""
from claude_agent_sdk import (
AssistantMessage,
ClaudeAgentOptions,
NotificationHookInput,
NotificationHookSpecificOutput,
PermissionRequestHookInput,
PermissionRequestHookSpecificOutput,
ResultMessage,
SubagentStartHookInput,
SubagentStartHookSpecificOutput,
)
from claude_agent_sdk.types import (
PostToolUseHookSpecificOutput,
PreToolUseHookSpecificOutput,
TextBlock,
ThinkingBlock,
ToolResultBlock,
ToolUseBlock,
UserMessage,
)
class TestMessageTypes:
"""Test message type creation and validation."""
def test_user_message_creation(self):
"""Test creating a UserMessage."""
msg = UserMessage(content="Hello, Claude!")
assert msg.content == "Hello, Claude!"
def test_assistant_message_with_text(self):
"""Test creating an AssistantMessage with text content."""
text_block = TextBlock(text="Hello, human!")
msg = AssistantMessage(content=[text_block], model="claude-opus-4-1-20250805")
assert len(msg.content) == 1
assert msg.content[0].text == "Hello, human!"
def test_assistant_message_with_thinking(self):
"""Test creating an AssistantMessage with thinking content."""
thinking_block = ThinkingBlock(thinking="I'm thinking...", signature="sig-123")
msg = AssistantMessage(
content=[thinking_block], model="claude-opus-4-1-20250805"
)
assert len(msg.content) == 1
assert msg.content[0].thinking == "I'm thinking..."
assert msg.content[0].signature == "sig-123"
def test_tool_use_block(self):
"""Test creating a ToolUseBlock."""
block = ToolUseBlock(
id="tool-123", name="Read", input={"file_path": "/test.txt"}
)
assert block.id == "tool-123"
assert block.name == "Read"
assert block.input["file_path"] == "/test.txt"
def test_tool_result_block(self):
"""Test creating a ToolResultBlock."""
block = ToolResultBlock(
tool_use_id="tool-123", content="File contents here", is_error=False
)
assert block.tool_use_id == "tool-123"
assert block.content == "File contents here"
assert block.is_error is False
def test_result_message(self):
"""Test creating a ResultMessage."""
msg = ResultMessage(
subtype="success",
duration_ms=1500,
duration_api_ms=1200,
is_error=False,
num_turns=1,
session_id="session-123",
total_cost_usd=0.01,
)
assert msg.subtype == "success"
assert msg.total_cost_usd == 0.01
assert msg.session_id == "session-123"
class TestOptions:
"""Test Options configuration."""
def test_default_options(self):
"""Test Options with default values."""
options = ClaudeAgentOptions()
assert options.allowed_tools == []
assert options.system_prompt is None
assert options.permission_mode is None
assert options.continue_conversation is False
assert options.disallowed_tools == []
def test_claude_code_options_with_tools(self):
"""Test Options with built-in tools."""
options = ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Edit"], disallowed_tools=["Bash"]
)
assert options.allowed_tools == ["Read", "Write", "Edit"]
assert options.disallowed_tools == ["Bash"]
def test_claude_code_options_with_permission_mode(self):
"""Test Options with permission mode."""
options = ClaudeAgentOptions(permission_mode="bypassPermissions")
assert options.permission_mode == "bypassPermissions"
options_plan = ClaudeAgentOptions(permission_mode="plan")
assert options_plan.permission_mode == "plan"
options_default = ClaudeAgentOptions(permission_mode="default")
assert options_default.permission_mode == "default"
options_accept = ClaudeAgentOptions(permission_mode="acceptEdits")
assert options_accept.permission_mode == "acceptEdits"
options_dont_ask = ClaudeAgentOptions(permission_mode="dontAsk")
assert options_dont_ask.permission_mode == "dontAsk"
options_auto = ClaudeAgentOptions(permission_mode="auto")
assert options_auto.permission_mode == "auto"
def test_claude_code_options_with_system_prompt_string(self):
"""Test Options with system prompt as string."""
options = ClaudeAgentOptions(
system_prompt="You are a helpful assistant.",
)
assert options.system_prompt == "You are a helpful assistant."
def test_claude_code_options_with_system_prompt_preset(self):
"""Test Options with system prompt preset."""
options = ClaudeAgentOptions(
system_prompt={"type": "preset", "preset": "claude_code"},
)
assert options.system_prompt == {"type": "preset", "preset": "claude_code"}
def test_claude_code_options_with_system_prompt_preset_and_append(self):
"""Test Options with system prompt preset and append."""
options = ClaudeAgentOptions(
system_prompt={
"type": "preset",
"preset": "claude_code",
"append": "Be concise.",
},
)
assert options.system_prompt == {
"type": "preset",
"preset": "claude_code",
"append": "Be concise.",
}
def test_claude_code_options_with_system_prompt_preset_exclude_dynamic_sections(
self,
):
"""Test Options with system prompt preset and exclude_dynamic_sections."""
options = ClaudeAgentOptions(
system_prompt={
"type": "preset",
"preset": "claude_code",
"exclude_dynamic_sections": True,
},
)
assert options.system_prompt == {
"type": "preset",
"preset": "claude_code",
"exclude_dynamic_sections": True,
}
def test_claude_code_options_with_system_prompt_file(self):
"""Test Options with system prompt file."""
options = ClaudeAgentOptions(
system_prompt={"type": "file", "path": "/path/to/prompt.md"},
)
assert options.system_prompt == {
"type": "file",
"path": "/path/to/prompt.md",
}
def test_claude_code_options_with_session_continuation(self):
"""Test Options with session continuation."""
options = ClaudeAgentOptions(continue_conversation=True, resume="session-123")
assert options.continue_conversation is True
assert options.resume == "session-123"
def test_claude_code_options_with_model_specification(self):
"""Test Options with model specification."""
options = ClaudeAgentOptions(
model="claude-sonnet-4-5", permission_prompt_tool_name="CustomTool"
)
assert options.model == "claude-sonnet-4-5"
assert options.permission_prompt_tool_name == "CustomTool"
class TestHookInputTypes:
"""Test hook input type definitions."""
def test_notification_hook_input(self):
"""Test NotificationHookInput construction."""
hook_input: NotificationHookInput = {
"session_id": "sess-1",
"transcript_path": "/tmp/transcript",
"cwd": "/home/user",
"hook_event_name": "Notification",
"message": "Task completed",
"notification_type": "info",
}
assert hook_input["hook_event_name"] == "Notification"
assert hook_input["message"] == "Task completed"
assert hook_input["notification_type"] == "info"
def test_notification_hook_input_with_title(self):
"""Test NotificationHookInput with optional title."""
hook_input: NotificationHookInput = {
"session_id": "sess-1",
"transcript_path": "/tmp/transcript",
"cwd": "/home/user",
"hook_event_name": "Notification",
"message": "Task completed",
"notification_type": "info",
"title": "Success",
}
assert hook_input["title"] == "Success"
def test_subagent_start_hook_input(self):
"""Test SubagentStartHookInput construction."""
hook_input: SubagentStartHookInput = {
"session_id": "sess-1",
"transcript_path": "/tmp/transcript",
"cwd": "/home/user",
"hook_event_name": "SubagentStart",
"agent_id": "agent-42",
"agent_type": "researcher",
}
assert hook_input["hook_event_name"] == "SubagentStart"
assert hook_input["agent_id"] == "agent-42"
assert hook_input["agent_type"] == "researcher"
def test_pre_tool_use_hook_input_with_agent_id(self):
"""PreToolUseHookInput accepts optional agent_id/agent_type.
When a tool is called from inside a Task sub-agent, the CLI includes
the calling agent's id so consumers can correlate the tool call to
the correct sub-agent — parallel sub-agents interleave their hook
callbacks over the same control channel and are otherwise
indistinguishable.
"""
from claude_agent_sdk.types import PreToolUseHookInput
# Tool called from inside a sub-agent: agent_id present,
# same value SubagentStart emits.
hook_input: PreToolUseHookInput = {
"session_id": "sess-1",
"transcript_path": "/tmp/transcript",
"cwd": "/home/user",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {"command": "echo hello"},
"tool_use_id": "toolu_abc123",
"agent_id": "agent-42",
"agent_type": "researcher",
}
assert hook_input.get("agent_id") == "agent-42"
assert hook_input.get("agent_type") == "researcher"
# Tool called on the main thread: agent_id absent. Still type-valid.
hook_input_main: PreToolUseHookInput = {
"session_id": "sess-1",
"transcript_path": "/tmp/transcript",
"cwd": "/home/user",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {"command": "echo hello"},
"tool_use_id": "toolu_def456",
}
assert hook_input_main.get("agent_id") is None
def test_post_tool_use_hook_input_with_agent_id(self):
"""PostToolUseHookInput accepts optional agent_id."""
from claude_agent_sdk.types import PostToolUseHookInput
hook_input: PostToolUseHookInput = {
"session_id": "sess-1",
"transcript_path": "/tmp/transcript",
"cwd": "/home/user",
"hook_event_name": "PostToolUse",
"tool_name": "Bash",
"tool_input": {"command": "echo hello"},
"tool_response": {"content": [{"type": "text", "text": "hello"}]},
"tool_use_id": "toolu_abc123",
"agent_id": "agent-42",
}
assert hook_input.get("agent_id") == "agent-42"
def test_permission_request_hook_input(self):
"""Test PermissionRequestHookInput construction."""
hook_input: PermissionRequestHookInput = {
"session_id": "sess-1",
"transcript_path": "/tmp/transcript",
"cwd": "/home/user",
"hook_event_name": "PermissionRequest",
"tool_name": "Bash",
"tool_input": {"command": "ls"},
}
assert hook_input["hook_event_name"] == "PermissionRequest"
assert hook_input["tool_name"] == "Bash"
assert hook_input["tool_input"] == {"command": "ls"}
def test_permission_request_hook_input_with_suggestions(self):
"""Test PermissionRequestHookInput with optional permission_suggestions."""
hook_input: PermissionRequestHookInput = {
"session_id": "sess-1",
"transcript_path": "/tmp/transcript",
"cwd": "/home/user",
"hook_event_name": "PermissionRequest",
"tool_name": "Bash",
"tool_input": {"command": "ls"},
"permission_suggestions": [{"type": "allow", "rule": "Bash(*)"}],
}
assert len(hook_input["permission_suggestions"]) == 1
class TestHookSpecificOutputTypes:
"""Test hook-specific output type definitions."""
def test_notification_hook_specific_output(self):
"""Test NotificationHookSpecificOutput construction."""
output: NotificationHookSpecificOutput = {
"hookEventName": "Notification",
"additionalContext": "Extra info",
}
assert output["hookEventName"] == "Notification"
assert output["additionalContext"] == "Extra info"
def test_subagent_start_hook_specific_output(self):
"""Test SubagentStartHookSpecificOutput construction."""
output: SubagentStartHookSpecificOutput = {
"hookEventName": "SubagentStart",
"additionalContext": "Starting subagent for research",
}
assert output["hookEventName"] == "SubagentStart"
def test_permission_request_hook_specific_output(self):
"""Test PermissionRequestHookSpecificOutput construction."""
output: PermissionRequestHookSpecificOutput = {
"hookEventName": "PermissionRequest",
"decision": {"type": "allow"},
}
assert output["hookEventName"] == "PermissionRequest"
assert output["decision"] == {"type": "allow"}
def test_pre_tool_use_output_has_additional_context(self):
"""Test PreToolUseHookSpecificOutput includes additionalContext field."""
output: PreToolUseHookSpecificOutput = {
"hookEventName": "PreToolUse",
"additionalContext": "context for claude",
}
assert output["additionalContext"] == "context for claude"
def test_post_tool_use_output_has_updated_mcp_tool_output(self):
"""Test PostToolUseHookSpecificOutput includes updatedMCPToolOutput field."""
output: PostToolUseHookSpecificOutput = {
"hookEventName": "PostToolUse",
"updatedMCPToolOutput": {"result": "modified"},
}
assert output["updatedMCPToolOutput"] == {"result": "modified"}
class TestMcpServerStatusTypes:
"""Test MCP server status type definitions."""
def test_mcp_server_status_importable_from_package(self):
"""Verify McpServerStatus and related types are exported."""
from claude_agent_sdk import (
McpServerConnectionStatus, # noqa: F401
McpServerInfo, # noqa: F401
McpServerStatus, # noqa: F401
McpServerStatusConfig, # noqa: F401
McpStatusResponse, # noqa: F401
McpToolAnnotations, # noqa: F401
McpToolInfo, # noqa: F401
)
def test_mcp_server_status_connected(self):
"""Test constructing a connected McpServerStatus with full fields."""
from claude_agent_sdk import McpServerStatus
status: McpServerStatus = {
"name": "my-server",
"status": "connected",
"serverInfo": {"name": "my-server", "version": "1.2.3"},
"config": {"type": "http", "url": "https://example.com"},
"scope": "project",
"tools": [
{
"name": "greet",
"description": "Greet a user",
"annotations": {
"readOnly": True,
"destructive": False,
"openWorld": False,
},
}
],
}
assert status["name"] == "my-server"
assert status["status"] == "connected"
assert status["serverInfo"]["version"] == "1.2.3"
assert status["tools"][0]["annotations"]["readOnly"] is True
def test_mcp_server_status_minimal(self):
"""Test constructing a minimal McpServerStatus (only required fields)."""
from claude_agent_sdk import McpServerStatus
status: McpServerStatus = {"name": "pending-server", "status": "pending"}
assert status["name"] == "pending-server"
assert status["status"] == "pending"
assert "error" not in status
assert "config" not in status
def test_mcp_server_status_failed_with_error(self):
"""Test McpServerStatus for a failed server includes error."""
from claude_agent_sdk import McpServerStatus
status: McpServerStatus = {
"name": "broken-server",
"status": "failed",
"error": "Connection refused",
}
assert status["status"] == "failed"
assert status["error"] == "Connection refused"
def test_mcp_server_status_config_claudeai_proxy(self):
"""Test McpServerStatusConfig accepts claudeai-proxy variant."""
from claude_agent_sdk import McpServerStatus
status: McpServerStatus = {
"name": "proxy-server",
"status": "needs-auth",
"config": {
"type": "claudeai-proxy",
"url": "https://claude.ai/proxy",
"id": "proxy-abc",
},
}
assert status["config"]["type"] == "claudeai-proxy"
assert status["config"]["id"] == "proxy-abc"
def test_mcp_status_response_wraps_servers(self):
"""Test McpStatusResponse wraps mcpServers list."""
from claude_agent_sdk import McpStatusResponse
response: McpStatusResponse = {
"mcpServers": [
{"name": "a", "status": "connected"},
{"name": "b", "status": "disabled"},
]
}
assert len(response["mcpServers"]) == 2
assert response["mcpServers"][0]["status"] == "connected"
assert response["mcpServers"][1]["status"] == "disabled"
class TestAgentDefinition:
"""Test AgentDefinition serialization contract.
AgentDefinition is sent to the CLI via the initialize control request.
The _internal/client.py serializer uses ``asdict()`` directly, so field
names here must match the CLI's expected JSON keys exactly.
"""
def _serialize(self, agent):
# Mirror the transform in _internal/client.py and client.py:
# {k: v for k, v in asdict(agent_def).items() if v is not None}
from dataclasses import asdict
return {k: v for k, v in asdict(agent).items() if v is not None}
def test_minimal_definition_omits_unset_fields(self):
from claude_agent_sdk import AgentDefinition
agent = AgentDefinition(description="test", prompt="You are a test")
payload = self._serialize(agent)
assert payload == {"description": "test", "prompt": "You are a test"}
def test_skills_and_memory_serialize_with_cli_keys(self):
from claude_agent_sdk import AgentDefinition
agent = AgentDefinition(
description="test",
prompt="p",
skills=["skill-a", "skill-b"],
memory="project",
)
payload = self._serialize(agent)
assert payload["skills"] == ["skill-a", "skill-b"]
assert payload["memory"] == "project"
def test_mcp_servers_serializes_as_camelcase(self):
"""CLI expects ``mcpServers`` (camelCase), not snake_case."""
from claude_agent_sdk import AgentDefinition
agent = AgentDefinition(
description="test",
prompt="p",
mcpServers=[
"slack",
{"local": {"command": "python", "args": ["server.py"]}},
],
)
payload = self._serialize(agent)
assert "mcpServers" in payload
assert "mcp_servers" not in payload
assert payload["mcpServers"][0] == "slack"
assert payload["mcpServers"][1]["local"]["command"] == "python"
def test_disallowed_tools_and_max_turns_serialize_as_camelcase(self):
"""CLI expects ``disallowedTools`` and ``maxTurns`` (camelCase)."""
from claude_agent_sdk import AgentDefinition
agent = AgentDefinition(
description="test",
prompt="p",
disallowedTools=["Bash", "Write"],
maxTurns=10,
)
payload = self._serialize(agent)
assert payload["disallowedTools"] == ["Bash", "Write"]
assert "disallowed_tools" not in payload
assert payload["maxTurns"] == 10
assert "max_turns" not in payload
def test_initial_prompt_serializes_as_camelcase(self):
from claude_agent_sdk import AgentDefinition
agent = AgentDefinition(
description="test",
prompt="p",
initialPrompt="/review-pr 123",
)
payload = self._serialize(agent)
assert payload["initialPrompt"] == "/review-pr 123"
assert "initial_prompt" not in payload
def test_model_accepts_full_model_id(self):
from claude_agent_sdk import AgentDefinition
agent = AgentDefinition(
description="test",
prompt="p",
model="claude-opus-4-5",
)
payload = self._serialize(agent)
assert payload["model"] == "claude-opus-4-5"
def test_background_serializes_correctly(self):
from claude_agent_sdk import AgentDefinition
agent = AgentDefinition(
description="test",
prompt="p",
background=True,
)
payload = self._serialize(agent)
assert payload["background"] is True
def test_effort_accepts_named_level(self):
from claude_agent_sdk import AgentDefinition
agent = AgentDefinition(
description="test",
prompt="p",
effort="high",
)
payload = self._serialize(agent)
assert payload["effort"] == "high"
def test_effort_accepts_integer(self):
from claude_agent_sdk import AgentDefinition
agent = AgentDefinition(
description="test",
prompt="p",
effort=32000,
)
payload = self._serialize(agent)
assert payload["effort"] == 32000
def test_permission_mode_serializes_as_camelcase(self):
"""CLI expects ``permissionMode`` (camelCase)."""
from claude_agent_sdk import AgentDefinition
agent = AgentDefinition(
description="test",
prompt="p",
permissionMode="bypassPermissions",
)
payload = self._serialize(agent)
assert payload["permissionMode"] == "bypassPermissions"
assert "permission_mode" not in payload
def test_new_fields_omitted_when_none(self):
"""New optional fields should not appear in payload when unset."""
from claude_agent_sdk import AgentDefinition
agent = AgentDefinition(description="test", prompt="p")
payload = self._serialize(agent)
assert "background" not in payload
assert "effort" not in payload
assert "permissionMode" not in payload