test_async_client.py
This file
Path
tests/client/test_async_client.py
335 lines · 10.8 KiB · Python
Last changed by
map_exceptions in request.aclose() (#1465)Adam Hooperbefore adoption0f280af
History of this fileTake it
The walk stopped after 200 commits: lines older than 330a825 point at it.
Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 1why, one step back1import typingPin isort version (#1053)Josep Cugatbefore adoption330a825
lines 2–3why, one step back2from datetime import timedelta3Context managed transports (#1218)Tom Christiebefore adoption534400e
line 4why, one step back4import httpcorePin isort version (#1053)Josep Cugatbefore adoption330a825
lines 5–12why, one step back5import pytest67import httpx8910@pytest.mark.usefixtures("async_environment")11async def test_get(server):12 url = server.urlHTTP/2 becomes fully optional (#1140)Tom Christiebefore adoption8d9dfb5
line 13why, one step back13 async with httpx.AsyncClient(http2=True) as client:Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 14–22why, one step back14 response = await client.get(url)15 assert response.status_code == 20016 assert response.text == "Hello, world!"17 assert response.http_version == "HTTP/1.1"18 assert response.headers19 assert repr(response) == "<Response [200 OK]>"20 assert response.elapsed > timedelta(seconds=0)2122Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef
lines 23–30why, one step back23@pytest.mark.parametrize(24 "url",25 [26 pytest.param("invalid://example.org", id="scheme-not-http(s)"),27 pytest.param("://example.org", id="no-scheme"),28 pytest.param("http://", id="no-host"),29 ],30)Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 31why, one step back31@pytest.mark.usefixtures("async_environment")Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef
line 32why, one step back32async def test_get_invalid_url(server, url):Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 33why, one step back33 async with httpx.AsyncClient() as client:Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722
line 34why, one step back34 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef
line 35why, one step back35 await client.get(url)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 36–56why, one step back363738@pytest.mark.usefixtures("async_environment")39async def test_build_request(server):40 url = server.url.copy_with(path="/echo_headers")41 headers = {"Custom-header": "value"}42 async with httpx.AsyncClient() as client:43 request = client.build_request("GET", url)44 request.headers.update(headers)45 response = await client.send(request)4647 assert response.status_code == 20048 assert response.url == url4950 assert response.json()["Custom-header"] == "value"515253@pytest.mark.usefixtures("async_environment")54async def test_post(server):55 url = server.url56 async with httpx.AsyncClient() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 57why, one step back57 response = await client.post(url, content=b"Hello, world!")Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 58–97why, one step back58 assert response.status_code == 200596061@pytest.mark.usefixtures("async_environment")62async def test_post_json(server):63 url = server.url64 async with httpx.AsyncClient() as client:65 response = await client.post(url, json={"text": "Hello, world!"})66 assert response.status_code == 200676869@pytest.mark.usefixtures("async_environment")70async def test_stream_response(server):71 async with httpx.AsyncClient() as client:72 async with client.stream("GET", server.url) as response:73 body = await response.aread()7475 assert response.status_code == 20076 assert body == b"Hello, world!"77 assert response.content == b"Hello, world!"787980@pytest.mark.usefixtures("async_environment")81async def test_access_content_stream_response(server):82 async with httpx.AsyncClient() as client:83 async with client.stream("GET", server.url) as response:84 pass8586 assert response.status_code == 20087 with pytest.raises(httpx.ResponseNotRead):88 response.content899091@pytest.mark.usefixtures("async_environment")92async def test_stream_request(server):93 async def hello_world():94 yield b"Hello, "95 yield b"world!"9697 async with httpx.AsyncClient() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 98why, one step back98 response = await client.request("POST", server.url, content=hello_world())Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 99–110why, one step back99 assert response.status_code == 200100101102@pytest.mark.usefixtures("async_environment")103async def test_raise_for_status(server):104 async with httpx.AsyncClient() as client:105 for status_code in (200, 400, 404, 500, 505):106 response = await client.request(107 "GET", server.url.copy_with(path=f"/status/{status_code}")108 )109110 if 400 <= status_code < 600:Raise HTTPStatusError in raise_from_status (#1072)François Voronbefore adoption27b0dbc
line 111why, one step back111 with pytest.raises(httpx.HTTPStatusError) as exc_info:Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 112–136why, one step back112 response.raise_for_status()113 assert exc_info.value.response == response114 else:115 assert response.raise_for_status() is None # type: ignore116117118@pytest.mark.usefixtures("async_environment")119async def test_options(server):120 async with httpx.AsyncClient() as client:121 response = await client.options(server.url)122 assert response.status_code == 200123 assert response.text == "Hello, world!"124125126@pytest.mark.usefixtures("async_environment")127async def test_head(server):128 async with httpx.AsyncClient() as client:129 response = await client.head(server.url)130 assert response.status_code == 200131 assert response.text == ""132133134@pytest.mark.usefixtures("async_environment")135async def test_put(server):136 async with httpx.AsyncClient() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 137why, one step back137 response = await client.put(server.url, content=b"Hello, world!")Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 138–143why, one step back138 assert response.status_code == 200139140141@pytest.mark.usefixtures("async_environment")142async def test_patch(server):143 async with httpx.AsyncClient() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 144why, one step back144 response = await client.patch(server.url, content=b"Hello, world!")Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 145–158why, one step back145 assert response.status_code == 200146147148@pytest.mark.usefixtures("async_environment")149async def test_delete(server):150 async with httpx.AsyncClient() as client:151 response = await client.delete(server.url)152 assert response.status_code == 200153 assert response.text == "Hello, world!"154155156@pytest.mark.usefixtures("async_environment")157async def test_100_continue(server):158 headers = {"Expect": "100-continue"}Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 159why, one step back159 content = b"Echo request body"Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 160–162why, one step back160161 async with httpx.AsyncClient() as client:162 response = await client.post(Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 163why, one step back163 server.url.copy_with(path="/echo_body"), headers=headers, content=contentPin isort version (#1053)Josep Cugatbefore adoption330a825
lines 164–166why, one step back164 )165166 assert response.status_code == 200Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 167why, one step back167 assert response.content == contentContext managed transports (#1218)Tom Christiebefore adoption534400e
lines 168–191why, one step back168169170@pytest.mark.usefixtures("async_environment")171async def test_context_managed_transport():172 class Transport(httpcore.AsyncHTTPTransport):173 def __init__(self):174 self.events = []175176 async def aclose(self):177 # The base implementation of httpcore.AsyncHTTPTransport just178 # calls into `.aclose`, so simple transport cases can just override179 # this method for any cleanup, where more complex cases180 # might want to additionally override `__aenter__`/`__aexit__`.181 self.events.append("transport.aclose")182183 async def __aenter__(self):184 await super().__aenter__()185 self.events.append("transport.__aenter__")186187 async def __aexit__(self, *args):188 await super().__aexit__(*args)189 self.events.append("transport.__aexit__")190191 transport = Transport()Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 192why, one step back192 async with httpx.AsyncClient(transport=transport):Context managed transports (#1218)Tom Christiebefore adoption534400e
lines 193–199why, one step back193 pass194195 assert transport.events == [196 "transport.__aenter__",197 "transport.aclose",198 "transport.__aexit__",199 ]Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 200–201why, one step back200201Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 202–242why, one step back202@pytest.mark.usefixtures("async_environment")203async def test_context_managed_transport_and_mount():204 class Transport(httpcore.AsyncHTTPTransport):205 def __init__(self, name: str):206 self.name: str = name207 self.events: typing.List[str] = []208209 async def aclose(self):210 # The base implementation of httpcore.AsyncHTTPTransport just211 # calls into `.aclose`, so simple transport cases can just override212 # this method for any cleanup, where more complex cases213 # might want to additionally override `__aenter__`/`__aexit__`.214 self.events.append(f"{self.name}.aclose")215216 async def __aenter__(self):217 await super().__aenter__()218 self.events.append(f"{self.name}.__aenter__")219220 async def __aexit__(self, *args):221 await super().__aexit__(*args)222 self.events.append(f"{self.name}.__aexit__")223224 transport = Transport(name="transport")225 mounted = Transport(name="mounted")226 async with httpx.AsyncClient(227 transport=transport, mounts={"http://www.example.org": mounted}228 ):229 pass230231 assert transport.events == [232 "transport.__aenter__",233 "transport.aclose",234 "transport.__aexit__",235 ]236 assert mounted.events == [237 "mounted.__aenter__",238 "mounted.aclose",239 "mounted.__aexit__",240 ]241242Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 243–244why, one step back243def hello_world(request):244 return httpx.Response(200, text="Hello, world!")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 245–247why, one step back245246247@pytest.mark.usefixtures("async_environment")Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 248why, one step back248async def test_client_closed_state_using_implicit_open():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 249why, one step back249 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 250why, one step back250Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 251why, one step back251 assert not client.is_closedIssue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 252–256why, one step back252 await client.get("http://example.com")253254 assert not client.is_closed255 await client.aclose()256Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 257–259why, one step back257 assert client.is_closed258 with pytest.raises(RuntimeError):259 await client.get("http://example.com")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 back261Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 262why, one step back262@pytest.mark.usefixtures("async_environment")Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 263why, one step back263async def test_client_closed_state_using_with_block():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 264why, one step back264 async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 265why, one step back265 assert not client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 266why, one step back266 await client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 267–268why, one step back267268 assert client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 269–270why, one step back269 with pytest.raises(RuntimeError):270 await client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 271–273why, one step back271272273@pytest.mark.usefixtures("async_environment")Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 274why, one step back274async def test_deleting_unclosed_async_client_causes_warning():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 275why, one step back275 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))Tighten 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
line 277why, one step back277 with pytest.warns(UserWarning):Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 278why, one step back278 del clientAdd support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 279–292why, one step back279280281def unmounted(request: httpx.Request) -> httpx.Response:282 data = {"app": "unmounted"}283 return httpx.Response(200, json=data)284285286def mounted(request: httpx.Request) -> httpx.Response:287 data = {"app": "mounted"}288 return httpx.Response(200, json=data)289290291@pytest.mark.usefixtures("async_environment")292async def test_mounted_transport():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 293–294why, one step back293 transport = httpx.MockTransport(unmounted)294 mounts = {"custom://": httpx.MockTransport(mounted)}Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 295–303why, one step back295296 async with httpx.AsyncClient(transport=transport, mounts=mounts) as client:297 response = await client.get("https://www.example.com")298 assert response.status_code == 200299 assert response.json() == {"app": "unmounted"}300301 response = await client.get("custom://www.example.com")302 assert response.status_code == 200303 assert response.json() == {"app": "mounted"}Allow handler to optionally be async when MockTransport is used with AsyncClient (#1449)Tom Christiebefore adoption084f356
lines 304–306why, one step back304305306@pytest.mark.usefixtures("async_environment")map_exceptions in request.aclose() (#1465)Adam Hooperbefore adoption0f280af
lines 307–325why, one step back307async def test_response_aclose_map_exceptions():308 class BrokenStream:309 async def __aiter__(self):310 # so we're an AsyncIterator311 pass # pragma: nocover312313 async def aclose(self):314 raise httpcore.CloseError(OSError(104, "Connection reset by peer"))315316 def handle(request: httpx.Request) -> httpx.Response:317 return httpx.Response(200, stream=BrokenStream())318319 async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client:320 async with client.stream("GET", "http://example.com") as response:321 with pytest.raises(httpx.CloseError):322 await response.aclose()323324325@pytest.mark.usefixtures("async_environment")Allow handler to optionally be async when MockTransport is used with AsyncClient (#1449)Tom Christiebefore adoption084f356
lines 326–335why, one step back326async def test_async_mock_transport():327 async def hello_world(request):328 return httpx.Response(200, text="Hello, world!")329330 transport = httpx.MockTransport(hello_world)331332 async with httpx.AsyncClient(transport=transport) as client:333 response = await client.get("https://www.example.com")334 assert response.status_code == 200335 assert response.text == "Hello, world!"