Skip to content
Myr

test_client.py

This file

Path

tests/client/test_client.py

273 lines · 8.1 KiB · Python

Last changed by

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

History of this file

Take it

1from datetime import timedelta23import httpcore4import pytest56import httpx789def test_get(server):10    url = server.url11    with httpx.Client(http2=True) as http:12        response = http.get(url)13    assert response.status_code == 20014    assert response.url == url15    assert response.content == b"Hello, world!"16    assert response.text == "Hello, world!"17    assert response.http_version == "HTTP/1.1"18    assert response.encoding is None19    assert response.request.url == url20    assert response.headers21    assert response.is_redirect is False22    assert repr(response) == "<Response [200 OK]>"23    assert response.elapsed > timedelta(0)2425    with pytest.raises(httpx.NotRedirectResponse):26        response.next()272829@pytest.mark.parametrize(30    "url",31    [32        pytest.param("invalid://example.org", id="scheme-not-http(s)"),33        pytest.param("://example.org", id="no-scheme"),34        pytest.param("http://", id="no-host"),35    ],36)37def test_get_invalid_url(server, url):38    with httpx.Client() as client:39        with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):40            client.get(url)414243def test_build_request(server):44    url = server.url.copy_with(path="/echo_headers")45    headers = {"Custom-header": "value"}4647    with httpx.Client() as client:48        request = client.build_request("GET", url)49        request.headers.update(headers)50        response = client.send(request)5152    assert response.status_code == 20053    assert response.url == url5455    assert response.json()["Custom-header"] == "value"565758def test_build_post_request(server):59    url = server.url.copy_with(path="/echo_headers")60    headers = {"Custom-header": "value"}6162    with httpx.Client() as client:63        request = client.build_request("POST", url)64        request.headers.update(headers)65        response = client.send(request)6667    assert response.status_code == 20068    assert response.url == url6970    assert response.json()["Content-length"] == "0"71    assert response.json()["Custom-header"] == "value"727374def test_post(server):75    with httpx.Client() as client:76        response = client.post(server.url, content=b"Hello, world!")77    assert response.status_code == 20078    assert response.reason_phrase == "OK"798081def test_post_json(server):82    with httpx.Client() as client:83        response = client.post(server.url, json={"text": "Hello, world!"})84    assert response.status_code == 20085    assert response.reason_phrase == "OK"868788def test_stream_response(server):89    with httpx.Client() as client:90        with client.stream("GET", server.url) as response:91            content = response.read()92    assert response.status_code == 20093    assert content == b"Hello, world!"949596def test_stream_iterator(server):97    body = b""9899    with httpx.Client() as client:100        with client.stream("GET", server.url) as response:101            for chunk in response.iter_bytes():102                body += chunk103104    assert response.status_code == 200105    assert body == b"Hello, world!"106107108def test_raw_iterator(server):109    body = b""110111    with httpx.Client() as client:112        with client.stream("GET", server.url) as response:113            for chunk in response.iter_raw():114                body += chunk115116    assert response.status_code == 200117    assert body == b"Hello, world!"118119120def test_raise_for_status(server):121    with httpx.Client() as client:122        for status_code in (200, 400, 404, 500, 505):123            response = client.request(124                "GET", server.url.copy_with(path=f"/status/{status_code}")125            )126            if 400 <= status_code < 600:127                with pytest.raises(httpx.HTTPStatusError) as exc_info:128                    response.raise_for_status()129                assert exc_info.value.response == response130                assert exc_info.value.request.url.path == f"/status/{status_code}"131            else:132                assert response.raise_for_status() is None  # type: ignore133134135def test_options(server):136    with httpx.Client() as client:137        response = client.options(server.url)138    assert response.status_code == 200139    assert response.reason_phrase == "OK"140141142def test_head(server):143    with httpx.Client() as client:144        response = client.head(server.url)145    assert response.status_code == 200146    assert response.reason_phrase == "OK"147148149def test_put(server):150    with httpx.Client() as client:151        response = client.put(server.url, content=b"Hello, world!")152    assert response.status_code == 200153    assert response.reason_phrase == "OK"154155156def test_patch(server):157    with httpx.Client() as client:158        response = client.patch(server.url, content=b"Hello, world!")159    assert response.status_code == 200160    assert response.reason_phrase == "OK"161162163def test_delete(server):164    with httpx.Client() as client:165        response = client.delete(server.url)166    assert response.status_code == 200167    assert response.reason_phrase == "OK"168169170def test_base_url(server):171    base_url = server.url172    with httpx.Client(base_url=base_url) as client:173        response = client.get("/")174    assert response.status_code == 200175    assert response.url == base_url176177178def test_merge_absolute_url():179    client = httpx.Client(base_url="https://www.example.com/")180    request = client.build_request("GET", "http://www.example.com/")181    assert request.url == "http://www.example.com/"182183184def test_merge_relative_url():185    client = httpx.Client(base_url="https://www.example.com/")186    request = client.build_request("GET", "/testing/123")187    assert request.url == "https://www.example.com/testing/123"188189190def test_merge_relative_url_with_path():191    client = httpx.Client(base_url="https://www.example.com/some/path")192    request = client.build_request("GET", "/testing/123")193    assert request.url == "https://www.example.com/some/path/testing/123"194195196def test_merge_relative_url_with_dotted_path():197    client = httpx.Client(base_url="https://www.example.com/some/path")198    request = client.build_request("GET", "../testing/123")199    assert request.url == "https://www.example.com/some/testing/123"200201202def test_pool_limits_deprecated():203    limits = httpx.Limits()204205    with pytest.warns(DeprecationWarning):206        httpx.Client(pool_limits=limits)207208    with pytest.warns(DeprecationWarning):209        httpx.AsyncClient(pool_limits=limits)210211212def test_context_managed_transport():213    class Transport(httpcore.SyncHTTPTransport):214        def __init__(self):215            self.events = []216217        def close(self):218            # The base implementation of httpcore.SyncHTTPTransport just219            # calls into `.close`, so simple transport cases can just override220            # this method for any cleanup, where more complex cases221            # might want to additionally override `__enter__`/`__exit__`.222            self.events.append("transport.close")223224        def __enter__(self):225            super().__enter__()226            self.events.append("transport.__enter__")227228        def __exit__(self, *args):229            super().__exit__(*args)230            self.events.append("transport.__exit__")231232    # Note that we're including 'proxies' here to *also* run through the233    # proxy context management, although we can't easily test that at the234    # moment, since we can't add proxies as transport instances.235    #236    # Once we have a more generalised Mount API we'll be able to remove this237    # in favour of ensuring all mounts are context managed, which will238    # also neccessarily include proxies.239    transport = Transport()240    with httpx.Client(transport=transport, proxies="http://www.example.com"):241        pass242243    assert transport.events == [244        "transport.__enter__",245        "transport.close",246        "transport.__exit__",247    ]248249250def test_that_client_is_closed_by_default():251    client = httpx.Client()252253    assert client.is_closed254255256def test_that_send_cause_client_to_be_not_closed():257    client = httpx.Client()258259    client.get("http://example.com")260261    assert not client.is_closed262263264def test_that_client_is_not_closed_in_with_block():265    with httpx.Client() as client:266        assert not client.is_closed267268269def test_that_client_is_closed_after_with_block():270    with httpx.Client() as client:271        pass272273    assert client.is_closed