Skip to content
Myr

test_async_client.py

This file

Path

tests/client/test_async_client.py

244 lines · 7.9 KiB · Python

Last changed by

Drop `.next()`/`.anext()` in favour of `response.next_request` (#1339)Tom Christiebefore adoption0eed6a3

History of this file

Take it

1from datetime import timedelta23import httpcore4import pytest56import httpx7from tests.utils import MockTransport8910@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    # Note that we're including 'proxies' here to *also* run through the192    # proxy context management, although we can't easily test that at the193    # moment, since we can't add proxies as transport instances.194    #195    # Once we have a more generalised Mount API we'll be able to remove this196    # in favour of ensuring all mounts are context managed, which will197    # also neccessarily include proxies.198    transport = Transport()199    async with httpx.AsyncClient(transport=transport, proxies="http://www.example.com"):200        pass201202    assert transport.events == [203        "transport.__aenter__",204        "transport.aclose",205        "transport.__aexit__",206    ]207208209def hello_world(request):210    return httpx.Response(200, text="Hello, world!")211212213@pytest.mark.usefixtures("async_environment")214async def test_client_closed_state_using_implicit_open():215    client = httpx.AsyncClient(transport=MockTransport(hello_world))216217    assert not client.is_closed218    await client.get("http://example.com")219220    assert not client.is_closed221    await client.aclose()222223    assert client.is_closed224    with pytest.raises(RuntimeError):225        await client.get("http://example.com")226227228@pytest.mark.usefixtures("async_environment")229async def test_client_closed_state_using_with_block():230    async with httpx.AsyncClient(transport=MockTransport(hello_world)) as client:231        assert not client.is_closed232        await client.get("http://example.com")233234    assert client.is_closed235    with pytest.raises(RuntimeError):236        await client.get("http://example.com")237238239@pytest.mark.usefixtures("async_environment")240async def test_deleting_unclosed_async_client_causes_warning():241    client = httpx.AsyncClient(transport=MockTransport(hello_world))242    await client.get("http://example.com")243    with pytest.warns(UserWarning):244        del client