|
| 1 | +"""Tests for AsyncClient.send_with_response — atomic (response, decoded) pair.""" |
| 2 | + |
| 3 | +from http import HTTPStatus |
| 4 | + |
| 5 | +import httpx2 |
| 6 | +import pydantic |
| 7 | +import pytest |
| 8 | + |
| 9 | +from httpware import AsyncClient, ClientError, DecodeError, NotFoundError |
| 10 | +from httpware.middleware import async_before_request |
| 11 | + |
| 12 | + |
| 13 | +class _User(pydantic.BaseModel): |
| 14 | + id: int |
| 15 | + name: str |
| 16 | + |
| 17 | + |
| 18 | +def _client_with_payload( |
| 19 | + payload: bytes, |
| 20 | + *, |
| 21 | + status: int = HTTPStatus.OK, |
| 22 | + headers: dict[str, str] | None = None, |
| 23 | +) -> AsyncClient: |
| 24 | + response_headers = {"content-type": "application/json"} |
| 25 | + if headers is not None: |
| 26 | + response_headers.update(headers) |
| 27 | + |
| 28 | + def handler(request: httpx2.Request) -> httpx2.Response: |
| 29 | + return httpx2.Response(status, content=payload, headers=response_headers, request=request) |
| 30 | + |
| 31 | + transport = httpx2.MockTransport(handler) |
| 32 | + return AsyncClient(httpx2_client=httpx2.AsyncClient(transport=transport)) |
| 33 | + |
| 34 | + |
| 35 | +async def test_send_with_response_returns_response_and_decoded() -> None: |
| 36 | + client = _client_with_payload(b'{"id": 1, "name": "ada"}') |
| 37 | + request = client.build_request("GET", "https://example.test/u") |
| 38 | + response, user = await client.send_with_response(request, response_model=_User) |
| 39 | + assert isinstance(response, httpx2.Response) |
| 40 | + assert isinstance(user, _User) |
| 41 | + assert user == _User(id=1, name="ada") |
| 42 | + assert response.content == b'{"id": 1, "name": "ada"}' |
| 43 | + |
| 44 | + |
| 45 | +async def test_send_with_response_preserves_response_headers() -> None: |
| 46 | + """Pagination callers read Link / X-Total-Count off the returned response.""" |
| 47 | + client = _client_with_payload( |
| 48 | + b'{"id": 1, "name": "p"}', |
| 49 | + headers={"link": '<https://example.test/u?page=2>; rel="next"', "x-total-count": "100"}, |
| 50 | + ) |
| 51 | + request = client.build_request("GET", "https://example.test/u?page=1") |
| 52 | + response, _ = await client.send_with_response(request, response_model=_User) |
| 53 | + assert response.headers.get("link") == '<https://example.test/u?page=2>; rel="next"' |
| 54 | + assert response.headers.get("x-total-count") == "100" |
| 55 | + |
| 56 | + |
| 57 | +async def test_send_with_response_response_request_url_populated() -> None: |
| 58 | + """Pagination loops do str(response.request.url) to compute the next page.""" |
| 59 | + client = _client_with_payload(b'{"id": 1, "name": "p"}') |
| 60 | + request = client.build_request("GET", "https://example.test/u?page=1") |
| 61 | + response, _ = await client.send_with_response(request, response_model=_User) |
| 62 | + assert str(response.request.url) == "https://example.test/u?page=1" |
| 63 | + |
| 64 | + |
| 65 | +async def test_send_with_response_decode_failure_raises_decode_error() -> None: |
| 66 | + client = _client_with_payload(b"null") |
| 67 | + request = client.build_request("GET", "https://example.test/u") |
| 68 | + with pytest.raises(DecodeError) as exc_info: |
| 69 | + await client.send_with_response(request, response_model=_User) |
| 70 | + exc = exc_info.value |
| 71 | + assert exc.response.status_code == HTTPStatus.OK |
| 72 | + assert exc.model is _User |
| 73 | + assert isinstance(exc.original, pydantic.ValidationError) |
| 74 | + assert exc.__cause__ is exc.original |
| 75 | + |
| 76 | + |
| 77 | +async def test_send_with_response_malformed_json_raises_decode_error() -> None: |
| 78 | + client = _client_with_payload(b"{not json") |
| 79 | + request = client.build_request("GET", "https://example.test/u") |
| 80 | + with pytest.raises(DecodeError) as exc_info: |
| 81 | + await client.send_with_response(request, response_model=_User) |
| 82 | + exc = exc_info.value |
| 83 | + assert exc.response.status_code == HTTPStatus.OK |
| 84 | + assert exc.model is _User |
| 85 | + assert isinstance(exc.original, pydantic.ValidationError) |
| 86 | + |
| 87 | + |
| 88 | +async def test_send_with_response_decode_error_caught_by_client_error() -> None: |
| 89 | + """The user-facing promise: `except ClientError` catches decode failures.""" |
| 90 | + client = _client_with_payload(b"null") |
| 91 | + request = client.build_request("GET", "https://example.test/u") |
| 92 | + with pytest.raises(ClientError) as exc_info: |
| 93 | + await client.send_with_response(request, response_model=_User) |
| 94 | + assert isinstance(exc_info.value, DecodeError) |
| 95 | + |
| 96 | + |
| 97 | +async def test_send_with_response_status_error_raised_before_decoder_runs() -> None: |
| 98 | + """4xx never produces a DecodeError — terminal raises StatusError first.""" |
| 99 | + client = _client_with_payload(b'{"id": 1, "name": "x"}', status=HTTPStatus.NOT_FOUND) |
| 100 | + request = client.build_request("GET", "https://example.test/u") |
| 101 | + with pytest.raises(NotFoundError): |
| 102 | + await client.send_with_response(request, response_model=_User) |
| 103 | + |
| 104 | + |
| 105 | +async def test_send_with_response_runs_middleware_chain() -> None: |
| 106 | + """User middleware mutates the request; mutation is visible on the wire.""" |
| 107 | + recorded: list[httpx2.Request] = [] |
| 108 | + |
| 109 | + async def stamp(request: httpx2.Request) -> httpx2.Request: |
| 110 | + request.headers["x-test"] = "ok" |
| 111 | + return request |
| 112 | + |
| 113 | + def handler(request: httpx2.Request) -> httpx2.Response: |
| 114 | + recorded.append(request) |
| 115 | + return httpx2.Response( |
| 116 | + HTTPStatus.OK, |
| 117 | + content=b'{"id": 1, "name": "z"}', |
| 118 | + headers={"content-type": "application/json"}, |
| 119 | + request=request, |
| 120 | + ) |
| 121 | + |
| 122 | + transport = httpx2.MockTransport(handler) |
| 123 | + client = AsyncClient( |
| 124 | + httpx2_client=httpx2.AsyncClient(transport=transport), |
| 125 | + middleware=[async_before_request(stamp)], |
| 126 | + ) |
| 127 | + request = client.build_request("GET", "https://example.test/u") |
| 128 | + response, _ = await client.send_with_response(request, response_model=_User) |
| 129 | + assert recorded[0].headers.get("x-test") == "ok" |
| 130 | + assert response.request.headers.get("x-test") == "ok" |
0 commit comments