-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_client_sync.py
More file actions
394 lines (288 loc) · 13 KB
/
Copy pathtest_client_sync.py
File metadata and controls
394 lines (288 loc) · 13 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
"""Tests for the sync Client — construction, methods, lifecycle, error mapping."""
from http import HTTPStatus
import httpx2
import pydantic
import pytest
from httpware import Client, NotFoundError
from httpware.decoders.pydantic import PydanticDecoder
from httpware.errors import MissingDecoderError, TransportError
# ---------- Construction ----------
def test_construction_with_no_args_works() -> None:
client = Client()
assert isinstance(client, Client)
client.close()
def test_construction_with_forwarded_kwargs() -> None:
client = Client(
base_url="https://example.test",
headers={"x-shared": "1"},
params={"trace": "yes"},
timeout=10.0,
)
assert isinstance(client, Client)
client.close()
def test_construction_with_caller_owned_httpx2_client() -> None:
transport = httpx2.MockTransport(lambda req: httpx2.Response(200, request=req))
caller = httpx2.Client(transport=transport)
client = Client(httpx2_client=caller)
assert isinstance(client, Client)
caller.close()
@pytest.mark.parametrize(
"kwargs",
[
{"base_url": "https://example.test"},
{"headers": {"x": "1"}},
{"params": {"x": "1"}},
{"cookies": {"x": "1"}},
{"timeout": 5.0},
{"limits": httpx2.Limits(max_connections=10)},
{"auth": httpx2.BasicAuth("u", "p")},
],
)
def test_caller_owned_client_with_forwarded_kwargs_is_typeerror(kwargs: dict) -> None:
transport = httpx2.MockTransport(lambda req: httpx2.Response(200, request=req))
caller = httpx2.Client(transport=transport)
with pytest.raises(TypeError, match="httpx2_client"):
Client(httpx2_client=caller, **kwargs)
caller.close()
def test_default_decoders_includes_pydantic_when_installed() -> None:
client = Client()
assert any(isinstance(d, PydanticDecoder) for d in client._decoders) # noqa: SLF001
client.close()
def test_explicit_decoders_is_honored() -> None:
class _Stub:
def can_decode(self, model: type) -> bool: # noqa: ARG002 # pragma: no cover
return True
def decode(self, content: bytes, model: type) -> object: # noqa: ARG002 # pragma: no cover
return None
stub = _Stub()
client = Client(decoders=[stub])
assert client._decoders == (stub,) # noqa: SLF001
client.close()
def test_empty_decoders_is_honored() -> None:
client = Client(decoders=[])
assert client._decoders == () # noqa: SLF001
client.close()
def test_sync_missing_decoder_raised_before_http_call() -> None:
def handler(_: httpx2.Request) -> httpx2.Response: # pragma: no cover
pytest.fail("transport should not be invoked when MissingDecoderError fires")
transport = httpx2.MockTransport(handler)
client = Client(
httpx2_client=httpx2.Client(transport=transport),
decoders=[],
)
class _Foo:
pass
with pytest.raises(MissingDecoderError) as exc_info:
client.get("https://example.test/x", response_model=_Foo)
assert exc_info.value.model is _Foo
assert exc_info.value.registered_names == ()
client.close()
@pytest.mark.parametrize(
"kwargs",
[
{"cookies": {"session": "abc"}},
{"limits": httpx2.Limits(max_connections=5)},
{"auth": httpx2.BasicAuth("user", "pass")},
],
)
def test_construction_with_optional_forwarded_kwargs(kwargs: dict) -> None:
"""Exercises cookies/limits/auth branches in __init__ when no httpx2_client is supplied."""
client = Client(**kwargs)
assert isinstance(client, Client)
client.close()
def test_explicit_middleware_is_honored() -> None:
class _Tag:
def __call__(self, request, next) -> httpx2.Response: # noqa: A002, ANN001 # pragma: no cover
return next(request)
client = Client(middleware=(_Tag(),))
assert len(client._user_middleware) == 1 # noqa: SLF001
client.close()
# ---------- Methods ----------
def _echo_handler(request: httpx2.Request) -> httpx2.Response:
return httpx2.Response(
HTTPStatus.OK,
request=request,
json={
"method": request.method,
"url": str(request.url),
"headers": dict(request.headers),
"content": request.content.decode() if request.content else "",
},
)
def _client_with_handler(handler, **kwargs) -> Client: # noqa: ANN001, ANN003
transport = httpx2.MockTransport(handler)
return Client(httpx2_client=httpx2.Client(transport=transport, **kwargs))
def test_get_returns_httpx2_response() -> None:
client = _client_with_handler(_echo_handler)
response = client.get("https://example.test/x")
assert isinstance(response, httpx2.Response)
assert response.json()["method"] == "GET"
@pytest.mark.parametrize(
"method_name",
["get", "post", "put", "patch", "delete", "head", "options"],
)
def test_each_per_method_helper_uses_correct_verb(method_name: str) -> None:
client = _client_with_handler(_echo_handler)
method = getattr(client, method_name)
response = method("https://example.test/x")
assert response.json()["method"] == method_name.upper()
def test_post_json_body_serialized() -> None:
client = _client_with_handler(_echo_handler)
response = client.post("https://example.test/x", json={"k": "v"})
payload = response.json()
assert "application/json" in payload["headers"]["content-type"]
assert payload["content"] == '{"k":"v"}'
def test_get_with_params_forwards_query() -> None:
captured: list[httpx2.Request] = []
def handler(request: httpx2.Request) -> httpx2.Response:
captured.append(request)
return httpx2.Response(HTTPStatus.OK, request=request)
client = _client_with_handler(handler)
client.get("https://example.test/x", params={"a": "1"})
assert "a=1" in str(captured[0].url)
def test_get_with_headers_merges() -> None:
captured: list[httpx2.Request] = []
def handler(request: httpx2.Request) -> httpx2.Response:
captured.append(request)
return httpx2.Response(HTTPStatus.OK, request=request)
client = _client_with_handler(handler)
client.get("https://example.test/x", headers={"x-trace": "abc"})
assert captured[0].headers["x-trace"] == "abc"
def test_get_raises_typed_status_error_on_404() -> None:
client = _client_with_handler(lambda req: httpx2.Response(HTTPStatus.NOT_FOUND, request=req))
with pytest.raises(NotFoundError):
client.get("https://example.test/missing")
def test_request_method_takes_arbitrary_verb() -> None:
client = _client_with_handler(_echo_handler)
response = client.request("PROPFIND", "https://example.test/x")
assert response.json()["method"] == "PROPFIND"
def test_base_url_is_applied() -> None:
captured: list[httpx2.Request] = []
def handler(request: httpx2.Request) -> httpx2.Response:
captured.append(request)
return httpx2.Response(HTTPStatus.OK, request=request)
transport = httpx2.MockTransport(handler)
underlying = httpx2.Client(transport=transport, base_url="https://example.test")
client = Client(httpx2_client=underlying)
client.get("/relative")
assert str(captured[0].url) == "https://example.test/relative"
def test_get_with_cookies_forwarded() -> None:
"""Exercises the cookies branch in _request_with_body."""
captured: list[httpx2.Request] = []
def handler(request: httpx2.Request) -> httpx2.Response:
captured.append(request)
return httpx2.Response(HTTPStatus.OK, request=request)
client = _client_with_handler(handler)
client.get("https://example.test/x", cookies={"token": "abc"})
assert "token=abc" in captured[0].headers.get("cookie", "")
def test_get_with_explicit_timeout() -> None:
"""Exercises the timeout branch in _request_with_body."""
client = _client_with_handler(_echo_handler)
response = client.get("https://example.test/x", timeout=5.0)
assert response.status_code == HTTPStatus.OK
def test_get_with_extensions() -> None:
"""Exercises the extensions branch in _request_with_body."""
client = _client_with_handler(_echo_handler)
response = client.get("https://example.test/x", extensions={"trace": True})
assert response.status_code == HTTPStatus.OK
def test_post_with_content_body() -> None:
"""Exercises the content branch in _request_with_body."""
client = _client_with_handler(_echo_handler)
response = client.post("https://example.test/x", content=b"raw-bytes")
assert response.json()["content"] == "raw-bytes"
def test_post_with_data_body() -> None:
"""Exercises the data branch in _request_with_body."""
client = _client_with_handler(_echo_handler)
response = client.post("https://example.test/x", data={"field": "value"})
assert response.status_code == HTTPStatus.OK
def test_post_with_files_body() -> None:
"""Exercises the files branch in _request_with_body."""
client = _client_with_handler(_echo_handler)
response = client.post("https://example.test/x", files={"upload": b"file-content"})
assert response.status_code == HTTPStatus.OK
def test_runtime_error_without_closed_reraises() -> None:
"""Exercises the RuntimeError re-raise branch in _terminal (error not containing 'closed')."""
def boom(request: httpx2.Request) -> httpx2.Response: # noqa: ARG001
msg = "unexpected internal failure"
raise RuntimeError(msg)
client = _client_with_handler(boom)
with pytest.raises(RuntimeError, match="unexpected internal failure"):
client.get("https://example.test/x")
def test_terminal_runtime_error_with_closed_maps_to_transport_error() -> None:
"""A RuntimeError mentioning 'closed' should be remapped to TransportError."""
transport = httpx2.MockTransport(lambda req: httpx2.Response(HTTPStatus.OK, request=req))
underlying = httpx2.Client(transport=transport)
client = Client(httpx2_client=underlying)
underlying.close()
with pytest.raises(TransportError):
client.get("https://example.test/x")
def test_send_with_response_model_decodes() -> None:
"""Exercises the response_model decode path in send()."""
class _User(pydantic.BaseModel):
id: int
name: str
def handler(request: httpx2.Request) -> httpx2.Response:
return httpx2.Response(HTTPStatus.OK, request=request, json={"id": 1, "name": "alice"})
client = _client_with_handler(handler)
user = client.get("https://example.test/u", response_model=_User)
assert isinstance(user, _User)
assert user.id == 1
assert user.name == "alice"
def test_build_request_delegates_to_underlying() -> None:
client = _client_with_handler(_echo_handler)
req = client.build_request("GET", "https://example.test/x")
assert isinstance(req, httpx2.Request)
assert req.method == "GET"
# ---------- Lifecycle ----------
def test_exit_closes_owned_httpx2_client() -> None:
client = Client()
with client:
pass
assert client._httpx2_client.is_closed # noqa: SLF001
def test_exit_does_not_close_borrowed_httpx2_client() -> None:
transport = httpx2.MockTransport(lambda req: httpx2.Response(HTTPStatus.OK, request=req))
underlying = httpx2.Client(transport=transport)
client = Client(httpx2_client=underlying)
with client:
pass
assert not underlying.is_closed
underlying.close()
def test_exit_is_idempotent_for_owned_client() -> None:
client = Client()
with client:
pass
# Second use should not raise
client.__exit__(None, None, None)
def test_close_closes_owned_httpx2_client() -> None:
client = Client()
client.close()
assert client._httpx2_client.is_closed # noqa: SLF001
def test_close_is_idempotent_for_owned_client() -> None:
client = Client()
client.close()
client.close()
assert client._httpx2_client.is_closed # noqa: SLF001
def test_close_does_not_close_borrowed_httpx2_client() -> None:
transport = httpx2.MockTransport(lambda req: httpx2.Response(HTTPStatus.OK, request=req))
underlying = httpx2.Client(transport=transport)
client = Client(httpx2_client=underlying)
client.close()
assert not underlying.is_closed
underlying.close()
def test_runtimeerror_unrelated_to_close_propagates_unchanged() -> None:
"""A RuntimeError NOT caused by client closure must propagate as-is (sync mirror)."""
msg = "downstream proxy hiccup — closed connection reset by peer"
def _handler(_request: httpx2.Request) -> httpx2.Response:
raise RuntimeError(msg)
transport = httpx2.MockTransport(_handler)
with Client(httpx2_client=httpx2.Client(transport=transport)) as client:
with pytest.raises(RuntimeError) as exc_info:
client.get("https://example.test/x")
assert not isinstance(exc_info.value, TransportError)
def test_runtimeerror_after_close_maps_to_transporterror() -> None:
"""After close(), sending raises a RuntimeError that should map to TransportError via is_closed (sync)."""
# Use an owned client (no httpx2_client= arg) so close() also closes the httpx2 layer.
client = Client()
client.close()
with pytest.raises(TransportError):
client.get("https://example.test/x")