Skip to content
Myr

test_client.py

This file

Path

tests/client/test_client.py

462 lines · 14.6 KiB · Python

Last changed by

Add support for zstd decoding (#3139)Michiel W. Beijenbefore adoption392dbe4

History of this file

Take it

1from __future__ import annotations23import typing4from datetime import timedelta56import chardet7import pytest89import httpx101112def autodetect(content):13    return chardet.detect(content).get("encoding")141516def test_get(server):17    url = server.url18    with httpx.Client(http2=True) as http:19        response = http.get(url)20    assert response.status_code == 20021    assert response.url == url22    assert response.content == b"Hello, world!"23    assert response.text == "Hello, world!"24    assert response.http_version == "HTTP/1.1"25    assert response.encoding == "utf-8"26    assert response.request.url == url27    assert response.headers28    assert response.is_redirect is False29    assert repr(response) == "<Response [200 OK]>"30    assert response.elapsed > timedelta(0)313233@pytest.mark.parametrize(34    "url",35    [36        pytest.param("invalid://example.org", id="scheme-not-http(s)"),37        pytest.param("://example.org", id="no-scheme"),38        pytest.param("http://", id="no-host"),39    ],40)41def test_get_invalid_url(server, url):42    with httpx.Client() as client:43        with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):44            client.get(url)454647def test_build_request(server):48    url = server.url.copy_with(path="/echo_headers")49    headers = {"Custom-header": "value"}5051    with httpx.Client() as client:52        request = client.build_request("GET", url)53        request.headers.update(headers)54        response = client.send(request)5556    assert response.status_code == 20057    assert response.url == url5859    assert response.json()["Custom-header"] == "value"606162def test_build_post_request(server):63    url = server.url.copy_with(path="/echo_headers")64    headers = {"Custom-header": "value"}6566    with httpx.Client() as client:67        request = client.build_request("POST", url)68        request.headers.update(headers)69        response = client.send(request)7071    assert response.status_code == 20072    assert response.url == url7374    assert response.json()["Content-length"] == "0"75    assert response.json()["Custom-header"] == "value"767778def test_post(server):79    with httpx.Client() as client:80        response = client.post(server.url, content=b"Hello, world!")81    assert response.status_code == 20082    assert response.reason_phrase == "OK"838485def test_post_json(server):86    with httpx.Client() as client:87        response = client.post(server.url, json={"text": "Hello, world!"})88    assert response.status_code == 20089    assert response.reason_phrase == "OK"909192def test_stream_response(server):93    with httpx.Client() as client:94        with client.stream("GET", server.url) as response:95            content = response.read()96    assert response.status_code == 20097    assert content == b"Hello, world!"9899100def test_stream_iterator(server):101    body = b""102103    with httpx.Client() as client:104        with client.stream("GET", server.url) as response:105            for chunk in response.iter_bytes():106                body += chunk107108    assert response.status_code == 200109    assert body == b"Hello, world!"110111112def test_raw_iterator(server):113    body = b""114115    with httpx.Client() as client:116        with client.stream("GET", server.url) as response:117            for chunk in response.iter_raw():118                body += chunk119120    assert response.status_code == 200121    assert body == b"Hello, world!"122123124def test_cannot_stream_async_request(server):125    async def hello_world() -> typing.AsyncIterator[bytes]:  # pragma: no cover126        yield b"Hello, "127        yield b"world!"128129    with httpx.Client() as client:130        with pytest.raises(RuntimeError):131            client.post(server.url, content=hello_world())132133134def test_raise_for_status(server):135    with httpx.Client() as client:136        for status_code in (200, 400, 404, 500, 505):137            response = client.request(138                "GET", server.url.copy_with(path=f"/status/{status_code}")139            )140            if 400 <= status_code < 600:141                with pytest.raises(httpx.HTTPStatusError) as exc_info:142                    response.raise_for_status()143                assert exc_info.value.response == response144                assert exc_info.value.request.url.path == f"/status/{status_code}"145            else:146                assert response.raise_for_status() is response147148149def test_options(server):150    with httpx.Client() as client:151        response = client.options(server.url)152    assert response.status_code == 200153    assert response.reason_phrase == "OK"154155156def test_head(server):157    with httpx.Client() as client:158        response = client.head(server.url)159    assert response.status_code == 200160    assert response.reason_phrase == "OK"161162163def test_put(server):164    with httpx.Client() as client:165        response = client.put(server.url, content=b"Hello, world!")166    assert response.status_code == 200167    assert response.reason_phrase == "OK"168169170def test_patch(server):171    with httpx.Client() as client:172        response = client.patch(server.url, content=b"Hello, world!")173    assert response.status_code == 200174    assert response.reason_phrase == "OK"175176177def test_delete(server):178    with httpx.Client() as client:179        response = client.delete(server.url)180    assert response.status_code == 200181    assert response.reason_phrase == "OK"182183184def test_base_url(server):185    base_url = server.url186    with httpx.Client(base_url=base_url) as client:187        response = client.get("/")188    assert response.status_code == 200189    assert response.url == base_url190191192def test_merge_absolute_url():193    client = httpx.Client(base_url="https://www.example.com/")194    request = client.build_request("GET", "http://www.example.com/")195    assert request.url == "http://www.example.com/"196197198def test_merge_relative_url():199    client = httpx.Client(base_url="https://www.example.com/")200    request = client.build_request("GET", "/testing/123")201    assert request.url == "https://www.example.com/testing/123"202203204def test_merge_relative_url_with_path():205    client = httpx.Client(base_url="https://www.example.com/some/path")206    request = client.build_request("GET", "/testing/123")207    assert request.url == "https://www.example.com/some/path/testing/123"208209210def test_merge_relative_url_with_dotted_path():211    client = httpx.Client(base_url="https://www.example.com/some/path")212    request = client.build_request("GET", "../testing/123")213    assert request.url == "https://www.example.com/some/testing/123"214215216def test_merge_relative_url_with_path_including_colon():217    client = httpx.Client(base_url="https://www.example.com/some/path")218    request = client.build_request("GET", "/testing:123")219    assert request.url == "https://www.example.com/some/path/testing:123"220221222def test_merge_relative_url_with_encoded_slashes():223    client = httpx.Client(base_url="https://www.example.com/")224    request = client.build_request("GET", "/testing%2F123")225    assert request.url == "https://www.example.com/testing%2F123"226227    client = httpx.Client(base_url="https://www.example.com/base%2Fpath")228    request = client.build_request("GET", "/testing")229    assert request.url == "https://www.example.com/base%2Fpath/testing"230231232def test_context_managed_transport():233    class Transport(httpx.BaseTransport):234        def __init__(self) -> None:235            self.events: list[str] = []236237        def close(self):238            # The base implementation of httpx.BaseTransport just239            # calls into `.close`, so simple transport cases can just override240            # this method for any cleanup, where more complex cases241            # might want to additionally override `__enter__`/`__exit__`.242            self.events.append("transport.close")243244        def __enter__(self):245            super().__enter__()246            self.events.append("transport.__enter__")247248        def __exit__(self, *args):249            super().__exit__(*args)250            self.events.append("transport.__exit__")251252    transport = Transport()253    with httpx.Client(transport=transport):254        pass255256    assert transport.events == [257        "transport.__enter__",258        "transport.close",259        "transport.__exit__",260    ]261262263def test_context_managed_transport_and_mount():264    class Transport(httpx.BaseTransport):265        def __init__(self, name: str) -> None:266            self.name: str = name267            self.events: list[str] = []268269        def close(self):270            # The base implementation of httpx.BaseTransport just271            # calls into `.close`, so simple transport cases can just override272            # this method for any cleanup, where more complex cases273            # might want to additionally override `__enter__`/`__exit__`.274            self.events.append(f"{self.name}.close")275276        def __enter__(self):277            super().__enter__()278            self.events.append(f"{self.name}.__enter__")279280        def __exit__(self, *args):281            super().__exit__(*args)282            self.events.append(f"{self.name}.__exit__")283284    transport = Transport(name="transport")285    mounted = Transport(name="mounted")286    with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}):287        pass288289    assert transport.events == [290        "transport.__enter__",291        "transport.close",292        "transport.__exit__",293    ]294    assert mounted.events == [295        "mounted.__enter__",296        "mounted.close",297        "mounted.__exit__",298    ]299300301def hello_world(request):302    return httpx.Response(200, text="Hello, world!")303304305def test_client_closed_state_using_implicit_open():306    client = httpx.Client(transport=httpx.MockTransport(hello_world))307308    assert not client.is_closed309    client.get("http://example.com")310311    assert not client.is_closed312    client.close()313314    assert client.is_closed315316    # Once we're close we cannot make any more requests.317    with pytest.raises(RuntimeError):318        client.get("http://example.com")319320    # Once we're closed we cannot reopen the client.321    with pytest.raises(RuntimeError):322        with client:323            pass  # pragma: no cover324325326def test_client_closed_state_using_with_block():327    with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:328        assert not client.is_closed329        client.get("http://example.com")330331    assert client.is_closed332    with pytest.raises(RuntimeError):333        client.get("http://example.com")334335336def echo_raw_headers(request: httpx.Request) -> httpx.Response:337    data = [338        (name.decode("ascii"), value.decode("ascii"))339        for name, value in request.headers.raw340    ]341    return httpx.Response(200, json=data)342343344def test_raw_client_header():345    """346    Set a header in the Client.347    """348    url = "http://example.org/echo_headers"349    headers = {"Example-Header": "example-value"}350351    client = httpx.Client(352        transport=httpx.MockTransport(echo_raw_headers), headers=headers353    )354    response = client.get(url)355356    assert response.status_code == 200357    assert response.json() == [358        ["Host", "example.org"],359        ["Accept", "*/*"],360        ["Accept-Encoding", "gzip, deflate, br, zstd"],361        ["Connection", "keep-alive"],362        ["User-Agent", f"python-httpx/{httpx.__version__}"],363        ["Example-Header", "example-value"],364    ]365366367def unmounted(request: httpx.Request) -> httpx.Response:368    data = {"app": "unmounted"}369    return httpx.Response(200, json=data)370371372def mounted(request: httpx.Request) -> httpx.Response:373    data = {"app": "mounted"}374    return httpx.Response(200, json=data)375376377def test_mounted_transport():378    transport = httpx.MockTransport(unmounted)379    mounts = {"custom://": httpx.MockTransport(mounted)}380381    client = httpx.Client(transport=transport, mounts=mounts)382383    response = client.get("https://www.example.com")384    assert response.status_code == 200385    assert response.json() == {"app": "unmounted"}386387    response = client.get("custom://www.example.com")388    assert response.status_code == 200389    assert response.json() == {"app": "mounted"}390391392def test_all_mounted_transport():393    mounts = {"all://": httpx.MockTransport(mounted)}394395    client = httpx.Client(mounts=mounts)396397    response = client.get("https://www.example.com")398    assert response.status_code == 200399    assert response.json() == {"app": "mounted"}400401402def test_server_extensions(server):403    url = server.url.copy_with(path="/http_version_2")404    with httpx.Client(http2=True) as client:405        response = client.get(url)406    assert response.status_code == 200407    assert response.extensions["http_version"] == b"HTTP/1.1"408409410def test_client_decode_text_using_autodetect():411    # Ensure that a 'default_encoding=autodetect' on the response allows for412    # encoding autodetection to be used when no "Content-Type: text/plain; charset=..."413    # info is present.414    #415    # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.416    text = (417        "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "418        "que la France a produits, sans excepter Voltaire lui-même, imprégné de "419        "l'esprit anglais par son séjour à Londres, c'est incontestablement "420        "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "421        "plus complète le fond du génie français."422    )423424    def cp1252_but_no_content_type(request):425        content = text.encode("ISO-8859-1")426        return httpx.Response(200, content=content)427428    transport = httpx.MockTransport(cp1252_but_no_content_type)429    with httpx.Client(transport=transport, default_encoding=autodetect) as client:430        response = client.get("http://www.example.com")431432        assert response.status_code == 200433        assert response.reason_phrase == "OK"434        assert response.encoding == "ISO-8859-1"435        assert response.text == text436437438def test_client_decode_text_using_explicit_encoding():439    # Ensure that a 'default_encoding="..."' on the response is used for text decoding440    # when no "Content-Type: text/plain; charset=..."" info is present.441    #442    # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.443    text = (444        "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "445        "que la France a produits, sans excepter Voltaire lui-même, imprégné de "446        "l'esprit anglais par son séjour à Londres, c'est incontestablement "447        "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "448        "plus complète le fond du génie français."449    )450451    def cp1252_but_no_content_type(request):452        content = text.encode("ISO-8859-1")453        return httpx.Response(200, content=content)454455    transport = httpx.MockTransport(cp1252_but_no_content_type)456    with httpx.Client(transport=transport, default_encoding=autodetect) as client:457        response = client.get("http://www.example.com")458459        assert response.status_code == 200460        assert response.reason_phrase == "OK"461        assert response.encoding == "ISO-8859-1"462        assert response.text == text