Repository navigation
Expand file tree
/
Copy pathtest_client_dispatch.py
More file actions
290 lines (226 loc) · 11.1 KB
/
Copy pathtest_client_dispatch.py
File metadata and controls
290 lines (226 loc) · 11.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
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
"""Dispatch routing across multiple registered decoders.
Native types route via their library regardless of order; shared shapes
route to the first decoder in the list.
"""
import contextlib
import dataclasses
from collections.abc import Iterator
from http import HTTPStatus
from unittest.mock import MagicMock, patch
import httpx2
import msgspec
import pydantic
import pytest
from httpware import AsyncClient, Client, MissingDecoderError, ResponseDecoder
from httpware.decoders.msgspec import MsgspecDecoder
from httpware.decoders.pydantic import PydanticDecoder
class _PydanticUser(pydantic.BaseModel):
id: int
name: str
class _MsgspecUser(msgspec.Struct):
id: int
name: str
@dataclasses.dataclass
class _DC:
id: int
name: str
def _async_client_with_body(payload: bytes, decoders: list) -> AsyncClient:
def handler(request: httpx2.Request) -> httpx2.Response:
return httpx2.Response(HTTPStatus.OK, content=payload, request=request)
transport = httpx2.MockTransport(handler)
return AsyncClient(
httpx2_client=httpx2.AsyncClient(transport=transport),
decoders=decoders,
)
def _sync_client_with_body(payload: bytes, decoders: list) -> Client:
def handler(request: httpx2.Request) -> httpx2.Response:
return httpx2.Response(HTTPStatus.OK, content=payload, request=request)
transport = httpx2.MockTransport(handler)
return Client(
httpx2_client=httpx2.Client(transport=transport),
decoders=decoders,
)
@contextlib.contextmanager
def _decode_spies(*decoders: ResponseDecoder) -> Iterator[list[MagicMock]]:
"""Wrap each decoder's `decode` so a test can assert WHICH one ran.
Two real decoders that both claim a shared shape (e.g. `dict[str, int]` or a
stdlib dataclass) produce identical output, so output equality can't prove
the ordering invariant. Spying on `decode` shows which decoder the dispatcher
actually selected. Spies are yielded in the same order as `decoders`.
"""
with contextlib.ExitStack() as stack:
yield [stack.enter_context(patch.object(d, "decode", wraps=d.decode)) for d in decoders]
async def test_async_basemodel_routes_to_pydantic() -> None:
client = _async_client_with_body(
b'{"id": 1, "name": "Ada"}',
decoders=[PydanticDecoder(), MsgspecDecoder()],
)
result = await client.get("https://example.test/x", response_model=_PydanticUser)
assert type(result) is _PydanticUser
assert result.id == 1
async def test_async_struct_routes_to_msgspec() -> None:
client = _async_client_with_body(
b'{"id": 1, "name": "Ada"}',
decoders=[PydanticDecoder(), MsgspecDecoder()],
)
result = await client.get("https://example.test/x", response_model=_MsgspecUser)
assert type(result) is _MsgspecUser
assert result.id == 1
async def test_async_dict_routes_to_first_decoder() -> None:
"""Shared shape (dict): the FIRST decoder in the list actually decodes it."""
pyd, msg = PydanticDecoder(), MsgspecDecoder()
client = _async_client_with_body(b'{"a": 1}', decoders=[pyd, msg])
with _decode_spies(pyd, msg) as (pyd_spy, msg_spy):
result = await client.get("https://example.test/x", response_model=dict[str, int])
assert result == {"a": 1}
pyd_spy.assert_called_once()
msg_spy.assert_not_called()
async def test_async_dict_routes_to_msgspec_when_first() -> None:
"""Reversed list: the shared shape now routes to msgspec, proven by the spy."""
msg, pyd = MsgspecDecoder(), PydanticDecoder()
client = _async_client_with_body(b'{"a": 1}', decoders=[msg, pyd])
with _decode_spies(msg, pyd) as (msg_spy, pyd_spy):
result = await client.get("https://example.test/x", response_model=dict[str, int])
assert result == {"a": 1}
msg_spy.assert_called_once()
pyd_spy.assert_not_called()
async def test_async_dataclass_routes_to_first_decoder() -> None:
"""Stdlib dataclass is a shared shape; the first decoder (pydantic) decodes it."""
pyd, msg = PydanticDecoder(), MsgspecDecoder()
client = _async_client_with_body(b'{"id": 1, "name": "Ada"}', decoders=[pyd, msg])
with _decode_spies(pyd, msg) as (pyd_spy, msg_spy):
result = await client.get("https://example.test/x", response_model=_DC)
assert type(result) is _DC
assert result.id == 1
pyd_spy.assert_called_once()
msg_spy.assert_not_called()
async def test_async_list_of_basemodel_routes_to_pydantic() -> None:
client = _async_client_with_body(
b'[{"id": 1, "name": "Ada"}, {"id": 2, "name": "Bo"}]',
decoders=[PydanticDecoder(), MsgspecDecoder()],
)
result = await client.get("https://example.test/x", response_model=list[_PydanticUser])
assert len(result) == 2 # noqa: PLR2004
assert all(type(item) is _PydanticUser for item in result)
async def test_async_missing_decoder_with_empty_list() -> None:
"""Empty decoder list and response_model= raises before HTTP call."""
def handler(_: httpx2.Request) -> httpx2.Response: # pragma: no cover — never invoked; decoder check fails first
pytest.fail("transport should not be invoked")
transport = httpx2.MockTransport(handler)
client = AsyncClient(
httpx2_client=httpx2.AsyncClient(transport=transport),
decoders=[],
)
with pytest.raises(MissingDecoderError) as exc_info:
await client.get("https://example.test/x", response_model=_PydanticUser)
assert exc_info.value.registered_names == ()
async def test_async_missing_decoder_when_none_claim() -> None:
"""Registered decoders that all reject the model raise MissingDecoderError."""
class _Stub:
def can_decode(self, model: type) -> bool: # noqa: ARG002
return False
def decode(self, content: bytes, model: type) -> object: # noqa: ARG002 # pragma: no cover — never invoked; can_decode() rejects every model
return None
def handler(_: httpx2.Request) -> httpx2.Response: # pragma: no cover — never invoked; decoder check fails first
pytest.fail("transport should not be invoked")
transport = httpx2.MockTransport(handler)
client = AsyncClient(
httpx2_client=httpx2.AsyncClient(transport=transport),
decoders=[_Stub()],
)
with pytest.raises(MissingDecoderError) as exc_info:
await client.get("https://example.test/x", response_model=_PydanticUser)
assert exc_info.value.registered_names == ("_Stub",)
def test_sync_basemodel_routes_to_pydantic() -> None:
client = _sync_client_with_body(
b'{"id": 1, "name": "Ada"}',
decoders=[PydanticDecoder(), MsgspecDecoder()],
)
result = client.get("https://example.test/x", response_model=_PydanticUser)
assert type(result) is _PydanticUser
client.close()
def test_sync_struct_routes_to_msgspec() -> None:
client = _sync_client_with_body(
b'{"id": 1, "name": "Ada"}',
decoders=[PydanticDecoder(), MsgspecDecoder()],
)
result = client.get("https://example.test/x", response_model=_MsgspecUser)
assert type(result) is _MsgspecUser
client.close()
def test_sync_dict_routes_to_first_decoder() -> None:
"""Sync twin: shared shape (dict) routes to the first decoder (pydantic)."""
pyd, msg = PydanticDecoder(), MsgspecDecoder()
client = _sync_client_with_body(b'{"a": 1}', decoders=[pyd, msg])
with _decode_spies(pyd, msg) as (pyd_spy, msg_spy):
result = client.get("https://example.test/x", response_model=dict[str, int])
assert result == {"a": 1}
pyd_spy.assert_called_once()
msg_spy.assert_not_called()
client.close()
def test_sync_dict_routes_to_msgspec_when_first() -> None:
"""Sync twin: reversed list routes the shared shape to msgspec."""
msg, pyd = MsgspecDecoder(), PydanticDecoder()
client = _sync_client_with_body(b'{"a": 1}', decoders=[msg, pyd])
with _decode_spies(msg, pyd) as (msg_spy, pyd_spy):
result = client.get("https://example.test/x", response_model=dict[str, int])
assert result == {"a": 1}
msg_spy.assert_called_once()
pyd_spy.assert_not_called()
client.close()
def test_sync_dataclass_routes_to_first_decoder() -> None:
"""Sync twin: stdlib dataclass routes to the first decoder (pydantic)."""
pyd, msg = PydanticDecoder(), MsgspecDecoder()
client = _sync_client_with_body(b'{"id": 1, "name": "Ada"}', decoders=[pyd, msg])
with _decode_spies(pyd, msg) as (pyd_spy, msg_spy):
result = client.get("https://example.test/x", response_model=_DC)
assert type(result) is _DC
assert result.id == 1
pyd_spy.assert_called_once()
msg_spy.assert_not_called()
client.close()
def test_sync_list_of_basemodel_routes_to_pydantic() -> None:
"""Sync twin: list[BaseModel] is claimed only by pydantic (msgspec rejects it)."""
client = _sync_client_with_body(
b'[{"id": 1, "name": "Ada"}, {"id": 2, "name": "Bo"}]',
decoders=[PydanticDecoder(), MsgspecDecoder()],
)
result = client.get("https://example.test/x", response_model=list[_PydanticUser])
assert len(result) == 2 # noqa: PLR2004
assert all(type(item) is _PydanticUser for item in result)
client.close()
def test_sync_missing_decoder_with_empty_list() -> None:
def handler(_: httpx2.Request) -> httpx2.Response: # pragma: no cover — never invoked; decoder check fails first
pytest.fail("transport should not be invoked")
transport = httpx2.MockTransport(handler)
client = Client(
httpx2_client=httpx2.Client(transport=transport),
decoders=[],
)
with pytest.raises(MissingDecoderError):
client.get("https://example.test/x", response_model=_PydanticUser)
client.close()
async def test_async_msgspec_only_list_of_basemodel_preflight_raises() -> None:
"""MsgspecDecoder-only client raises MissingDecoderError for list[BaseModel] without sending a request."""
def handler(_: httpx2.Request) -> httpx2.Response: # pragma: no cover — never invoked; decoder check fails first
pytest.fail("transport should not be invoked: pre-flight must reject first")
transport = httpx2.MockTransport(handler)
client = AsyncClient(
httpx2_client=httpx2.AsyncClient(transport=transport),
decoders=[MsgspecDecoder()],
)
with pytest.raises(MissingDecoderError) as exc_info:
await client.get("https://example.test/x", response_model=list[_PydanticUser])
assert exc_info.value.registered_names == ("MsgspecDecoder",)
def test_sync_msgspec_only_list_of_basemodel_preflight_raises() -> None:
"""Sync MsgspecDecoder-only client raises MissingDecoderError for list[BaseModel] without sending a request."""
def handler(_: httpx2.Request) -> httpx2.Response: # pragma: no cover — never invoked; decoder check fails first
pytest.fail("transport should not be invoked: pre-flight must reject first")
transport = httpx2.MockTransport(handler)
client = Client(
httpx2_client=httpx2.Client(transport=transport),
decoders=[MsgspecDecoder()],
)
with pytest.raises(MissingDecoderError) as exc_info:
client.get("https://example.test/x", response_model=list[_PydanticUser])
assert exc_info.value.registered_names == ("MsgspecDecoder",)
client.close()