test_async_client.py
This file
Path
tests/client/test_async_client.py
335 lines · 10.7 KiB · Python
Last changed by
Drop 'Response(on_close=...)' from API (#1572)Tom Christiebefore adoption073a328
History of this fileTake it
The walk stopped after 200 commits: lines older than 842ccfa point at it.
Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 1why, one step back1import typingAdd exported members test (#1179)Josep Cugatbefore adoption842ccfa
lines 2–55why, one step back2from datetime import timedelta34import pytest56import httpx789@pytest.mark.usefixtures("async_environment")10async def test_get(server):11 url = server.url12 async with httpx.AsyncClient(http2=True) as client: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:33 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):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 back56 response = await client.post(url, content=b"Hello, world!")Add exported members test (#1179)Josep Cugatbefore adoption842ccfa
lines 57–96why, one step back57 assert response.status_code == 200585960@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:Drop 'Response(on_close=...)' from API (#1572)Tom Christiebefore adoption073a328
line 97why, one step back97 response = await client.post(server.url, content=hello_world())Add exported members test (#1179)Josep Cugatbefore adoption842ccfa
line 98why, one step back98 assert response.status_code == 200Drop 'Response(on_close=...)' from API (#1572)Tom Christiebefore adoption073a328
lines 99–109why, one step back99100101@pytest.mark.usefixtures("async_environment")102async def test_cannot_stream_sync_request(server):103 def hello_world(): # pragma: nocover104 yield b"Hello, "105 yield b"world!"106107 async with httpx.AsyncClient() as client:108 with pytest.raises(RuntimeError):109 await client.post(server.url, content=hello_world())Add exported members test (#1179)Josep Cugatbefore adoption842ccfa
lines 110–146why, one step back110111112@pytest.mark.usefixtures("async_environment")113async def test_raise_for_status(server):114 async with httpx.AsyncClient() as client:115 for status_code in (200, 400, 404, 500, 505):116 response = await client.request(117 "GET", server.url.copy_with(path=f"/status/{status_code}")118 )119120 if 400 <= status_code < 600:121 with pytest.raises(httpx.HTTPStatusError) as exc_info:122 response.raise_for_status()123 assert exc_info.value.response == response124 else:125 assert response.raise_for_status() is None # type: ignore126127128@pytest.mark.usefixtures("async_environment")129async def test_options(server):130 async with httpx.AsyncClient() as client:131 response = await client.options(server.url)132 assert response.status_code == 200133 assert response.text == "Hello, world!"134135136@pytest.mark.usefixtures("async_environment")137async def test_head(server):138 async with httpx.AsyncClient() as client:139 response = await client.head(server.url)140 assert response.status_code == 200141 assert response.text == ""142143144@pytest.mark.usefixtures("async_environment")145async def test_put(server):146 async with httpx.AsyncClient() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 147why, one step back147 response = await client.put(server.url, content=b"Hello, world!")Add exported members test (#1179)Josep Cugatbefore adoption842ccfa
lines 148–153why, one step back148 assert response.status_code == 200149150151@pytest.mark.usefixtures("async_environment")152async def test_patch(server):153 async with httpx.AsyncClient() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 154why, one step back154 response = await client.patch(server.url, content=b"Hello, world!")Add exported members test (#1179)Josep Cugatbefore adoption842ccfa
lines 155–168why, one step back155 assert response.status_code == 200156157158@pytest.mark.usefixtures("async_environment")159async def test_delete(server):160 async with httpx.AsyncClient() as client:161 response = await client.delete(server.url)162 assert response.status_code == 200163 assert response.text == "Hello, world!"164165166@pytest.mark.usefixtures("async_environment")167async def test_100_continue(server):168 headers = {"Expect": "100-continue"}Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 169why, one step back169 content = b"Echo request body"Add exported members test (#1179)Josep Cugatbefore adoption842ccfa
lines 170–172why, one step back170171 async with httpx.AsyncClient() as client:172 response = await client.post(Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 173why, one step back173 server.url.copy_with(path="/echo_body"), headers=headers, content=contentAdd exported members test (#1179)Josep Cugatbefore adoption842ccfa
lines 174–176why, one step back174 )175176 assert response.status_code == 200Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 177why, one step back177 assert response.content == contentContext managed transports (#1218)Tom Christiebefore adoption534400e
lines 178–181why, one step back178179180@pytest.mark.usefixtures("async_environment")181async def test_context_managed_transport():Transport API (#1522)Tom Christiebefore adoption1a6e254
line 182why, one step back182 class Transport(httpx.AsyncBaseTransport):Context managed transports (#1218)Tom Christiebefore adoption534400e
lines 183–186why, one step back183 def __init__(self):184 self.events = []185186 async def aclose(self):Transport API (#1522)Tom Christiebefore adoption1a6e254
line 187why, one step back187 # The base implementation of httpx.AsyncBaseTransport justContext managed transports (#1218)Tom Christiebefore adoption534400e
lines 188–201why, one step back188 # calls into `.aclose`, so simple transport cases can just override189 # this method for any cleanup, where more complex cases190 # might want to additionally override `__aenter__`/`__aexit__`.191 self.events.append("transport.aclose")192193 async def __aenter__(self):194 await super().__aenter__()195 self.events.append("transport.__aenter__")196197 async def __aexit__(self, *args):198 await super().__aexit__(*args)199 self.events.append("transport.__aexit__")200201 transport = Transport()Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 202why, one step back202 async with httpx.AsyncClient(transport=transport):Context managed transports (#1218)Tom Christiebefore adoption534400e
lines 203–209why, one step back203 pass204205 assert transport.events == [206 "transport.__aenter__",207 "transport.aclose",208 "transport.__aexit__",209 ]Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 210–211why, one step back210211Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 212–213why, one step back212@pytest.mark.usefixtures("async_environment")213async def test_context_managed_transport_and_mount():Transport API (#1522)Tom Christiebefore adoption1a6e254
line 214why, one step back214 class Transport(httpx.AsyncBaseTransport):Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 215–219why, one step back215 def __init__(self, name: str):216 self.name: str = name217 self.events: typing.List[str] = []218219 async def aclose(self):Transport API (#1522)Tom Christiebefore adoption1a6e254
line 220why, one step back220 # The base implementation of httpx.AsyncBaseTransport justAdd support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 221–252why, one step back221 # calls into `.aclose`, so simple transport cases can just override222 # this method for any cleanup, where more complex cases223 # might want to additionally override `__aenter__`/`__aexit__`.224 self.events.append(f"{self.name}.aclose")225226 async def __aenter__(self):227 await super().__aenter__()228 self.events.append(f"{self.name}.__aenter__")229230 async def __aexit__(self, *args):231 await super().__aexit__(*args)232 self.events.append(f"{self.name}.__aexit__")233234 transport = Transport(name="transport")235 mounted = Transport(name="mounted")236 async with httpx.AsyncClient(237 transport=transport, mounts={"http://www.example.org": mounted}238 ):239 pass240241 assert transport.events == [242 "transport.__aenter__",243 "transport.aclose",244 "transport.__aexit__",245 ]246 assert mounted.events == [247 "mounted.__aenter__",248 "mounted.aclose",249 "mounted.__aexit__",250 ]251252Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 253–254why, one step back253def hello_world(request):254 return httpx.Response(200, text="Hello, world!")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 255–257why, one step back255256257@pytest.mark.usefixtures("async_environment")Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 258why, one step back258async def test_client_closed_state_using_implicit_open():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 259why, one step back259 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 260why, one step back260Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 261why, one step back261 assert not client.is_closedIssue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 262–266why, one step back262 await client.get("http://example.com")263264 assert not client.is_closed265 await client.aclose()266Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 267–269why, one step back267 assert client.is_closed268 with pytest.raises(RuntimeError):269 await client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 270why, one step back270Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 271why, one step back271Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 272why, one step back272@pytest.mark.usefixtures("async_environment")Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 273why, one step back273async def test_client_closed_state_using_with_block():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 274why, one step back274 async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 275why, one step back275 assert not client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 276why, one step back276 await client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 277–278why, one step back277278 assert client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 279–280why, one step back279 with pytest.raises(RuntimeError):280 await client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 281–283why, one step back281282283@pytest.mark.usefixtures("async_environment")Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 284why, one step back284async def test_deleting_unclosed_async_client_causes_warning():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 285why, one step back285 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 286why, one step back286 await client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 287why, one step back287 with pytest.warns(UserWarning):Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 288why, one step back288 del clientAdd support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 289–302why, one step back289290291def unmounted(request: httpx.Request) -> httpx.Response:292 data = {"app": "unmounted"}293 return httpx.Response(200, json=data)294295296def mounted(request: httpx.Request) -> httpx.Response:297 data = {"app": "mounted"}298 return httpx.Response(200, json=data)299300301@pytest.mark.usefixtures("async_environment")302async def test_mounted_transport():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 303–304why, one step back303 transport = httpx.MockTransport(unmounted)304 mounts = {"custom://": httpx.MockTransport(mounted)}Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 305–313why, one step back305306 async with httpx.AsyncClient(transport=transport, mounts=mounts) as client:307 response = await client.get("https://www.example.com")308 assert response.status_code == 200309 assert response.json() == {"app": "unmounted"}310311 response = await client.get("custom://www.example.com")312 assert response.status_code == 200313 assert response.json() == {"app": "mounted"}map_exceptions in request.aclose() (#1465)Adam Hooperbefore adoption0f280af
lines 314–316why, one step back314315316@pytest.mark.usefixtures("async_environment")Allow handler to optionally be async when MockTransport is used with AsyncClient (#1449)Tom Christiebefore adoption084f356
lines 317–326why, one step back317async def test_async_mock_transport():318 async def hello_world(request):319 return httpx.Response(200, text="Hello, world!")320321 transport = httpx.MockTransport(hello_world)322323 async with httpx.AsyncClient(transport=transport) as client:324 response = await client.get("https://www.example.com")325 assert response.status_code == 200326 assert response.text == "Hello, world!"Fix extenstions typo in AsyncHTTPTransport (#1549)Jonas Lundbergbefore adoption52dd95f
lines 327–335why, one step back327328329@pytest.mark.usefixtures("async_environment")330async def test_server_extensions(server):331 url = server.url332 async with httpx.AsyncClient(http2=True) as client:333 response = await client.get(url)334 assert response.status_code == 200335 assert response.extensions["http_version"] == b"HTTP/1.1"