test_client.py
This file
Path
tests/client/test_client.py
276 lines · 8.3 KiB · Python
Last changed by
Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
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)2526 with pytest.raises(httpx.NotRedirectResponse):27 response.next()282930@pytest.mark.parametrize(31 "url",32 [33 pytest.param("invalid://example.org", id="scheme-not-http(s)"),34 pytest.param("://example.org", id="no-scheme"),35 pytest.param("http://", id="no-host"),36 ],37)38def test_get_invalid_url(server, url):39 with httpx.Client() as client:40 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):41 client.get(url)424344def test_build_request(server):45 url = server.url.copy_with(path="/echo_headers")46 headers = {"Custom-header": "value"}4748 with httpx.Client() as client:49 request = client.build_request("GET", url)50 request.headers.update(headers)51 response = client.send(request)5253 assert response.status_code == 20054 assert response.url == url5556 assert response.json()["Custom-header"] == "value"575859def test_build_post_request(server):60 url = server.url.copy_with(path="/echo_headers")61 headers = {"Custom-header": "value"}6263 with httpx.Client() as client:64 request = client.build_request("POST", url)65 request.headers.update(headers)66 response = client.send(request)6768 assert response.status_code == 20069 assert response.url == url7071 assert response.json()["Content-length"] == "0"72 assert response.json()["Custom-header"] == "value"737475def test_post(server):76 with httpx.Client() as client:77 response = client.post(server.url, content=b"Hello, world!")78 assert response.status_code == 20079 assert response.reason_phrase == "OK"808182def test_post_json(server):83 with httpx.Client() as client:84 response = client.post(server.url, json={"text": "Hello, world!"})85 assert response.status_code == 20086 assert response.reason_phrase == "OK"878889def test_stream_response(server):90 with httpx.Client() as client:91 with client.stream("GET", server.url) as response:92 content = response.read()93 assert response.status_code == 20094 assert content == b"Hello, world!"959697def test_stream_iterator(server):98 body = b""99100 with httpx.Client() as client:101 with client.stream("GET", server.url) as response:102 for chunk in response.iter_bytes():103 body += chunk104105 assert response.status_code == 200106 assert body == b"Hello, world!"107108109def test_raw_iterator(server):110 body = b""111112 with httpx.Client() as client:113 with client.stream("GET", server.url) as response:114 for chunk in response.iter_raw():115 body += chunk116117 assert response.status_code == 200118 assert body == b"Hello, world!"119120121def test_raise_for_status(server):122 with httpx.Client() as client:123 for status_code in (200, 400, 404, 500, 505):124 response = client.request(125 "GET", server.url.copy_with(path=f"/status/{status_code}")126 )127 if 400 <= status_code < 600:128 with pytest.raises(httpx.HTTPStatusError) as exc_info:129 response.raise_for_status()130 assert exc_info.value.response == response131 assert exc_info.value.request.url.path == f"/status/{status_code}"132 else:133 assert response.raise_for_status() is None # type: ignore134135136def test_options(server):137 with httpx.Client() as client:138 response = client.options(server.url)139 assert response.status_code == 200140 assert response.reason_phrase == "OK"141142143def test_head(server):144 with httpx.Client() as client:145 response = client.head(server.url)146 assert response.status_code == 200147 assert response.reason_phrase == "OK"148149150def test_put(server):151 with httpx.Client() as client:152 response = client.put(server.url, content=b"Hello, world!")153 assert response.status_code == 200154 assert response.reason_phrase == "OK"155156157def test_patch(server):158 with httpx.Client() as client:159 response = client.patch(server.url, content=b"Hello, world!")160 assert response.status_code == 200161 assert response.reason_phrase == "OK"162163164def test_delete(server):165 with httpx.Client() as client:166 response = client.delete(server.url)167 assert response.status_code == 200168 assert response.reason_phrase == "OK"169170171def test_base_url(server):172 base_url = server.url173 with httpx.Client(base_url=base_url) as client:174 response = client.get("/")175 assert response.status_code == 200176 assert response.url == base_url177178179def test_merge_absolute_url():180 client = httpx.Client(base_url="https://www.example.com/")181 request = client.build_request("GET", "http://www.example.com/")182 assert request.url == "http://www.example.com/"183184185def test_merge_relative_url():186 client = httpx.Client(base_url="https://www.example.com/")187 request = client.build_request("GET", "/testing/123")188 assert request.url == "https://www.example.com/testing/123"189190191def test_merge_relative_url_with_path():192 client = httpx.Client(base_url="https://www.example.com/some/path")193 request = client.build_request("GET", "/testing/123")194 assert request.url == "https://www.example.com/some/path/testing/123"195196197def test_merge_relative_url_with_dotted_path():198 client = httpx.Client(base_url="https://www.example.com/some/path")199 request = client.build_request("GET", "../testing/123")200 assert request.url == "https://www.example.com/some/testing/123"201202203def test_pool_limits_deprecated():204 limits = httpx.Limits()205206 with pytest.warns(DeprecationWarning):207 httpx.Client(pool_limits=limits)208209 with pytest.warns(DeprecationWarning):210 httpx.AsyncClient(pool_limits=limits)211212213def test_context_managed_transport():214 class Transport(httpcore.SyncHTTPTransport):215 def __init__(self):216 self.events = []217218 def close(self):219 # The base implementation of httpcore.SyncHTTPTransport just220 # calls into `.close`, so simple transport cases can just override221 # this method for any cleanup, where more complex cases222 # might want to additionally override `__enter__`/`__exit__`.223 self.events.append("transport.close")224225 def __enter__(self):226 super().__enter__()227 self.events.append("transport.__enter__")228229 def __exit__(self, *args):230 super().__exit__(*args)231 self.events.append("transport.__exit__")232233 # Note that we're including 'proxies' here to *also* run through the234 # proxy context management, although we can't easily test that at the235 # moment, since we can't add proxies as transport instances.236 #237 # Once we have a more generalised Mount API we'll be able to remove this238 # in favour of ensuring all mounts are context managed, which will239 # also neccessarily include proxies.240 transport = Transport()241 with httpx.Client(transport=transport, proxies="http://www.example.com"):242 pass243244 assert transport.events == [245 "transport.__enter__",246 "transport.close",247 "transport.__exit__",248 ]249250251def hello_world(request):252 return httpx.Response(200, text="Hello, world!")253254255def test_client_closed_state_using_implicit_open():256 client = httpx.Client(transport=MockTransport(hello_world))257258 assert not client.is_closed259 client.get("http://example.com")260261 assert not client.is_closed262 client.close()263264 assert client.is_closed265 with pytest.raises(RuntimeError):266 client.get("http://example.com")267268269def test_client_closed_state_using_with_block():270 with httpx.Client(transport=MockTransport(hello_world)) as client:271 assert not client.is_closed272 client.get("http://example.com")273274 assert client.is_closed275 with pytest.raises(RuntimeError):276 client.get("http://example.com")