-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathtest_clients.py
More file actions
815 lines (676 loc) · 34.6 KB
/
test_clients.py
File metadata and controls
815 lines (676 loc) · 34.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
import os
from typing import Any, cast
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import pytest
from databricks.sdk import WorkspaceClient
from httpx import Request
from openai import APIConnectionError, APIStatusError, AsyncOpenAI, OpenAI
from openai._types import NOT_GIVEN, Omit
from openai.resources.chat.completions import AsyncCompletions, Completions
from openai.resources.responses import AsyncResponses, Responses
from databricks_openai import AsyncDatabricksOpenAI, DatabricksOpenAI
from databricks_openai.utils.clients import (
_get_ai_gateway_base_url,
_get_app_url,
_get_authorized_async_http_client,
_get_authorized_http_client,
_get_openai_api_key,
_should_strip_strict,
_strip_strict_from_tools,
_validate_oauth_for_apps,
_wrap_app_error,
)
@pytest.fixture
def mock_workspace_client():
"""Create a mock WorkspaceClient for testing."""
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://test.databricks.com"
# Mock the authenticate method to return headers
mock_client.config.authenticate.return_value = {"Authorization": "Bearer test-token-123"}
return mock_client
@pytest.fixture
def mock_workspace_client_with_oauth():
"""Create a mock WorkspaceClient with OAuth support for testing."""
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://test.databricks.com"
mock_client.config.authenticate.return_value = {"Authorization": "Bearer oauth-token"}
mock_client.config.oauth_token.return_value = "oauth-token"
# Mock app lookup
mock_app = MagicMock()
mock_app.url = "https://my-app.aws.databricksapps.com"
mock_client.apps.get.return_value = mock_app
return mock_client
@pytest.fixture
def mock_workspace_client_no_oauth():
"""Create a mock WorkspaceClient without OAuth support for testing."""
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://test.databricks.com"
mock_client.config.authenticate.return_value = {"Authorization": "Bearer pat-token"}
mock_client.config.oauth_token.side_effect = Exception("No OAuth token available")
return mock_client
class TestDatabricksOpenAI:
"""Tests for DatabricksOpenAI client."""
def test_init_with_default_workspace_client(self):
"""Test initialization with default WorkspaceClient."""
env = {k: v for k, v in os.environ.items() if k != "OPENAI_API_KEY"}
with (
patch.dict("os.environ", env, clear=True),
patch("databricks_openai.utils.clients.WorkspaceClient") as mock_ws_client_class,
):
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://default.databricks.com"
mock_client.config.authenticate.return_value = {"Authorization": "Bearer default-token"}
mock_ws_client_class.return_value = mock_client
client = DatabricksOpenAI()
# Verify WorkspaceClient was created with no arguments
mock_ws_client_class.assert_called_once_with()
# Verify the client was initialized correctly
assert isinstance(client, OpenAI)
assert client.base_url.path == "/serving-endpoints/"
assert "default.databricks.com" in str(client.base_url)
assert client.api_key == "no-token"
def test_init_uses_openai_api_key_env_var(self):
with (
patch.dict("os.environ", {"OPENAI_API_KEY": "sk-from-env"}),
patch("databricks_openai.utils.clients.WorkspaceClient") as mock_ws_client_class,
):
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://default.databricks.com"
mock_client.config.authenticate.return_value = {"Authorization": "Bearer token"}
mock_ws_client_class.return_value = mock_client
client = DatabricksOpenAI()
assert client.api_key == "sk-from-env"
def test_bearer_auth_flow(self, mock_workspace_client):
"""Test that BearerAuth correctly adds Authorization header."""
http_client = _get_authorized_http_client(mock_workspace_client)
# Create a test request
request = Request("GET", "https://test.databricks.com/api/test")
# Authenticate the request
assert http_client.auth is not None
auth_flow = http_client.auth.auth_flow(request)
authenticated_request = next(auth_flow)
# Verify Authorization header was added
assert "Authorization" in authenticated_request.headers
assert authenticated_request.headers["Authorization"] == "Bearer test-token-123"
# Verify authenticate was called
mock_workspace_client.config.authenticate.assert_called()
class TestAsyncDatabricksOpenAI:
"""Tests for AsyncDatabricksOpenAI client."""
def test_init_with_default_workspace_client(self):
"""Test initialization with default WorkspaceClient."""
env = {k: v for k, v in os.environ.items() if k != "OPENAI_API_KEY"}
with (
patch.dict("os.environ", env, clear=True),
patch("databricks_openai.utils.clients.WorkspaceClient") as mock_ws_client_class,
):
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://default.databricks.com"
mock_client.config.authenticate.return_value = {"Authorization": "Bearer default-token"}
mock_ws_client_class.return_value = mock_client
client = AsyncDatabricksOpenAI()
# Verify the client was initialized correctly
assert isinstance(client, AsyncOpenAI)
assert client.base_url.path == "/serving-endpoints/"
assert "default.databricks.com" in str(client.base_url)
assert client.api_key == "no-token"
def test_bearer_auth_flow(self, mock_workspace_client):
"""Test that BearerAuth correctly adds Authorization header for async client."""
http_client = _get_authorized_async_http_client(mock_workspace_client)
# Create a test request
request = Request("GET", "https://test.databricks.com/api/test")
# Authenticate the request
assert http_client.auth is not None
auth_flow = http_client.auth.auth_flow(request)
authenticated_request = next(auth_flow)
# Verify Authorization header was added
assert "Authorization" in authenticated_request.headers
assert authenticated_request.headers["Authorization"] == "Bearer test-token-123"
# Verify authenticate was called
mock_workspace_client.config.authenticate.assert_called()
class TestStrictFieldStripping:
"""Tests for strict field stripping helper functions."""
def test_strip_strict_from_tools_removes_strict(self):
tools = [
{"type": "function", "function": {"name": "test", "strict": True, "parameters": {}}}
]
_strip_strict_from_tools(tools)
assert "strict" not in tools[0]["function"]
def test_strip_strict_from_tools_handles_none(self):
assert _strip_strict_from_tools(None) is None
def test_strip_strict_from_tools_handles_openai_not_given_sentinel(self):
"""OpenAI Agents SDK may pass NOT_GIVEN instead of None or a list."""
# Should not raise TypeError: 'NotGiven' object is not iterable
result = _strip_strict_from_tools(NOT_GIVEN)
assert result is NOT_GIVEN
def test_strip_strict_from_tools_handles_openai_omit_sentinel(self):
"""OpenAI Agents SDK may pass Omit() instead of None or a list."""
omit = Omit()
# Should not raise TypeError: 'Omit' object is not iterable
result = _strip_strict_from_tools(omit)
assert result is omit
def test_strip_strict_from_tools_handles_empty_list(self):
tools = []
_strip_strict_from_tools(tools)
assert tools == []
def test_strip_strict_from_tools_handles_tool_without_function(self):
tools = [{"type": "other"}]
_strip_strict_from_tools(tools)
assert tools == [{"type": "other"}]
def test_strip_strict_preserves_other_fields(self):
tools = [
{
"type": "function",
"function": {
"name": "test",
"description": "desc",
"strict": True,
"parameters": {"type": "object"},
},
}
]
_strip_strict_from_tools(tools)
tool: dict[str, Any] = tools[0]
function = cast(dict[str, Any], tool["function"])
assert function["name"] == "test"
assert function["description"] == "desc"
assert function["parameters"] == {"type": "object"}
assert "strict" not in tools[0]["function"]
@pytest.mark.parametrize(
"model,should_strip",
[
("databricks-claude-3-7-sonnet", True),
("databricks-meta-llama-3-1-70b-instruct", True),
("databricks-mixtral-8x7b-instruct", True),
("databricks-gpt-4o", False),
("databricks-gpt-5-2", False),
("gpt-4", False),
("GPT-4-turbo", False),
(None, True),
("", True),
],
)
def test_should_strip_strict_by_model(self, model, should_strip):
assert _should_strip_strict(model) == should_strip
class TestDatabricksOpenAIStrictStripping:
"""Tests for strict stripping in DatabricksOpenAI."""
def test_chat_completions_strips_strict_for_claude(self):
with patch("databricks_openai.utils.clients.WorkspaceClient") as mock_ws:
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://test.databricks.com"
mock_client.config.authenticate.return_value = {"Authorization": "Bearer token"}
mock_ws.return_value = mock_client
client = DatabricksOpenAI()
with patch.object(Completions, "create") as mock_create:
mock_create.return_value = MagicMock()
tools: list[Any] = [
{"type": "function", "function": {"name": "test", "strict": True}}
]
client.chat.completions.create(
model="databricks-claude-3-7-sonnet",
messages=[{"role": "user", "content": "hi"}],
tools=cast(Any, tools),
)
call_kwargs = mock_create.call_args.kwargs
assert "strict" not in call_kwargs["tools"][0]["function"]
def test_chat_completions_preserves_strict_for_gpt(self):
with patch("databricks_openai.utils.clients.WorkspaceClient") as mock_ws:
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://test.databricks.com"
mock_client.config.authenticate.return_value = {"Authorization": "Bearer token"}
mock_ws.return_value = mock_client
client = DatabricksOpenAI()
with patch.object(Completions, "create") as mock_create:
mock_create.return_value = MagicMock()
tools: list[Any] = [
{"type": "function", "function": {"name": "test", "strict": True}}
]
client.chat.completions.create(
model="databricks-gpt-4o",
messages=[{"role": "user", "content": "hi"}],
tools=cast(Any, tools),
)
call_kwargs = mock_create.call_args.kwargs
assert call_kwargs["tools"][0]["function"]["strict"] is True
def test_chat_completions_works_without_tools(self):
with patch("databricks_openai.utils.clients.WorkspaceClient") as mock_ws:
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://test.databricks.com"
mock_client.config.authenticate.return_value = {"Authorization": "Bearer token"}
mock_ws.return_value = mock_client
client = DatabricksOpenAI()
with patch.object(Completions, "create") as mock_create:
mock_create.return_value = MagicMock()
client.chat.completions.create(
model="databricks-claude-3-7-sonnet",
messages=[{"role": "user", "content": "hi"}],
)
mock_create.assert_called_once()
class TestAsyncDatabricksOpenAIStrictStripping:
"""Tests for strict stripping in AsyncDatabricksOpenAI."""
@pytest.mark.asyncio
async def test_chat_completions_strips_strict_for_claude(self):
with patch("databricks_openai.utils.clients.WorkspaceClient") as mock_ws:
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://test.databricks.com"
mock_client.config.authenticate.return_value = {"Authorization": "Bearer token"}
mock_ws.return_value = mock_client
client = AsyncDatabricksOpenAI()
with patch.object(AsyncCompletions, "create", new_callable=AsyncMock) as mock_create:
tools: list[Any] = [
{"type": "function", "function": {"name": "test", "strict": True}}
]
await client.chat.completions.create(
model="databricks-claude-3-7-sonnet",
messages=[{"role": "user", "content": "hi"}],
tools=cast(Any, tools),
)
call_kwargs = mock_create.call_args.kwargs
assert "strict" not in call_kwargs["tools"][0]["function"]
@pytest.mark.asyncio
async def test_chat_completions_preserves_strict_for_gpt(self):
with patch("databricks_openai.utils.clients.WorkspaceClient") as mock_ws:
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://test.databricks.com"
mock_client.config.authenticate.return_value = {"Authorization": "Bearer token"}
mock_ws.return_value = mock_client
client = AsyncDatabricksOpenAI()
with patch.object(AsyncCompletions, "create", new_callable=AsyncMock) as mock_create:
tools: list[Any] = [
{"type": "function", "function": {"name": "test", "strict": True}}
]
await client.chat.completions.create(
model="databricks-gpt-4o",
messages=[{"role": "user", "content": "hi"}],
tools=cast(Any, tools),
)
call_kwargs = mock_create.call_args.kwargs
assert call_kwargs["tools"][0]["function"]["strict"] is True
class TestDatabricksAppsSupport:
"""Tests for Databricks Apps support."""
def test_validate_oauth_for_apps_success(self, mock_workspace_client_with_oauth):
_validate_oauth_for_apps(mock_workspace_client_with_oauth)
mock_workspace_client_with_oauth.config.oauth_token.assert_called_once()
def test_validate_oauth_for_apps_failure(self, mock_workspace_client_no_oauth):
with pytest.raises(ValueError, match="OAuth authentication"):
_validate_oauth_for_apps(mock_workspace_client_no_oauth)
def test_get_app_url_success(self, mock_workspace_client_with_oauth):
url = _get_app_url(mock_workspace_client_with_oauth, "my-app")
assert url == "https://my-app.aws.databricksapps.com"
mock_workspace_client_with_oauth.apps.get.assert_called_once_with(name="my-app")
def test_get_app_url_app_not_found(self, mock_workspace_client_with_oauth):
mock_workspace_client_with_oauth.apps.get.side_effect = Exception("App not found")
with pytest.raises(ValueError, match="Failed to get Databricks App"):
_get_app_url(mock_workspace_client_with_oauth, "nonexistent-app")
def test_get_app_url_no_url(self, mock_workspace_client_with_oauth):
mock_app = MagicMock()
mock_app.url = None
mock_workspace_client_with_oauth.apps.get.return_value = mock_app
with pytest.raises(ValueError, match="has no URL"):
_get_app_url(mock_workspace_client_with_oauth, "my-app")
class TestDatabricksClientWithBaseUrl:
"""Tests for DatabricksOpenAI and AsyncDatabricksOpenAI with base_url parameter."""
@pytest.mark.parametrize("client_cls_name", ["DatabricksOpenAI", "AsyncDatabricksOpenAI"])
def test_init_with_base_url_validates_oauth(
self, client_cls_name, mock_workspace_client_with_oauth
):
client_cls = (
DatabricksOpenAI if client_cls_name == "DatabricksOpenAI" else AsyncDatabricksOpenAI
)
client = client_cls(
workspace_client=mock_workspace_client_with_oauth,
base_url="https://my-app.aws.databricksapps.com",
)
assert "my-app.aws.databricksapps.com" in str(client.base_url)
mock_workspace_client_with_oauth.config.oauth_token.assert_called_once()
@pytest.mark.parametrize("client_cls_name", ["DatabricksOpenAI", "AsyncDatabricksOpenAI"])
def test_init_with_base_url_requires_oauth(
self, client_cls_name, mock_workspace_client_no_oauth
):
client_cls = (
DatabricksOpenAI if client_cls_name == "DatabricksOpenAI" else AsyncDatabricksOpenAI
)
with pytest.raises(ValueError, match="OAuth authentication"):
client_cls(
workspace_client=mock_workspace_client_no_oauth,
base_url="https://my-app.aws.databricksapps.com",
)
def test_init_without_base_url_uses_serving_endpoints(self, mock_workspace_client_with_oauth):
client = DatabricksOpenAI(workspace_client=mock_workspace_client_with_oauth)
assert "/serving-endpoints/" in str(client.base_url)
mock_workspace_client_with_oauth.config.oauth_token.assert_not_called()
@pytest.mark.parametrize("client_cls_name", ["DatabricksOpenAI", "AsyncDatabricksOpenAI"])
def test_init_with_non_databricksapps_base_url_does_not_require_oauth(
self, client_cls_name, mock_workspace_client_no_oauth
):
client_cls = (
DatabricksOpenAI if client_cls_name == "DatabricksOpenAI" else AsyncDatabricksOpenAI
)
# Non-databricksapps URLs should not require OAuth
client = client_cls(
workspace_client=mock_workspace_client_no_oauth,
base_url="https://custom-endpoint.example.com/v1",
)
assert "custom-endpoint.example.com" in str(client.base_url)
# OAuth should not be validated for non-databricksapps URLs
mock_workspace_client_no_oauth.config.oauth_token.assert_not_called()
class TestAppsRouting:
"""Tests for apps/ prefix routing in DatabricksOpenAI and AsyncDatabricksOpenAI."""
def test_sync_responses_create_routes_to_app(self, mock_workspace_client_with_oauth):
client = DatabricksOpenAI(workspace_client=mock_workspace_client_with_oauth)
with patch.object(Responses, "create") as mock_create:
mock_create.return_value = MagicMock()
client.responses.create(
model="apps/my-agent",
input=[{"role": "user", "content": "Hello"}],
)
mock_create.assert_called_once()
call_kwargs = mock_create.call_args.kwargs
assert call_kwargs["model"] == "apps/my-agent"
mock_workspace_client_with_oauth.apps.get.assert_called_once_with(name="my-agent")
@pytest.mark.asyncio
async def test_async_responses_create_routes_to_app(self, mock_workspace_client_with_oauth):
client = AsyncDatabricksOpenAI(workspace_client=mock_workspace_client_with_oauth)
with patch.object(AsyncResponses, "create", new_callable=AsyncMock) as mock_create:
await client.responses.create(
model="apps/my-agent",
input=[{"role": "user", "content": "Hello"}],
)
mock_create.assert_called_once()
mock_workspace_client_with_oauth.apps.get.assert_called_once_with(name="my-agent")
def test_responses_caches_app_clients(self, mock_workspace_client_with_oauth):
client = DatabricksOpenAI(workspace_client=mock_workspace_client_with_oauth)
with patch.object(Responses, "create") as mock_create:
mock_create.return_value = MagicMock()
client.responses.create(model="apps/my-agent", input=[{"role": "user", "content": "1"}])
client.responses.create(model="apps/my-agent", input=[{"role": "user", "content": "2"}])
assert mock_workspace_client_with_oauth.apps.get.call_count == 1
def test_sync_responses_validates_oauth_for_apps_prefix(self, mock_workspace_client_no_oauth):
client = DatabricksOpenAI(workspace_client=mock_workspace_client_no_oauth)
with pytest.raises(ValueError, match="OAuth authentication"):
client.responses.create(
model="apps/my-agent",
input=[{"role": "user", "content": "Hello"}],
)
@pytest.mark.asyncio
async def test_async_responses_validates_oauth_for_apps_prefix(
self, mock_workspace_client_no_oauth
):
client = AsyncDatabricksOpenAI(workspace_client=mock_workspace_client_no_oauth)
with pytest.raises(ValueError, match="OAuth authentication"):
await client.responses.create(
model="apps/my-agent",
input=[{"role": "user", "content": "Hello"}],
)
def _make_api_status_error(status_code: int, message: str) -> APIStatusError:
"""Helper to create an APIStatusError with a properly configured request/response."""
request = httpx.Request("POST", "https://test.databricksapps.com/v1/responses")
response = httpx.Response(status_code, json={"detail": message}, request=request)
return APIStatusError(message=message, response=response, body=None)
class TestAppErrorWrapping:
@pytest.mark.parametrize(
"status_code,message,expected_hints",
[
(404, "Not Found", ["/responses endpoint"]),
(405, "Method Not Allowed", ["/responses endpoint"]),
(403, "Forbidden", ["CAN_USE"]),
(500, "Internal Server Error", ["internal error", "Check the app logs"]),
(502, "Bad Gateway", ["internal error", "Check the app logs"]),
(503, "Service Unavailable", ["internal error", "Check the app logs"]),
(429, "Too Many Requests", []), # No specific hint for rate limiting
],
)
def test_wrap_app_error_status_errors(self, status_code, message, expected_hints):
error = _make_api_status_error(status_code, message)
wrapped = _wrap_app_error(error, "my-app")
wrapped_str = str(wrapped)
assert str(status_code) in wrapped_str
assert message in wrapped_str
for hint in expected_hints:
assert "Hint:" in wrapped_str
assert hint in wrapped_str
@pytest.mark.parametrize(
"message,expected_hint",
[
("DNS resolution failure", "stopped or unavailable"),
("Connection refused", "starting up or unavailable"),
],
)
def test_wrap_app_error_connection_errors(self, message, expected_hint):
request = httpx.Request("POST", "https://test.databricksapps.com/v1/responses")
error = APIConnectionError(message=message, request=request)
wrapped = _wrap_app_error(error, "my-app")
wrapped_str = str(wrapped)
assert message in wrapped_str
assert "Hint:" in wrapped_str
assert expected_hint in wrapped_str
class TestDatabricksOpenAIAppsErrorHandling:
@pytest.mark.parametrize(
"error,expected_match",
[
(_make_api_status_error(405, "Method Not Allowed"), r"(?s)405.*Hint:"),
(
APIConnectionError(
message="DNS resolution failure",
request=httpx.Request("POST", "https://test.databricksapps.com/v1/responses"),
),
r"(?s)DNS resolution failure.*Hint:",
),
],
)
def test_responses_wraps_app_errors(
self, mock_workspace_client_with_oauth, error, expected_match
):
client = DatabricksOpenAI(workspace_client=mock_workspace_client_with_oauth)
with patch.object(Responses, "create", side_effect=error):
with pytest.raises(ValueError, match=expected_match):
client.responses.create(
model="apps/my-agent",
input=[{"role": "user", "content": "Hello"}],
)
def test_responses_non_apps_model_does_not_wrap_errors(self, mock_workspace_client_with_oauth):
client = DatabricksOpenAI(workspace_client=mock_workspace_client_with_oauth)
with patch.object(
Responses, "create", side_effect=_make_api_status_error(500, "Internal Server Error")
):
with pytest.raises(APIStatusError):
client.responses.create(
model="databricks-claude-3-7-sonnet",
input=[{"role": "user", "content": "Hello"}],
)
class TestAsyncDatabricksOpenAIAppsErrorHandling:
@pytest.mark.asyncio
@pytest.mark.parametrize(
"error,expected_match",
[
(_make_api_status_error(405, "Method Not Allowed"), r"(?s)405.*Hint:"),
(
APIConnectionError(
message="DNS resolution failure",
request=httpx.Request("POST", "https://test.databricksapps.com/v1/responses"),
),
r"(?s)DNS resolution failure.*Hint:",
),
],
)
async def test_responses_wraps_app_errors(
self, mock_workspace_client_with_oauth, error, expected_match
):
client = AsyncDatabricksOpenAI(workspace_client=mock_workspace_client_with_oauth)
with patch.object(AsyncResponses, "create", new_callable=AsyncMock) as mock_create:
mock_create.side_effect = error
with pytest.raises(ValueError, match=expected_match):
await client.responses.create(
model="apps/my-agent",
input=[{"role": "user", "content": "Hello"}],
)
class TestChatCompletionsEmptyContentFix:
@pytest.mark.parametrize(
"model,expected_content",
[
("databricks-claude-3-7-sonnet", " "),
("databricks-gpt-4o", ""),
],
)
def test_sync_empty_content_fix(self, model, expected_content):
with patch("databricks_openai.utils.clients.WorkspaceClient") as mock_ws:
mock_ws.return_value = _mock_workspace_client()
client = DatabricksOpenAI()
with patch.object(Completions, "create", return_value=MagicMock()) as mock_create:
messages = _messages_with_empty_assistant_content()
client.chat.completions.create(model=model, messages=cast(Any, messages))
assert mock_create.call_args.kwargs["messages"][1]["content"] == expected_content
@pytest.mark.asyncio
@pytest.mark.parametrize(
"model,expected_content",
[
("databricks-claude-3-7-sonnet", " "),
("databricks-gpt-4o", ""),
],
)
async def test_async_empty_content_fix(self, model, expected_content):
with patch("databricks_openai.utils.clients.WorkspaceClient") as mock_ws:
mock_ws.return_value = _mock_workspace_client()
client = AsyncDatabricksOpenAI()
with patch.object(AsyncCompletions, "create", new_callable=AsyncMock) as mock_create:
messages = _messages_with_empty_assistant_content()
await client.chat.completions.create(model=model, messages=cast(Any, messages))
assert mock_create.call_args.kwargs["messages"][1]["content"] == expected_content
def _mock_workspace_client():
mock_client = MagicMock(spec=WorkspaceClient)
mock_client.config.host = "https://test.databricks.com"
mock_client.config.authenticate.return_value = {"Authorization": "Bearer token"}
return mock_client
def _messages_with_empty_assistant_content() -> list[dict[str, Any]]:
return [
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "", "tool_calls": [{"id": "1"}]},
{"role": "tool", "content": "result", "tool_call_id": "1"},
]
class TestOpenAIApiKey:
def test_uses_env_var_when_set(self):
with patch.dict("os.environ", {"OPENAI_API_KEY": "sk-test-key"}):
assert _get_openai_api_key() == "sk-test-key"
def test_falls_back_to_no_token_when_unset(self):
env = {k: v for k, v in os.environ.items() if k != "OPENAI_API_KEY"}
with patch.dict("os.environ", env, clear=True):
assert _get_openai_api_key() == "no-token"
def test_falls_back_to_no_token_when_empty_string(self):
with patch.dict("os.environ", {"OPENAI_API_KEY": ""}):
assert _get_openai_api_key() == "no-token"
def _mock_httpx_response(status_code: int, json_data: Any = None) -> MagicMock:
"""Create a mock httpx Response."""
response = MagicMock()
response.status_code = status_code
response.json.return_value = json_data or {}
return response
class TestAIGatewayV2Detection:
"""Tests for _get_ai_gateway_base_url."""
def test_returns_base_url_when_endpoints_exist(self):
mock_client = MagicMock(spec=httpx.Client)
mock_client.get.return_value = _mock_httpx_response(
200,
{
"endpoints": [
{
"name": "databricks-claude-sonnet-4-6",
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"created_by": "Databricks",
"ai_gateway_url": "https://12345.ai-gateway.cloud.databricks.com",
}
]
},
)
result = _get_ai_gateway_base_url(mock_client, "https://test.databricks.com")
assert result == "https://12345.ai-gateway.cloud.databricks.com/mlflow/v1"
mock_client.get.assert_called_once_with(
"https://test.databricks.com/api/ai-gateway/v2/endpoints"
)
def test_returns_none_on_404(self):
mock_client = MagicMock(spec=httpx.Client)
mock_client.get.return_value = _mock_httpx_response(404)
result = _get_ai_gateway_base_url(mock_client, "https://test.databricks.com")
assert result is None
def test_returns_none_on_empty_endpoints(self):
mock_client = MagicMock(spec=httpx.Client)
mock_client.get.return_value = _mock_httpx_response(200, {"endpoints": []})
result = _get_ai_gateway_base_url(mock_client, "https://test.databricks.com")
assert result is None
def test_returns_none_on_network_exception(self):
mock_client = MagicMock(spec=httpx.Client)
mock_client.get.side_effect = Exception("Connection refused")
result = _get_ai_gateway_base_url(mock_client, "https://test.databricks.com")
assert result is None
def test_returns_none_on_missing_ai_gateway_url(self):
mock_client = MagicMock(spec=httpx.Client)
mock_client.get.return_value = _mock_httpx_response(
200,
{"endpoints": [{"name": "my-endpoint"}]},
)
result = _get_ai_gateway_base_url(mock_client, "https://test.databricks.com")
assert result is None
def test_parses_base_url_from_different_workspace(self):
mock_client = MagicMock(spec=httpx.Client)
mock_client.get.return_value = _mock_httpx_response(
200,
{
"endpoints": [
{
"name": "databricks-gpt-5-2",
"ai_gateway_url": "https://ws-123.ai-gateway.us-east-1.cloud.databricks.com",
}
]
},
)
result = _get_ai_gateway_base_url(mock_client, "https://test.databricks.com")
assert result == "https://ws-123.ai-gateway.us-east-1.cloud.databricks.com/mlflow/v1"
class TestDatabricksOpenAIWithGateway:
"""Tests for AI Gateway V2 integration in DatabricksOpenAI and AsyncDatabricksOpenAI."""
@pytest.mark.parametrize("client_cls_name", ["DatabricksOpenAI", "AsyncDatabricksOpenAI"])
def test_gateway_available_uses_gateway_url(self, client_cls_name, mock_workspace_client):
client_cls = (
DatabricksOpenAI if client_cls_name == "DatabricksOpenAI" else AsyncDatabricksOpenAI
)
with patch(
"databricks_openai.utils.clients._get_ai_gateway_base_url",
return_value="https://12345.ai-gateway.cloud.databricks.com/mlflow/v1",
):
client = client_cls(workspace_client=mock_workspace_client, use_ai_gateway=True)
assert "ai-gateway" in str(client.base_url)
assert "12345.ai-gateway.cloud.databricks.com" in str(client.base_url)
@pytest.mark.parametrize("client_cls_name", ["DatabricksOpenAI", "AsyncDatabricksOpenAI"])
def test_gateway_unavailable_raises_error(self, client_cls_name, mock_workspace_client):
client_cls = (
DatabricksOpenAI if client_cls_name == "DatabricksOpenAI" else AsyncDatabricksOpenAI
)
with patch(
"databricks_openai.utils.clients._get_ai_gateway_base_url",
return_value=None,
):
with pytest.raises(ValueError, match="use_ai_gateway=True but AI Gateway V2"):
client_cls(workspace_client=mock_workspace_client, use_ai_gateway=True)
@pytest.mark.parametrize("client_cls_name", ["DatabricksOpenAI", "AsyncDatabricksOpenAI"])
def test_gateway_disabled_no_api_call(self, client_cls_name, mock_workspace_client):
client_cls = (
DatabricksOpenAI if client_cls_name == "DatabricksOpenAI" else AsyncDatabricksOpenAI
)
with patch(
"databricks_openai.utils.clients._get_ai_gateway_base_url",
) as mock_gateway:
client = client_cls(workspace_client=mock_workspace_client, use_ai_gateway=False)
mock_gateway.assert_not_called()
assert "/serving-endpoints/" in str(client.base_url)
@pytest.mark.parametrize("client_cls_name", ["DatabricksOpenAI", "AsyncDatabricksOpenAI"])
def test_explicit_base_url_skips_gateway_check(self, client_cls_name, mock_workspace_client):
client_cls = (
DatabricksOpenAI if client_cls_name == "DatabricksOpenAI" else AsyncDatabricksOpenAI
)
with patch(
"databricks_openai.utils.clients._get_ai_gateway_base_url",
) as mock_gateway:
client = client_cls(
workspace_client=mock_workspace_client,
base_url="https://custom.example.com/v1",
)
mock_gateway.assert_not_called()
assert "custom.example.com" in str(client.base_url)