-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_platform.py
More file actions
340 lines (298 loc) · 14.6 KB
/
Copy pathtest_platform.py
File metadata and controls
340 lines (298 loc) · 14.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
"""Tests for PlatformSettings."""
import os
from unittest.mock import MagicMock, patch
import pytest
from httpx import Request, Response
from pydantic import ValidationError
from uipath.llm_client.settings import PlatformSettings, UiPathAPIConfig
from uipath.llm_client.settings.constants import ApiType, RoutingMode
class TestPlatformSettings:
"""Tests for PlatformSettings."""
def test_build_base_url_passthrough(
self, platform_env_vars, mock_platform_auth, passthrough_api_config
):
"""Test build_base_url for passthrough completions mode."""
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
url = settings.build_base_url(
model_name="gpt-4o",
api_config=passthrough_api_config,
)
assert "llm/raw/vendor/openai/model/gpt-4o/completions" in url
def test_build_base_url_passthrough_with_api_version(
self, platform_env_vars, mock_platform_auth
):
"""Test build_base_url for passthrough completions with api_version (vendor endpoint ignores it)."""
api_config = UiPathAPIConfig(
api_type=ApiType.COMPLETIONS,
routing_mode=RoutingMode.PASSTHROUGH,
vendor_type="openai",
api_version="2025-03-01",
)
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
url = settings.build_base_url(
model_name="gpt-4o",
api_config=api_config,
)
assert "llm/raw/vendor/openai/model/gpt-4o/completions" in url
assert "api-version" not in url
def test_build_base_url_normalized(
self, platform_env_vars, mock_platform_auth, normalized_api_config
):
"""Test build_base_url for normalized mode."""
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
url = settings.build_base_url(
model_name="gpt-4o",
api_config=normalized_api_config,
)
assert "agenthub_/llm/api/chat/completions" in url
def test_build_auth_headers_has_default_config(self, platform_env_vars, mock_platform_auth):
"""Test build_auth_headers includes default agenthub_config."""
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
headers = settings.build_auth_headers()
assert headers == {
"x-uipath-internal-accountid": "test-org-id",
"x-uipath-internal-tenantid": "test-tenant-id",
"x-uipath-agenthub-config": "agentsruntime",
}
def test_build_auth_headers_with_tracing(self, platform_env_vars, mock_platform_auth):
"""Test build_auth_headers includes tracing headers when set."""
env = {
**platform_env_vars,
"UIPATH_AGENTHUB_CONFIG": "test-config",
"UIPATH_PROCESS_KEY": "test-process",
"UIPATH_JOB_KEY": "test-job",
}
with patch.dict(os.environ, env, clear=True):
settings = PlatformSettings()
headers = settings.build_auth_headers()
assert headers["x-uipath-agenthub-config"] == "test-config"
assert headers["x-uipath-processkey"] == "test-process"
assert headers["x-uipath-jobkey"] == "test-job"
def test_build_auth_headers_process_key_is_url_encoded(
self, platform_env_vars, mock_platform_auth
):
"""Process key must be URL-encoded for safe transport in headers."""
env = {
**platform_env_vars,
"UIPATH_PROCESS_KEY": "path/with+special=chars",
}
with patch.dict(os.environ, env, clear=True):
settings = PlatformSettings()
headers = settings.build_auth_headers()
assert headers["x-uipath-processkey"] == "path%2Fwith%2Bspecial%3Dchars"
def test_build_auth_pipeline_returns_auth(self, platform_env_vars, mock_platform_auth):
"""Test build_auth_pipeline returns an Auth instance."""
from httpx import Auth
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
auth = settings.build_auth_pipeline()
assert isinstance(auth, Auth)
def test_build_auth_pipeline_with_access_token(self, platform_env_vars, mock_platform_auth):
"""Test auth pipeline uses access_token when provided."""
from uipath.llm_client.settings.platform.auth import PlatformAuth
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
auth = settings.build_auth_pipeline()
assert isinstance(auth, PlatformAuth)
def test_build_base_url_passthrough_embeddings(self, platform_env_vars, mock_platform_auth):
"""Test build_base_url for passthrough embeddings with api_version."""
api_config = UiPathAPIConfig(
api_type=ApiType.EMBEDDINGS,
routing_mode=RoutingMode.PASSTHROUGH,
vendor_type="openai",
api_version="2024-02-01",
)
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
url = settings.build_base_url(
model_name="text-embedding-3-large",
api_config=api_config,
)
assert "embeddings" in url
assert "text-embedding-3-large" in url
assert "api-version=2024-02-01" in url
def test_build_base_url_passthrough_embeddings_no_api_version(
self, platform_env_vars, mock_platform_auth
):
"""Test build_base_url for passthrough embeddings without api_version."""
api_config = UiPathAPIConfig(
api_type=ApiType.EMBEDDINGS,
routing_mode=RoutingMode.PASSTHROUGH,
vendor_type="openai",
)
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
url = settings.build_base_url(
model_name="text-embedding-3-large",
api_config=api_config,
)
assert "embeddings" in url
assert "text-embedding-3-large" in url
assert "api-version" not in url
def test_build_base_url_passthrough_embeddings_non_openai_raises(
self, platform_env_vars, mock_platform_auth
):
"""Test build_base_url raises for non-OpenAI passthrough embeddings."""
api_config = UiPathAPIConfig(
api_type=ApiType.EMBEDDINGS,
routing_mode=RoutingMode.PASSTHROUGH,
vendor_type="vertexai",
)
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
with pytest.raises(ValueError, match="only supports OpenAI-compatible models"):
settings.build_base_url(
model_name="gemini-embedding-001",
api_config=api_config,
)
def test_build_base_url_normalized_embeddings_raises(
self, platform_env_vars, mock_platform_auth
):
"""Test build_base_url raises ValueError for normalized embeddings."""
normalized_embeddings_config = UiPathAPIConfig(
api_type=ApiType.EMBEDDINGS,
routing_mode=RoutingMode.NORMALIZED,
)
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
with pytest.raises(ValueError, match="Normalized embeddings are not supported"):
settings.build_base_url(
model_name="text-embedding-3-large",
api_config=normalized_embeddings_config,
)
def test_build_base_url_requires_model_name(
self, platform_env_vars, mock_platform_auth, normalized_api_config
):
"""Test build_base_url raises ValueError when model_name is None."""
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
with pytest.raises(ValueError, match="model_name is required"):
settings.build_base_url(model_name=None, api_config=normalized_api_config)
def test_build_base_url_requires_api_config(self, platform_env_vars, mock_platform_auth):
"""Test build_base_url raises ValueError when api_config is None."""
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
with pytest.raises(ValueError, match="api_config is required"):
settings.build_base_url(model_name="gpt-4o", api_config=None)
def test_build_auth_headers_only_required_when_no_optional(
self, platform_env_vars, mock_platform_auth
):
"""Test build_auth_headers with no optional tracing fields set."""
env = {**platform_env_vars, "UIPATH_AGENTHUB_CONFIG": ""}
with patch.dict(os.environ, env, clear=True):
settings = PlatformSettings()
settings.agenthub_config = ""
settings.process_key = None
settings.job_key = None
headers = settings.build_auth_headers()
assert headers == {
"x-uipath-internal-accountid": "test-org-id",
"x-uipath-internal-tenantid": "test-tenant-id",
}
def test_validation_requires_all_fields(self, mock_platform_auth):
"""Test validation fails without required fields."""
env = {
"UIPATH_ACCESS_TOKEN": "test-access-token",
# Missing base_url, tenant_id, organization_id
}
with patch.dict(os.environ, env, clear=True):
with pytest.raises(ValidationError):
PlatformSettings()
def test_validation_fails_on_expired_token(self):
"""Test validation fails when access token is expired."""
with (
patch(
"uipath.llm_client.settings.platform.settings.is_token_expired",
return_value=True,
),
patch(
"uipath.llm_client.settings.platform.settings.parse_access_token",
return_value={"client_id": "test-client-id"},
),
):
env = {
"UIPATH_ACCESS_TOKEN": "test-access-token",
"UIPATH_URL": "https://cloud.uipath.com/org/tenant",
"UIPATH_TENANT_ID": "test-tenant-id",
"UIPATH_ORGANIZATION_ID": "test-org-id",
}
with patch.dict(os.environ, env, clear=True):
with pytest.raises(ValueError, match="Access token is expired"):
PlatformSettings()
def test_validate_byo_model_is_noop(self, platform_env_vars, mock_platform_auth):
"""Test validate_byo_model does nothing (no-op)."""
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
result = settings.validate_byo_model({"modelName": "custom-model"})
assert result is None
class TestPlatformAuthRefresh:
"""Tests for PlatformAuth token refresh logic."""
@pytest.fixture(autouse=True)
def clear_auth_singleton(self):
"""Clear PlatformAuth singleton before each test."""
from uipath.llm_client.settings.utils import SingletonMeta
SingletonMeta._instances.clear()
yield
SingletonMeta._instances.clear()
def test_auth_flow_adds_bearer_token(self, platform_env_vars, mock_platform_auth):
"""Test auth_flow adds Authorization header."""
from uipath.llm_client.settings.platform.auth import PlatformAuth
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
auth = PlatformAuth(settings=settings)
request = Request("GET", "https://example.com")
flow = auth.auth_flow(request)
modified_request = next(flow)
assert "Authorization" in modified_request.headers
assert modified_request.headers["Authorization"] == "Bearer test-access-token"
def test_auth_flow_refreshes_on_401(self, platform_env_vars, mock_platform_auth):
"""Test auth_flow refreshes token on 401 response."""
from uipath.llm_client.settings.platform.auth import PlatformAuth
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
# Mock get_access_token to return a new token on refresh
with patch.object(PlatformAuth, "get_access_token", return_value="initial-token"):
auth = PlatformAuth(settings=settings)
request = Request("GET", "https://example.com")
flow = auth.auth_flow(request)
# First yield - initial request
modified_request = next(flow)
assert "Bearer" in modified_request.headers["Authorization"]
# Simulate 401 response
mock_response = MagicMock(spec=Response)
mock_response.status_code = 401
# Mock the get_access_token method to return a new token
with patch.object(PlatformAuth, "get_access_token", return_value="refreshed-token"):
try:
retry_request = flow.send(mock_response)
assert retry_request.headers["Authorization"] == "Bearer refreshed-token"
except StopIteration:
pass
def test_auth_singleton_reuses_instance_for_same_settings(
self, platform_env_vars, mock_platform_auth
):
"""Test that PlatformAuth reuses the same instance for identical settings."""
from uipath.llm_client.settings.platform.auth import PlatformAuth
with patch.dict(os.environ, platform_env_vars, clear=True):
settings = PlatformSettings()
auth1 = PlatformAuth(settings=settings)
auth2 = PlatformAuth(settings=settings)
assert auth1 is auth2
def test_auth_creates_separate_instances_for_different_settings(
self, platform_env_vars, mock_platform_auth
):
"""Test that PlatformAuth creates separate instances for different credentials."""
from uipath.llm_client.settings.platform.auth import PlatformAuth
env1 = {**platform_env_vars, "UIPATH_ACCESS_TOKEN": "token-x"}
env2 = {**platform_env_vars, "UIPATH_ACCESS_TOKEN": "token-y"}
with patch.dict(os.environ, env1, clear=True):
settings1 = PlatformSettings()
with patch.dict(os.environ, env2, clear=True):
settings2 = PlatformSettings()
auth1 = PlatformAuth(settings=settings1)
auth2 = PlatformAuth(settings=settings2)
assert auth1 is not auth2