Skip to content
Myr

test_async_client.py

This file

Path

tests/client/test_async_client.py

315 lines · 10.1 KiB · Python

Last changed by

Transport API (#1522)Tom Christiebefore adoption1a6e254

History of this file

Take it

The walk stopped after 200 commits: lines older than 31e587c point at it.

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

line 1why, one step back
1import typing

Pin pytestTom Christiebefore adoption31e587c

lines 2–11why, one step back
2from datetime import timedelta
34import pytest56import httpx789@pytest.mark.usefixtures("async_environment")10async def test_get(server):11 url = server.url

HTTP/2 becomes fully optional (#1140)Tom Christiebefore adoption8d9dfb5

line 12why, one step back
12 async with httpx.AsyncClient(http2=True) as client:

Pin pytestTom Christiebefore adoption31e587c

lines 13–32why, one step back
13 response = await client.get(url)
14 assert response.status_code == 20015 assert response.text == "Hello, world!"16 assert response.http_version == "HTTP/1.1"17 assert response.headers18 assert repr(response) == "<Response [200 OK]>"19 assert response.elapsed > timedelta(seconds=0)202122@pytest.mark.parametrize(23 "url",24 [25 pytest.param("invalid://example.org", id="scheme-not-http(s)"),26 pytest.param("://example.org", id="no-scheme"),27 pytest.param("http://", id="no-host"),28 ],29)30@pytest.mark.usefixtures("async_environment")31async def test_get_invalid_url(server, url):32 async with httpx.AsyncClient() as client:

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

line 33why, one step back
33 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):

Pin pytestTom Christiebefore adoption31e587c

lines 34–55why, one step back
34 await client.get(url)
353637@pytest.mark.usefixtures("async_environment")38async def test_build_request(server):39 url = server.url.copy_with(path="/echo_headers")40 headers = {"Custom-header": "value"}41 async with httpx.AsyncClient() as client:42 request = client.build_request("GET", url)43 request.headers.update(headers)44 response = await client.send(request)4546 assert response.status_code == 20047 assert response.url == url4849 assert response.json()["Custom-header"] == "value"505152@pytest.mark.usefixtures("async_environment")53async def test_post(server):54 url = server.url55 async with httpx.AsyncClient() as client:

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 56why, one step back
56 response = await client.post(url, content=b"Hello, world!")

Pin pytestTom Christiebefore adoption31e587c

lines 57–96why, one step back
57 assert response.status_code == 200
585960@pytest.mark.usefixtures("async_environment")61async def test_post_json(server):62 url = server.url63 async with httpx.AsyncClient() as client:64 response = await client.post(url, json={"text": "Hello, world!"})65 assert response.status_code == 200666768@pytest.mark.usefixtures("async_environment")69async def test_stream_response(server):70 async with httpx.AsyncClient() as client:71 async with client.stream("GET", server.url) as response:72 body = await response.aread()7374 assert response.status_code == 20075 assert body == b"Hello, world!"76 assert response.content == b"Hello, world!"777879@pytest.mark.usefixtures("async_environment")80async def test_access_content_stream_response(server):81 async with httpx.AsyncClient() as client:82 async with client.stream("GET", server.url) as response:83 pass8485 assert response.status_code == 20086 with pytest.raises(httpx.ResponseNotRead):87 response.content888990@pytest.mark.usefixtures("async_environment")91async def test_stream_request(server):92 async def hello_world():93 yield b"Hello, "94 yield b"world!"9596 async with httpx.AsyncClient() as client:

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 97why, one step back
97 response = await client.request("POST", server.url, content=hello_world())

Pin pytestTom Christiebefore adoption31e587c

lines 98–135why, one step back
98 assert response.status_code == 200
99100101@pytest.mark.usefixtures("async_environment")102async def test_raise_for_status(server):103 async with httpx.AsyncClient() as client:104 for status_code in (200, 400, 404, 500, 505):105 response = await client.request(106 "GET", server.url.copy_with(path=f"/status/{status_code}")107 )108109 if 400 <= status_code < 600:110 with pytest.raises(httpx.HTTPStatusError) as exc_info:111 response.raise_for_status()112 assert exc_info.value.response == response113 else:114 assert response.raise_for_status() is None # type: ignore115116117@pytest.mark.usefixtures("async_environment")118async def test_options(server):119 async with httpx.AsyncClient() as client:120 response = await client.options(server.url)121 assert response.status_code == 200122 assert response.text == "Hello, world!"123124125@pytest.mark.usefixtures("async_environment")126async def test_head(server):127 async with httpx.AsyncClient() as client:128 response = await client.head(server.url)129 assert response.status_code == 200130 assert response.text == ""131132133@pytest.mark.usefixtures("async_environment")134async def test_put(server):135 async with httpx.AsyncClient() as client:

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 136why, one step back
136 response = await client.put(server.url, content=b"Hello, world!")

Pin pytestTom Christiebefore adoption31e587c

lines 137–142why, one step back
137 assert response.status_code == 200
138139140@pytest.mark.usefixtures("async_environment")141async def test_patch(server):142 async with httpx.AsyncClient() as client:

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 143why, one step back
143 response = await client.patch(server.url, content=b"Hello, world!")

Pin pytestTom Christiebefore adoption31e587c

lines 144–157why, one step back
144 assert response.status_code == 200
145146147@pytest.mark.usefixtures("async_environment")148async def test_delete(server):149 async with httpx.AsyncClient() as client:150 response = await client.delete(server.url)151 assert response.status_code == 200152 assert response.text == "Hello, world!"153154155@pytest.mark.usefixtures("async_environment")156async def test_100_continue(server):157 headers = {"Expect": "100-continue"}

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 158why, one step back
158 content = b"Echo request body"

Pin pytestTom Christiebefore adoption31e587c

lines 159–161why, one step back
159
160 async with httpx.AsyncClient() as client:161 response = await client.post(

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 162why, one step back
162 server.url.copy_with(path="/echo_body"), headers=headers, content=content

Pin pytestTom Christiebefore adoption31e587c

lines 163–165why, one step back
163 )
164165 assert response.status_code == 200

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 166why, one step back
166 assert response.content == content

Context managed transports (#1218)Tom Christiebefore adoption534400e

lines 167–170why, one step back
167
168169@pytest.mark.usefixtures("async_environment")170async def test_context_managed_transport():

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 171why, one step back
171 class Transport(httpx.AsyncBaseTransport):

Context managed transports (#1218)Tom Christiebefore adoption534400e

lines 172–175why, one step back
172 def __init__(self):
173 self.events = []174175 async def aclose(self):

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 176why, one step back
176 # The base implementation of httpx.AsyncBaseTransport just

Context managed transports (#1218)Tom Christiebefore adoption534400e

lines 177–190why, one step back
177 # calls into `.aclose`, so simple transport cases can just override
178 # this method for any cleanup, where more complex cases179 # might want to additionally override `__aenter__`/`__aexit__`.180 self.events.append("transport.aclose")181182 async def __aenter__(self):183 await super().__aenter__()184 self.events.append("transport.__aenter__")185186 async def __aexit__(self, *args):187 await super().__aexit__(*args)188 self.events.append("transport.__aexit__")189190 transport = Transport()

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

line 191why, one step back
191 async with httpx.AsyncClient(transport=transport):

Context managed transports (#1218)Tom Christiebefore adoption534400e

lines 192–198why, one step back
192 pass
193194 assert transport.events == [195 "transport.__aenter__",196 "transport.aclose",197 "transport.__aexit__",198 ]

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 199–200why, one step back
199
200

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 201–202why, one step back
201@pytest.mark.usefixtures("async_environment")
202async def test_context_managed_transport_and_mount():

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 203why, one step back
203 class Transport(httpx.AsyncBaseTransport):

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 204–208why, one step back
204 def __init__(self, name: str):
205 self.name: str = name206 self.events: typing.List[str] = []207208 async def aclose(self):

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 209why, one step back
209 # The base implementation of httpx.AsyncBaseTransport just

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 210–241why, one step back
210 # calls into `.aclose`, so simple transport cases can just override
211 # this method for any cleanup, where more complex cases212 # might want to additionally override `__aenter__`/`__aexit__`.213 self.events.append(f"{self.name}.aclose")214215 async def __aenter__(self):216 await super().__aenter__()217 self.events.append(f"{self.name}.__aenter__")218219 async def __aexit__(self, *args):220 await super().__aexit__(*args)221 self.events.append(f"{self.name}.__aexit__")222223 transport = Transport(name="transport")224 mounted = Transport(name="mounted")225 async with httpx.AsyncClient(226 transport=transport, mounts={"http://www.example.org": mounted}227 ):228 pass229230 assert transport.events == [231 "transport.__aenter__",232 "transport.aclose",233 "transport.__aexit__",234 ]235 assert mounted.events == [236 "mounted.__aenter__",237 "mounted.aclose",238 "mounted.__aexit__",239 ]240241

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

lines 242–243why, one step back
242def hello_world(request):
243 return httpx.Response(200, text="Hello, world!")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 244–246why, one step back
244
245246@pytest.mark.usefixtures("async_environment")

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 247why, one step back
247async def test_client_closed_state_using_implicit_open():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 248why, one step back
248 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 249why, one step back
249

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 250why, one step back
250 assert not client.is_closed

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 251–255why, one step back
251 await client.get("http://example.com")
252253 assert not client.is_closed254 await client.aclose()255

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

lines 256–258why, one step back
256 assert client.is_closed
257 with pytest.raises(RuntimeError):258 await client.get("http://example.com")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 259why, one step back
259

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 260why, one step back
260

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 261why, one step back
261@pytest.mark.usefixtures("async_environment")

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 262why, one step back
262async def test_client_closed_state_using_with_block():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 263why, one step back
263 async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 264why, one step back
264 assert not client.is_closed

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 265why, one step back
265 await client.get("http://example.com")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 266–267why, one step back
266
267 assert client.is_closed

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

lines 268–269why, one step back
268 with pytest.raises(RuntimeError):
269 await client.get("http://example.com")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 270–272why, one step back
270
271272@pytest.mark.usefixtures("async_environment")

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 273why, one step back
273async def test_deleting_unclosed_async_client_causes_warning():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 274why, one step back
274 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 275why, one step back
275 await client.get("http://example.com")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 276why, one step back
276 with pytest.warns(UserWarning):

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 277why, one step back
277 del client

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 278–291why, one step back
278
279280def unmounted(request: httpx.Request) -> httpx.Response:281 data = {"app": "unmounted"}282 return httpx.Response(200, json=data)283284285def mounted(request: httpx.Request) -> httpx.Response:286 data = {"app": "mounted"}287 return httpx.Response(200, json=data)288289290@pytest.mark.usefixtures("async_environment")291async def test_mounted_transport():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

lines 292–293why, one step back
292 transport = httpx.MockTransport(unmounted)
293 mounts = {"custom://": httpx.MockTransport(mounted)}

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 294–302why, one step back
294
295 async with httpx.AsyncClient(transport=transport, mounts=mounts) as client:296 response = await client.get("https://www.example.com")297 assert response.status_code == 200298 assert response.json() == {"app": "unmounted"}299300 response = await client.get("custom://www.example.com")301 assert response.status_code == 200302 assert response.json() == {"app": "mounted"}

map_exceptions in request.aclose() (#1465)Adam Hooperbefore adoption0f280af

lines 303–305why, one step back
303
304305@pytest.mark.usefixtures("async_environment")

Allow handler to optionally be async when MockTransport is used with AsyncClient (#1449)Tom Christiebefore adoption084f356

lines 306–315why, one step back
306async def test_async_mock_transport():
307 async def hello_world(request):308 return httpx.Response(200, text="Hello, world!")309310 transport = httpx.MockTransport(hello_world)311312 async with httpx.AsyncClient(transport=transport) as client:313 response = await client.get("https://www.example.com")314 assert response.status_code == 200315 assert response.text == "Hello, world!"