Skip to content
Myr

test_async_client.py

This file

Path

tests/client/test_async_client.py

250 lines · 7.8 KiB · Python

Last changed by

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

History of this file

Take it

1from datetime import timedelta23import httpcore4import pytest56import httpx789@pytest.mark.usefixtures("async_environment")10async def test_get(server):11    url = server.url12    async with httpx.AsyncClient(http2=True) as client:13        response = await client.get(url)14    assert response.status_code == 20015    assert response.text == "Hello, world!"16    assert response.http_version == "HTTP/1.1"17    assert response.headers18    assert repr(response) == "<Response [200 OK]>"19    assert response.elapsed > timedelta(seconds=0)2021    with pytest.raises(httpx.NotRedirectResponse):22        await response.anext()232425@pytest.mark.parametrize(26    "url",27    [28        pytest.param("invalid://example.org", id="scheme-not-http(s)"),29        pytest.param("://example.org", id="no-scheme"),30        pytest.param("http://", id="no-host"),31    ],32)33@pytest.mark.usefixtures("async_environment")34async def test_get_invalid_url(server, url):35    async with httpx.AsyncClient() as client:36        with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):37            await client.get(url)383940@pytest.mark.usefixtures("async_environment")41async def test_build_request(server):42    url = server.url.copy_with(path="/echo_headers")43    headers = {"Custom-header": "value"}44    async with httpx.AsyncClient() as client:45        request = client.build_request("GET", url)46        request.headers.update(headers)47        response = await client.send(request)4849    assert response.status_code == 20050    assert response.url == url5152    assert response.json()["Custom-header"] == "value"535455@pytest.mark.usefixtures("async_environment")56async def test_post(server):57    url = server.url58    async with httpx.AsyncClient() as client:59        response = await client.post(url, content=b"Hello, world!")60    assert response.status_code == 200616263@pytest.mark.usefixtures("async_environment")64async def test_post_json(server):65    url = server.url66    async with httpx.AsyncClient() as client:67        response = await client.post(url, json={"text": "Hello, world!"})68    assert response.status_code == 200697071@pytest.mark.usefixtures("async_environment")72async def test_stream_response(server):73    async with httpx.AsyncClient() as client:74        async with client.stream("GET", server.url) as response:75            body = await response.aread()7677    assert response.status_code == 20078    assert body == b"Hello, world!"79    assert response.content == b"Hello, world!"808182@pytest.mark.usefixtures("async_environment")83async def test_access_content_stream_response(server):84    async with httpx.AsyncClient() as client:85        async with client.stream("GET", server.url) as response:86            pass8788    assert response.status_code == 20089    with pytest.raises(httpx.ResponseNotRead):90        response.content919293@pytest.mark.usefixtures("async_environment")94async def test_stream_request(server):95    async def hello_world():96        yield b"Hello, "97        yield b"world!"9899    async with httpx.AsyncClient() as client:100        response = await client.request("POST", server.url, content=hello_world())101    assert response.status_code == 200102103104@pytest.mark.usefixtures("async_environment")105async def test_raise_for_status(server):106    async with httpx.AsyncClient() as client:107        for status_code in (200, 400, 404, 500, 505):108            response = await client.request(109                "GET", server.url.copy_with(path=f"/status/{status_code}")110            )111112            if 400 <= status_code < 600:113                with pytest.raises(httpx.HTTPStatusError) as exc_info:114                    response.raise_for_status()115                assert exc_info.value.response == response116            else:117                assert response.raise_for_status() is None  # type: ignore118119120@pytest.mark.usefixtures("async_environment")121async def test_options(server):122    async with httpx.AsyncClient() as client:123        response = await client.options(server.url)124    assert response.status_code == 200125    assert response.text == "Hello, world!"126127128@pytest.mark.usefixtures("async_environment")129async def test_head(server):130    async with httpx.AsyncClient() as client:131        response = await client.head(server.url)132    assert response.status_code == 200133    assert response.text == ""134135136@pytest.mark.usefixtures("async_environment")137async def test_put(server):138    async with httpx.AsyncClient() as client:139        response = await client.put(server.url, content=b"Hello, world!")140    assert response.status_code == 200141142143@pytest.mark.usefixtures("async_environment")144async def test_patch(server):145    async with httpx.AsyncClient() as client:146        response = await client.patch(server.url, content=b"Hello, world!")147    assert response.status_code == 200148149150@pytest.mark.usefixtures("async_environment")151async def test_delete(server):152    async with httpx.AsyncClient() as client:153        response = await client.delete(server.url)154    assert response.status_code == 200155    assert response.text == "Hello, world!"156157158@pytest.mark.usefixtures("async_environment")159async def test_100_continue(server):160    headers = {"Expect": "100-continue"}161    content = b"Echo request body"162163    async with httpx.AsyncClient() as client:164        response = await client.post(165            server.url.copy_with(path="/echo_body"), headers=headers, content=content166        )167168    assert response.status_code == 200169    assert response.content == content170171172@pytest.mark.usefixtures("async_environment")173async def test_context_managed_transport():174    class Transport(httpcore.AsyncHTTPTransport):175        def __init__(self):176            self.events = []177178        async def aclose(self):179            # The base implementation of httpcore.AsyncHTTPTransport just180            # calls into `.aclose`, so simple transport cases can just override181            # this method for any cleanup, where more complex cases182            # might want to additionally override `__aenter__`/`__aexit__`.183            self.events.append("transport.aclose")184185        async def __aenter__(self):186            await super().__aenter__()187            self.events.append("transport.__aenter__")188189        async def __aexit__(self, *args):190            await super().__aexit__(*args)191            self.events.append("transport.__aexit__")192193    # Note that we're including 'proxies' here to *also* run through the194    # proxy context management, although we can't easily test that at the195    # moment, since we can't add proxies as transport instances.196    #197    # Once we have a more generalised Mount API we'll be able to remove this198    # in favour of ensuring all mounts are context managed, which will199    # also neccessarily include proxies.200    transport = Transport()201    async with httpx.AsyncClient(transport=transport, proxies="http://www.example.com"):202        pass203204    assert transport.events == [205        "transport.__aenter__",206        "transport.aclose",207        "transport.__aexit__",208    ]209210211@pytest.mark.usefixtures("async_environment")212async def test_that_async_client_is_closed_by_default():213    client = httpx.AsyncClient()214215    assert client.is_closed216217218@pytest.mark.usefixtures("async_environment")219async def test_that_send_cause_async_client_to_be_not_closed():220    client = httpx.AsyncClient()221222    await client.get("http://example.com")223224    assert not client.is_closed225226    await client.aclose()227228229@pytest.mark.usefixtures("async_environment")230async def test_that_async_client_is_not_closed_in_with_block():231    async with httpx.AsyncClient() as client:232        assert not client.is_closed233234235@pytest.mark.usefixtures("async_environment")236async def test_that_async_client_is_closed_after_with_block():237    async with httpx.AsyncClient() as client:238        pass239240    assert client.is_closed241242243@pytest.mark.usefixtures("async_environment")244async def test_that_async_client_caused_warning_when_being_deleted():245    async_client = httpx.AsyncClient()246247    await async_client.get("http://example.com")248249    with pytest.warns(UserWarning):250        del async_client