forked from openai/openai-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_httpx2_workload.py
More file actions
261 lines (204 loc) · 10.1 KB
/
Copy pathtest_httpx2_workload.py
File metadata and controls
261 lines (204 loc) · 10.1 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
from __future__ import annotations
import json
from typing import Any
import httpx2
import pytest
import openai._base_client as base_client
import openai.auth._workload as workload
from openai import (
OpenAI,
OAuthError,
AsyncOpenAI,
APITimeoutError,
APIConnectionError,
DefaultHttpx2Client,
DefaultAsyncHttpx2Client,
)
from openai.auth import WorkloadIdentity
def workload_identity(get_token: Any = lambda: "subject-token") -> WorkloadIdentity:
return {
"identity_provider_id": "idp_123",
"service_account_id": "sa_123",
"provider": {"get_token": get_token, "token_type": "jwt"},
}
def exchange_payload(access_token: str) -> dict[str, object]:
return {"access_token": access_token, "expires_in": 3600}
def test_sync_httpx2_workload_exchange_is_native_and_cached(monkeypatch: pytest.MonkeyPatch) -> None:
exchange_requests: list[Any] = []
api_requests: list[Any] = []
provider_calls = 0
def get_token() -> str:
nonlocal provider_calls
provider_calls += 1
return "subject-token"
def exchange_handler(request: Any) -> Any:
exchange_requests.append(request)
return httpx2.Response(200, request=request, json=exchange_payload("access-token"))
def exchange_client(**kwargs: Any) -> Any:
assert kwargs == {"follow_redirects": False}
return httpx2.Client(transport=httpx2.MockTransport(exchange_handler), trust_env=False)
def api_handler(request: Any) -> Any:
api_requests.append(request)
return httpx2.Response(200, request=request, json={"object": "list", "data": []})
monkeypatch.setattr(workload, "DefaultHttpx2Client", exchange_client)
with OpenAI(
workload_identity=workload_identity(get_token),
base_url="https://api.example.test/v1",
http_client=httpx2.Client(transport=httpx2.MockTransport(api_handler), trust_env=False),
max_retries=0,
) as client:
assert client.models.list().object == "list"
assert client.models.list().object == "list"
assert provider_calls == 1
assert len(exchange_requests) == 1
assert len(api_requests) == 2
assert isinstance(exchange_requests[0], httpx2.Request)
assert str(exchange_requests[0].url) == "https://auth.openai.com/oauth/token"
assert json.loads(exchange_requests[0].content) == {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"subject_token": "subject-token",
"subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
"identity_provider_id": "idp_123",
"service_account_id": "sa_123",
}
assert all(isinstance(request, httpx2.Request) for request in api_requests)
assert [request.headers["authorization"] for request in api_requests] == ["Bearer access-token"] * 2
async def test_async_httpx2_workload_401_reexchanges_with_sync_native_client(monkeypatch: pytest.MonkeyPatch) -> None:
exchange_requests: list[Any] = []
api_requests: list[Any] = []
api_authorizations: list[str] = []
tokens = iter(["access-token-1", "access-token-2"])
def exchange_handler(request: Any) -> Any:
exchange_requests.append(request)
return httpx2.Response(200, request=request, json=exchange_payload(next(tokens)))
def exchange_client(**kwargs: Any) -> Any:
assert kwargs == {"follow_redirects": False}
return httpx2.Client(transport=httpx2.MockTransport(exchange_handler), trust_env=False)
async def api_handler(request: Any) -> Any:
api_requests.append(request)
api_authorizations.append(request.headers["authorization"])
status_code = 401 if len(api_requests) == 1 else 200
return httpx2.Response(status_code, request=request, json={"object": "list", "data": []})
monkeypatch.setattr(workload, "DefaultHttpx2Client", exchange_client)
async with AsyncOpenAI(
workload_identity=workload_identity(),
base_url="https://api.example.test/v1",
http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(api_handler), trust_env=False),
max_retries=0,
) as client:
assert (await client.models.list()).object == "list"
assert len(exchange_requests) == 2
assert all(isinstance(request, httpx2.Request) for request in exchange_requests)
assert len(api_requests) == 2
assert all(isinstance(request, httpx2.Request) for request in api_requests)
assert api_authorizations == ["Bearer access-token-1", "Bearer access-token-2"]
def test_sync_httpx2_default_workload_exchange_is_native(monkeypatch: pytest.MonkeyPatch) -> None:
exchange_requests: list[Any] = []
api_requests: list[Any] = []
def exchange_handler(request: Any) -> Any:
exchange_requests.append(request)
return httpx2.Response(200, request=request, json=exchange_payload("access-token"))
def exchange_client(**kwargs: Any) -> Any:
assert kwargs == {"follow_redirects": False}
return httpx2.Client(transport=httpx2.MockTransport(exchange_handler), trust_env=False)
def api_handler(request: Any) -> Any:
api_requests.append(request)
return httpx2.Response(200, request=request, json={"object": "list", "data": []})
def default_client(**kwargs: Any) -> Any:
return DefaultHttpx2Client(transport=httpx2.MockTransport(api_handler), trust_env=False, **kwargs)
monkeypatch.setattr(base_client, "SyncHttpxClientWrapper", default_client)
monkeypatch.setattr(workload, "DefaultHttpx2Client", exchange_client)
with OpenAI(
workload_identity=workload_identity(),
base_url="https://api.example.test/v1",
max_retries=0,
) as client:
assert isinstance(client._client, httpx2.Client)
assert client.models.list().object == "list"
assert len(exchange_requests) == 1
assert len(api_requests) == 1
assert isinstance(exchange_requests[0], httpx2.Request)
assert isinstance(api_requests[0], httpx2.Request)
assert api_requests[0].headers["authorization"] == "Bearer access-token"
async def test_async_httpx2_default_workload_exchange_is_native(monkeypatch: pytest.MonkeyPatch) -> None:
exchange_requests: list[Any] = []
api_requests: list[Any] = []
def exchange_handler(request: Any) -> Any:
exchange_requests.append(request)
return httpx2.Response(200, request=request, json=exchange_payload("access-token"))
def exchange_client(**kwargs: Any) -> Any:
assert kwargs == {"follow_redirects": False}
return httpx2.Client(transport=httpx2.MockTransport(exchange_handler), trust_env=False)
async def api_handler(request: Any) -> Any:
api_requests.append(request)
return httpx2.Response(200, request=request, json={"object": "list", "data": []})
def default_client(**kwargs: Any) -> Any:
return DefaultAsyncHttpx2Client(transport=httpx2.MockTransport(api_handler), trust_env=False, **kwargs)
monkeypatch.setattr(base_client, "AsyncHttpxClientWrapper", default_client)
monkeypatch.setattr(workload, "DefaultHttpx2Client", exchange_client)
async with AsyncOpenAI(
workload_identity=workload_identity(),
base_url="https://api.example.test/v1",
max_retries=0,
) as client:
assert isinstance(client._client, httpx2.AsyncClient)
assert (await client.models.list()).object == "list"
assert len(exchange_requests) == 1
assert len(api_requests) == 1
assert isinstance(exchange_requests[0], httpx2.Request)
assert isinstance(api_requests[0], httpx2.Request)
assert api_requests[0].headers["authorization"] == "Bearer access-token"
def test_httpx2_workload_oauth_error_preserves_native_response(monkeypatch: pytest.MonkeyPatch) -> None:
api_calls = 0
def exchange_handler(request: Any) -> Any:
return httpx2.Response(
401,
request=request,
json={"error": "invalid_grant", "error_description": "invalid workload identity"},
)
def exchange_client(**kwargs: Any) -> Any:
assert kwargs == {"follow_redirects": False}
return httpx2.Client(transport=httpx2.MockTransport(exchange_handler), trust_env=False)
def api_handler(request: Any) -> Any:
nonlocal api_calls
api_calls += 1
return httpx2.Response(200, request=request, json={"object": "list", "data": []})
monkeypatch.setattr(workload, "DefaultHttpx2Client", exchange_client)
with OpenAI(
workload_identity=workload_identity(),
base_url="https://api.example.test/v1",
http_client=httpx2.Client(transport=httpx2.MockTransport(api_handler), trust_env=False),
max_retries=0,
) as client:
with pytest.raises(OAuthError) as exc_info:
client.models.list()
assert exc_info.value.message == "invalid workload identity"
assert isinstance(exc_info.value.response, httpx2.Response)
assert isinstance(exc_info.value.request, httpx2.Request)
assert api_calls == 0
@pytest.mark.parametrize(
("failure", "expected"),
[("timeout", APITimeoutError), ("connection", APIConnectionError)],
)
def test_httpx2_workload_exchange_transport_failure(
failure: str, expected: type[Exception], monkeypatch: pytest.MonkeyPatch
) -> None:
def exchange_handler(request: Any) -> Any:
if failure == "timeout":
raise httpx2.ReadTimeout("exchange timeout", request=request)
raise httpx2.ConnectError("exchange unavailable", request=request)
def exchange_client(**kwargs: Any) -> Any:
assert kwargs == {"follow_redirects": False}
return httpx2.Client(transport=httpx2.MockTransport(exchange_handler), trust_env=False)
def api_handler(request: Any) -> Any:
return httpx2.Response(200, request=request)
monkeypatch.setattr(workload, "DefaultHttpx2Client", exchange_client)
with OpenAI(
workload_identity=workload_identity(),
base_url="https://api.example.test/v1",
http_client=httpx2.Client(transport=httpx2.MockTransport(api_handler)),
max_retries=0,
) as client:
with pytest.raises(expected) as exc_info:
client.models.list()
assert type(exc_info.value.__cause__).__module__ == "httpx2"