Skip to content
Myr

test_async_client.py

This file

Path

tests/client/test_async_client.py

247 lines · 8.0 KiB · Python

Last changed by

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

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)2122    with pytest.raises(httpx.NotRedirectResponse):23        await response.anext()242526@pytest.mark.parametrize(27    "url",28    [29        pytest.param("invalid://example.org", id="scheme-not-http(s)"),30        pytest.param("://example.org", id="no-scheme"),31        pytest.param("http://", id="no-host"),32    ],33)34@pytest.mark.usefixtures("async_environment")35async def test_get_invalid_url(server, url):36    async with httpx.AsyncClient() as client:37        with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):38            await client.get(url)394041@pytest.mark.usefixtures("async_environment")42async def test_build_request(server):43    url = server.url.copy_with(path="/echo_headers")44    headers = {"Custom-header": "value"}45    async with httpx.AsyncClient() as client:46        request = client.build_request("GET", url)47        request.headers.update(headers)48        response = await client.send(request)4950    assert response.status_code == 20051    assert response.url == url5253    assert response.json()["Custom-header"] == "value"545556@pytest.mark.usefixtures("async_environment")57async def test_post(server):58    url = server.url59    async with httpx.AsyncClient() as client:60        response = await client.post(url, content=b"Hello, world!")61    assert response.status_code == 200626364@pytest.mark.usefixtures("async_environment")65async def test_post_json(server):66    url = server.url67    async with httpx.AsyncClient() as client:68        response = await client.post(url, json={"text": "Hello, world!"})69    assert response.status_code == 200707172@pytest.mark.usefixtures("async_environment")73async def test_stream_response(server):74    async with httpx.AsyncClient() as client:75        async with client.stream("GET", server.url) as response:76            body = await response.aread()7778    assert response.status_code == 20079    assert body == b"Hello, world!"80    assert response.content == b"Hello, world!"818283@pytest.mark.usefixtures("async_environment")84async def test_access_content_stream_response(server):85    async with httpx.AsyncClient() as client:86        async with client.stream("GET", server.url) as response:87            pass8889    assert response.status_code == 20090    with pytest.raises(httpx.ResponseNotRead):91        response.content929394@pytest.mark.usefixtures("async_environment")95async def test_stream_request(server):96    async def hello_world():97        yield b"Hello, "98        yield b"world!"99100    async with httpx.AsyncClient() as client:101        response = await client.request("POST", server.url, content=hello_world())102    assert response.status_code == 200103104105@pytest.mark.usefixtures("async_environment")106async def test_raise_for_status(server):107    async with httpx.AsyncClient() as client:108        for status_code in (200, 400, 404, 500, 505):109            response = await client.request(110                "GET", server.url.copy_with(path=f"/status/{status_code}")111            )112113            if 400 <= status_code < 600:114                with pytest.raises(httpx.HTTPStatusError) as exc_info:115                    response.raise_for_status()116                assert exc_info.value.response == response117            else:118                assert response.raise_for_status() is None  # type: ignore119120121@pytest.mark.usefixtures("async_environment")122async def test_options(server):123    async with httpx.AsyncClient() as client:124        response = await client.options(server.url)125    assert response.status_code == 200126    assert response.text == "Hello, world!"127128129@pytest.mark.usefixtures("async_environment")130async def test_head(server):131    async with httpx.AsyncClient() as client:132        response = await client.head(server.url)133    assert response.status_code == 200134    assert response.text == ""135136137@pytest.mark.usefixtures("async_environment")138async def test_put(server):139    async with httpx.AsyncClient() as client:140        response = await client.put(server.url, content=b"Hello, world!")141    assert response.status_code == 200142143144@pytest.mark.usefixtures("async_environment")145async def test_patch(server):146    async with httpx.AsyncClient() as client:147        response = await client.patch(server.url, content=b"Hello, world!")148    assert response.status_code == 200149150151@pytest.mark.usefixtures("async_environment")152async def test_delete(server):153    async with httpx.AsyncClient() as client:154        response = await client.delete(server.url)155    assert response.status_code == 200156    assert response.text == "Hello, world!"157158159@pytest.mark.usefixtures("async_environment")160async def test_100_continue(server):161    headers = {"Expect": "100-continue"}162    content = b"Echo request body"163164    async with httpx.AsyncClient() as client:165        response = await client.post(166            server.url.copy_with(path="/echo_body"), headers=headers, content=content167        )168169    assert response.status_code == 200170    assert response.content == content171172173@pytest.mark.usefixtures("async_environment")174async def test_context_managed_transport():175    class Transport(httpcore.AsyncHTTPTransport):176        def __init__(self):177            self.events = []178179        async def aclose(self):180            # The base implementation of httpcore.AsyncHTTPTransport just181            # calls into `.aclose`, so simple transport cases can just override182            # this method for any cleanup, where more complex cases183            # might want to additionally override `__aenter__`/`__aexit__`.184            self.events.append("transport.aclose")185186        async def __aenter__(self):187            await super().__aenter__()188            self.events.append("transport.__aenter__")189190        async def __aexit__(self, *args):191            await super().__aexit__(*args)192            self.events.append("transport.__aexit__")193194    # Note that we're including 'proxies' here to *also* run through the195    # proxy context management, although we can't easily test that at the196    # moment, since we can't add proxies as transport instances.197    #198    # Once we have a more generalised Mount API we'll be able to remove this199    # in favour of ensuring all mounts are context managed, which will200    # also neccessarily include proxies.201    transport = Transport()202    async with httpx.AsyncClient(transport=transport, proxies="http://www.example.com"):203        pass204205    assert transport.events == [206        "transport.__aenter__",207        "transport.aclose",208        "transport.__aexit__",209    ]210211212def hello_world(request):213    return httpx.Response(200, text="Hello, world!")214215216@pytest.mark.usefixtures("async_environment")217async def test_client_closed_state_using_implicit_open():218    client = httpx.AsyncClient(transport=MockTransport(hello_world))219220    assert not client.is_closed221    await client.get("http://example.com")222223    assert not client.is_closed224    await client.aclose()225226    assert client.is_closed227    with pytest.raises(RuntimeError):228        await client.get("http://example.com")229230231@pytest.mark.usefixtures("async_environment")232async def test_client_closed_state_using_with_block():233    async with httpx.AsyncClient(transport=MockTransport(hello_world)) as client:234        assert not client.is_closed235        await client.get("http://example.com")236237    assert client.is_closed238    with pytest.raises(RuntimeError):239        await client.get("http://example.com")240241242@pytest.mark.usefixtures("async_environment")243async def test_deleting_unclosed_async_client_causes_warning():244    client = httpx.AsyncClient(transport=MockTransport(hello_world))245    await client.get("http://example.com")246    with pytest.warns(UserWarning):247        del client