-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathtest_cli.py
More file actions
1323 lines (1158 loc) · 53.2 KB
/
Copy pathtest_cli.py
File metadata and controls
1323 lines (1158 loc) · 53.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
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 CLI subcommand routing and passthrough args."""
from __future__ import annotations
import os
import re
from unittest.mock import patch
import pytest
from typer.testing import CliRunner
from ucode.cli import app
_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
def _strip_ansi(text: str) -> str:
"""Drop SGR escape sequences so substring assertions match regardless of
whether the runner forces color rendering (e.g. CI sets FORCE_COLOR=1,
which makes rich split styled tokens like ``--agents`` with ANSI codes)."""
return _ANSI_RE.sub("", text)
runner = CliRunner()
TOOLS = ["codex", "claude", "gemini", "opencode"]
@pytest.fixture(autouse=True)
def no_state_writes():
"""Prevent any test from writing to the real state file on disk."""
with (
patch("ucode.state.save_state"),
patch("ucode.cli.save_state"),
patch("ucode.agents.__init__.save_state"),
patch("ucode.agents.codex.save_state"),
patch("ucode.agents.claude.save_state"),
patch("ucode.agents.gemini.save_state"),
patch("ucode.agents.opencode.save_state"),
):
yield
MINIMAL_STATE = {
"workspace": "https://example.databricks.com",
"base_urls": {
"codex": "https://example.databricks.com/ai-gateway/codex",
"claude": "https://example.databricks.com/ai-gateway/anthropic",
"gemini": "https://example.databricks.com/ai-gateway/gemini",
"opencode": "https://example.databricks.com/ai-gateway/opencode",
},
"claude_models": {"sonnet": "databricks-claude-sonnet-4"},
"gemini_models": ["gemini-2.0-flash"],
"codex_models": ["codex-mini"],
"opencode_models": {"anthropic": ["databricks-claude-sonnet-4"]},
"managed_configs": {},
"available_tools": TOOLS,
}
class TestHelp:
def test_no_args_shows_help(self):
result = runner.invoke(app, [])
# no_args_is_help=True exits with code 0 or 2 depending on typer version
assert result.exit_code in (0, 2)
assert "Usage:" in result.output
def test_help_lists_all_agent_subcommands(self):
result = runner.invoke(app, ["--help"])
assert result.exit_code == 0
for tool in TOOLS:
assert tool in result.output
@pytest.mark.parametrize("tool", TOOLS)
def test_subcommand_help(self, tool):
result = runner.invoke(app, [tool, "--help"])
assert result.exit_code == 0
assert "Usage:" in result.output
def test_configure_help_lists_agents_flag(self):
result = runner.invoke(app, ["configure", "--help"])
assert result.exit_code == 0
output = _strip_ansi(result.output)
# Typer wraps long help text across lines and pads with box-drawing
# characters; collapse whitespace + box chars before substring-matching.
flat = re.sub(r"[│╭╮╯╰─\s]+", " ", output)
assert "--agents" in output
assert "comma-separated list of agents" in flat
assert "--workspaces" in output
def _patch_launch(tool: str):
"""Return a context-manager stack that makes _launch_tool a no-op.
load_state returns MINIMAL_STATE (workspace + tool already configured) so
the auto-configure path is skipped entirely. configure_shared_state is
also stubbed to avoid the launch-time refetch hitting the network.
"""
return [
patch("ucode.cli.ensure_bootstrap_dependencies"),
patch("ucode.cli.load_state", return_value=MINIMAL_STATE),
patch(
"ucode.cli.ensure_provider_state",
return_value=MINIMAL_STATE,
),
patch(
"ucode.cli.configure_shared_state",
return_value=MINIMAL_STATE,
),
patch(
"ucode.cli.resolve_launch_model",
return_value=(MINIMAL_STATE, "databricks-claude-sonnet-4"),
),
patch(
"ucode.cli.configure_tool",
return_value=MINIMAL_STATE,
),
patch("ucode.cli.launch_agent"),
]
class TestSubcommandRouting:
@pytest.mark.parametrize("tool", TOOLS)
def test_subcommand_calls_correct_tool(self, tool):
patches = _patch_launch(tool)
with (
patches[0],
patches[1],
patches[2],
patches[3],
patches[4],
patches[5],
patches[6] as mock_launch,
):
result = runner.invoke(app, [tool])
assert result.exit_code == 0, result.output
mock_launch.assert_called_once()
called_tool = mock_launch.call_args[0][0]
assert called_tool == tool
def test_no_agent_flag(self):
"""--agent flag must no longer exist."""
result = runner.invoke(app, ["--agent", "claude"])
assert result.exit_code != 0
class TestMcpSubcommands:
def test_web_search_subcommand_help(self):
result = runner.invoke(app, ["mcp", "web-search", "--help"])
assert result.exit_code == 0
assert "Usage:" in result.output
def test_mcp_group_lists_web_search(self):
result = runner.invoke(app, ["mcp", "--help"])
assert result.exit_code == 0
assert "web-search" in result.output
class TestAuthTokenCommand:
"""`ucode auth-token` is the cross-platform apiKeyHelper (#116)."""
@pytest.fixture(autouse=True)
def _isolated_bearer(self):
# The --use-pat path writes DATABRICKS_BEARER directly; restore it so
# writes by code under test don't leak into other tests.
original = os.environ.pop("DATABRICKS_BEARER", None)
yield
if original is None:
os.environ.pop("DATABRICKS_BEARER", None)
else:
os.environ["DATABRICKS_BEARER"] = original
def test_prints_only_the_token_to_stdout(self):
with (
patch("ucode.cli.load_state", return_value={"workspace": "https://ws"}),
patch("ucode.cli.get_databricks_token", return_value="tok-123") as fetch,
):
result = runner.invoke(app, ["auth-token"])
assert result.exit_code == 0
# Nothing but the bare token (plus trailing newline) may reach stdout,
# or the consuming agent will treat the noise as part of the token.
assert result.stdout == "tok-123\n"
# force_refresh=True so each 15-min apiKeyHelper cycle yields a token with
# a full fresh lifetime (long sessions otherwise die at ~1h expiry).
fetch.assert_called_once_with("https://ws", None, force_refresh=True)
def test_host_and_profile_override_state(self):
with (
patch("ucode.cli.load_state", return_value={"workspace": "https://saved"}),
patch("ucode.cli.get_databricks_token", return_value="tok") as fetch,
):
result = runner.invoke(
app, ["auth-token", "--host", "https://override", "--profile", "prod"]
)
assert result.exit_code == 0
fetch.assert_called_once_with("https://override", "prod", force_refresh=True)
def test_errors_without_workspace(self):
with patch("ucode.cli.load_state", return_value={}):
result = runner.invoke(app, ["auth-token"])
assert result.exit_code == 1
# The error goes to stderr, never stdout.
assert result.stdout == ""
def test_hidden_from_top_level_help(self):
result = runner.invoke(app, ["--help"])
assert "auth-token" not in _strip_ansi(result.output)
def test_use_pat_emits_resolved_pat(self, monkeypatch):
# --use-pat reads the profile's static PAT, exports it as
# DATABRICKS_BEARER, and get_databricks_token returns it directly.
monkeypatch.delenv("DATABRICKS_BEARER", raising=False)
monkeypatch.setattr("ucode.databricks.resolve_pat_token", lambda p: "dapi-pat")
with (
patch("ucode.cli.load_state", return_value={"workspace": "https://ws"}),
patch(
"ucode.cli.get_databricks_token",
side_effect=lambda w, p, *, force_refresh=False: os.environ.get(
"DATABRICKS_BEARER", ""
),
),
):
result = runner.invoke(app, ["auth-token", "--use-pat", "--profile", "p"])
assert result.exit_code == 0
assert result.stdout == "dapi-pat\n"
def test_use_pat_ignores_empty_bearer_env(self, monkeypatch):
# A stray empty DATABRICKS_BEARER must not shadow the PAT and force the
# OAuth path (the regression that motivated ensure_pat_bearer).
monkeypatch.setenv("DATABRICKS_BEARER", "")
monkeypatch.setattr("ucode.databricks.resolve_pat_token", lambda p: "dapi-pat")
with (
patch("ucode.cli.load_state", return_value={"workspace": "https://ws"}),
patch(
"ucode.cli.get_databricks_token",
side_effect=lambda w, p, *, force_refresh=False: os.environ.get(
"DATABRICKS_BEARER", ""
),
),
):
result = runner.invoke(app, ["auth-token", "--use-pat", "--profile", "p"])
assert result.exit_code == 0
assert result.stdout == "dapi-pat\n"
def test_use_pat_fails_closed_without_pat(self, monkeypatch):
# --use-pat with no resolvable PAT must error, NOT fall through to OAuth
# (which can't serve a PAT-only profile and yields a misleading message).
monkeypatch.delenv("DATABRICKS_BEARER", raising=False)
monkeypatch.setattr("ucode.databricks.resolve_pat_token", lambda p: None)
with (
patch("ucode.cli.load_state", return_value={"workspace": "https://ws"}),
patch("ucode.cli.get_databricks_token", return_value="oauth-tok") as fetch,
):
result = runner.invoke(app, ["auth-token", "--use-pat", "--profile", "p"])
assert result.exit_code == 1
# Never attempted OAuth, and nothing leaked to stdout.
fetch.assert_not_called()
assert result.stdout == ""
def test_use_pat_honors_non_empty_bearer_env(self, monkeypatch):
# A real pre-set bearer (CI escape hatch) wins over the profile PAT.
monkeypatch.setenv("DATABRICKS_BEARER", "ci-bearer")
monkeypatch.setattr("ucode.databricks.resolve_pat_token", lambda p: "dapi-pat")
with (
patch("ucode.cli.load_state", return_value={"workspace": "https://ws"}),
patch(
"ucode.cli.get_databricks_token",
side_effect=lambda w, p, *, force_refresh=False: os.environ.get(
"DATABRICKS_BEARER", ""
),
),
):
result = runner.invoke(app, ["auth-token", "--use-pat", "--profile", "p"])
assert result.exit_code == 0
assert result.stdout == "ci-bearer\n"
class TestStatus:
def test_shows_mcp_list_commands(self):
with patch("ucode.cli.load_state", return_value=MINIMAL_STATE):
result = runner.invoke(app, ["status"])
assert result.exit_code == 0, result.output
assert "Managed by Databricks" not in result.output
assert "MCP list command:" in result.output
assert "claude mcp list" in result.output
assert "codex mcp list" in result.output
assert "gemini mcp list" in result.output
assert "opencode mcp list" in result.output
assert "copilot mcp list" not in result.output
def test_shows_mcp_servers_configured_by_ucode(self):
state = {
**MINIMAL_STATE,
"mcp_servers": [
{
"name": "github-mcp",
"url": "https://example.databricks.com/api/2.0/mcp/external/github-mcp",
"auth": "env:OAUTH_TOKEN",
"clients": ["claude", "codex"],
},
{
"name": "databricks-sql",
"url": "https://example.databricks.com/api/2.0/mcp/sql",
"auth": "env:OAUTH_TOKEN",
"clients": ["gemini"],
},
],
}
with patch("ucode.cli.load_state", return_value=state):
result = runner.invoke(app, ["status"])
assert result.exit_code == 0, result.output
assert "github-mcp" in result.output
assert "MCP servers: github-mcp" in result.output
assert "databricks-sql" in result.output
assert "MCP servers: databricks-sql" in result.output
assert "MCP Servers" not in result.output
assert "MCP Server:" not in result.output
assert "Configured tools:" not in result.output
def test_status_treats_available_tools_as_configured_agents(self):
state = {
**MINIMAL_STATE,
"available_tools": ["copilot"],
"base_urls": {
**MINIMAL_STATE["base_urls"],
"copilot": "https://example.databricks.com/ai-gateway/copilot",
},
"mcp_servers": [
{
"name": "databricks-sql",
"url": "https://example.databricks.com/api/2.0/mcp/sql",
"auth": "env:OAUTH_TOKEN",
"clients": ["copilot"],
}
],
}
with patch("ucode.cli.load_state", return_value=state):
result = runner.invoke(app, ["status"])
assert result.exit_code == 0, result.output
assert "copilot mcp list" in result.output
assert "MCP servers: databricks-sql" in result.output
assert "codex mcp list" not in result.output
assert "claude mcp list" not in result.output
assert "gemini mcp list" not in result.output
assert "https://example.databricks.com/ai-gateway/anthropic" not in result.output
assert "https://example.databricks.com/ai-gateway/gemini" not in result.output
class TestRevert:
def test_reverts_mcp_configs_before_clearing_state(self):
state = {
**MINIMAL_STATE,
"mcp_servers": [{"name": "github-mcp", "clients": ["claude"]}],
}
reverted_mcp: list[dict] = []
cleared: list[bool] = []
with (
patch("ucode.cli.load_state", return_value=state),
patch("ucode.cli.restore_file", return_value=False),
patch(
"ucode.cli.revert_mcp_configs",
side_effect=lambda loaded_state: (
reverted_mcp.append(loaded_state) or {"claude": True}
),
),
patch("ucode.cli.clear_state", side_effect=lambda: cleared.append(True)),
):
result = runner.invoke(app, ["revert"])
assert result.exit_code == 0, result.output
assert reverted_mcp == [state]
assert cleared == [True]
assert "Claude Code MCP config: restored" in result.output
class TestAutoConfigureOnFirstRun:
def test_triggers_when_no_workspace(self):
"""Auto-configure runs when state has no workspace."""
empty_state = {}
configured_state = {**MINIMAL_STATE}
with (
patch("ucode.cli.ensure_bootstrap_dependencies") as mock_bootstrap,
patch("ucode.cli.load_state", return_value=empty_state),
patch("ucode.cli._auto_configure_tool") as mock_auto,
patch("ucode.cli.configure_shared_state", return_value=MINIMAL_STATE),
patch(
"ucode.cli.ensure_provider_state",
return_value=configured_state,
),
patch(
"ucode.cli.resolve_launch_model",
return_value=(configured_state, "databricks-claude-sonnet-4"),
),
patch("ucode.cli.configure_tool", return_value=configured_state),
patch("ucode.cli.launch_agent"),
):
result = runner.invoke(app, ["claude"])
assert result.exit_code == 0, result.output
mock_bootstrap.assert_called_once_with("claude", update_existing=True)
mock_auto.assert_called_once_with("claude")
def test_triggers_when_tool_not_in_available_tools(self):
"""Auto-configure runs when workspace exists but the tool wasn't configured."""
state_without_tool = {**MINIMAL_STATE, "available_tools": ["codex"]}
with (
patch("ucode.cli.ensure_bootstrap_dependencies") as mock_bootstrap,
patch("ucode.cli.load_state", return_value=state_without_tool),
patch("ucode.cli._auto_configure_tool") as mock_auto,
patch("ucode.cli.configure_shared_state", return_value=MINIMAL_STATE),
patch(
"ucode.cli.ensure_provider_state",
return_value=MINIMAL_STATE,
),
patch(
"ucode.cli.resolve_launch_model",
return_value=(MINIMAL_STATE, "databricks-claude-sonnet-4"),
),
patch("ucode.cli.configure_tool", return_value=MINIMAL_STATE),
patch("ucode.cli.launch_agent"),
):
result = runner.invoke(app, ["claude"])
assert result.exit_code == 0, result.output
mock_bootstrap.assert_called_once_with("claude", update_existing=True)
mock_auto.assert_called_once_with("claude")
def test_skipped_when_already_configured(self):
"""Auto-configure is skipped when workspace and tool are already set up."""
with (
patch("ucode.cli.ensure_bootstrap_dependencies") as mock_bootstrap,
patch("ucode.cli.load_state", return_value=MINIMAL_STATE),
patch("ucode.cli._auto_configure_tool") as mock_auto,
patch("ucode.cli.configure_shared_state", return_value=MINIMAL_STATE),
patch(
"ucode.cli.ensure_provider_state",
return_value=MINIMAL_STATE,
),
patch(
"ucode.cli.resolve_launch_model",
return_value=(MINIMAL_STATE, "databricks-claude-sonnet-4"),
),
patch("ucode.cli.configure_tool", return_value=MINIMAL_STATE),
patch("ucode.cli.launch_agent"),
):
runner.invoke(app, ["claude"])
mock_bootstrap.assert_called_once_with("claude", update_existing=False)
mock_auto.assert_not_called()
class TestPassthroughArgs:
@pytest.mark.parametrize(
"tool,extra_args",
[
("claude", ["-r"]),
("claude", ["--resume"]),
("codex", ["--full-auto"]),
("gemini", ["--debug"]),
("opencode", ["--model", "my-model"]),
("claude", ["-r", "--some-flag", "value"]),
],
)
def test_extra_args_forwarded(self, tool, extra_args):
patches = _patch_launch(tool)
with (
patches[0],
patches[1],
patches[2],
patches[3],
patches[4],
patches[5],
patches[6] as mock_launch,
):
result = runner.invoke(app, [tool, *extra_args])
assert result.exit_code == 0, result.output
forwarded = mock_launch.call_args[0][2]
assert forwarded == extra_args
def test_no_extra_args_passes_empty_list(self):
patches = _patch_launch("claude")
with (
patches[0],
patches[1],
patches[2],
patches[3],
patches[4],
patches[5],
patches[6] as mock_launch,
):
runner.invoke(app, ["claude"])
forwarded = mock_launch.call_args[0][2]
assert forwarded == []
class TestConfigureAgentFlag:
def test_no_flag_calls_configure_all(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure"])
assert result.exit_code == 0, result.output
mock_cfg.assert_called_once_with(prompt_optional_updates=True)
def test_agents_flag_calls_configure_with_tools(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary") as mock_install,
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--agents", "claude,codex"])
assert result.exit_code == 0, result.output
mock_install.assert_not_called()
mock_cfg.assert_called_once_with(
selected_tools=["claude", "codex"],
prompt_optional_updates=True,
)
def test_agents_flag_normalizes_aliases_and_dedupes(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--agents", " claude-code, codex,claude "])
assert result.exit_code == 0, result.output
mock_cfg.assert_called_once_with(
selected_tools=["claude", "codex"],
prompt_optional_updates=True,
)
def test_workspaces_flag_calls_configure_with_workspaces(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(
app,
[
"configure",
"--workspaces",
"first.databricks.com,https://second.databricks.com/",
],
)
assert result.exit_code == 0, result.output
mock_cfg.assert_called_once_with(
workspaces=[
("https://first.databricks.com", None),
("https://second.databricks.com", None),
],
prompt_optional_updates=True,
)
def test_agents_and_workspaces_flags_call_configure_with_both(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(
app,
["configure", "--agents", "claude,codex", "--workspaces", "https://first.com"],
)
assert result.exit_code == 0, result.output
mock_cfg.assert_called_once_with(
selected_tools=["claude", "codex"],
workspaces=[("https://first.com", None)],
prompt_optional_updates=True,
)
def test_agent_and_workspaces_flags_call_configure_with_both(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary") as mock_install,
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(
app,
["configure", "--agent", "claude", "--workspaces", "https://first.com"],
)
assert result.exit_code == 0, result.output
mock_install.assert_called_once_with(
"claude", strict=True, update_existing=True, prompt_optional_updates=True
)
mock_cfg.assert_called_once_with("claude", workspaces=[("https://first.com", None)])
def test_agent_flag_calls_configure_with_tool(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary") as mock_install,
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--agent", "claude"])
assert result.exit_code == 0, result.output
mock_install.assert_called_once_with(
"claude", strict=True, update_existing=True, prompt_optional_updates=True
)
mock_cfg.assert_called_once_with("claude")
def test_skip_upgrade_flag_disables_optional_update_prompt(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--skip-upgrade"])
assert result.exit_code == 0, result.output
mock_cfg.assert_called_once_with(prompt_optional_updates=False)
def test_skip_upgrade_flag_with_agent_skips_optional_update(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary") as mock_install,
patch("ucode.cli.configure_workspace_command"),
):
result = runner.invoke(app, ["configure", "--agent", "claude", "--skip-upgrade"])
assert result.exit_code == 0, result.output
mock_install.assert_called_once_with(
"claude", strict=True, update_existing=True, prompt_optional_updates=False
)
def test_skip_upgrade_flag_with_agents_forwards_to_configure(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--agents", "claude,codex", "--skip-upgrade"])
assert result.exit_code == 0, result.output
mock_cfg.assert_called_once_with(
selected_tools=["claude", "codex"],
prompt_optional_updates=False,
)
def test_agent_flag_normalizes_alias(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--agent", "claude-code"])
assert result.exit_code == 0, result.output
mock_cfg.assert_called_once_with("claude")
def test_upgrade_runs_uv_tool_install(self):
with patch("subprocess.run") as mock_run:
result = runner.invoke(app, ["upgrade"])
assert result.exit_code == 0, result.output
mock_run.assert_called_once()
cmd = mock_run.call_args[0][0]
assert cmd[:3] == ["uv", "tool", "install"]
assert "--reinstall" in cmd
assert any("github.com/databricks/ucode" in s for s in cmd)
def test_upgrade_handles_uv_missing(self):
with patch("subprocess.run", side_effect=FileNotFoundError):
result = runner.invoke(app, ["upgrade"])
assert result.exit_code != 0
assert "uv" in result.output.lower()
def test_agent_flag_rejects_unknown(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--agent", "bogus"])
assert result.exit_code != 0
mock_cfg.assert_not_called()
def test_agents_flag_rejects_unknown(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--agents", "claude,bogus"])
assert result.exit_code != 0
assert "Unsupported tool 'bogus'" in result.output
assert "codex, claude, gemini, opencode, copilot, pi" in " ".join(result.output.split())
mock_cfg.assert_not_called()
def test_agents_flag_rejects_empty_list(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--agents", ","])
assert result.exit_code != 0
mock_cfg.assert_not_called()
def test_agent_and_agents_flags_are_mutually_exclusive(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--agent", "claude", "--agents", "codex"])
assert result.exit_code != 0
mock_cfg.assert_not_called()
def test_workspaces_flag_rejects_empty_list(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--workspaces", ","])
assert result.exit_code != 0
mock_cfg.assert_not_called()
class TestConfigureAgentsSelection:
def test_selected_tools_skip_picker(self, monkeypatch):
import ucode.cli as cli_mod
state = {**MINIMAL_STATE, "available_tools": []}
monkeypatch.setattr(
cli_mod,
"_prompt_for_configuration",
lambda tool=None: ("https://example.com", None),
)
monkeypatch.setattr(cli_mod, "configure_shared_state", lambda *args, **kwargs: state)
monkeypatch.setattr(
cli_mod, "check_gateway_endpoint", lambda state, tool: tool in {"claude", "codex"}
)
monkeypatch.setattr(
cli_mod,
"prompt_for_tools",
lambda available: pytest.fail("prompt_for_tools should not be called"),
)
install_calls: list[str] = []
monkeypatch.setattr(
cli_mod,
"install_tool_binary",
lambda tool, strict=False, update_existing=False, prompt_optional_updates=True: (
install_calls.append(tool) or True
),
)
configured: list[list[str]] = []
monkeypatch.setattr(
cli_mod,
"configure_selected_tools",
lambda state, tools: configured.append(tools) or {**state, "available_tools": tools},
)
monkeypatch.setattr(cli_mod, "validate_all_tools", lambda state: None)
assert cli_mod.configure_workspace_command(selected_tools=["claude", "codex"]) == 0
assert install_calls == ["claude", "codex"]
assert configured == [["claude", "codex"]]
def test_provider_picker_gated_by_interactive_path(self, monkeypatch):
import ucode.cli as cli_mod
state = {**MINIMAL_STATE, "available_tools": []}
monkeypatch.setattr(cli_mod, "configure_shared_state", lambda *a, **k: state)
monkeypatch.setattr(cli_mod, "check_gateway_endpoint", lambda s, t: t == "claude")
monkeypatch.setattr(cli_mod, "install_tool_binary", lambda *a, **k: True)
monkeypatch.setattr(
cli_mod, "configure_selected_tools", lambda s, tools: {**s, "available_tools": tools}
)
monkeypatch.setattr(cli_mod, "validate_all_tools", lambda s: None)
picked_for: list[str] = []
monkeypatch.setattr(
cli_mod,
"_maybe_select_provider_service",
lambda tool, s: picked_for.append(tool) or s,
)
# Non-interactive (--agents passed): no provider picker.
cli_mod.configure_workspace_command(
selected_tools=["claude"], workspaces=[("https://w.com", None)]
)
assert picked_for == []
# Interactive (`ucode configure`): picker offered for each picked tool.
monkeypatch.setattr(
cli_mod, "_prompt_for_configuration", lambda tool=None: ("https://w.com", None)
)
monkeypatch.setattr(cli_mod, "prompt_for_tools", lambda options: ["claude"])
cli_mod.configure_workspace_command()
assert picked_for == ["claude"]
def test_unavailable_selected_tool_errors_before_configure(self, monkeypatch):
import ucode.cli as cli_mod
state = {**MINIMAL_STATE, "available_tools": []}
monkeypatch.setattr(
cli_mod,
"_prompt_for_configuration",
lambda tool=None: ("https://example.com", None),
)
monkeypatch.setattr(cli_mod, "configure_shared_state", lambda *args, **kwargs: state)
monkeypatch.setattr(cli_mod, "check_gateway_endpoint", lambda state, tool: tool == "claude")
monkeypatch.setattr(cli_mod, "install_tool_binary", lambda *args, **kwargs: None)
monkeypatch.setattr(
cli_mod,
"configure_selected_tools",
lambda state, tools: pytest.fail("configure_selected_tools should not be called"),
)
with pytest.raises(RuntimeError, match="Codex"):
cli_mod.configure_workspace_command(selected_tools=["claude", "codex"])
def test_multiple_workspaces_configure_all_and_use_first(self, monkeypatch):
import ucode.cli as cli_mod
states = {
"https://first.com": {**MINIMAL_STATE, "workspace": "https://first.com"},
"https://second.com": {**MINIMAL_STATE, "workspace": "https://second.com"},
}
configured_shared: list[tuple[str, str | None, tuple[str, ...] | None, bool]] = []
def fake_configure_shared_state(
workspace,
profile=None,
tools=None,
force_login=False,
use_pat=False,
):
configured_shared.append(
(workspace, profile, tuple(tools) if tools is not None else None, force_login)
)
return states[workspace]
saved: list[str] = []
configured_tools: list[tuple[str, list[str]]] = []
monkeypatch.setattr(cli_mod, "configure_shared_state", fake_configure_shared_state)
monkeypatch.setattr(cli_mod, "save_state", lambda state: saved.append(state["workspace"]))
monkeypatch.setattr(cli_mod, "check_gateway_endpoint", lambda state, tool: True)
monkeypatch.setattr(cli_mod, "prompt_for_tools", lambda available: ["codex"])
monkeypatch.setattr(cli_mod, "_maybe_select_provider_service", lambda tool, state: state)
monkeypatch.setattr(cli_mod, "install_tool_binary", lambda *args, **kwargs: True)
monkeypatch.setattr(
cli_mod,
"configure_selected_tools",
lambda state, tools: (
configured_tools.append((state["workspace"], tools))
or {**state, "available_tools": tools}
),
)
monkeypatch.setattr(cli_mod, "validate_all_tools", lambda state: None)
assert (
cli_mod.configure_workspace_command(
workspaces=[("https://first.com", None), ("https://second.com", None)]
)
== 0
)
assert configured_shared == [
("https://first.com", None, None, True),
("https://second.com", None, None, True),
]
assert saved == ["https://first.com"]
assert configured_tools == [("https://first.com", ["codex"])]
class TestParseProfilesOption:
@staticmethod
def _patch_profiles(monkeypatch, entries):
import ucode.cli as cli_mod
monkeypatch.setattr(cli_mod, "list_profile_entries", lambda: entries)
return cli_mod
def test_resolves_profiles_to_workspace_entries(self, monkeypatch):
cli_mod = self._patch_profiles(
monkeypatch,
[
{"name": "DEFAULT", "host": "https://first.databricks.com/", "auth_type": "pat"},
{
"name": "second",
"host": "https://second.databricks.com",
"auth_type": "databricks-cli",
},
],
)
assert cli_mod._parse_profiles_option("DEFAULT, second") == [
("https://first.databricks.com", "DEFAULT"),
("https://second.databricks.com", "second"),
]
def test_unknown_profile_raises_with_available_names(self, monkeypatch):
cli_mod = self._patch_profiles(
monkeypatch,
[{"name": "DEFAULT", "host": "https://first.databricks.com", "auth_type": "pat"}],
)
with pytest.raises(RuntimeError, match=r"'missing' was not found.*DEFAULT"):
cli_mod._parse_profiles_option("missing")
def test_profile_without_host_raises(self, monkeypatch):
cli_mod = self._patch_profiles(monkeypatch, [{"name": "DEFAULT", "auth_type": "pat"}])
with pytest.raises(RuntimeError, match="no host configured"):
cli_mod._parse_profiles_option("DEFAULT")
def test_empty_value_raises(self, monkeypatch):
cli_mod = self._patch_profiles(monkeypatch, [])
with pytest.raises(RuntimeError, match="No profiles provided"):
cli_mod._parse_profiles_option(" , ")
class TestConfigureProfilesFlag:
PROFILE_ENTRIES = [
{"name": "DEFAULT", "host": "https://first.databricks.com", "auth_type": "pat"}
]
def test_profiles_flag_resolves_workspaces(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.list_profile_entries", return_value=self.PROFILE_ENTRIES),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--profiles", "DEFAULT"])
assert result.exit_code == 0, result.output
# Auth behaves like --workspaces: no skip flags are forwarded, so the
# default forced OAuth login applies.
mock_cfg.assert_called_once_with(
workspaces=[("https://first.databricks.com", "DEFAULT")],
prompt_optional_updates=True,
)
def test_profiles_flag_with_agents(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.list_profile_entries", return_value=self.PROFILE_ENTRIES),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(
app, ["configure", "--agents", "claude,codex", "--profiles", "DEFAULT"]
)
assert result.exit_code == 0, result.output
mock_cfg.assert_called_once_with(
selected_tools=["claude", "codex"],
workspaces=[("https://first.databricks.com", "DEFAULT")],
prompt_optional_updates=True,
)
def test_profiles_flag_with_agent(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.list_profile_entries", return_value=self.PROFILE_ENTRIES),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(app, ["configure", "--agent", "claude", "--profiles", "DEFAULT"])
assert result.exit_code == 0, result.output
mock_cfg.assert_called_once_with(
"claude",
workspaces=[("https://first.databricks.com", "DEFAULT")],
)
def test_use_pat_and_skip_validate_are_forwarded(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.install_tool_binary"),
patch("ucode.cli.list_profile_entries", return_value=self.PROFILE_ENTRIES),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(
app,
[
"configure",
"--agents",
"claude,codex",
"--profiles",
"DEFAULT",
"--use-pat",
"--skip-validate",
],
)
assert result.exit_code == 0, result.output
mock_cfg.assert_called_once_with(
selected_tools=["claude", "codex"],
workspaces=[("https://first.databricks.com", "DEFAULT")],
prompt_optional_updates=True,
use_pat=True,
skip_validate=True,
)
def test_use_pat_requires_profiles(self):
with (
patch("ucode.cli.install_databricks_cli"),
patch("ucode.cli.configure_workspace_command") as mock_cfg,
):
result = runner.invoke(
app,
["configure", "--workspaces", "https://first.databricks.com", "--use-pat"],
)
assert result.exit_code == 1
assert "--use-pat requires --profiles" in _strip_ansi(result.output)
mock_cfg.assert_not_called()
def test_profiles_and_workspaces_are_mutually_exclusive(self):