Skip to content

Commit ae5a742

Browse files
lesnik512claude
andcommitted
feat(client): __aenter__/__aexit__ honors owned vs. borrowed httpx2 client
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent fcac5d1 commit ae5a742

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

‎src/httpware/client.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -645,3 +645,17 @@ async def request( # noqa: PLR0913 — mirrors httpx2 per-method signatures
645645
files=files,
646646
response_model=response_model,
647647
)
648+
649+
async def __aenter__(self) -> typing.Self:
650+
"""Enter the async context manager; return self."""
651+
return self
652+
653+
async def __aexit__(
654+
self,
655+
exc_type: type[BaseException] | None,
656+
exc: BaseException | None,
657+
tb: object,
658+
) -> None:
659+
"""Exit the async context manager; close the underlying client only if owned."""
660+
if self._owns_client and not self._httpx2_client.is_closed:
661+
await self._httpx2_client.aclose()

‎tests/test_client_lifecycle.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""Tests for AsyncClient.__aenter__/__aexit__ lifecycle and ownership."""
2+
3+
from http import HTTPStatus
4+
5+
import httpx2
6+
7+
from httpware import AsyncClient
8+
9+
10+
async def test_aexit_closes_owned_httpx2_client() -> None:
11+
client = AsyncClient()
12+
async with client:
13+
pass
14+
assert client._httpx2_client.is_closed # noqa: SLF001
15+
16+
17+
async def test_aexit_does_not_close_borrowed_httpx2_client() -> None:
18+
transport = httpx2.MockTransport(lambda req: httpx2.Response(HTTPStatus.OK, request=req))
19+
underlying = httpx2.AsyncClient(transport=transport)
20+
client = AsyncClient(httpx2_client=underlying)
21+
async with client:
22+
pass
23+
assert not underlying.is_closed
24+
await underlying.aclose()
25+
26+
27+
async def test_aexit_is_idempotent_for_owned_client() -> None:
28+
client = AsyncClient()
29+
async with client:
30+
pass
31+
# Second use should not raise — the boolean prevents a double-close on httpx2 internals.
32+
await client.__aexit__(None, None, None)

0 commit comments

Comments
 (0)