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

1from __future__ import annotations23import typing4from datetime import timedelta56import pytest78import httpx91011@pytest.mark.anyio12async 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)32@pytest.mark.anyio33async 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)373839@pytest.mark.anyio40async 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.anyio55async 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 == 200606162@pytest.mark.anyio63async 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.anyio71async 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.anyio82async 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.content  # noqa: B018909192@pytest.mark.anyio93async def test_stream_request(server):94    async def hello_world() -> typing.AsyncIterator[bytes]: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 == 200101102103@pytest.mark.anyio104async def test_cannot_stream_sync_request(server):105    def hello_world() -> typing.Iterator[bytes]:  # pragma: no cover106        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())112113114@pytest.mark.anyio115async 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:127                assert response.raise_for_status() is response128129130@pytest.mark.anyio131async 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!"136137138@pytest.mark.anyio139async 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 == ""144145146@pytest.mark.anyio147async 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 == 200151152153@pytest.mark.anyio154async 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 == 200158159160@pytest.mark.anyio161async 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!"166167168@pytest.mark.anyio169async 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 == content180181182@pytest.mark.anyio183async def test_context_managed_transport():184    class Transport(httpx.AsyncBaseTransport):185        def __init__(self) -> None:186            self.events: list[str] = []187188        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    ]212213214@pytest.mark.anyio215async def test_context_managed_transport_and_mount():216    class Transport(httpx.AsyncBaseTransport):217        def __init__(self, name: str) -> None:218            self.name: str = name219            self.events: list[str] = []220221        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!")257258259@pytest.mark.anyio260async 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:277            pass  # pragma: no cover278279280@pytest.mark.anyio281async 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)299300301@pytest.mark.anyio302async 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"}314315316@pytest.mark.anyio317async def test_async_mock_transport():318    async def hello_world(request: httpx.Request) -> httpx.Response: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!"327328329@pytest.mark.anyio330async 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()351                yield b", world"  # pragma: no cover352353            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_closed367368369@pytest.mark.anyio370async 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"