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 fileTake it
1import typing2from 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:56 response = await client.post(url, content=b"Hello, world!")57 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:97 response = await client.request("POST", server.url, content=hello_world())98 assert response.status_code == 20099100101@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:136 response = await client.put(server.url, content=b"Hello, world!")137 assert response.status_code == 200138139140@pytest.mark.usefixtures("async_environment")141async def test_patch(server):142 async with httpx.AsyncClient() as client:143 response = await client.patch(server.url, content=b"Hello, world!")144 assert response.status_code == 200145146147@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"}158 content = b"Echo request body"159160 async with httpx.AsyncClient() as client:161 response = await client.post(162 server.url.copy_with(path="/echo_body"), headers=headers, content=content163 )164165 assert response.status_code == 200166 assert response.content == content167168169@pytest.mark.usefixtures("async_environment")170async def test_context_managed_transport():171 class Transport(httpx.AsyncBaseTransport):172 def __init__(self):173 self.events = []174175 async def aclose(self):176 # The base implementation of httpx.AsyncBaseTransport just177 # calls into `.aclose`, so simple transport cases can just override178 # 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()191 async with httpx.AsyncClient(transport=transport):192 pass193194 assert transport.events == [195 "transport.__aenter__",196 "transport.aclose",197 "transport.__aexit__",198 ]199200201@pytest.mark.usefixtures("async_environment")202async def test_context_managed_transport_and_mount():203 class Transport(httpx.AsyncBaseTransport):204 def __init__(self, name: str):205 self.name: str = name206 self.events: typing.List[str] = []207208 async def aclose(self):209 # The base implementation of httpx.AsyncBaseTransport just210 # calls into `.aclose`, so simple transport cases can just override211 # 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 ]240241242def hello_world(request):243 return httpx.Response(200, text="Hello, world!")244245246@pytest.mark.usefixtures("async_environment")247async def test_client_closed_state_using_implicit_open():248 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))249250 assert not client.is_closed251 await client.get("http://example.com")252253 assert not client.is_closed254 await client.aclose()255256 assert client.is_closed257 with pytest.raises(RuntimeError):258 await client.get("http://example.com")259260261@pytest.mark.usefixtures("async_environment")262async def test_client_closed_state_using_with_block():263 async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:264 assert not client.is_closed265 await client.get("http://example.com")266267 assert client.is_closed268 with pytest.raises(RuntimeError):269 await client.get("http://example.com")270271272@pytest.mark.usefixtures("async_environment")273async def test_deleting_unclosed_async_client_causes_warning():274 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))275 await client.get("http://example.com")276 with pytest.warns(UserWarning):277 del client278279280def 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():292 transport = httpx.MockTransport(unmounted)293 mounts = {"custom://": httpx.MockTransport(mounted)}294295 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"}303304305@pytest.mark.usefixtures("async_environment")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!"