test_async_client.py
This file
Path
tests/client/test_async_client.py
304 lines · 9.7 KiB · Python
Last changed by
Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
History of this fileTake it
The walk stopped after 200 commits: lines older than 620b067 point at it.
Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 1why, one step back1import typingIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 2–3why, one step back2from datetime import timedelta3Context managed transports (#1218)Tom Christiebefore adoption534400e
line 4why, one step back4import httpcoreIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 5–7why, one step back5import pytest67import httpxTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 8why, one step back8from tests.utils import MockTransportIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 9–13why, one step back91011@pytest.mark.usefixtures("async_environment")12async def test_get(server):13 url = server.urlHTTP/2 becomes fully optional (#1140)Tom Christiebefore adoption8d9dfb5
line 14why, one step back14 async with httpx.AsyncClient(http2=True) as client:Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 15–23why, one step back15 response = await client.get(url)16 assert response.status_code == 20017 assert response.text == "Hello, world!"18 assert response.http_version == "HTTP/1.1"19 assert response.headers20 assert repr(response) == "<Response [200 OK]>"21 assert response.elapsed > timedelta(seconds=0)2223Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef
lines 24–31why, one step back24@pytest.mark.parametrize(25 "url",26 [27 pytest.param("invalid://example.org", id="scheme-not-http(s)"),28 pytest.param("://example.org", id="no-scheme"),29 pytest.param("http://", id="no-host"),30 ],31)Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 32why, one step back32@pytest.mark.usefixtures("async_environment")Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef
line 33why, one step back33async def test_get_invalid_url(server, url):Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 34why, one step back34 async with httpx.AsyncClient() as client:Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722
line 35why, one step back35 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef
line 36why, one step back36 await client.get(url)Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 37–57why, one step back373839@pytest.mark.usefixtures("async_environment")40async def test_build_request(server):41 url = server.url.copy_with(path="/echo_headers")42 headers = {"Custom-header": "value"}43 async with httpx.AsyncClient() as client:44 request = client.build_request("GET", url)45 request.headers.update(headers)46 response = await client.send(request)4748 assert response.status_code == 20049 assert response.url == url5051 assert response.json()["Custom-header"] == "value"525354@pytest.mark.usefixtures("async_environment")55async def test_post(server):56 url = server.url57 async with httpx.AsyncClient() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 58why, one step back58 response = await client.post(url, content=b"Hello, world!")Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 59–98why, one step back59 assert response.status_code == 200606162@pytest.mark.usefixtures("async_environment")63async def test_post_json(server):64 url = server.url65 async with httpx.AsyncClient() as client:66 response = await client.post(url, json={"text": "Hello, world!"})67 assert response.status_code == 200686970@pytest.mark.usefixtures("async_environment")71async def test_stream_response(server):72 async with httpx.AsyncClient() as client:73 async with client.stream("GET", server.url) as response:74 body = await response.aread()7576 assert response.status_code == 20077 assert body == b"Hello, world!"78 assert response.content == b"Hello, world!"798081@pytest.mark.usefixtures("async_environment")82async def test_access_content_stream_response(server):83 async with httpx.AsyncClient() as client:84 async with client.stream("GET", server.url) as response:85 pass8687 assert response.status_code == 20088 with pytest.raises(httpx.ResponseNotRead):89 response.content909192@pytest.mark.usefixtures("async_environment")93async def test_stream_request(server):94 async def hello_world():95 yield b"Hello, "96 yield b"world!"9798 async with httpx.AsyncClient() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 99why, one step back99 response = await client.request("POST", server.url, content=hello_world())Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 100–111why, one step back100 assert response.status_code == 200101102103@pytest.mark.usefixtures("async_environment")104async def test_raise_for_status(server):105 async with httpx.AsyncClient() as client:106 for status_code in (200, 400, 404, 500, 505):107 response = await client.request(108 "GET", server.url.copy_with(path=f"/status/{status_code}")109 )110111 if 400 <= status_code < 600:Raise HTTPStatusError in raise_from_status (#1072)François Voronbefore adoption27b0dbc
line 112why, one step back112 with pytest.raises(httpx.HTTPStatusError) as exc_info:Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 113–137why, one step back113 response.raise_for_status()114 assert exc_info.value.response == response115 else:116 assert response.raise_for_status() is None # type: ignore117118119@pytest.mark.usefixtures("async_environment")120async def test_options(server):121 async with httpx.AsyncClient() as client:122 response = await client.options(server.url)123 assert response.status_code == 200124 assert response.text == "Hello, world!"125126127@pytest.mark.usefixtures("async_environment")128async def test_head(server):129 async with httpx.AsyncClient() as client:130 response = await client.head(server.url)131 assert response.status_code == 200132 assert response.text == ""133134135@pytest.mark.usefixtures("async_environment")136async def test_put(server):137 async with httpx.AsyncClient() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 138why, one step back138 response = await client.put(server.url, content=b"Hello, world!")Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 139–144why, one step back139 assert response.status_code == 200140141142@pytest.mark.usefixtures("async_environment")143async def test_patch(server):144 async with httpx.AsyncClient() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 145why, one step back145 response = await client.patch(server.url, content=b"Hello, world!")Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 146–159why, one step back146 assert response.status_code == 200147148149@pytest.mark.usefixtures("async_environment")150async def test_delete(server):151 async with httpx.AsyncClient() as client:152 response = await client.delete(server.url)153 assert response.status_code == 200154 assert response.text == "Hello, world!"155156157@pytest.mark.usefixtures("async_environment")158async def test_100_continue(server):159 headers = {"Expect": "100-continue"}Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 160why, one step back160 content = b"Echo request body"Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 161–163why, one step back161162 async with httpx.AsyncClient() as client:163 response = await client.post(Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 164why, one step back164 server.url.copy_with(path="/echo_body"), headers=headers, content=contentIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 165–167why, one step back165 )166167 assert response.status_code == 200Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 168why, one step back168 assert response.content == contentContext managed transports (#1218)Tom Christiebefore adoption534400e
lines 169–192why, one step back169170171@pytest.mark.usefixtures("async_environment")172async def test_context_managed_transport():173 class Transport(httpcore.AsyncHTTPTransport):174 def __init__(self):175 self.events = []176177 async def aclose(self):178 # The base implementation of httpcore.AsyncHTTPTransport just179 # calls into `.aclose`, so simple transport cases can just override180 # this method for any cleanup, where more complex cases181 # might want to additionally override `__aenter__`/`__aexit__`.182 self.events.append("transport.aclose")183184 async def __aenter__(self):185 await super().__aenter__()186 self.events.append("transport.__aenter__")187188 async def __aexit__(self, *args):189 await super().__aexit__(*args)190 self.events.append("transport.__aexit__")191192 transport = Transport()Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 193why, one step back193 async with httpx.AsyncClient(transport=transport):Context managed transports (#1218)Tom Christiebefore adoption534400e
lines 194–200why, one step back194 pass195196 assert transport.events == [197 "transport.__aenter__",198 "transport.aclose",199 "transport.__aexit__",200 ]Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 201–202why, one step back201202Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 203–243why, one step back203@pytest.mark.usefixtures("async_environment")204async def test_context_managed_transport_and_mount():205 class Transport(httpcore.AsyncHTTPTransport):206 def __init__(self, name: str):207 self.name: str = name208 self.events: typing.List[str] = []209210 async def aclose(self):211 # The base implementation of httpcore.AsyncHTTPTransport just212 # calls into `.aclose`, so simple transport cases can just override213 # this method for any cleanup, where more complex cases214 # might want to additionally override `__aenter__`/`__aexit__`.215 self.events.append(f"{self.name}.aclose")216217 async def __aenter__(self):218 await super().__aenter__()219 self.events.append(f"{self.name}.__aenter__")220221 async def __aexit__(self, *args):222 await super().__aexit__(*args)223 self.events.append(f"{self.name}.__aexit__")224225 transport = Transport(name="transport")226 mounted = Transport(name="mounted")227 async with httpx.AsyncClient(228 transport=transport, mounts={"http://www.example.org": mounted}229 ):230 pass231232 assert transport.events == [233 "transport.__aenter__",234 "transport.aclose",235 "transport.__aexit__",236 ]237 assert mounted.events == [238 "mounted.__aenter__",239 "mounted.aclose",240 "mounted.__aexit__",241 ]242243Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 244–245why, one step back244def hello_world(request):245 return httpx.Response(200, text="Hello, world!")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 246–248why, one step back246247248@pytest.mark.usefixtures("async_environment")Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 249–250why, one step back249async def test_client_closed_state_using_implicit_open():250 client = httpx.AsyncClient(transport=MockTransport(hello_world))Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 251why, one step back251Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 252why, one step back252 assert not client.is_closedIssue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 253–257why, one step back253 await client.get("http://example.com")254255 assert not client.is_closed256 await client.aclose()257Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 258–260why, one step back258 assert client.is_closed259 with pytest.raises(RuntimeError):260 await client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 261why, one step back261Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 262why, one step back262Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 263why, one step back263@pytest.mark.usefixtures("async_environment")Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 264–265why, one step back264async def test_client_closed_state_using_with_block():265 async with httpx.AsyncClient(transport=MockTransport(hello_world)) as client:Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 266why, one step back266 assert not client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 267why, one step back267 await client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 268–269why, one step back268269 assert client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 270–271why, one step back270 with pytest.raises(RuntimeError):271 await client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 272–274why, one step back272273274@pytest.mark.usefixtures("async_environment")Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 275–277why, one step back275async def test_deleting_unclosed_async_client_causes_warning():276 client = httpx.AsyncClient(transport=MockTransport(hello_world))277 await client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 278why, one step back278 with pytest.warns(UserWarning):Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 279why, one step back279 del clientAdd support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 280–304why, one step back280281282def unmounted(request: httpx.Request) -> httpx.Response:283 data = {"app": "unmounted"}284 return httpx.Response(200, json=data)285286287def mounted(request: httpx.Request) -> httpx.Response:288 data = {"app": "mounted"}289 return httpx.Response(200, json=data)290291292@pytest.mark.usefixtures("async_environment")293async def test_mounted_transport():294 transport = MockTransport(unmounted)295 mounts = {"custom://": MockTransport(mounted)}296297 async with httpx.AsyncClient(transport=transport, mounts=mounts) as client:298 response = await client.get("https://www.example.com")299 assert response.status_code == 200300 assert response.json() == {"app": "unmounted"}301302 response = await client.get("custom://www.example.com")303 assert response.status_code == 200304 assert response.json() == {"app": "mounted"}