-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathtest_transport.py
More file actions
2103 lines (1708 loc) · 77 KB
/
test_transport.py
File metadata and controls
2103 lines (1708 loc) · 77 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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for Claude SDK transport layer."""
import os
import uuid
from contextlib import nullcontext
from unittest.mock import AsyncMock, MagicMock, patch
import anyio
import pytest
from claude_agent_sdk._internal.transport.subprocess_cli import SubprocessCLITransport
from claude_agent_sdk.types import ClaudeAgentOptions
DEFAULT_CLI_PATH = "/usr/bin/claude"
_ABSENT = object() # sentinel for "field not sent on the wire"
def make_options(**kwargs: object) -> ClaudeAgentOptions:
"""Construct options using the standard CLI path unless overridden."""
cli_path = kwargs.pop("cli_path", DEFAULT_CLI_PATH)
return ClaudeAgentOptions(cli_path=cli_path, **kwargs)
class TestSubprocessCLITransport:
"""Test subprocess transport implementation."""
def test_find_cli_not_found(self):
"""Test CLI not found error is raised during connect()."""
async def _test():
from claude_agent_sdk._errors import CLINotFoundError
transport = SubprocessCLITransport(
prompt="test", options=ClaudeAgentOptions()
)
assert transport._cli_path is None
with (
patch(
"claude_agent_sdk._internal.transport.subprocess_cli.shutil.which",
return_value=None,
),
patch("pathlib.Path.exists", return_value=False),
pytest.raises(CLINotFoundError) as exc_info,
):
await transport.connect()
assert "Claude Code not found" in str(exc_info.value)
anyio.run(_test)
def test_init_does_not_call_find_cli(self):
"""Test that __init__ defers CLI discovery instead of blocking."""
transport = SubprocessCLITransport(prompt="test", options=ClaudeAgentOptions())
assert transport._cli_path is None
def test_init_uses_provided_cli_path(self):
"""Test that __init__ uses cli_path when provided."""
transport = SubprocessCLITransport(
prompt="test",
options=ClaudeAgentOptions(cli_path="/usr/bin/claude"),
)
assert transport._cli_path == "/usr/bin/claude"
def test_build_command_basic(self):
"""Test building basic CLI command."""
transport = SubprocessCLITransport(prompt="Hello", options=make_options())
cmd = transport._build_command()
assert cmd[0] == "/usr/bin/claude"
assert "--output-format" in cmd
assert "stream-json" in cmd
# Always use streaming mode (matching TypeScript SDK)
assert "--input-format" in cmd
assert "--print" not in cmd # Never use --print anymore
# Prompt is sent via stdin, not CLI args
assert "--system-prompt" in cmd
assert cmd[cmd.index("--system-prompt") + 1] == ""
def test_build_command_include_hook_events(self):
"""Test that include_hook_events emits the --include-hook-events flag."""
transport = SubprocessCLITransport(
prompt="Hello", options=make_options(include_hook_events=True)
)
cmd = transport._build_command()
assert "--include-hook-events" in cmd
transport_off = SubprocessCLITransport(prompt="Hello", options=make_options())
cmd_off = transport_off._build_command()
assert "--include-hook-events" not in cmd_off
def test_build_command_strict_mcp_config(self):
"""Test that --strict-mcp-config is emitted only when enabled."""
transport = SubprocessCLITransport(
prompt="test", options=make_options(strict_mcp_config=True)
)
assert "--strict-mcp-config" in transport._build_command()
transport = SubprocessCLITransport(prompt="test", options=make_options())
assert "--strict-mcp-config" not in transport._build_command()
def test_cli_path_accepts_pathlib_path(self):
"""Test that cli_path accepts pathlib.Path objects."""
from pathlib import Path
path = Path("/usr/bin/claude")
transport = SubprocessCLITransport(
prompt="Hello",
options=ClaudeAgentOptions(cli_path=path),
)
# Path object is converted to string, compare with str(path)
assert transport._cli_path == str(path)
def test_build_command_with_effort_xhigh(self):
transport = SubprocessCLITransport(
prompt="test",
options=make_options(effort="xhigh"),
)
cmd = transport._build_command()
assert "--effort" in cmd
assert cmd[cmd.index("--effort") + 1] == "xhigh"
def test_build_command_with_system_prompt_string(self):
"""Test building CLI command with system prompt as string."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
system_prompt="Be helpful",
),
)
cmd = transport._build_command()
assert "--system-prompt" in cmd
assert "Be helpful" in cmd
def test_build_command_with_system_prompt_preset(self):
"""Test building CLI command with system prompt preset."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
system_prompt={"type": "preset", "preset": "claude_code"},
),
)
cmd = transport._build_command()
assert "--system-prompt" not in cmd
assert "--append-system-prompt" not in cmd
def test_build_command_with_system_prompt_preset_and_append(self):
"""Test building CLI command with system prompt preset and append."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
system_prompt={
"type": "preset",
"preset": "claude_code",
"append": "Be concise.",
},
),
)
cmd = transport._build_command()
assert "--system-prompt" not in cmd
assert "--append-system-prompt" in cmd
assert "Be concise." in cmd
def test_build_command_with_system_prompt_file(self):
"""Test building CLI command with system prompt file."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
system_prompt={"type": "file", "path": "/path/to/prompt.md"},
),
)
cmd = transport._build_command()
assert "--system-prompt" not in cmd
assert "--append-system-prompt" not in cmd
assert "--system-prompt-file" in cmd
assert "/path/to/prompt.md" in cmd
def test_build_command_with_options(self):
"""Test building CLI command with options."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
allowed_tools=["Read", "Write"],
disallowed_tools=["Bash"],
model="claude-sonnet-4-5",
permission_mode="acceptEdits",
max_turns=5,
),
)
cmd = transport._build_command()
assert "--allowedTools" in cmd
assert "Read,Write" in cmd
assert "--disallowedTools" in cmd
assert "Bash" in cmd
assert "--model" in cmd
assert "claude-sonnet-4-5" in cmd
assert "--permission-mode" in cmd
assert "acceptEdits" in cmd
assert "--max-turns" in cmd
assert "5" in cmd
def test_build_command_with_dont_ask_permission_mode(self):
"""Test building CLI command with dontAsk permission mode."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(permission_mode="dontAsk"),
)
cmd = transport._build_command()
assert "--permission-mode" in cmd
assert "dontAsk" in cmd
def test_build_command_with_fallback_model(self):
"""Test building CLI command with fallback_model option."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
model="opus",
fallback_model="sonnet",
),
)
cmd = transport._build_command()
assert "--model" in cmd
assert "opus" in cmd
assert "--fallback-model" in cmd
assert "sonnet" in cmd
def test_build_command_with_task_budget(self):
"""Test building CLI command with task_budget option."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(task_budget={"total": 100000}),
)
cmd = transport._build_command()
assert "--task-budget" in cmd
assert "100000" in cmd
def test_build_command_without_task_budget(self):
"""Test that --task-budget is not included when task_budget is None."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(),
)
cmd = transport._build_command()
assert "--task-budget" not in cmd
def test_build_command_with_max_thinking_tokens(self):
"""Test building CLI command with max_thinking_tokens option."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(max_thinking_tokens=5000),
)
cmd = transport._build_command()
assert "--max-thinking-tokens" in cmd
assert "5000" in cmd
@pytest.mark.parametrize(
("thinking", "expected", "absent"),
[
({"type": "adaptive"}, ["--thinking", "adaptive"], "--max-thinking-tokens"),
(
{"type": "enabled", "budget_tokens": 5000},
["--max-thinking-tokens", "5000"],
"--thinking",
),
({"type": "disabled"}, ["--thinking", "disabled"], "--max-thinking-tokens"),
],
)
def test_build_command_with_thinking(self, thinking, expected, absent):
"""Test building CLI command with thinking option."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(thinking=thinking),
)
cmd = transport._build_command()
idx = cmd.index(expected[0])
assert cmd[idx : idx + 2] == expected
assert absent not in cmd
@pytest.mark.parametrize(
("thinking", "expected_display"),
[
(
{"type": "adaptive", "display": "summarized"},
["--thinking-display", "summarized"],
),
(
{"type": "enabled", "budget_tokens": 20000, "display": "omitted"},
["--thinking-display", "omitted"],
),
],
)
def test_build_command_thinking_display_forwarded(self, thinking, expected_display):
"""`display` in thinking config is forwarded as --thinking-display."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(thinking=thinking),
)
cmd = transport._build_command()
idx = cmd.index(expected_display[0])
assert cmd[idx : idx + 2] == expected_display
def test_build_command_thinking_without_display(self):
"""Omitting `display` leaves --thinking-display off the command."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(thinking={"type": "adaptive"}),
)
cmd = transport._build_command()
assert "--thinking-display" not in cmd
def test_build_command_thinking_display_with_enabled_budget(self):
"""enabled + display emits both --max-thinking-tokens and --thinking-display."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
thinking={
"type": "enabled",
"budget_tokens": 20000,
"display": "omitted",
}
),
)
cmd = transport._build_command()
budget_idx = cmd.index("--max-thinking-tokens")
assert cmd[budget_idx : budget_idx + 2] == ["--max-thinking-tokens", "20000"]
display_idx = cmd.index("--thinking-display")
assert cmd[display_idx : display_idx + 2] == ["--thinking-display", "omitted"]
def test_build_command_thinking_precedence_over_max_thinking_tokens(self):
"""thinking takes precedence over deprecated max_thinking_tokens."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
thinking={"type": "adaptive"}, max_thinking_tokens=9999
),
)
cmd = transport._build_command()
idx = cmd.index("--thinking")
assert cmd[idx : idx + 2] == ["--thinking", "adaptive"]
assert "--max-thinking-tokens" not in cmd
def test_build_command_with_add_dirs(self):
"""Test building CLI command with add_dirs option."""
from pathlib import Path
dir1 = "/path/to/dir1"
dir2 = Path("/path/to/dir2")
transport = SubprocessCLITransport(
prompt="test",
options=make_options(add_dirs=[dir1, dir2]),
)
cmd = transport._build_command()
# Check that both directories are in the command
assert "--add-dir" in cmd
add_dir_indices = [i for i, x in enumerate(cmd) if x == "--add-dir"]
assert len(add_dir_indices) == 2
# The directories should appear after --add-dir flags
dirs_in_cmd = [cmd[i + 1] for i in add_dir_indices]
assert dir1 in dirs_in_cmd
assert str(dir2) in dirs_in_cmd
def test_session_continuation(self):
"""Test session continuation options."""
transport = SubprocessCLITransport(
prompt="Continue from before",
options=make_options(continue_conversation=True, resume="session-123"),
)
cmd = transport._build_command()
assert "--continue" in cmd
assert "--resume" in cmd
assert "session-123" in cmd
def test_session_id(self):
"""Test custom session ID option."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(session_id="550e8400-e29b-41d4-a716-446655440000"),
)
cmd = transport._build_command()
assert "--session-id" in cmd
idx = cmd.index("--session-id")
assert cmd[idx + 1] == "550e8400-e29b-41d4-a716-446655440000"
def test_session_id_not_set_by_default(self):
"""Test that --session-id is not passed when session_id is None."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(),
)
cmd = transport._build_command()
assert "--session-id" not in cmd
def test_connect_close(self):
"""Test connect and close lifecycle."""
async def _test():
with patch("anyio.open_process") as mock_exec:
# Mock version check process
mock_version_process = MagicMock()
mock_version_process.stdout = MagicMock()
mock_version_process.stdout.receive = AsyncMock(
return_value=b"2.0.0 (Claude Code)"
)
mock_version_process.terminate = MagicMock()
mock_version_process.wait = AsyncMock()
# Mock main process
mock_process = MagicMock()
mock_process.returncode = None
mock_process.terminate = MagicMock()
mock_process.wait = AsyncMock()
mock_process.stdout = MagicMock()
mock_process.stderr = MagicMock()
# Mock stdin with aclose method
mock_stdin = MagicMock()
mock_stdin.aclose = AsyncMock()
mock_process.stdin = mock_stdin
# Return version process first, then main process
mock_exec.side_effect = [mock_version_process, mock_process]
transport = SubprocessCLITransport(
prompt="test",
options=make_options(),
)
await transport.connect()
assert transport._process is not None
assert transport.is_ready()
await transport.close()
# After stdin EOF, the process is given time to exit
# gracefully. Since the mock's wait() returns immediately,
# terminate should NOT be called.
mock_process.terminate.assert_not_called()
mock_process.wait.assert_called()
anyio.run(_test)
def test_read_messages(self):
"""Test reading messages from CLI output."""
# This test is simplified to just test the transport creation
# The full async stream handling is tested in integration tests
transport = SubprocessCLITransport(prompt="test", options=make_options())
# The transport now just provides raw message reading via read_messages()
# So we just verify the transport can be created and basic structure is correct
assert transport._prompt == "test"
assert transport._cli_path == "/usr/bin/claude"
def test_connect_with_nonexistent_cwd(self):
"""Test that connect raises CLIConnectionError when cwd doesn't exist."""
from claude_agent_sdk._errors import CLIConnectionError
async def _test():
transport = SubprocessCLITransport(
prompt="test",
options=make_options(cwd="/this/directory/does/not/exist"),
)
with pytest.raises(CLIConnectionError) as exc_info:
await transport.connect()
assert "/this/directory/does/not/exist" in str(exc_info.value)
anyio.run(_test)
def test_build_command_with_settings_file(self):
"""Test building CLI command with settings as file path."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(settings="/path/to/settings.json"),
)
cmd = transport._build_command()
assert "--settings" in cmd
assert "/path/to/settings.json" in cmd
def test_build_command_with_settings_json(self):
"""Test building CLI command with settings as JSON object."""
settings_json = '{"permissions": {"allow": ["Bash(ls:*)"]}}'
transport = SubprocessCLITransport(
prompt="test",
options=make_options(settings=settings_json),
)
cmd = transport._build_command()
assert "--settings" in cmd
assert settings_json in cmd
def test_build_command_setting_sources_omitted_when_not_provided(self):
"""Test that --setting-sources is omitted when setting_sources is not provided."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(),
)
cmd = transport._build_command()
assert not any(a.startswith("--setting-sources") for a in cmd)
def test_build_command_setting_sources_empty_list_disables_all(self):
"""Test that setting_sources=[] passes --setting-sources= to disable all sources."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(setting_sources=[]),
)
cmd = transport._build_command()
assert "--setting-sources=" in cmd
def test_build_command_setting_sources_included_when_provided(self):
"""Test that --setting-sources is included when setting_sources has values."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(setting_sources=["user", "project"]),
)
cmd = transport._build_command()
assert "--setting-sources=user,project" in cmd
def test_build_command_skills_none_leaves_options_untouched(self):
"""When skills is None (default), neither allowed_tools nor setting_sources change."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(),
)
cmd = transport._build_command()
assert "--allowedTools" not in cmd
assert not any(a.startswith("--setting-sources") for a in cmd)
def test_build_command_skills_all_enables_skill_tool(self):
"""skills='all' enables the bare Skill tool and defaults setting_sources."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(skills="all"),
)
cmd = transport._build_command()
assert "--allowedTools" in cmd
assert cmd[cmd.index("--allowedTools") + 1] == "Skill"
assert "--setting-sources=user,project" in cmd
def test_build_command_skills_empty_list_adds_no_skill_entries(self):
"""skills=[] is a degenerate subset: setting_sources defaults, no Skill entries."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(skills=[]),
)
cmd = transport._build_command()
assert "--allowedTools" not in cmd
assert "--setting-sources=user,project" in cmd
def test_build_command_skills_named_list_uses_skill_patterns(self):
"""Non-empty skills list adds Skill(name) entries and defaults setting_sources."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(skills=["pdf", "docx"]),
)
cmd = transport._build_command()
assert "--allowedTools" in cmd
assert cmd[cmd.index("--allowedTools") + 1] == "Skill(pdf),Skill(docx)"
assert "--setting-sources=user,project" in cmd
def test_build_command_skills_merges_with_existing_allowed_tools(self):
"""skills augment (not replace) an existing allowed_tools list."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
allowed_tools=["Read", "Write"],
skills=["pdf"],
),
)
cmd = transport._build_command()
assert cmd[cmd.index("--allowedTools") + 1] == "Read,Write,Skill(pdf)"
def test_build_command_skills_preserves_user_setting_sources(self):
"""When setting_sources is explicitly provided, skills should not override it."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
skills="all",
setting_sources=["local"],
),
)
cmd = transport._build_command()
assert "--setting-sources=local" in cmd
def test_build_command_skills_does_not_mutate_options(self):
"""Applying skills defaults must not mutate the caller's options object."""
options = make_options(allowed_tools=["Read"], skills=["pdf"])
transport = SubprocessCLITransport(prompt="test", options=options)
transport._build_command()
assert options.allowed_tools == ["Read"]
assert options.setting_sources is None
def test_build_command_skills_does_not_duplicate_entries(self):
"""Injecting Skill entries is idempotent when caller already listed them."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
allowed_tools=["Skill(pdf)"],
skills=["pdf"],
),
)
cmd = transport._build_command()
assert cmd[cmd.index("--allowedTools") + 1] == "Skill(pdf)"
@pytest.mark.parametrize(
("skills", "extra", "want_tools", "want_sources", "want_init_skills"),
[
# (1) default: no auto-config
(None, {}, None, None, _ABSENT),
# (2) old manual way still works (skills=None, user wires it)
(
None,
{
"allowed_tools": ["Skill", "Read"],
"setting_sources": ["user", "project"],
},
"Skill,Read",
"user,project",
_ABSENT,
),
# (3) "all": bare Skill, default sources, no wire filter
("all", {}, "Skill", "user,project", _ABSENT),
# (4) named subset
(
["pdf", "docx"],
{},
"Skill(pdf),Skill(docx)",
"user,project",
["pdf", "docx"],
),
# (5) subset + explicit setting_sources (user wins)
(
["pdf"],
{"setting_sources": ["project"]},
"Skill(pdf)",
"project",
["pdf"],
),
# (6) subset merges into existing allowed_tools
(
["pdf"],
{"allowed_tools": ["Read", "Bash"]},
"Read,Bash,Skill(pdf)",
"user,project",
["pdf"],
),
# (7) empty list = degenerate subset (not "all")
([], {}, None, "user,project", []),
],
ids=[
"default-none",
"old-manual",
"all",
"subset",
"subset+explicit-sources",
"subset+merge-tools",
"empty-list",
],
)
def test_skills_option_matrix(
self, skills, extra, want_tools, want_sources, want_init_skills
):
"""Documented behavior table for ClaudeAgentOptions.skills.
Asserts the full (input) -> (allowedTools, setting_sources,
initialize.skills) mapping in one place. See also
test_query.py::test_initialize_* for the wire-level half.
"""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(skills=skills, **extra),
)
cmd = transport._build_command()
if want_tools is None:
assert "--allowedTools" not in cmd
else:
assert cmd[cmd.index("--allowedTools") + 1] == want_tools
if want_sources is None:
assert not any(a.startswith("--setting-sources") for a in cmd)
else:
assert f"--setting-sources={want_sources}" in cmd
# Wire-level: what the Query layer would send on initialize.
# 'all' and None both omit the field; only an explicit list is sent.
if want_init_skills is _ABSENT:
assert not isinstance(skills, list)
else:
assert skills == want_init_skills
def test_build_command_with_extra_args(self):
"""Test building CLI command with extra_args for future flags."""
transport = SubprocessCLITransport(
prompt="test",
options=make_options(
extra_args={
"new-flag": "value",
"boolean-flag": None,
"another-option": "test-value",
}
),
)
cmd = transport._build_command()
cmd_str = " ".join(cmd)
# Check flags with values
assert "--new-flag value" in cmd_str
assert "--another-option test-value" in cmd_str
# Check boolean flag (no value)
assert "--boolean-flag" in cmd
# Make sure boolean flag doesn't have a value after it
boolean_idx = cmd.index("--boolean-flag")
# Either it's the last element or the next element is another flag
assert boolean_idx == len(cmd) - 1 or cmd[boolean_idx + 1].startswith("--")
def test_build_command_with_mcp_servers(self):
"""Test building CLI command with mcp_servers option."""
import json
mcp_servers = {
"test-server": {
"type": "stdio",
"command": "/path/to/server",
"args": ["--option", "value"],
}
}
transport = SubprocessCLITransport(
prompt="test",
options=make_options(mcp_servers=mcp_servers),
)
cmd = transport._build_command()
# Find the --mcp-config flag and its value
assert "--mcp-config" in cmd
mcp_idx = cmd.index("--mcp-config")
mcp_config_value = cmd[mcp_idx + 1]
# Parse the JSON and verify structure
config = json.loads(mcp_config_value)
assert "mcpServers" in config
assert config["mcpServers"] == mcp_servers
def test_build_command_with_mcp_servers_as_file_path(self):
"""Test building CLI command with mcp_servers as file path."""
from pathlib import Path
# Test with string path
string_path = "/path/to/mcp-config.json"
transport = SubprocessCLITransport(
prompt="test",
options=make_options(mcp_servers=string_path),
)
cmd = transport._build_command()
assert "--mcp-config" in cmd
mcp_idx = cmd.index("--mcp-config")
assert cmd[mcp_idx + 1] == string_path
# Test with Path object
path_obj = Path("/path/to/mcp-config.json")
transport = SubprocessCLITransport(
prompt="test",
options=make_options(mcp_servers=path_obj),
)
cmd = transport._build_command()
assert "--mcp-config" in cmd
mcp_idx = cmd.index("--mcp-config")
# Path object gets converted to string, compare with str(path_obj)
assert cmd[mcp_idx + 1] == str(path_obj)
def test_build_command_with_mcp_servers_as_json_string(self):
"""Test building CLI command with mcp_servers as JSON string."""
json_config = '{"mcpServers": {"server": {"type": "stdio", "command": "test"}}}'
transport = SubprocessCLITransport(
prompt="test",
options=make_options(mcp_servers=json_config),
)
cmd = transport._build_command()
assert "--mcp-config" in cmd
mcp_idx = cmd.index("--mcp-config")
assert cmd[mcp_idx + 1] == json_config
def test_env_vars_passed_to_subprocess(self):
"""Test that custom environment variables are passed to the subprocess."""
async def _test():
test_value = f"test-{uuid.uuid4().hex[:8]}"
custom_env = {
"MY_TEST_VAR": test_value,
}
options = make_options(env=custom_env)
# Mock the subprocess to capture the env argument
with patch(
"anyio.open_process", new_callable=AsyncMock
) as mock_open_process:
# Mock version check process
mock_version_process = MagicMock()
mock_version_process.stdout = MagicMock()
mock_version_process.stdout.receive = AsyncMock(
return_value=b"2.0.0 (Claude Code)"
)
mock_version_process.terminate = MagicMock()
mock_version_process.wait = AsyncMock()
# Mock main process
mock_process = MagicMock()
mock_process.stdout = MagicMock()
mock_stdin = MagicMock()
mock_stdin.aclose = AsyncMock() # Add async aclose method
mock_process.stdin = mock_stdin
mock_process.returncode = None
# Return version process first, then main process
mock_open_process.side_effect = [mock_version_process, mock_process]
transport = SubprocessCLITransport(
prompt="test",
options=options,
)
await transport.connect()
# Verify open_process was called twice (version check + main process)
assert mock_open_process.call_count == 2
# Check the second call (main process) for env vars
second_call_kwargs = mock_open_process.call_args_list[1].kwargs
assert "env" in second_call_kwargs
env_passed = second_call_kwargs["env"]
# Check that custom env var was passed
assert env_passed["MY_TEST_VAR"] == test_value
# Verify SDK entrypoint default is applied (overrides inherited env)
assert "CLAUDE_CODE_ENTRYPOINT" in env_passed
assert env_passed["CLAUDE_CODE_ENTRYPOINT"] == "sdk-py"
# Verify system env vars are also included with correct values
if "PATH" in os.environ:
assert "PATH" in env_passed
assert env_passed["PATH"] == os.environ["PATH"]
anyio.run(_test)
def test_caller_can_override_entrypoint(self):
"""Test that a caller-supplied CLAUDE_CODE_ENTRYPOINT survives the env merge."""
async def _test():
custom_env = {"CLAUDE_CODE_ENTRYPOINT": "custom-caller"}
options = make_options(env=custom_env)
with patch(
"anyio.open_process", new_callable=AsyncMock
) as mock_open_process:
mock_version_process = MagicMock()
mock_version_process.stdout = MagicMock()
mock_version_process.stdout.receive = AsyncMock(
return_value=b"2.0.0 (Claude Code)"
)
mock_version_process.terminate = MagicMock()
mock_version_process.wait = AsyncMock()
mock_process = MagicMock()
mock_process.stdout = MagicMock()
mock_stdin = MagicMock()
mock_stdin.aclose = AsyncMock()
mock_process.stdin = mock_stdin
mock_process.returncode = None
mock_open_process.side_effect = [mock_version_process, mock_process]
transport = SubprocessCLITransport(
prompt="test",
options=options,
)
await transport.connect()
env_passed = mock_open_process.call_args_list[1].kwargs["env"]
# Caller's entrypoint must win over the sdk-py default
assert env_passed["CLAUDE_CODE_ENTRYPOINT"] == "custom-caller"
# CLAUDE_AGENT_SDK_VERSION is still SDK-controlled
assert "CLAUDE_AGENT_SDK_VERSION" in env_passed
anyio.run(_test)
def test_otel_trace_context_propagated_to_subprocess(self):
"""Active OTEL trace context is injected as TRACEPARENT/TRACESTATE."""
async def _test():
options = make_options()
def fake_inject(carrier: dict[str, str]) -> None:
carrier["traceparent"] = (
"00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
)
carrier["tracestate"] = "vendor=value"
fake_propagate = MagicMock()
fake_propagate.inject = fake_inject
with (
patch.dict(
"sys.modules",
{
"opentelemetry": MagicMock(propagate=fake_propagate),
"opentelemetry.propagate": fake_propagate,
},
),
patch(
"anyio.open_process", new_callable=AsyncMock
) as mock_open_process,
):
mock_version_process = MagicMock()
mock_version_process.stdout = MagicMock()
mock_version_process.stdout.receive = AsyncMock(
return_value=b"2.0.0 (Claude Code)"
)
mock_version_process.terminate = MagicMock()
mock_version_process.wait = AsyncMock()
mock_process = MagicMock()
mock_process.stdout = MagicMock()
mock_stdin = MagicMock()
mock_stdin.aclose = AsyncMock()
mock_process.stdin = mock_stdin
mock_process.returncode = None
mock_open_process.side_effect = [mock_version_process, mock_process]
transport = SubprocessCLITransport(prompt="test", options=options)
await transport.connect()
env_passed = mock_open_process.call_args_list[1].kwargs["env"]
assert (
env_passed["TRACEPARENT"]
== "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
)
assert env_passed["TRACESTATE"] == "vendor=value"
anyio.run(_test)
def test_otel_trace_context_does_not_override_user_env(self):
"""User-supplied TRACEPARENT in options.env wins over OTEL propagator."""
async def _test():
options = make_options(env={"TRACEPARENT": "custom"})
def fake_inject(carrier: dict[str, str]) -> None:
carrier["traceparent"] = "00-aaaa-bbbb-01"
fake_propagate = MagicMock()
fake_propagate.inject = fake_inject
with (
patch.dict(
"sys.modules",
{
"opentelemetry": MagicMock(propagate=fake_propagate),
"opentelemetry.propagate": fake_propagate,
},
),
patch(
"anyio.open_process", new_callable=AsyncMock
) as mock_open_process,