Skip to content
Myr

test_client.py

This file

Path

tests/client/test_client.py

275 lines · 8.1 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 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/"182    with pytest.warns(DeprecationWarning):183        assert not request.url.is_ssl184185186def test_merge_relative_url():187    client = httpx.Client(base_url="https://www.example.com/")188    request = client.build_request("GET", "/testing/123")189    assert request.url == "https://www.example.com/testing/123"190191192def test_merge_relative_url_with_path():193    client = httpx.Client(base_url="https://www.example.com/some/path")194    request = client.build_request("GET", "/testing/123")195    assert request.url == "https://www.example.com/some/path/testing/123"196197198def test_merge_relative_url_with_dotted_path():199    client = httpx.Client(base_url="https://www.example.com/some/path")200    request = client.build_request("GET", "../testing/123")201    assert request.url == "https://www.example.com/some/testing/123"202203204def test_pool_limits_deprecated():205    limits = httpx.Limits()206207    with pytest.warns(DeprecationWarning):208        httpx.Client(pool_limits=limits)209210    with pytest.warns(DeprecationWarning):211        httpx.AsyncClient(pool_limits=limits)212213214def test_context_managed_transport():215    class Transport(httpcore.SyncHTTPTransport):216        def __init__(self):217            self.events = []218219        def close(self):220            # The base implementation of httpcore.SyncHTTPTransport just221            # calls into `.close`, so simple transport cases can just override222            # this method for any cleanup, where more complex cases223            # might want to additionally override `__enter__`/`__exit__`.224            self.events.append("transport.close")225226        def __enter__(self):227            super().__enter__()228            self.events.append("transport.__enter__")229230        def __exit__(self, *args):231            super().__exit__(*args)232            self.events.append("transport.__exit__")233234    # Note that we're including 'proxies' here to *also* run through the235    # proxy context management, although we can't easily test that at the236    # moment, since we can't add proxies as transport instances.237    #238    # Once we have a more generalised Mount API we'll be able to remove this239    # in favour of ensuring all mounts are context managed, which will240    # also neccessarily include proxies.241    transport = Transport()242    with httpx.Client(transport=transport, proxies="http://www.example.com"):243        pass244245    assert transport.events == [246        "transport.__enter__",247        "transport.close",248        "transport.__exit__",249    ]250251252def test_that_client_is_closed_by_default():253    client = httpx.Client()254255    assert client.is_closed256257258def test_that_send_cause_client_to_be_not_closed():259    client = httpx.Client()260261    client.get("http://example.com")262263    assert not client.is_closed264265266def test_that_client_is_not_closed_in_with_block():267    with httpx.Client() as client:268        assert not client.is_closed269270271def test_that_client_is_closed_after_with_block():272    with httpx.Client() as client:273        pass274275    assert client.is_closed