Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/vws/transports.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,26 @@ class HTTPXTransport:

Use this transport for environments where ``httpx`` is
preferred over ``requests``.
A single ``httpx.Client`` is reused across requests
for connection pooling.
"""

def __init__(self) -> None:
"""Create an ``HTTPXTransport``."""
self._client = httpx.Client()

def close(self) -> None:
"""Close the underlying ``httpx.Client``."""
self._client.close()

def __enter__(self) -> Self:
"""Enter the context manager."""
return self

def __exit__(self, *_args: object) -> None:
"""Exit the context manager and close the client."""
self.close()
Comment thread
cursor[bot] marked this conversation as resolved.

def __call__(
self,
*,
Expand Down Expand Up @@ -136,7 +154,7 @@ def __call__(
pool=None,
)

httpx_response = httpx.request(
httpx_response = self._client.request(
method=method,
url=url,
headers=headers,
Expand Down
22 changes: 22 additions & 0 deletions tests/test_transports.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,28 @@ def test_tuple_timeout() -> None:
assert isinstance(response, Response)
assert response.status_code == HTTPStatus.OK

@staticmethod
@respx.mock
def test_context_manager() -> None:
"""``HTTPXTransport`` can be used as a context manager."""
route = respx.post(url="https://example.com/test").mock(
return_value=httpx.Response(
status_code=HTTPStatus.OK,
text="OK",
),
)
with HTTPXTransport() as transport:
response = transport(
method="POST",
url="https://example.com/test",
headers={"Content-Type": "text/plain"},
data=b"hello",
request_timeout=30.0,
)
assert route.called
assert isinstance(response, Response)
assert response.status_code == HTTPStatus.OK


class TestAsyncHTTPXTransport:
"""Tests for ``AsyncHTTPXTransport``."""
Expand Down
Loading