Skip to content
Myr

test_async_client.py

This file

Path

tests/client/test_async_client.py

304 lines · 9.7 KiB · Python

Last changed by

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

History of this file

Take it

1import typing2from datetime import timedelta34import httpcore5import pytest67import httpx8from tests.utils import MockTransport91011@pytest.mark.usefixtures("async_environment")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)32@pytest.mark.usefixtures("async_environment")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)373839@pytest.mark.usefixtures("async_environment")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"525354@pytest.mark.usefixtures("async_environment")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 == 200606162@pytest.mark.usefixtures("async_environment")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 == 200686970@pytest.mark.usefixtures("async_environment")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!"798081@pytest.mark.usefixtures("async_environment")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):89        response.content909192@pytest.mark.usefixtures("async_environment")93async def test_stream_request(server):94    async def hello_world():95        yield b"Hello, "96        yield b"world!"9798    async with httpx.AsyncClient() as client:99        response = await client.request("POST", server.url, content=hello_world())100    assert response.status_code == 200101102103@pytest.mark.usefixtures("async_environment")104async def test_raise_for_status(server):105    async with httpx.AsyncClient() as client:106        for status_code in (200, 400, 404, 500, 505):107            response = await client.request(108                "GET", server.url.copy_with(path=f"/status/{status_code}")109            )110111            if 400 <= status_code < 600:112                with pytest.raises(httpx.HTTPStatusError) as exc_info:113                    response.raise_for_status()114                assert exc_info.value.response == response115            else:116                assert response.raise_for_status() is None  # type: ignore117118119@pytest.mark.usefixtures("async_environment")120async def test_options(server):121    async with httpx.AsyncClient() as client:122        response = await client.options(server.url)123    assert response.status_code == 200124    assert response.text == "Hello, world!"125126127@pytest.mark.usefixtures("async_environment")128async def test_head(server):129    async with httpx.AsyncClient() as client:130        response = await client.head(server.url)131    assert response.status_code == 200132    assert response.text == ""133134135@pytest.mark.usefixtures("async_environment")136async def test_put(server):137    async with httpx.AsyncClient() as client:138        response = await client.put(server.url, content=b"Hello, world!")139    assert response.status_code == 200140141142@pytest.mark.usefixtures("async_environment")143async def test_patch(server):144    async with httpx.AsyncClient() as client:145        response = await client.patch(server.url, content=b"Hello, world!")146    assert response.status_code == 200147148149@pytest.mark.usefixtures("async_environment")150async def test_delete(server):151    async with httpx.AsyncClient() as client:152        response = await client.delete(server.url)153    assert response.status_code == 200154    assert response.text == "Hello, world!"155156157@pytest.mark.usefixtures("async_environment")158async def test_100_continue(server):159    headers = {"Expect": "100-continue"}160    content = b"Echo request body"161162    async with httpx.AsyncClient() as client:163        response = await client.post(164            server.url.copy_with(path="/echo_body"), headers=headers, content=content165        )166167    assert response.status_code == 200168    assert response.content == content169170171@pytest.mark.usefixtures("async_environment")172async def test_context_managed_transport():173    class Transport(httpcore.AsyncHTTPTransport):174        def __init__(self):175            self.events = []176177        async def aclose(self):178            # The base implementation of httpcore.AsyncHTTPTransport just179            # calls into `.aclose`, so simple transport cases can just override180            # this method for any cleanup, where more complex cases181            # might want to additionally override `__aenter__`/`__aexit__`.182            self.events.append("transport.aclose")183184        async def __aenter__(self):185            await super().__aenter__()186            self.events.append("transport.__aenter__")187188        async def __aexit__(self, *args):189            await super().__aexit__(*args)190            self.events.append("transport.__aexit__")191192    transport = Transport()193    async with httpx.AsyncClient(transport=transport):194        pass195196    assert transport.events == [197        "transport.__aenter__",198        "transport.aclose",199        "transport.__aexit__",200    ]201202203@pytest.mark.usefixtures("async_environment")204async def test_context_managed_transport_and_mount():205    class Transport(httpcore.AsyncHTTPTransport):206        def __init__(self, name: str):207            self.name: str = name208            self.events: typing.List[str] = []209210        async def aclose(self):211            # The base implementation of httpcore.AsyncHTTPTransport just212            # calls into `.aclose`, so simple transport cases can just override213            # this method for any cleanup, where more complex cases214            # might want to additionally override `__aenter__`/`__aexit__`.215            self.events.append(f"{self.name}.aclose")216217        async def __aenter__(self):218            await super().__aenter__()219            self.events.append(f"{self.name}.__aenter__")220221        async def __aexit__(self, *args):222            await super().__aexit__(*args)223            self.events.append(f"{self.name}.__aexit__")224225    transport = Transport(name="transport")226    mounted = Transport(name="mounted")227    async with httpx.AsyncClient(228        transport=transport, mounts={"http://www.example.org": mounted}229    ):230        pass231232    assert transport.events == [233        "transport.__aenter__",234        "transport.aclose",235        "transport.__aexit__",236    ]237    assert mounted.events == [238        "mounted.__aenter__",239        "mounted.aclose",240        "mounted.__aexit__",241    ]242243244def hello_world(request):245    return httpx.Response(200, text="Hello, world!")246247248@pytest.mark.usefixtures("async_environment")249async def test_client_closed_state_using_implicit_open():250    client = httpx.AsyncClient(transport=MockTransport(hello_world))251252    assert not client.is_closed253    await client.get("http://example.com")254255    assert not client.is_closed256    await client.aclose()257258    assert client.is_closed259    with pytest.raises(RuntimeError):260        await client.get("http://example.com")261262263@pytest.mark.usefixtures("async_environment")264async def test_client_closed_state_using_with_block():265    async with httpx.AsyncClient(transport=MockTransport(hello_world)) as client:266        assert not client.is_closed267        await client.get("http://example.com")268269    assert client.is_closed270    with pytest.raises(RuntimeError):271        await client.get("http://example.com")272273274@pytest.mark.usefixtures("async_environment")275async def test_deleting_unclosed_async_client_causes_warning():276    client = httpx.AsyncClient(transport=MockTransport(hello_world))277    await client.get("http://example.com")278    with pytest.warns(UserWarning):279        del client280281282def unmounted(request: httpx.Request) -> httpx.Response:283    data = {"app": "unmounted"}284    return httpx.Response(200, json=data)285286287def mounted(request: httpx.Request) -> httpx.Response:288    data = {"app": "mounted"}289    return httpx.Response(200, json=data)290291292@pytest.mark.usefixtures("async_environment")293async def test_mounted_transport():294    transport = MockTransport(unmounted)295    mounts = {"custom://": MockTransport(mounted)}296297    async with httpx.AsyncClient(transport=transport, mounts=mounts) as client:298        response = await client.get("https://www.example.com")299        assert response.status_code == 200300        assert response.json() == {"app": "unmounted"}301302        response = await client.get("custom://www.example.com")303        assert response.status_code == 200304        assert response.json() == {"app": "mounted"}