test_async_client.py
This file
Path
tests/client/test_async_client.py
373 lines · 11.4 KiB · Python
Last changed by
add missing type hints to __init__(...) (#2938)Petr Belskiybefore adoption87f39f1
History of this fileTake it
The walk stopped after 200 commits: lines older than a754e71 point at it.
Replace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 1–8why, one step back1import typing2from datetime import timedelta34import pytest56import httpx78replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 9why, one step back9@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 10–29why, one step back10async 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)replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 30why, one step back30@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 31–36why, one step back31async 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)3536replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 37why, one step back37@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 38–51why, one step back38async 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"5051replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 52why, one step back52@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 53–59why, one step back53async def test_post(server):54 url = server.url55 async with httpx.AsyncClient() as client:56 response = await client.post(url, content=b"Hello, world!")57 assert response.status_code == 2005859replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 60why, one step back60@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 61–67why, one step back61async 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 == 2006667replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 68why, one step back68@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 69–78why, one step back69async 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!"7778replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 79why, one step back79@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 80–86why, one step back80async 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):Use ruff instead of flake8, autoflake and isort (#2648)Marcelo Trylesinskibefore adoptiondaec2bd
line 87why, one step back87 response.content # noqa: B018Replace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 88–89why, one step back8889replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 90why, one step back90@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
line 91why, one step back91async def test_stream_request(server):Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 92why, one step back92 async def hello_world() -> typing.AsyncIterator[bytes]:Replace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 93–100why, one step back93 yield b"Hello, "94 yield b"world!"9596 async with httpx.AsyncClient() as client:97 response = await client.post(server.url, content=hello_world())98 assert response.status_code == 20099100replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 101why, one step back101@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
line 102why, one step back102async def test_cannot_stream_sync_request(server):Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 103why, one step back103 def hello_world() -> typing.Iterator[bytes]: # pragma: no coverReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 104–111why, one step back104 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())110111replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 112why, one step back112@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 113–124why, one step back113async 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:Make `raise_for_status` chainable (#2776)Trim21before adoption9415af6
line 125why, one step back125 assert response.raise_for_status() is responseReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 126–127why, one step back126127replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 128why, one step back128@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 129–135why, one step back129async 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!"134135replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 136why, one step back136@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 137–143why, one step back137async 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 == ""142143replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 144why, one step back144@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 145–150why, one step back145async def test_put(server):146 async with httpx.AsyncClient() as client:147 response = await client.put(server.url, content=b"Hello, world!")148 assert response.status_code == 200149150replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 151why, one step back151@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 152–157why, one step back152async def test_patch(server):153 async with httpx.AsyncClient() as client:154 response = await client.patch(server.url, content=b"Hello, world!")155 assert response.status_code == 200156157replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 158why, one step back158@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 159–165why, one step back159async 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!"164165replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 166why, one step back166@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 167–179why, one step back167async def test_100_continue(server):168 headers = {"Expect": "100-continue"}169 content = b"Echo request body"170171 async with httpx.AsyncClient() as client:172 response = await client.post(173 server.url.copy_with(path="/echo_body"), headers=headers, content=content174 )175176 assert response.status_code == 200177 assert response.content == content178179replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 180why, one step back180@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 181–182why, one step back181async def test_context_managed_transport():182 class Transport(httpx.AsyncBaseTransport):Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
lines 183–184why, one step back183 def __init__(self) -> None:184 self.events: typing.List[str] = []Replace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 185–211why, one step back185186 async def aclose(self):187 # The base implementation of httpx.AsyncBaseTransport just188 # 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()202 async with httpx.AsyncClient(transport=transport):203 pass204205 assert transport.events == [206 "transport.__aenter__",207 "transport.aclose",208 "transport.__aexit__",209 ]210211replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 212why, one step back212@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 213–214why, one step back213async def test_context_managed_transport_and_mount():214 class Transport(httpx.AsyncBaseTransport):add missing type hints to __init__(...) (#2938)Petr Belskiybefore adoption87f39f1
line 215why, one step back215 def __init__(self, name: str) -> None:Replace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 216–256why, one step back216 self.name: str = name217 self.events: typing.List[str] = []218219 async def aclose(self):220 # The base implementation of httpx.AsyncBaseTransport just221 # 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 ]251252253def hello_world(request):254 return httpx.Response(200, text="Hello, world!")255256replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 257why, one step back257@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 258–274why, one step back258async def test_client_closed_state_using_implicit_open():259 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))260261 assert not client.is_closed262 await client.get("http://example.com")263264 assert not client.is_closed265 await client.aclose()266267 assert client.is_closed268 # Once we're close we cannot make any more requests.269 with pytest.raises(RuntimeError):270 await client.get("http://example.com")271272 # Once we're closed we cannot reopen the client.273 with pytest.raises(RuntimeError):274 async with client:use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
line 275why, one step back275 pass # pragma: no coverReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 276–277why, one step back276277replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 278why, one step back278@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 279–298why, one step back279async def test_client_closed_state_using_with_block():280 async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:281 assert not client.is_closed282 await client.get("http://example.com")283284 assert client.is_closed285 with pytest.raises(RuntimeError):286 await client.get("http://example.com")287288289def unmounted(request: httpx.Request) -> httpx.Response:290 data = {"app": "unmounted"}291 return httpx.Response(200, json=data)292293294def mounted(request: httpx.Request) -> httpx.Response:295 data = {"app": "mounted"}296 return httpx.Response(200, json=data)297298replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 299why, one step back299@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 300–313why, one step back300async def test_mounted_transport():301 transport = httpx.MockTransport(unmounted)302 mounts = {"custom://": httpx.MockTransport(mounted)}303304 async with httpx.AsyncClient(transport=transport, mounts=mounts) as client:305 response = await client.get("https://www.example.com")306 assert response.status_code == 200307 assert response.json() == {"app": "unmounted"}308309 response = await client.get("custom://www.example.com")310 assert response.status_code == 200311 assert response.json() == {"app": "mounted"}312313replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 314why, one step back314@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
line 315why, one step back315async def test_async_mock_transport():fix type annotation for MockTransport (#2581)Adrian Garcia Badaraccobefore adoptionf0fd919
line 316why, one step back316 async def hello_world(request: httpx.Request) -> httpx.Response:Replace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 317–326why, one step back317 return httpx.Response(200, text="Hello, world!")318319 transport = httpx.MockTransport(hello_world)320321 async with httpx.AsyncClient(transport=transport) as client:322 response = await client.get("https://www.example.com")323 assert response.status_code == 200324 assert response.text == "Hello, world!"325326replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 327why, one step back327@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 328–348why, one step back328async def test_cancellation_during_stream():329 """330 If any BaseException is raised during streaming the response, then the331 stream should be closed.332333 This includes:334335 * `asyncio.CancelledError` (A subclass of BaseException from Python 3.8 onwards.)336 * `trio.Cancelled`337 * `KeyboardInterrupt`338 * `SystemExit`339340 See https://github.com/encode/httpx/issues/2139341 """342 stream_was_closed = False343344 def response_with_cancel_during_stream(request):345 class CancelledStream(httpx.AsyncByteStream):346 async def __aiter__(self) -> typing.AsyncIterator[bytes]:347 yield b"Hello"348 raise KeyboardInterrupt()use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
line 349why, one step back349 yield b", world" # pragma: no coverReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 350–366why, one step back350351 async def aclose(self) -> None:352 nonlocal stream_was_closed353 stream_was_closed = True354355 return httpx.Response(356 200, headers={"Content-Length": "12"}, stream=CancelledStream()357 )358359 transport = httpx.MockTransport(response_with_cancel_during_stream)360361 async with httpx.AsyncClient(transport=transport) as client:362 with pytest.raises(KeyboardInterrupt):363 await client.get("https://www.example.com")364 assert stream_was_closed365366replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 367why, one step back367@pytest.mark.anyioReplace `black` Python target version from 3.6 to 3.7 (#2343)Marcelo Trylesinskibefore adoptiona754e71
lines 368–373why, one step back368async def test_server_extensions(server):369 url = server.url370 async with httpx.AsyncClient(http2=True) as client:371 response = await client.get(url)372 assert response.status_code == 200373 assert response.extensions["http_version"] == b"HTTP/1.1"