Skip to content
Myr

test_async_client.py

This file

Path

tests/client/test_async_client.py

375 lines · 11.4 KiB · Python

Last changed by

Use `__future__.annotations` (#3068)Kar Petrosyanbefore adoption371b6e9

History of this file

Take it

The walk stopped after 200 commits: lines older than deb904d point at it.

Use `__future__.annotations` (#3068)Kar Petrosyanbefore adoption371b6e9

lines 1–2why, one step back
1from __future__ import annotations
2

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 3–10why, one step back
3import typing
4from datetime import timedelta56import pytest78import httpx910

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 11why, one step back
11@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 12–31why, one step back
12async def test_get(server):
13 url = server.url14 async with httpx.AsyncClient(http2=True) as client:15 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)222324@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)

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 32why, one step back
32@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 33–38why, one step back
33async def test_get_invalid_url(server, url):
34 async with httpx.AsyncClient() as client:35 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):36 await client.get(url)3738

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 39why, one step back
39@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 40–53why, one step back
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"5253

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 54why, one step back
54@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 55–61why, one step back
55async def test_post(server):
56 url = server.url57 async with httpx.AsyncClient() as client:58 response = await client.post(url, content=b"Hello, world!")59 assert response.status_code == 2006061

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 62why, one step back
62@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 63–69why, one step back
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 == 2006869

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 70why, one step back
70@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 71–80why, one step back
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!"7980

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 81why, one step back
81@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 82–88why, one step back
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):

