Skip to content

Commit fcac5d1

Browse files
lesnik512claude
andcommitted
test(client): response_model decoding + middleware chain integration
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent d1ebd3b commit fcac5d1

2 files changed

Lines changed: 162 additions & 0 deletions

File tree

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
"""Tests for AsyncClient ↔ middleware chain integration."""
2+
3+
from http import HTTPStatus
4+
5+
import httpx2
6+
import pytest
7+
8+
from httpware import AsyncClient, InternalServerError, Next, NotFoundError, after_response, before_request, on_error
9+
10+
11+
async def test_before_request_runs() -> None:
12+
@before_request
13+
async def add_header(request: httpx2.Request) -> httpx2.Request:
14+
return httpx2.Request(
15+
request.method,
16+
request.url,
17+
headers={**request.headers, "x-injected": "1"},
18+
)
19+
20+
captured: list[httpx2.Request] = []
21+
22+
def handler(request: httpx2.Request) -> httpx2.Response:
23+
captured.append(request)
24+
return httpx2.Response(HTTPStatus.OK, request=request)
25+
26+
transport = httpx2.MockTransport(handler)
27+
client = AsyncClient(
28+
httpx2_client=httpx2.AsyncClient(transport=transport),
29+
middleware=(add_header,),
30+
)
31+
await client.get("https://example.test/x")
32+
assert captured[0].headers["x-injected"] == "1"
33+
34+
35+
async def test_after_response_runs() -> None:
36+
@after_response
37+
async def tag_status(request: httpx2.Request, response: httpx2.Response) -> httpx2.Response:
38+
return httpx2.Response(
39+
HTTPStatus.IM_USED,
40+
request=request,
41+
headers=response.headers,
42+
content=response.content,
43+
)
44+
45+
transport = httpx2.MockTransport(lambda req: httpx2.Response(HTTPStatus.OK, request=req))
46+
client = AsyncClient(
47+
httpx2_client=httpx2.AsyncClient(transport=transport),
48+
middleware=(tag_status,),
49+
)
50+
response = await client.get("https://example.test/x")
51+
assert response.status_code == HTTPStatus.IM_USED
52+
53+
54+
async def test_on_error_catches_status_error() -> None:
55+
@on_error
56+
async def convert_404(request: httpx2.Request, exc: Exception) -> httpx2.Response | None:
57+
if isinstance(exc, NotFoundError):
58+
return httpx2.Response(HTTPStatus.OK, request=request, content=b"recovered")
59+
return None # let other exceptions propagate
60+
61+
transport_404 = httpx2.MockTransport(lambda req: httpx2.Response(HTTPStatus.NOT_FOUND, request=req))
62+
client = AsyncClient(
63+
httpx2_client=httpx2.AsyncClient(transport=transport_404),
64+
middleware=(convert_404,),
65+
)
66+
response = await client.get("https://example.test/x")
67+
assert response.status_code == HTTPStatus.OK
68+
assert response.content == b"recovered"
69+
70+
# Also exercise the return-None branch (non-404 → passes through to re-raise).
71+
transport_500 = httpx2.MockTransport(lambda req: httpx2.Response(HTTPStatus.INTERNAL_SERVER_ERROR, request=req))
72+
client2 = AsyncClient(
73+
httpx2_client=httpx2.AsyncClient(transport=transport_500),
74+
middleware=(convert_404,),
75+
)
76+
with pytest.raises(InternalServerError):
77+
await client2.get("https://example.test/x")
78+
79+
80+
async def test_middleware_runs_outer_to_inner_then_inner_to_outer() -> None:
81+
order: list[str] = []
82+
83+
class _Tag:
84+
def __init__(self, name: str) -> None:
85+
self.name = name
86+
87+
async def __call__(self, request: httpx2.Request, next: Next) -> httpx2.Response: # noqa: A002
88+
order.append(f"{self.name}.in")
89+
response = await next(request)
90+
order.append(f"{self.name}.out")
91+
return response
92+
93+
transport = httpx2.MockTransport(lambda req: httpx2.Response(HTTPStatus.OK, request=req))
94+
client = AsyncClient(
95+
httpx2_client=httpx2.AsyncClient(transport=transport),
96+
middleware=(_Tag("a"), _Tag("b")),
97+
)
98+
await client.get("https://example.test/x")
99+
assert order == ["a.in", "b.in", "b.out", "a.out"]
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""Tests for response_model decoding integration."""
2+
3+
from http import HTTPStatus
4+
5+
import httpx2
6+
import pydantic
7+
import pytest
8+
9+
from httpware import AsyncClient, NotFoundError
10+
11+
12+
class _User(pydantic.BaseModel):
13+
id: int
14+
name: str
15+
16+
17+
def _client_with_payload(payload: bytes, content_type: str = "application/json") -> AsyncClient:
18+
def handler(request: httpx2.Request) -> httpx2.Response:
19+
return httpx2.Response(
20+
HTTPStatus.OK,
21+
content=payload,
22+
headers={"content-type": content_type},
23+
request=request,
24+
)
25+
26+
transport = httpx2.MockTransport(handler)
27+
return AsyncClient(httpx2_client=httpx2.AsyncClient(transport=transport))
28+
29+
30+
async def test_get_with_response_model_returns_typed_object() -> None:
31+
client = _client_with_payload(b'{"id": 1, "name": "ada"}')
32+
user = await client.get("https://example.test/u", response_model=_User)
33+
assert isinstance(user, _User)
34+
assert user == _User(id=1, name="ada")
35+
36+
37+
async def test_post_with_response_model_returns_typed_object() -> None:
38+
client = _client_with_payload(b'{"id": 2, "name": "bob"}')
39+
user = await client.post("https://example.test/u", json={"name": "bob"}, response_model=_User)
40+
assert isinstance(user, _User)
41+
42+
43+
async def test_send_with_response_model_returns_typed_object() -> None:
44+
client = _client_with_payload(b'{"id": 3, "name": "cat"}')
45+
request = client.build_request("GET", "https://example.test/u")
46+
user = await client.send(request, response_model=_User)
47+
assert isinstance(user, _User)
48+
49+
50+
async def test_decoder_validation_error_propagates_unwrapped() -> None:
51+
client = _client_with_payload(b'{"id": "not-an-int", "name": "x"}')
52+
with pytest.raises(pydantic.ValidationError):
53+
await client.get("https://example.test/u", response_model=_User)
54+
55+
56+
async def test_status_error_raised_before_decoder_runs() -> None:
57+
def handler(request: httpx2.Request) -> httpx2.Response:
58+
return httpx2.Response(HTTPStatus.NOT_FOUND, content=b'{"id": 1, "name": "x"}', request=request)
59+
60+
transport = httpx2.MockTransport(handler)
61+
client = AsyncClient(httpx2_client=httpx2.AsyncClient(transport=transport))
62+
with pytest.raises(NotFoundError):
63+
await client.get("https://example.test/u", response_model=_User)

0 commit comments

Comments
 (0)