File tree Expand file tree Collapse file tree 2 files changed +41
-1
lines changed
Expand file tree Collapse file tree 2 files changed +41
-1
lines changed Original file line number Diff line number Diff line change @@ -97,8 +97,26 @@ class HTTPXTransport:
9797
9898 Use this transport for environments where ``httpx`` is
9999 preferred over ``requests``.
100+ A single ``httpx.Client`` is reused across requests
101+ for connection pooling.
100102 """
101103
104+ def __init__ (self ) -> None :
105+ """Create an ``HTTPXTransport``."""
106+ self ._client = httpx .Client ()
107+
108+ def close (self ) -> None :
109+ """Close the underlying ``httpx.Client``."""
110+ self ._client .close ()
111+
112+ def __enter__ (self ) -> Self :
113+ """Enter the context manager."""
114+ return self
115+
116+ def __exit__ (self , * _args : object ) -> None :
117+ """Exit the context manager and close the client."""
118+ self .close ()
119+
102120 def __call__ (
103121 self ,
104122 * ,
@@ -136,7 +154,7 @@ def __call__(
136154 pool = None ,
137155 )
138156
139- httpx_response = httpx .request (
157+ httpx_response = self . _client .request (
140158 method = method ,
141159 url = url ,
142160 headers = headers ,
Original file line number Diff line number Diff line change @@ -61,6 +61,28 @@ def test_tuple_timeout() -> None:
6161 assert isinstance (response , Response )
6262 assert response .status_code == HTTPStatus .OK
6363
64+ @staticmethod
65+ @respx .mock
66+ def test_context_manager () -> None :
67+ """``HTTPXTransport`` can be used as a context manager."""
68+ route = respx .post (url = "https://example.com/test" ).mock (
69+ return_value = httpx .Response (
70+ status_code = HTTPStatus .OK ,
71+ text = "OK" ,
72+ ),
73+ )
74+ with HTTPXTransport () as transport :
75+ response = transport (
76+ method = "POST" ,
77+ url = "https://example.com/test" ,
78+ headers = {"Content-Type" : "text/plain" },
79+ data = b"hello" ,
80+ request_timeout = 30.0 ,
81+ )
82+ assert route .called
83+ assert isinstance (response , Response )
84+ assert response .status_code == HTTPStatus .OK
85+
6486
6587class TestAsyncHTTPXTransport :
6688 """Tests for ``AsyncHTTPXTransport``."""
You can’t perform that action at this time.
0 commit comments