Skip to content
Myr

test_async_client.py

This file

Path

tests/client/test_async_client.py

303 lines · 9.6 KiB · Python

Last changed by

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

History of this file

Take 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 back
1import typing

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 2–3why, one step back
2from datetime import timedelta
3

Context managed transports (#1218)Tom Christiebefore adoption534400e

line 4why, one step back
4import httpcore

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 5–12why, one step back
5import pytest
67import httpx8910@pytest.mark.usefixtures("async_environment")11async def test_get(server):12 url = server.url

HTTP/2 becomes fully optional (#1140)Tom Christiebefore adoption8d9dfb5

line 13why, one step back
13 async with httpx.AsyncClient(http2=True) as client:

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 14–22why, one step back
14 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)2122

Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef

lines 23–30why, one step back
23@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 back
31@pytest.mark.usefixtures("async_environment")

Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef

line 32why, one step back
32async def test_get_invalid_url(server, url):

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 33why, one step back
33 async with httpx.AsyncClient() as client:

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

line 34why, one step back
34 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):

Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef

line 35why, one step back
35 await client.get(url)

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 36–56why, one step back
36
3738@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 back
57 response = await client.post(url, content=b"Hello, world!")

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 58–97why, one step back
58 assert response.status_code == 200
596061@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 back
98 response = await client.request("POST", server.url, content=hello_world())

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 99–110why, one step back
99 assert response.status_code == 200
100101102@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 back
111 with pytest.raises(httpx.HTTPStatusError) as exc_info:

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 112–136why, one step back
112 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 back
137 response = await client.put(server.url, content=b"Hello, world!")

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 138–143why, one step back
138 assert response.status_code == 200
139140141@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 back
144 response = await client.patch(server.url, content=b"Hello, world!")

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 145–158why, one step back
145 assert response.status_code == 200
146147148@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 back
159 content = b"Echo request body"

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 160–162why, one step back
160
161 async with httpx.AsyncClient() as client:162 response = await client.post(

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 163why, one step back
163 server.url.copy_with(path="/echo_body"), headers=headers, content=content

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 164–166why, one step back
164 )
165166 assert response.status_code == 200

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 167why, one step back
167 assert response.content == content

Context managed transports (#1218)Tom Christiebefore adoption534400e

lines 168–191why, one step back
168
169170@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 back
192 async with httpx.AsyncClient(transport=transport):

Context managed transports (#1218)Tom Christiebefore adoption534400e

lines 193–199why, one step back
193 pass
194195 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 back
200
201

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 202–242why, one step back
202@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 ]241242

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

lines 243–244why, one step back
243def hello_world(request):
244 return httpx.Response(200, text="Hello, world!")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 245–247why, one step back
245
246247@pytest.mark.usefixtures("async_environment")

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 248why, one step back
248async def test_client_closed_state_using_implicit_open():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 249why, one step back
249 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 250why, one step back
250

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 251why, one step back
251 assert not client.is_closed

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 252–256why, one step back
252 await client.get("http://example.com")
253254 assert not client.is_closed255 await client.aclose()256

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

lines 257–259why, one step back
257 assert client.is_closed
258 with pytest.raises(RuntimeError):259 await client.get("http://example.com")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 260why, one step back
260

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 261why, one step back
261

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 262why, one step back
262@pytest.mark.usefixtures("async_environment")

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 263why, one step back
263async def test_client_closed_state_using_with_block():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 264why, one step back
264 async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 265why, one step back
265 assert not client.is_closed

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 266why, one step back
266 await client.get("http://example.com")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 267–268why, one step back
267
268 assert client.is_closed

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

lines 269–270why, one step back
269 with pytest.raises(RuntimeError):
270 await client.get("http://example.com")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 271–273why, one step back
271
272273@pytest.mark.usefixtures("async_environment")

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 274why, one step back
274async def test_deleting_unclosed_async_client_causes_warning():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 275why, one step back
275 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 276why, one step back
276 await client.get("http://example.com")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 277why, one step back
277 with pytest.warns(UserWarning):

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 278why, one step back
278 del client

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 279–292why, one step back
279
280281def 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 back
293 transport = httpx.MockTransport(unmounted)
294 mounts = {"custom://": httpx.MockTransport(mounted)}

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 295–303why, one step back
295
296 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"}