test_client.py
This file
Path
tests/client/test_client.py
302 lines · 9.1 KiB · Python
Last changed by
Preserve header casing (#1338)Tom Christiebefore adoptionc725387
History of this fileTake it
1from datetime import timedelta23import httpcore4import pytest56import httpx7from tests.utils import MockTransport8910def 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_pool_limits_deprecated():201 limits = httpx.Limits()202203 with pytest.warns(DeprecationWarning):204 httpx.Client(pool_limits=limits)205206 with pytest.warns(DeprecationWarning):207 httpx.AsyncClient(pool_limits=limits)208209210def test_context_managed_transport():211 class Transport(httpcore.SyncHTTPTransport):212 def __init__(self):213 self.events = []214215 def close(self):216 # The base implementation of httpcore.SyncHTTPTransport just217 # calls into `.close`, so simple transport cases can just override218 # this method for any cleanup, where more complex cases219 # might want to additionally override `__enter__`/`__exit__`.220 self.events.append("transport.close")221222 def __enter__(self):223 super().__enter__()224 self.events.append("transport.__enter__")225226 def __exit__(self, *args):227 super().__exit__(*args)228 self.events.append("transport.__exit__")229230 # Note that we're including 'proxies' here to *also* run through the231 # proxy context management, although we can't easily test that at the232 # moment, since we can't add proxies as transport instances.233 #234 # Once we have a more generalised Mount API we'll be able to remove this235 # in favour of ensuring all mounts are context managed, which will236 # also neccessarily include proxies.237 transport = Transport()238 with httpx.Client(transport=transport, proxies="http://www.example.com"):239 pass240241 assert transport.events == [242 "transport.__enter__",243 "transport.close",244 "transport.__exit__",245 ]246247248def hello_world(request):249 return httpx.Response(200, text="Hello, world!")250251252def test_client_closed_state_using_implicit_open():253 client = httpx.Client(transport=MockTransport(hello_world))254255 assert not client.is_closed256 client.get("http://example.com")257258 assert not client.is_closed259 client.close()260261 assert client.is_closed262 with pytest.raises(RuntimeError):263 client.get("http://example.com")264265266def test_client_closed_state_using_with_block():267 with httpx.Client(transport=MockTransport(hello_world)) as client:268 assert not client.is_closed269 client.get("http://example.com")270271 assert client.is_closed272 with pytest.raises(RuntimeError):273 client.get("http://example.com")274275276def echo_raw_headers(request: httpx.Request) -> httpx.Response:277 data = [278 (name.decode("ascii"), value.decode("ascii"))279 for name, value in request.headers.raw280 ]281 return httpx.Response(200, json=data)282283284def test_raw_client_header():285 """286 Set a header in the Client.287 """288 url = "http://example.org/echo_headers"289 headers = {"Example-Header": "example-value"}290291 client = httpx.Client(transport=MockTransport(echo_raw_headers), headers=headers)292 response = client.get(url)293294 assert response.status_code == 200295 assert response.json() == [296 ["Host", "example.org"],297 ["Accept", "*/*"],298 ["Accept-Encoding", "gzip, deflate, br"],299 ["Connection", "keep-alive"],300 ["User-Agent", f"python-httpx/{httpx.__version__}"],301 ["Example-Header", "example-value"],302 ]