Use ruff instead of flake8, autoflake and isort (#2648)Marcelo Trylesinskibefore adoptiondaec2bd

line 89why, one step back
89 response.content # noqa: B018

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 90–91why, one step back
90
91

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 92why, one step back
92@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

line 93why, one step back
93async def test_stream_request(server):

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 94why, one step back
94 async def hello_world() -> typing.AsyncIterator[bytes]:

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 95–102why, one step back
95 yield b"Hello, "
96 yield b"world!"9798 async with httpx.AsyncClient() as client:99 response = await client.post(server.url, content=hello_world())100 assert response.status_code == 200101102

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 103why, one step back
103@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

line 104why, one step back
104async def test_cannot_stream_sync_request(server):

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 105why, one step back
105 def hello_world() -> typing.Iterator[bytes]: # pragma: no cover

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 106–113why, one step back
106 yield b"Hello, "
107 yield b"world!"108109 async with httpx.AsyncClient() as client:110 with pytest.raises(RuntimeError):111 await client.post(server.url, content=hello_world())112113

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 114why, one step back
114@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 115–126why, one step back
115async def test_raise_for_status(server):
116 async with httpx.AsyncClient() as client:117 for status_code in (200, 400, 404, 500, 505):118 response = await client.request(119 "GET", server.url.copy_with(path=f"/status/{status_code}")120 )121122 if 400 <= status_code < 600:123 with pytest.raises(httpx.HTTPStatusError) as exc_info:124 response.raise_for_status()125 assert exc_info.value.response == response126 else:

Make `raise_for_status` chainable (#2776)Trim21before adoption9415af6

line 127why, one step back
127 assert response.raise_for_status() is response

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 128–129why, one step back
128
129

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 130why, one step back
130@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 131–137why, one step back
131async def test_options(server):
132 async with httpx.AsyncClient() as client:133 response = await client.options(server.url)134 assert response.status_code == 200135 assert response.text == "Hello, world!"136137

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 138why, one step back
138@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 139–145why, one step back
139async def test_head(server):
140 async with httpx.AsyncClient() as client:141 response = await client.head(server.url)142 assert response.status_code == 200143 assert response.text == ""144145

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 146why, one step back
146@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 147–152why, one step back
147async def test_put(server):
148 async with httpx.AsyncClient() as client:149 response = await client.put(server.url, content=b"Hello, world!")150 assert response.status_code == 200151152

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 153why, one step back
153@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 154–159why, one step back
154async def test_patch(server):
155 async with httpx.AsyncClient() as client:156 response = await client.patch(server.url, content=b"Hello, world!")157 assert response.status_code == 200158159

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 160why, one step back
160@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 161–167why, one step back
161async def test_delete(server):
162 async with httpx.AsyncClient() as client:163 response = await client.delete(server.url)164 assert response.status_code == 200165 assert response.text == "Hello, world!"166167

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 168why, one step back
168@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 169–181why, one step back
169async def test_100_continue(server):
170 headers = {"Expect": "100-continue"}171 content = b"Echo request body"172173 async with httpx.AsyncClient() as client:174 response = await client.post(175 server.url.copy_with(path="/echo_body"), headers=headers, content=content176 )177178 assert response.status_code == 200179 assert response.content == content180181

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 182why, one step back
182@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 183–184why, one step back
183async def test_context_managed_transport():
184 class Transport(httpx.AsyncBaseTransport):

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 185why, one step back
185 def __init__(self) -> None:

Use `__future__.annotations` (#3068)Kar Petrosyanbefore adoption371b6e9

line 186why, one step back
186 self.events: list[str] = []

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 187–213why, one step back
187
188 async def aclose(self):189 # The base implementation of httpx.AsyncBaseTransport just190 # calls into `.aclose`, so simple transport cases can just override191 # this method for any cleanup, where more complex cases192 # might want to additionally override `__aenter__`/`__aexit__`.193 self.events.append("transport.aclose")194195 async def __aenter__(self):196 await super().__aenter__()197 self.events.append("transport.__aenter__")198199 async def __aexit__(self, *args):200 await super().__aexit__(*args)201 self.events.append("transport.__aexit__")202203 transport = Transport()204 async with httpx.AsyncClient(transport=transport):205 pass206207 assert transport.events == [208 "transport.__aenter__",209 "transport.aclose",210 "transport.__aexit__",211 ]212213

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 214why, one step back
214@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 215–216why, one step back
215async def test_context_managed_transport_and_mount():
216 class Transport(httpx.AsyncBaseTransport):

add missing type hints to __init__(...) (#2938)Petr Belskiybefore adoption87f39f1

line 217why, one step back
217 def __init__(self, name: str) -> None:

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

line 218why, one step back
218 self.name: str = name

Use `__future__.annotations` (#3068)Kar Petrosyanbefore adoption371b6e9

line 219why, one step back
219 self.events: list[str] = []

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 220–258why, one step back
220
221 async def aclose(self):222 # The base implementation of httpx.AsyncBaseTransport just223 # calls into `.aclose`, so simple transport cases can just override224 # this method for any cleanup, where more complex cases225 # might want to additionally override `__aenter__`/`__aexit__`.226 self.events.append(f"{self.name}.aclose")227228 async def __aenter__(self):229 await super().__aenter__()230 self.events.append(f"{self.name}.__aenter__")231232 async def __aexit__(self, *args):233 await super().__aexit__(*args)234 self.events.append(f"{self.name}.__aexit__")235236 transport = Transport(name="transport")237 mounted = Transport(name="mounted")238 async with httpx.AsyncClient(239 transport=transport, mounts={"http://www.example.org": mounted}240 ):241 pass242243 assert transport.events == [244 "transport.__aenter__",245 "transport.aclose",246 "transport.__aexit__",247 ]248 assert mounted.events == [249 "mounted.__aenter__",250 "mounted.aclose",251 "mounted.__aexit__",252 ]253254255def hello_world(request):256 return httpx.Response(200, text="Hello, world!")257258

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 259why, one step back
259@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 260–276why, one step back
260async def test_client_closed_state_using_implicit_open():
261 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))262263 assert not client.is_closed264 await client.get("http://example.com")265266 assert not client.is_closed267 await client.aclose()268269 assert client.is_closed270 # Once we're close we cannot make any more requests.271 with pytest.raises(RuntimeError):272 await client.get("http://example.com")273274 # Once we're closed we cannot reopen the client.275 with pytest.raises(RuntimeError):276 async with client:

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 277why, one step back
277 pass # pragma: no cover

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 278–279why, one step back
278
279

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 280why, one step back
280@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 281–300why, one step back
281async def test_client_closed_state_using_with_block():
282 async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:283 assert not client.is_closed284 await client.get("http://example.com")285286 assert client.is_closed287 with pytest.raises(RuntimeError):288 await client.get("http://example.com")289290291def unmounted(request: httpx.Request) -> httpx.Response:292 data = {"app": "unmounted"}293 return httpx.Response(200, json=data)294295296def mounted(request: httpx.Request) -> httpx.Response:297 data = {"app": "mounted"}298 return httpx.Response(200, json=data)299300

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 301why, one step back
301@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 302–315why, one step back
302async def test_mounted_transport():
303 transport = httpx.MockTransport(unmounted)304 mounts = {"custom://": httpx.MockTransport(mounted)}305306 async with httpx.AsyncClient(transport=transport, mounts=mounts) as client:307 response = await client.get("https://www.example.com")308 assert response.status_code == 200309 assert response.json() == {"app": "unmounted"}310311 response = await client.get("custom://www.example.com")312 assert response.status_code == 200313 assert response.json() == {"app": "mounted"}314315

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 316why, one step back
316@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

line 317why, one step back
317async def test_async_mock_transport():

fix type annotation for MockTransport (#2581)Adrian Garcia Badaraccobefore adoptionf0fd919

line 318why, one step back
318 async def hello_world(request: httpx.Request) -> httpx.Response:

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 319–328why, one step back
319 return httpx.Response(200, text="Hello, world!")
320321 transport = httpx.MockTransport(hello_world)322323 async with httpx.AsyncClient(transport=transport) as client:324 response = await client.get("https://www.example.com")325 assert response.status_code == 200326 assert response.text == "Hello, world!"327328

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 329why, one step back
329@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 330–350why, one step back
330async def test_cancellation_during_stream():
331 """332 If any BaseException is raised during streaming the response, then the333 stream should be closed.334335 This includes:336337 * `asyncio.CancelledError` (A subclass of BaseException from Python 3.8 onwards.)338 * `trio.Cancelled`339 * `KeyboardInterrupt`340 * `SystemExit`341342 See https://github.com/encode/httpx/issues/2139343 """344 stream_was_closed = False345346 def response_with_cancel_during_stream(request):347 class CancelledStream(httpx.AsyncByteStream):348 async def __aiter__(self) -> typing.AsyncIterator[bytes]:349 yield b"Hello"350 raise KeyboardInterrupt()

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 351why, one step back
351 yield b", world" # pragma: no cover

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 352–368why, one step back
352
353 async def aclose(self) -> None:354 nonlocal stream_was_closed355 stream_was_closed = True356357 return httpx.Response(358 200, headers={"Content-Length": "12"}, stream=CancelledStream()359 )360361 transport = httpx.MockTransport(response_with_cancel_during_stream)362363 async with httpx.AsyncClient(transport=transport) as client:364 with pytest.raises(KeyboardInterrupt):365 await client.get("https://www.example.com")366 assert stream_was_closed367368

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 369why, one step back
369@pytest.mark.anyio

remove `chunk_size` from api docs for `iter_lines` variants (#2464)Simon Kbefore adoptiondeb904d

lines 370–375why, one step back
370async def test_server_extensions(server):
371 url = server.url372 async with httpx.AsyncClient(http2=True) as client:373 response = await client.get(url)374 assert response.status_code == 200375 assert response.extensions["http_version"] == b"HTTP/1.1"