Skip to content
Myr

test_client.py

This file

Path

tests/client/test_client.py

380 lines · 11.3 KiB · Python

Last changed by

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

History of this file

Take it

1import typing2from datetime import timedelta34import httpcore5import pytest67import httpx8910def test_get(server):11    url = server.url12    with httpx.Client(http2=True) as http:13        response = http.get(url)14    assert response.status_code == 20015    assert response.url == url16    assert response.content == b"Hello, world!"17    assert response.text == "Hello, world!"18    assert response.http_version == "HTTP/1.1"19    assert response.encoding is None20    assert response.request.url == url21    assert response.headers22    assert response.is_redirect is False23    assert repr(response) == "<Response [200 OK]>"24    assert response.elapsed > timedelta(0)252627@pytest.mark.parametrize(28    "url",29    [30        pytest.param("invalid://example.org", id="scheme-not-http(s)"),31        pytest.param("://example.org", id="no-scheme"),32        pytest.param("http://", id="no-host"),33    ],34)35def test_get_invalid_url(server, url):36    with httpx.Client() as client:37        with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):38            client.get(url)394041def test_build_request(server):42    url = server.url.copy_with(path="/echo_headers")43    headers = {"Custom-header": "value"}4445    with httpx.Client() as client:46        request = client.build_request("GET", url)47        request.headers.update(headers)48        response = client.send(request)4950    assert response.status_code == 20051    assert response.url == url5253    assert response.json()["Custom-header"] == "value"545556def test_build_post_request(server):57    url = server.url.copy_with(path="/echo_headers")58    headers = {"Custom-header": "value"}5960    with httpx.Client() as client:61        request = client.build_request("POST", url)62        request.headers.update(headers)63        response = client.send(request)6465    assert response.status_code == 20066    assert response.url == url6768    assert response.json()["Content-length"] == "0"69    assert response.json()["Custom-header"] == "value"707172def test_post(server):73    with httpx.Client() as client:74        response = client.post(server.url, content=b"Hello, world!")75    assert response.status_code == 20076    assert response.reason_phrase == "OK"777879def test_post_json(server):80    with httpx.Client() as client:81        response = client.post(server.url, json={"text": "Hello, world!"})82    assert response.status_code == 20083    assert response.reason_phrase == "OK"848586def test_stream_response(server):87    with httpx.Client() as client:88        with client.stream("GET", server.url) as response:89            content = response.read()90    assert response.status_code == 20091    assert content == b"Hello, world!"929394def test_stream_iterator(server):95    body = b""9697    with httpx.Client() as client:98        with client.stream("GET", server.url) as response:99            for chunk in response.iter_bytes():100                body += chunk101102    assert response.status_code == 200103    assert body == b"Hello, world!"104105106def test_raw_iterator(server):107    body = b""108109    with httpx.Client() as client:110        with client.stream("GET", server.url) as response:111            for chunk in response.iter_raw():112                body += chunk113114    assert response.status_code == 200115    assert body == b"Hello, world!"116117118def test_raise_for_status(server):119    with httpx.Client() as client:120        for status_code in (200, 400, 404, 500, 505):121            response = client.request(122                "GET", server.url.copy_with(path=f"/status/{status_code}")123            )124            if 400 <= status_code < 600:125                with pytest.raises(httpx.HTTPStatusError) as exc_info:126                    response.raise_for_status()127                assert exc_info.value.response == response128                assert exc_info.value.request.url.path == f"/status/{status_code}"129            else:130                assert response.raise_for_status() is None  # type: ignore131132133def test_options(server):134    with httpx.Client() as client:135        response = client.options(server.url)136    assert response.status_code == 200137    assert response.reason_phrase == "OK"138139140def test_head(server):141    with httpx.Client() as client:142        response = client.head(server.url)143    assert response.status_code == 200144    assert response.reason_phrase == "OK"145146147def test_put(server):148    with httpx.Client() as client:149        response = client.put(server.url, content=b"Hello, world!")150    assert response.status_code == 200151    assert response.reason_phrase == "OK"152153154def test_patch(server):155    with httpx.Client() as client:156        response = client.patch(server.url, content=b"Hello, world!")157    assert response.status_code == 200158    assert response.reason_phrase == "OK"159160161def test_delete(server):162    with httpx.Client() as client:163        response = client.delete(server.url)164    assert response.status_code == 200165    assert response.reason_phrase == "OK"166167168def test_base_url(server):169    base_url = server.url170    with httpx.Client(base_url=base_url) as client:171        response = client.get("/")172    assert response.status_code == 200173    assert response.url == base_url174175176def test_merge_absolute_url():177    client = httpx.Client(base_url="https://www.example.com/")178    request = client.build_request("GET", "http://www.example.com/")179    assert request.url == "http://www.example.com/"180181182def test_merge_relative_url():183    client = httpx.Client(base_url="https://www.example.com/")184    request = client.build_request("GET", "/testing/123")185    assert request.url == "https://www.example.com/testing/123"186187188def test_merge_relative_url_with_path():189    client = httpx.Client(base_url="https://www.example.com/some/path")190    request = client.build_request("GET", "/testing/123")191    assert request.url == "https://www.example.com/some/path/testing/123"192193194def test_merge_relative_url_with_dotted_path():195    client = httpx.Client(base_url="https://www.example.com/some/path")196    request = client.build_request("GET", "../testing/123")197    assert request.url == "https://www.example.com/some/testing/123"198199200def test_merge_relative_url_with_encoded_slashes():201    client = httpx.Client(base_url="https://www.example.com/")202    request = client.build_request("GET", "/testing%2F123")203    assert request.url == "https://www.example.com/testing%2F123"204205    client = httpx.Client(base_url="https://www.example.com/base%2Fpath")206    request = client.build_request("GET", "/testing")207    assert request.url == "https://www.example.com/base%2Fpath/testing"208209210def test_pool_limits_deprecated():211    limits = httpx.Limits()212213    with pytest.warns(DeprecationWarning):214        httpx.Client(pool_limits=limits)215216    with pytest.warns(DeprecationWarning):217        httpx.AsyncClient(pool_limits=limits)218219220def test_context_managed_transport():221    class Transport(httpcore.SyncHTTPTransport):222        def __init__(self):223            self.events = []224225        def close(self):226            # The base implementation of httpcore.SyncHTTPTransport just227            # calls into `.close`, so simple transport cases can just override228            # this method for any cleanup, where more complex cases229            # might want to additionally override `__enter__`/`__exit__`.230            self.events.append("transport.close")231232        def __enter__(self):233            super().__enter__()234            self.events.append("transport.__enter__")235236        def __exit__(self, *args):237            super().__exit__(*args)238            self.events.append("transport.__exit__")239240    transport = Transport()241    with httpx.Client(transport=transport):242        pass243244    assert transport.events == [245        "transport.__enter__",246        "transport.close",247        "transport.__exit__",248    ]249250251def test_context_managed_transport_and_mount():252    class Transport(httpcore.SyncHTTPTransport):253        def __init__(self, name: str):254            self.name: str = name255            self.events: typing.List[str] = []256257        def close(self):258            # The base implementation of httpcore.SyncHTTPTransport just259            # calls into `.close`, so simple transport cases can just override260            # this method for any cleanup, where more complex cases261            # might want to additionally override `__enter__`/`__exit__`.262            self.events.append(f"{self.name}.close")263264        def __enter__(self):265            super().__enter__()266            self.events.append(f"{self.name}.__enter__")267268        def __exit__(self, *args):269            super().__exit__(*args)270            self.events.append(f"{self.name}.__exit__")271272    transport = Transport(name="transport")273    mounted = Transport(name="mounted")274    with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}):275        pass276277    assert transport.events == [278        "transport.__enter__",279        "transport.close",280        "transport.__exit__",281    ]282    assert mounted.events == [283        "mounted.__enter__",284        "mounted.close",285        "mounted.__exit__",286    ]287288289def hello_world(request):290    return httpx.Response(200, text="Hello, world!")291292293def test_client_closed_state_using_implicit_open():294    client = httpx.Client(transport=httpx.MockTransport(hello_world))295296    assert not client.is_closed297    client.get("http://example.com")298299    assert not client.is_closed300    client.close()301302    assert client.is_closed303    with pytest.raises(RuntimeError):304        client.get("http://example.com")305306307def test_client_closed_state_using_with_block():308    with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:309        assert not client.is_closed310        client.get("http://example.com")311312    assert client.is_closed313    with pytest.raises(RuntimeError):314        client.get("http://example.com")315316317def echo_raw_headers(request: httpx.Request) -> httpx.Response:318    data = [319        (name.decode("ascii"), value.decode("ascii"))320        for name, value in request.headers.raw321    ]322    return httpx.Response(200, json=data)323324325def test_raw_client_header():326    """327    Set a header in the Client.328    """329    url = "http://example.org/echo_headers"330    headers = {"Example-Header": "example-value"}331332    client = httpx.Client(333        transport=httpx.MockTransport(echo_raw_headers), headers=headers334    )335    response = client.get(url)336337    assert response.status_code == 200338    assert response.json() == [339        ["Host", "example.org"],340        ["Accept", "*/*"],341        ["Accept-Encoding", "gzip, deflate, br"],342        ["Connection", "keep-alive"],343        ["User-Agent", f"python-httpx/{httpx.__version__}"],344        ["Example-Header", "example-value"],345    ]346347348def unmounted(request: httpx.Request) -> httpx.Response:349    data = {"app": "unmounted"}350    return httpx.Response(200, json=data)351352353def mounted(request: httpx.Request) -> httpx.Response:354    data = {"app": "mounted"}355    return httpx.Response(200, json=data)356357358def test_mounted_transport():359    transport = httpx.MockTransport(unmounted)360    mounts = {"custom://": httpx.MockTransport(mounted)}361362    client = httpx.Client(transport=transport, mounts=mounts)363364    response = client.get("https://www.example.com")365    assert response.status_code == 200366    assert response.json() == {"app": "unmounted"}367368    response = client.get("custom://www.example.com")369    assert response.status_code == 200370    assert response.json() == {"app": "mounted"}371372373def test_all_mounted_transport():374    mounts = {"all://": httpx.MockTransport(mounted)}375376    client = httpx.Client(mounts=mounts)377378    response = client.get("https://www.example.com")379    assert response.status_code == 200380    assert response.json() == {"app": "mounted"}