-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathtest_databricks.py
More file actions
1716 lines (1396 loc) · 64.6 KB
/
Copy pathtest_databricks.py
File metadata and controls
1716 lines (1396 loc) · 64.6 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 databricks.py — pure helpers and URL builders that don't hit the network."""
from __future__ import annotations
import json
import os
import subprocess
import pytest
import ucode.databricks as db_mod
from ucode.databricks import (
AI_GATEWAY_V2_DOCS_URL,
_format_subprocess_result,
_parse_databricks_cli_version,
_run_databricks_cli_installer,
_scrub_databrickscfg,
_scrub_json,
build_auth_shell_command,
build_auth_token_argv,
build_databricks_cli_env,
build_opencode_base_urls,
build_shared_base_urls,
build_tool_base_url,
ensure_databricks_cli_version,
ensure_pat_bearer,
get_databricks_token,
list_databricks_apps,
list_databricks_connections,
list_genie_spaces,
workspace_hostname,
)
WS = "https://example.databricks.com"
class TestWorkspaceHostname:
def test_extracts_hostname(self):
assert workspace_hostname(WS) == "example.databricks.com"
def test_handles_path(self):
assert (
workspace_hostname("https://foo.azuredatabricks.net/some/path")
== "foo.azuredatabricks.net"
)
def test_invalid_url_raises(self):
with pytest.raises((RuntimeError, ValueError)):
workspace_hostname("")
class TestBuildDatabricksCliEnv:
def test_sets_databricks_host(self):
env = build_databricks_cli_env(WS)
assert env["DATABRICKS_HOST"] == WS
def test_strips_ambient_profile_without_explicit_profile(self, monkeypatch):
monkeypatch.setenv("DATABRICKS_CONFIG_PROFILE", "other-workspace")
env = build_databricks_cli_env(WS)
assert env["DATABRICKS_HOST"] == WS
assert "DATABRICKS_CONFIG_PROFILE" not in env
def test_preserves_ambient_profile_with_explicit_profile(self, monkeypatch):
monkeypatch.setenv("DATABRICKS_CONFIG_PROFILE", "other-workspace")
env = build_databricks_cli_env(WS, profile="stablebox")
assert env["DATABRICKS_HOST"] == WS
assert env["DATABRICKS_CONFIG_PROFILE"] == "other-workspace"
class TestBuildToolBaseUrl:
def test_codex(self):
url = build_tool_base_url("codex", WS)
assert url == f"{WS}/ai-gateway/codex/v1"
def test_claude(self):
url = build_tool_base_url("claude", WS)
assert url == f"{WS}/ai-gateway/anthropic"
def test_gemini(self):
url = build_tool_base_url("gemini", WS)
assert url == f"{WS}/ai-gateway/gemini"
def test_opencode_raises(self):
with pytest.raises(RuntimeError, match="multiple base URLs"):
build_tool_base_url("opencode", WS)
def test_unsupported_tool_raises(self):
with pytest.raises(RuntimeError, match="Unsupported"):
build_tool_base_url("unknown", WS)
class TestBuildOpencodeBaseUrls:
def test_returns_anthropic_gemini_and_oss(self):
urls = build_opencode_base_urls(WS)
assert urls["anthropic"] == f"{WS}/ai-gateway/anthropic/v1"
assert urls["gemini"] == f"{WS}/ai-gateway/gemini/v1beta"
assert urls["oss"] == f"{WS}/ai-gateway/mlflow/v1"
class TestBuildSharedBaseUrls:
def test_contains_all_tools(self):
urls = build_shared_base_urls(WS)
assert "codex" in urls
assert "claude" in urls
assert "gemini" in urls
assert "opencode" in urls
def test_opencode_is_dict(self):
urls = build_shared_base_urls(WS)
assert isinstance(urls["opencode"], dict)
def test_codex_url_format(self):
urls = build_shared_base_urls(WS)
assert urls["codex"] == f"{WS}/ai-gateway/codex/v1"
class TestDiscoverClaudeModels:
def test_selects_opus_4_8_when_advertised(self, monkeypatch):
payload = {
"data": [
{"id": "databricks-claude-opus-4-7"},
{"id": "databricks-claude-opus-4-8"},
{"id": "databricks-claude-sonnet-4-6"},
]
}
monkeypatch.setattr(db_mod, "_http_get_json", lambda url, token: (payload, None))
models, reason = db_mod.discover_claude_models(WS, "token")
assert reason is None
assert models["opus"] == "databricks-claude-opus-4-8"
def _model_service(model_id: str) -> dict:
"""A model-services entry whose `name` strips to `model_id`."""
return {"name": f"model-services/{model_id}"}
class TestModelTokenLimits:
def test_glm_is_capped(self):
assert db_mod.model_token_limits("system.ai.glm-5-2") == {
"context": 200_000,
"output": 25_000,
}
def test_glm_matches_any_version(self):
assert db_mod.model_token_limits("system.ai.glm-4-6-flash") == {
"context": 200_000,
"output": 25_000,
}
def test_uncapped_model_returns_none(self):
assert db_mod.model_token_limits("system.ai.kimi-k2-7-code") is None
class TestDiscoverModelServices:
def test_buckets_families_by_name(self, monkeypatch):
payload = {
"model_services": [
_model_service("system.ai.claude-opus-4-7"),
_model_service("system.ai.claude-opus-4-8"),
_model_service("system.ai.claude-sonnet-4-6"),
_model_service("system.ai.gpt-5"),
_model_service("system.ai.gemini-2-5-flash"),
_model_service("system.ai.gemini-3-5-flash"),
_model_service("system.ai.kimi-k2-7-code"),
_model_service("system.ai.glm-5-2"),
_model_service("system.ai.llama-4-maverick"),
]
}
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=10: (payload, None)
)
claude, codex, gemini, oss, reason = db_mod.discover_model_services(WS, "token")
assert reason is None
# Newest opus wins; sonnet bucketed; haiku absent.
assert claude == {
"opus": "system.ai.claude-opus-4-8",
"sonnet": "system.ai.claude-sonnet-4-6",
}
assert codex == ["system.ai.gpt-5"]
# Gemini ordered newest-first via the shared sort key.
assert gemini[0] == "system.ai.gemini-3-5-flash"
# kimi and glm are the allowlisted OSS families; llama is not.
assert oss == ["system.ai.glm-5-2", "system.ai.kimi-k2-7-code"]
def test_oss_allowlist_drops_unsupported_families(self, monkeypatch):
# Only kimi/glm are allowlisted; other families are dropped.
payload = {
"model_services": [
_model_service("system.ai.glm-5-2"),
_model_service("system.ai.kimi-k2-7-code"),
_model_service("system.ai.qwen-3-coder"),
_model_service("system.ai.deepseek-v3"),
_model_service("system.ai.gte-large-embed"),
_model_service("system.ai.bge-reranker-v2"),
]
}
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=10: (payload, None)
)
claude, codex, gemini, oss, reason = db_mod.discover_model_services(WS, "token")
assert reason is None
assert (claude, codex, gemini) == ({}, [], [])
assert oss == ["system.ai.glm-5-2", "system.ai.kimi-k2-7-code"]
def test_paginates_via_next_page_token(self, monkeypatch):
pages = {
None: {
"model_services": [_model_service("system.ai.gpt-5")],
"next_page_token": "tok2",
},
"tok2": {
"model_services": [_model_service("system.ai.claude-opus-4-8")],
},
}
def fake_get(url, token, timeout=10):
token_param = None
if "page_token=" in url:
token_param = url.split("page_token=")[1].split("&")[0]
return pages[token_param], None
monkeypatch.setattr(db_mod, "_http_get_json", fake_get)
claude, codex, _, _, reason = db_mod.discover_model_services(WS, "token")
assert reason is None
assert codex == ["system.ai.gpt-5"]
assert claude == {"opus": "system.ai.claude-opus-4-8"}
def test_http_failure_returns_reason(self, monkeypatch):
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=10: (None, "HTTP 500 Server Error")
)
claude, codex, gemini, oss, reason = db_mod.discover_model_services(WS, "token")
assert (claude, codex, gemini, oss) == ({}, [], [], [])
assert reason == "HTTP 500 Server Error"
def test_no_matching_families_reports_sample(self, monkeypatch):
payload = {"model_services": [_model_service("system.ai.llama-4-maverick")]}
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=10: (payload, None)
)
claude, codex, gemini, oss, reason = db_mod.discover_model_services(WS, "token")
assert (claude, codex, gemini, oss) == ({}, [], [], [])
assert reason is not None and "llama-4-maverick" in reason
def test_ignores_non_system_ai_schemas(self, monkeypatch):
# The metastore listing returns services from every schema; only
# system.ai.* foundation models should be picked up.
payload = {
"model_services": [
_model_service("system.ai.gpt-5"),
_model_service("main.svenwb.gpt-5-5"),
_model_service("temp.erni.kimi-k2-7-code"),
_model_service("temp.erni.claude-opus-4-8"),
_model_service("dnasi_agent_cuj.default.dnasi-gpt55-test"),
]
}
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=10: (payload, None)
)
claude, codex, gemini, oss, reason = db_mod.discover_model_services(WS, "token")
assert reason is None
assert codex == ["system.ai.gpt-5"]
assert claude == {} # temp.erni.claude-* must not be bucketed
assert gemini == []
assert oss == []
def test_requests_bounded_page_size(self, monkeypatch):
# The endpoint 499s without a bounded page_size, so every request must
# carry one.
urls: list[str] = []
def fake_get(url, token, timeout=10):
urls.append(url)
return {"model_services": [_model_service("system.ai.gpt-5")]}, None
monkeypatch.setattr(db_mod, "_http_get_json", fake_get)
ids, reason = db_mod.list_model_services(WS, "token")
assert ids == ["system.ai.gpt-5"]
assert reason is None
assert all("page_size=" in u for u in urls)
def test_retries_page_before_giving_up(self, monkeypatch):
payload = {"model_services": [_model_service("system.ai.gpt-5")]}
calls = {"n": 0}
def flaky_get(url, token, timeout=10):
calls["n"] += 1
if calls["n"] < 3:
return None, "HTTP 499 Unknown"
return payload, None
monkeypatch.setattr(db_mod, "_http_get_json", flaky_get)
ids, reason = db_mod.list_model_services(WS, "token")
assert reason is None
assert ids == ["system.ai.gpt-5"]
assert calls["n"] == 3 # two failures, third succeeds
class TestListModelProviderServices:
_PAYLOAD = {
"model_provider_services": [
{
"name": "model-provider-services/main.aarushi.anthropic-svc",
"config": {"provider_type": "EXTERNAL_MODEL_PROVIDER_TYPE_ANTHROPIC"},
},
{
"name": "model-provider-services/main.aarushi.openai-svc",
"config": {"provider_type": "EXTERNAL_MODEL_PROVIDER_TYPE_OPENAI"},
},
{
"name": "model-provider-services/main.bob.bedrock-svc",
"config": {
"provider_type": "EXTERNAL_MODEL_PROVIDER_TYPE_AMAZON_BEDROCK",
"allow_all_targets": False,
"targets": [
{
"model": "us.anthropic.claude-sonnet-4-6",
"native_api_types": ["anthropic/v1/messages"],
},
{"model": "global.anthropic.claude-opus-4-8"},
],
},
},
{
"name": "model-provider-services/main.bob.bedrock-titan-svc",
"config": {
"provider_type": "EXTERNAL_MODEL_PROVIDER_TYPE_AMAZON_BEDROCK",
"targets": [{"model": "amazon.titan-text-express-v1"}],
},
},
]
}
def test_strips_prefix_and_tags_provider_type(self, monkeypatch):
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: (self._PAYLOAD, None)
)
services, reason = db_mod.list_model_provider_services(WS, "token")
assert reason is None
assert services[0] == {
"name": "main.aarushi.anthropic-svc",
"provider_type": "anthropic",
"targets": [],
"allow_all_targets": False,
}
assert {s["provider_type"] for s in services} == {
"anthropic",
"openai",
"amazon_bedrock",
}
def test_extracts_targets(self, monkeypatch):
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: (self._PAYLOAD, None)
)
services, _ = db_mod.list_model_provider_services(WS, "token")
bedrock = next(s for s in services if s["name"] == "main.bob.bedrock-svc")
assert bedrock["targets"] == [
"us.anthropic.claude-sonnet-4-6",
"global.anthropic.claude-opus-4-8",
]
def test_returns_reason_on_failure(self, monkeypatch):
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: (None, "HTTP 500 Server Error")
)
services, reason = db_mod.list_model_provider_services(WS, "token")
assert services == []
assert reason == "HTTP 500 Server Error"
def test_claude_includes_anthropic_and_usable_bedrock(self, monkeypatch):
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: (self._PAYLOAD, None)
)
names, reason = db_mod.list_tool_provider_services("claude", WS, "token")
assert reason is None
# Anthropic + the Bedrock service with Claude targets; the Bedrock service
# exposing only Titan is hidden (no Claude models to pin).
assert names == ["main.aarushi.anthropic-svc", "main.bob.bedrock-svc"]
def test_codex_filters_to_openai(self, monkeypatch):
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: (self._PAYLOAD, None)
)
names, _ = db_mod.list_tool_provider_services("codex", WS, "token")
assert names == ["main.aarushi.openai-svc"]
class TestMapBedrockClaudeModels:
def test_maps_families(self):
models = db_mod.map_bedrock_claude_models(
[
"us.anthropic.claude-sonnet-4-6",
"global.anthropic.claude-opus-4-8",
"anthropic.claude-haiku-4-5",
"amazon.titan-text-express-v1",
]
)
assert models == {
"sonnet": "us.anthropic.claude-sonnet-4-6",
"opus": "global.anthropic.claude-opus-4-8",
"haiku": "anthropic.claude-haiku-4-5",
}
def test_prefers_highest_version(self):
models = db_mod.map_bedrock_claude_models(
["us.anthropic.claude-sonnet-4-5", "us.anthropic.claude-sonnet-4-6"]
)
assert models["sonnet"] == "us.anthropic.claude-sonnet-4-6"
def test_region_tie_break_prefers_global(self):
models = db_mod.map_bedrock_claude_models(
[
"us.anthropic.claude-opus-4-8",
"global.anthropic.claude-opus-4-8",
"eu.anthropic.claude-opus-4-8",
]
)
assert models["opus"] == "global.anthropic.claude-opus-4-8"
def test_empty_when_no_claude(self):
assert db_mod.map_bedrock_claude_models(["amazon.titan-text-express-v1"]) == {}
class TestResolveProviderService:
_PAYLOAD = TestListModelProviderServices._PAYLOAD
def _patch(self, monkeypatch):
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: (self._PAYLOAD, None)
)
def test_anthropic_ok(self, monkeypatch):
self._patch(monkeypatch)
service, error = db_mod.resolve_provider_service(
"claude", "main.aarushi.anthropic-svc", WS, "token"
)
assert error is None
assert service["provider_type"] == "anthropic"
def test_bedrock_with_claude_ok(self, monkeypatch):
self._patch(monkeypatch)
service, error = db_mod.resolve_provider_service(
"claude", "main.bob.bedrock-svc", WS, "token"
)
assert error is None
assert service["provider_type"] == "amazon_bedrock"
def test_wrong_type_rejected(self, monkeypatch):
self._patch(monkeypatch)
service, error = db_mod.resolve_provider_service(
"claude", "main.aarushi.openai-svc", WS, "token"
)
assert service is None
assert "can't route to" in error
def test_bedrock_without_claude_rejected(self, monkeypatch):
self._patch(monkeypatch)
service, error = db_mod.resolve_provider_service(
"claude", "main.bob.bedrock-titan-svc", WS, "token"
)
assert service is None
assert "no Claude models" in error
def test_not_found_lists_usable(self, monkeypatch):
self._patch(monkeypatch)
service, error = db_mod.resolve_provider_service("claude", "main.x.missing", WS, "token")
assert service is None
assert "was not found" in error
assert "main.aarushi.anthropic-svc" in error
def test_feature_unavailable(self, monkeypatch):
reason = "HTTP 400 Bad Request: ModelProviderService feature is not available"
monkeypatch.setattr(db_mod, "_http_get_json", lambda url, token, timeout=30: (None, reason))
service, error = db_mod.resolve_provider_service("claude", "main.x.y", WS, "token")
assert service is None
assert "not available" in error
class TestModelProviderFeatureUnavailable:
def test_detects_feature_not_available(self):
reason = (
'HTTP 400 Bad Request: {"error_code":"BAD_REQUEST",'
'"message":"ModelProviderService feature is not available"}'
)
assert db_mod.is_model_provider_feature_unavailable(reason) is True
def test_false_for_other_errors(self):
assert db_mod.is_model_provider_feature_unavailable("HTTP 500 Server Error") is False
assert db_mod.is_model_provider_feature_unavailable(None) is False
class TestListMcpServices:
def test_accepts_entries_without_connection_status(self, monkeypatch):
payload = {
"mcp_services": [
{
"name": "mcp-services/system.ai.github",
"config": {"usage_tracking": {"enabled": True}, "tracing": {"enabled": True}},
},
{
"name": "mcp-services/system.ai.atlassian",
"config": {},
},
{
"name": "mcp-services/system.ai.slack",
},
]
}
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: (payload, None)
)
names, reason = db_mod.list_mcp_services(WS, "token")
assert reason is None
assert names == ["system.ai.atlassian", "system.ai.github", "system.ai.slack"]
def test_accepts_legacy_active_status(self, monkeypatch):
payload = {
"mcp_services": [
{
"name": "mcp-services/system.ai.github",
"config": {"connection": {"status": "ACTIVE"}},
},
]
}
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: (payload, None)
)
names, reason = db_mod.list_mcp_services(WS, "token")
assert reason is None
assert names == ["system.ai.github"]
def test_rejects_explicit_non_active_status(self, monkeypatch):
# If the field is present and non-ACTIVE, drop the entry — the
# backing connection is broken and the proxy will fail.
payload = {
"mcp_services": [
{
"name": "mcp-services/system.ai.github",
"config": {"connection": {"status": "ACTIVE"}},
},
{
"name": "mcp-services/system.ai.broken",
"config": {"connection": {"status": "FAILED"}},
},
]
}
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: (payload, None)
)
names, _reason = db_mod.list_mcp_services(WS, "token")
assert names == ["system.ai.github"]
def test_ignores_non_system_ai_entries(self, monkeypatch):
payload = {
"mcp_services": [
{"name": "mcp-services/system.ai.github"},
{"name": "mcp-services/main.svenwb.github_mcp"},
{"name": "mcp-services/temp.erni.github_mcp"},
]
}
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: (payload, None)
)
names, _reason = db_mod.list_mcp_services(WS, "token")
assert names == ["system.ai.github"]
def test_http_failure_propagates_reason(self, monkeypatch):
monkeypatch.setattr(
db_mod,
"_http_get_json",
lambda url, token, timeout=30: (None, "HTTP 500 Server Error"),
)
names, reason = db_mod.list_mcp_services(WS, "token")
assert names == []
assert reason == "HTTP 500 Server Error"
def test_empty_payload_is_successful_with_no_reason(self, monkeypatch):
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: ({"mcp_services": []}, None)
)
names, reason = db_mod.list_mcp_services(WS, "token")
assert names == []
assert reason is None
def test_custom_parent_passes_through_to_url(self, monkeypatch):
captured: dict[str, str] = {}
def fake_get(url, token, timeout=30):
captured["url"] = url
return {"mcp_services": []}, None
monkeypatch.setattr(db_mod, "_http_get_json", fake_get)
db_mod.list_mcp_services(WS, "token", parent="main.svenwb")
assert "parent=schemas%2Fmain.svenwb" in captured["url"]
def test_custom_parent_filters_to_namespace(self, monkeypatch):
payload = {
"mcp_services": [
{"name": "mcp-services/main.svenwb.github"},
{"name": "mcp-services/main.svenwb.slack"},
{"name": "mcp-services/system.ai.github"},
]
}
monkeypatch.setattr(
db_mod, "_http_get_json", lambda url, token, timeout=30: (payload, None)
)
names, reason = db_mod.list_mcp_services(WS, "token", parent="main.svenwb")
assert reason is None
assert names == ["main.svenwb.github", "main.svenwb.slack"]
def test_http_404_reason_surfaces_for_invalid_parent(self, monkeypatch):
monkeypatch.setattr(
db_mod,
"_http_get_json",
lambda url, token, timeout=30: (None, "HTTP 404 Not Found: NOT_FOUND"),
)
names, reason = db_mod.list_mcp_services(WS, "token", parent="nope.nope")
assert names == []
assert reason and reason.startswith("HTTP 404")
def _foundation_models_payload(names):
return {
"endpoints": [
{
"name": name,
"config": {
"served_entities": [
{
"foundation_model": {
"ai_gateway_v2_supported": True,
"api_types": ["gemini/v1/generateContent"],
}
}
]
},
}
for name in names
]
}
class TestModelVersionSortKey:
def test_orders_newest_version_first(self):
names = [
"databricks-gemini-2-5-flash",
"databricks-gemini-2-5-pro",
"databricks-gemini-3-1-flash-lite",
"databricks-gemini-3-1-pro",
"databricks-gemini-3-5-flash",
"databricks-gemini-3-flash",
"databricks-gemini-3-pro",
]
ordered = sorted(names, key=db_mod.model_version_sort_key)
assert ordered[0] == "databricks-gemini-3-5-flash"
def test_treats_bare_major_as_dot_zero(self):
# 3-flash is 3.0, so 3-5-flash (3.5) must sort ahead of it.
names = ["databricks-gemini-3-flash", "databricks-gemini-3-5-flash"]
ordered = sorted(names, key=db_mod.model_version_sort_key)
assert ordered == [
"databricks-gemini-3-5-flash",
"databricks-gemini-3-flash",
]
def test_unversioned_names_sort_last_alphabetically(self):
names = ["databricks-gemini-2-5-flash", "custom-endpoint", "another-endpoint"]
ordered = sorted(names, key=db_mod.model_version_sort_key)
assert ordered[0] == "databricks-gemini-2-5-flash"
assert ordered[1:] == ["another-endpoint", "custom-endpoint"]
class TestDiscoverGeminiModels:
def test_returns_newest_flash_first(self, monkeypatch):
payload = _foundation_models_payload(
[
"databricks-gemini-2-5-flash",
"databricks-gemini-3-5-flash",
"databricks-gemini-3-flash",
]
)
monkeypatch.setattr(db_mod, "_http_get_json", lambda url, token: (payload, None))
models, reason = db_mod.discover_gemini_models(WS, "token")
assert reason is None
assert models[0] == "databricks-gemini-3-5-flash"
def test_codex_discovery_keeps_alphabetical_order(self, monkeypatch):
# Codex passes no sort_key, so ordering must stay the plain alphabetical
# default — guarding against the gemini change leaking across tools.
payload = {
"endpoints": [
{
"name": name,
"config": {
"served_entities": [
{
"foundation_model": {
"ai_gateway_v2_supported": True,
"api_types": ["openai/v1/responses"],
}
}
]
},
}
for name in ["databricks-gpt-5-2-codex", "databricks-gpt-4-1"]
]
}
monkeypatch.setattr(db_mod, "_http_get_json", lambda url, token: (payload, None))
models, reason = db_mod.discover_codex_models(WS, "token")
assert reason is None
assert models == ["databricks-gpt-4-1", "databricks-gpt-5-2-codex"]
class TestResolvePatToken:
def test_reads_pat_profile_token_from_cfg(self, monkeypatch, tmp_path):
cfg = tmp_path / "databrickscfg"
cfg.write_text(f"[lakebox]\nhost = {WS}\ntoken = dapi-from-cfg\n")
monkeypatch.setenv("DATABRICKS_CONFIG_FILE", str(cfg))
monkeypatch.setattr(
db_mod,
"list_profile_entries",
lambda: [{"name": "lakebox", "host": WS, "auth_type": "pat"}],
)
assert db_mod.resolve_pat_token("lakebox") == "dapi-from-cfg"
def test_default_section_token_does_not_leak_into_named_profiles(self, monkeypatch, tmp_path):
cfg = tmp_path / "databrickscfg"
cfg.write_text(
f"[DEFAULT]\nhost = {WS}\ntoken = dapi-default\n"
"[other]\nhost = https://other.databricks.com\n"
)
monkeypatch.setenv("DATABRICKS_CONFIG_FILE", str(cfg))
monkeypatch.setattr(
db_mod,
"list_profile_entries",
lambda: [
{"name": "DEFAULT", "host": WS, "auth_type": "pat"},
{"name": "other", "host": "https://other.databricks.com", "auth_type": "pat"},
],
)
assert db_mod.resolve_pat_token("DEFAULT") == "dapi-default"
assert db_mod.resolve_pat_token("other") is None
def test_returns_none_for_oauth_profile(self, monkeypatch):
monkeypatch.setattr(
db_mod,
"list_profile_entries",
lambda: [{"name": "oauth", "host": WS, "auth_type": "databricks-cli"}],
)
assert db_mod.resolve_pat_token("oauth") is None
def test_returns_none_without_profile(self):
assert db_mod.resolve_pat_token(None) is None
class TestApplyPatEnvironment:
@pytest.fixture(autouse=True)
def _isolated_bearer(self):
# apply_pat_environment writes os.environ directly; restore it even
# though monkeypatch can't track writes made by code under test.
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_exports_bearer_for_use_pat_state(self, monkeypatch):
monkeypatch.setattr(db_mod, "resolve_pat_token", lambda p: "dapi-pat")
db_mod.apply_pat_environment({"use_pat": True, "profile": "DEFAULT"})
assert os.environ["DATABRICKS_BEARER"] == "dapi-pat"
def test_noop_without_use_pat(self, monkeypatch):
monkeypatch.setattr(db_mod, "resolve_pat_token", lambda p: "dapi-pat")
db_mod.apply_pat_environment({"profile": "DEFAULT"})
assert "DATABRICKS_BEARER" not in os.environ
def test_existing_bearer_wins(self, monkeypatch):
monkeypatch.setenv("DATABRICKS_BEARER", "explicit-bearer")
monkeypatch.setattr(db_mod, "resolve_pat_token", lambda p: "dapi-pat")
db_mod.apply_pat_environment({"use_pat": True, "profile": "DEFAULT"})
assert os.environ["DATABRICKS_BEARER"] == "explicit-bearer"
class TestBuildAuthTokenArgv:
def test_basic_argv(self):
argv = build_auth_token_argv(WS)
# First element resolves to the ucode executable; the rest is the
# cross-platform helper invocation — no `sh`, no `jq`, no shell syntax.
assert argv[0].endswith("ucode") or argv[0] == "ucode"
assert argv[1:] == ["auth-token", "--host", WS]
def test_strips_trailing_slash_from_host(self):
argv = build_auth_token_argv(WS + "/")
assert "--host" in argv
assert argv[argv.index("--host") + 1] == WS
def test_embeds_profile_when_provided(self):
argv = build_auth_token_argv(WS, profile="stablebox")
assert argv[argv.index("--profile") + 1] == "stablebox"
def test_profile_passed_as_separate_argv_element(self):
# Metacharacters need no shell quoting — argv is never parsed by a shell.
argv = build_auth_token_argv(WS, profile="weird name; rm -rf /")
assert "weird name; rm -rf /" in argv
def test_use_pat_flag(self):
argv = build_auth_token_argv(WS, profile="DEFAULT", use_pat=True)
assert "--use-pat" in argv
assert argv[argv.index("--profile") + 1] == "DEFAULT"
def test_no_use_pat_flag_by_default(self):
assert "--use-pat" not in build_auth_token_argv(WS)
class TestBuildAuthShellCommand:
def test_contains_workspace(self):
cmd = build_auth_shell_command(WS)
assert WS in cmd
def test_is_ucode_auth_token_invocation(self):
# The persisted helper now points at the `ucode auth-token` executable
# on every platform — not a POSIX `databricks ... | jq` pipeline.
cmd = build_auth_shell_command(WS)
assert "auth-token" in cmd
assert "--host" in cmd
# POSIX-only constructs that broke Windows (#116) must be gone.
assert "jq" not in cmd
assert "if [ -n" not in cmd
def test_embeds_profile_when_provided(self):
cmd = build_auth_shell_command(WS, profile="stablebox")
assert "--profile stablebox" in cmd
def test_quotes_profile_shell_metacharacters(self):
cmd = build_auth_shell_command(WS, profile="weird name; rm -rf /")
# On POSIX shlex.join quotes the value so the string form cannot be
# interpreted as a shell injection if a tool runs it via a shell.
if os.name != "nt":
assert "'weird name; rm -rf /'" in cmd
def test_use_pat_emits_flag(self):
cmd = build_auth_shell_command(WS, profile="DEFAULT", use_pat=True)
assert "--use-pat" in cmd
assert "--profile DEFAULT" in cmd
class TestEnsurePatBearer:
"""ensure_pat_bearer is the empty-aware DATABRICKS_BEARER export used by the
--use-pat path on configure, launch, and the auth-token helper."""
@pytest.fixture(autouse=True)
def _isolated_bearer(self):
# ensure_pat_bearer writes os.environ directly; restore it even though
# monkeypatch can't track writes made by code under test.
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_exports_pat_when_env_absent(self, monkeypatch):
monkeypatch.setattr(db_mod, "resolve_pat_token", lambda p: "dapi-pat")
assert ensure_pat_bearer("p") is True
assert os.environ["DATABRICKS_BEARER"] == "dapi-pat"
def test_overwrites_empty_env(self, monkeypatch):
# The regression: an empty DATABRICKS_BEARER must be treated as absent
# so the PAT is still exported (old `if [ -n ... ]` parity).
monkeypatch.setenv("DATABRICKS_BEARER", "")
monkeypatch.setattr(db_mod, "resolve_pat_token", lambda p: "dapi-pat")
assert ensure_pat_bearer("p") is True
assert os.environ["DATABRICKS_BEARER"] == "dapi-pat"
def test_non_empty_env_wins_without_resolving(self, monkeypatch):
monkeypatch.setenv("DATABRICKS_BEARER", "ci-bearer")
called = []
monkeypatch.setattr(db_mod, "resolve_pat_token", lambda p: called.append(p) or "dapi-pat")
assert ensure_pat_bearer("p") is True
# Pre-set bearer is honored; we don't even read the PAT.
assert os.environ["DATABRICKS_BEARER"] == "ci-bearer"
assert called == []
def test_returns_false_when_no_pat(self, monkeypatch):
monkeypatch.setattr(db_mod, "resolve_pat_token", lambda p: None)
assert ensure_pat_bearer("p") is False
assert "DATABRICKS_BEARER" not in os.environ
def test_whitespace_only_env_treated_as_empty(self, monkeypatch):
monkeypatch.setenv("DATABRICKS_BEARER", " ")
monkeypatch.setattr(db_mod, "resolve_pat_token", lambda p: "dapi-pat")
assert ensure_pat_bearer("p") is True
assert os.environ["DATABRICKS_BEARER"] == "dapi-pat"
def test_explicit_pat_arg_skips_cfg_read(self, monkeypatch):
# Callers that already resolved the PAT (configure_shared_state) pass it
# in; ensure_pat_bearer must use it without re-reading ~/.databrickscfg.
called = []
monkeypatch.setattr(db_mod, "resolve_pat_token", lambda p: called.append(p) or "from-cfg")
assert ensure_pat_bearer("p", "explicit-pat") is True
assert os.environ["DATABRICKS_BEARER"] == "explicit-pat"
assert called == []
class TestFormatSubprocessResult:
def test_suppresses_stdout_on_success(self):
result = subprocess.CompletedProcess(
args=["databricks", "auth", "token"],
returncode=0,
stdout='{"access_token": "dapi-secret-do-not-leak", "token_type": "Bearer"}',
stderr="",
)
formatted = _format_subprocess_result(result)
assert "dapi-secret-do-not-leak" not in formatted
assert "rc=0" in formatted
def test_includes_stdout_on_failure(self):
result = subprocess.CompletedProcess(
args=["databricks", "auth", "token"],
returncode=1,
stdout="useful diagnostic output",
stderr="error: no matching profile",
)
formatted = _format_subprocess_result(result)
assert "rc=1" in formatted
assert "useful diagnostic output" in formatted
assert "no matching profile" in formatted
class TestScrubDatabrickscfg:
def test_redacts_token_value(self):
text = "[DEFAULT]\nhost = https://example.databricks.com\ntoken = dapi-secret\n"
scrubbed = _scrub_databrickscfg(text)
assert "dapi-secret" not in scrubbed
assert "token = <redacted>" in scrubbed
assert "host = https://example.databricks.com" in scrubbed
def test_redacts_various_secret_keys(self):
text = (
"[p]\n"
"client_secret = secret-val-1\n"
"bearer_token = secret-val-2\n"
"api_key = secret-val-3\n"
"password = secret-val-4\n"
"auth_type = oauth-u2m\n"
)
scrubbed = _scrub_databrickscfg(text)
for secret in ("secret-val-1", "secret-val-2", "secret-val-3", "secret-val-4"):