Skip to content
Myr

test_client.py

This file

Path

tests/client/test_client.py

460 lines · 14.6 KiB · Python

Last changed by

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

History of this file

Take it

1import typing2from datetime import timedelta34import chardet5import pytest67import httpx8910def autodetect(content):11    return chardet.detect(content).get("encoding")121314def test_get(server):15    url = server.url16    with httpx.Client(http2=True) as http:17        response = http.get(url)18    assert response.status_code == 20019    assert response.url == url20    assert response.content == b"Hello, world!"21    assert response.text == "Hello, world!"22    assert response.http_version == "HTTP/1.1"23    assert response.encoding == "utf-8"24    assert response.request.url == url25    assert response.headers26    assert response.is_redirect is False27    assert repr(response) == "<Response [200 OK]>"28    assert response.elapsed > timedelta(0)293031@pytest.mark.parametrize(32    "url",33    [34        pytest.param("invalid://example.org", id="scheme-not-http(s)"),35        pytest.param("://example.org", id="no-scheme"),36        pytest.param("http://", id="no-host"),37    ],38)39def test_get_invalid_url(server, url):40    with httpx.Client() as client:41        with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):42            client.get(url)434445def test_build_request(server):46    url = server.url.copy_with(path="/echo_headers")47    headers = {"Custom-header": "value"}4849    with httpx.Client() as client:50        request = client.build_request("GET", url)51        request.headers.update(headers)52        response = client.send(request)5354    assert response.status_code == 20055    assert response.url == url5657    assert response.json()["Custom-header"] == "value"585960def test_build_post_request(server):61    url = server.url.copy_with(path="/echo_headers")62    headers = {"Custom-header": "value"}6364    with httpx.Client() as client:65        request = client.build_request("POST", url)66        request.headers.update(headers)67        response = client.send(request)6869    assert response.status_code == 20070    assert response.url == url7172    assert response.json()["Content-length"] == "0"73    assert response.json()["Custom-header"] == "value"747576def test_post(server):77    with httpx.Client() as client:78        response = client.post(server.url, content=b"Hello, world!")79    assert response.status_code == 20080    assert response.reason_phrase == "OK"818283def test_post_json(server):84    with httpx.Client() as client:85        response = client.post(server.url, json={"text": "Hello, world!"})86    assert response.status_code == 20087    assert response.reason_phrase == "OK"888990def test_stream_response(server):91    with httpx.Client() as client:92        with client.stream("GET", server.url) as response:93            content = response.read()94    assert response.status_code == 20095    assert content == b"Hello, world!"969798def test_stream_iterator(server):99    body = b""100101    with httpx.Client() as client:102        with client.stream("GET", server.url) as response:103            for chunk in response.iter_bytes():104                body += chunk105106    assert response.status_code == 200107    assert body == b"Hello, world!"108109110def test_raw_iterator(server):111    body = b""112113    with httpx.Client() as client:114        with client.stream("GET", server.url) as response:115            for chunk in response.iter_raw():116                body += chunk117118    assert response.status_code == 200119    assert body == b"Hello, world!"120121122def test_cannot_stream_async_request(server):123    async def hello_world():  # pragma: nocover124        yield b"Hello, "125        yield b"world!"126127    with httpx.Client() as client:128        with pytest.raises(RuntimeError):129            client.post(server.url, content=hello_world())130131132def test_raise_for_status(server):133    with httpx.Client() as client:134        for status_code in (200, 400, 404, 500, 505):135            response = client.request(136                "GET", server.url.copy_with(path=f"/status/{status_code}")137            )138            if 400 <= status_code < 600:139                with pytest.raises(httpx.HTTPStatusError) as exc_info:140                    response.raise_for_status()141                assert exc_info.value.response == response142                assert exc_info.value.request.url.path == f"/status/{status_code}"143            else:144                assert response.raise_for_status() is None  # type: ignore145146147def test_options(server):148    with httpx.Client() as client:149        response = client.options(server.url)150    assert response.status_code == 200151    assert response.reason_phrase == "OK"152153154def test_head(server):155    with httpx.Client() as client:156        response = client.head(server.url)157    assert response.status_code == 200158    assert response.reason_phrase == "OK"159160161def test_put(server):162    with httpx.Client() as client:163        response = client.put(server.url, content=b"Hello, world!")164    assert response.status_code == 200165    assert response.reason_phrase == "OK"166167168def test_patch(server):169    with httpx.Client() as client:170        response = client.patch(server.url, content=b"Hello, world!")171    assert response.status_code == 200172    assert response.reason_phrase == "OK"173174175def test_delete(server):176    with httpx.Client() as client:177        response = client.delete(server.url)178    assert response.status_code == 200179    assert response.reason_phrase == "OK"180181182def test_base_url(server):183    base_url = server.url184    with httpx.Client(base_url=base_url) as client:185        response = client.get("/")186    assert response.status_code == 200187    assert response.url == base_url188189190def test_merge_absolute_url():191    client = httpx.Client(base_url="https://www.example.com/")192    request = client.build_request("GET", "http://www.example.com/")193    assert request.url == "http://www.example.com/"194195196def test_merge_relative_url():197    client = httpx.Client(base_url="https://www.example.com/")198    request = client.build_request("GET", "/testing/123")199    assert request.url == "https://www.example.com/testing/123"200201202def test_merge_relative_url_with_path():203    client = httpx.Client(base_url="https://www.example.com/some/path")204    request = client.build_request("GET", "/testing/123")205    assert request.url == "https://www.example.com/some/path/testing/123"206207208def test_merge_relative_url_with_dotted_path():209    client = httpx.Client(base_url="https://www.example.com/some/path")210    request = client.build_request("GET", "../testing/123")211    assert request.url == "https://www.example.com/some/testing/123"212213214def test_merge_relative_url_with_path_including_colon():215    client = httpx.Client(base_url="https://www.example.com/some/path")216    request = client.build_request("GET", "/testing:123")217    assert request.url == "https://www.example.com/some/path/testing:123"218219220def test_merge_relative_url_with_encoded_slashes():221    client = httpx.Client(base_url="https://www.example.com/")222    request = client.build_request("GET", "/testing%2F123")223    assert request.url == "https://www.example.com/testing%2F123"224225    client = httpx.Client(base_url="https://www.example.com/base%2Fpath")226    request = client.build_request("GET", "/testing")227    assert request.url == "https://www.example.com/base%2Fpath/testing"228229230def test_context_managed_transport():231    class Transport(httpx.BaseTransport):232        def __init__(self):233            self.events = []234235        def close(self):236            # The base implementation of httpx.BaseTransport just237            # calls into `.close`, so simple transport cases can just override238            # this method for any cleanup, where more complex cases239            # might want to additionally override `__enter__`/`__exit__`.240            self.events.append("transport.close")241242        def __enter__(self):243            super().__enter__()244            self.events.append("transport.__enter__")245246        def __exit__(self, *args):247            super().__exit__(*args)248            self.events.append("transport.__exit__")249250    transport = Transport()251    with httpx.Client(transport=transport):252        pass253254    assert transport.events == [255        "transport.__enter__",256        "transport.close",257        "transport.__exit__",258    ]259260261def test_context_managed_transport_and_mount():262    class Transport(httpx.BaseTransport):263        def __init__(self, name: str):264            self.name: str = name265            self.events: typing.List[str] = []266267        def close(self):268            # The base implementation of httpx.BaseTransport just269            # calls into `.close`, so simple transport cases can just override270            # this method for any cleanup, where more complex cases271            # might want to additionally override `__enter__`/`__exit__`.272            self.events.append(f"{self.name}.close")273274        def __enter__(self):275            super().__enter__()276            self.events.append(f"{self.name}.__enter__")277278        def __exit__(self, *args):279            super().__exit__(*args)280            self.events.append(f"{self.name}.__exit__")281282    transport = Transport(name="transport")283    mounted = Transport(name="mounted")284    with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}):285        pass286287    assert transport.events == [288        "transport.__enter__",289        "transport.close",290        "transport.__exit__",291    ]292    assert mounted.events == [293        "mounted.__enter__",294        "mounted.close",295        "mounted.__exit__",296    ]297298299def hello_world(request):300    return httpx.Response(200, text="Hello, world!")301302303def test_client_closed_state_using_implicit_open():304    client = httpx.Client(transport=httpx.MockTransport(hello_world))305306    assert not client.is_closed307    client.get("http://example.com")308309    assert not client.is_closed310    client.close()311312    assert client.is_closed313314    # Once we're close we cannot make any more requests.315    with pytest.raises(RuntimeError):316        client.get("http://example.com")317318    # Once we're closed we cannot reopen the client.319    with pytest.raises(RuntimeError):320        with client:321            pass  # pragma: nocover322323324def test_client_closed_state_using_with_block():325    with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:326        assert not client.is_closed327        client.get("http://example.com")328329    assert client.is_closed330    with pytest.raises(RuntimeError):331        client.get("http://example.com")332333334def echo_raw_headers(request: httpx.Request) -> httpx.Response:335    data = [336        (name.decode("ascii"), value.decode("ascii"))337        for name, value in request.headers.raw338    ]339    return httpx.Response(200, json=data)340341342def test_raw_client_header():343    """344    Set a header in the Client.345    """346    url = "http://example.org/echo_headers"347    headers = {"Example-Header": "example-value"}348349    client = httpx.Client(350        transport=httpx.MockTransport(echo_raw_headers), headers=headers351    )352    response = client.get(url)353354    assert response.status_code == 200355    assert response.json() == [356        ["Host", "example.org"],357        ["Accept", "*/*"],358        ["Accept-Encoding", "gzip, deflate, br"],359        ["Connection", "keep-alive"],360        ["User-Agent", f"python-httpx/{httpx.__version__}"],361        ["Example-Header", "example-value"],362    ]363364365def unmounted(request: httpx.Request) -> httpx.Response:366    data = {"app": "unmounted"}367    return httpx.Response(200, json=data)368369370def mounted(request: httpx.Request) -> httpx.Response:371    data = {"app": "mounted"}372    return httpx.Response(200, json=data)373374375def test_mounted_transport():376    transport = httpx.MockTransport(unmounted)377    mounts = {"custom://": httpx.MockTransport(mounted)}378379    client = httpx.Client(transport=transport, mounts=mounts)380381    response = client.get("https://www.example.com")382    assert response.status_code == 200383    assert response.json() == {"app": "unmounted"}384385    response = client.get("custom://www.example.com")386    assert response.status_code == 200387    assert response.json() == {"app": "mounted"}388389390def test_all_mounted_transport():391    mounts = {"all://": httpx.MockTransport(mounted)}392393    client = httpx.Client(mounts=mounts)394395    response = client.get("https://www.example.com")396    assert response.status_code == 200397    assert response.json() == {"app": "mounted"}398399400def test_server_extensions(server):401    url = server.url.copy_with(path="/http_version_2")402    with httpx.Client(http2=True) as client:403        response = client.get(url)404    assert response.status_code == 200405    assert response.extensions["http_version"] == b"HTTP/1.1"406407408def test_client_decode_text_using_autodetect():409    # Ensure that a 'default_encoding=autodetect' on the response allows for410    # encoding autodetection to be used when no "Content-Type: text/plain; charset=..."411    # info is present.412    #413    # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.414    text = (415        "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "416        "que la France a produits, sans excepter Voltaire lui-même, imprégné de "417        "l'esprit anglais par son séjour à Londres, c'est incontestablement "418        "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "419        "plus complète le fond du génie français."420    )421422    def cp1252_but_no_content_type(request):423        content = text.encode("ISO-8859-1")424        return httpx.Response(200, content=content)425426    transport = httpx.MockTransport(cp1252_but_no_content_type)427    with httpx.Client(transport=transport, default_encoding=autodetect) as client:428        response = client.get("http://www.example.com")429430        assert response.status_code == 200431        assert response.reason_phrase == "OK"432        assert response.encoding == "ISO-8859-1"433        assert response.text == text434435436def test_client_decode_text_using_explicit_encoding():437    # Ensure that a 'default_encoding="..."' on the response is used for text decoding438    # when no "Content-Type: text/plain; charset=..."" info is present.439    #440    # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.441    text = (442        "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "443        "que la France a produits, sans excepter Voltaire lui-même, imprégné de "444        "l'esprit anglais par son séjour à Londres, c'est incontestablement "445        "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "446        "plus complète le fond du génie français."447    )448449    def cp1252_but_no_content_type(request):450        content = text.encode("ISO-8859-1")451        return httpx.Response(200, content=content)452453    transport = httpx.MockTransport(cp1252_but_no_content_type)454    with httpx.Client(transport=transport, default_encoding=autodetect) as client:455        response = client.get("http://www.example.com")456457        assert response.status_code == 200458        assert response.reason_phrase == "OK"459        assert response.encoding == "ISO-8859-1"460        assert response.text == text