Skip to content
Myr

test_async_client.py

This file

Path

tests/client/test_async_client.py

335 lines · 10.8 KiB · Python

Last changed by

map_exceptions in request.aclose() (#1465)Adam Hooperbefore adoption0f280af

History of this file

Take it

1import typing2from datetime import timedelta34import httpcore5import pytest67import httpx8910@pytest.mark.usefixtures("async_environment")11async def test_get(server):12    url = server.url13    async with httpx.AsyncClient(http2=True) as client: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)212223@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)31@pytest.mark.usefixtures("async_environment")32async def test_get_invalid_url(server, url):33    async with httpx.AsyncClient() as client:34        with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):35            await client.get(url)363738@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:57        response = await client.post(url, content=b"Hello, world!")58    assert response.status_code == 200596061@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:98        response = await client.request("POST", server.url, content=hello_world())99    assert response.status_code == 200100101102@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:111                with pytest.raises(httpx.HTTPStatusError) as exc_info: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:137        response = await client.put(server.url, content=b"Hello, world!")138    assert response.status_code == 200139140141@pytest.mark.usefixtures("async_environment")142async def test_patch(server):143    async with httpx.AsyncClient() as client:144        response = await client.patch(server.url, content=b"Hello, world!")145    assert response.status_code == 200146147148@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"}159    content = b"Echo request body"160161    async with httpx.AsyncClient() as client:162        response = await client.post(163            server.url.copy_with(path="/echo_body"), headers=headers, content=content164        )165166    assert response.status_code == 200167    assert response.content == content168169170@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()192    async with httpx.AsyncClient(transport=transport):193        pass194195    assert transport.events == [196        "transport.__aenter__",197        "transport.aclose",198        "transport.__aexit__",199    ]200201202@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    ]241242243def hello_world(request):244    return httpx.Response(200, text="Hello, world!")245246247@pytest.mark.usefixtures("async_environment")248async def test_client_closed_state_using_implicit_open():249    client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))250251    assert not client.is_closed252    await client.get("http://example.com")253254    assert not client.is_closed255    await client.aclose()256257    assert client.is_closed258    with pytest.raises(RuntimeError):259        await client.get("http://example.com")260261262@pytest.mark.usefixtures("async_environment")263async def test_client_closed_state_using_with_block():264    async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:265        assert not client.is_closed266        await client.get("http://example.com")267268    assert client.is_closed269    with pytest.raises(RuntimeError):270        await client.get("http://example.com")271272273@pytest.mark.usefixtures("async_environment")274async def test_deleting_unclosed_async_client_causes_warning():275    client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))276    await client.get("http://example.com")277    with pytest.warns(UserWarning):278        del client279280281def 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():293    transport = httpx.MockTransport(unmounted)294    mounts = {"custom://": httpx.MockTransport(mounted)}295296    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"}304305306@pytest.mark.usefixtures("async_environment")307async def test_response_aclose_map_exceptions():308    class BrokenStream:309        async def __aiter__(self):310            # so we're an AsyncIterator311            pass  # pragma: nocover312313        async def aclose(self):314            raise httpcore.CloseError(OSError(104, "Connection reset by peer"))315316    def handle(request: httpx.Request) -> httpx.Response:317        return httpx.Response(200, stream=BrokenStream())318319    async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client:320        async with client.stream("GET", "http://example.com") as response:321            with pytest.raises(httpx.CloseError):322                await response.aclose()323324325@pytest.mark.usefixtures("async_environment")326async def test_async_mock_transport():327    async def hello_world(request):328        return httpx.Response(200, text="Hello, world!")329330    transport = httpx.MockTransport(hello_world)331332    async with httpx.AsyncClient(transport=transport) as client:333        response = await client.get("https://www.example.com")334        assert response.status_code == 200335        assert response.text == "Hello, world!"