test_client.py
This file
Path
tests/client/test_client.py
369 lines · 10.9 KiB · Python
Last changed by
Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
History of this fileTake it
1import typing2from datetime import timedelta34import httpcore5import pytest67import httpx8from tests.utils import MockTransport91011def test_get(server):12 url = server.url13 with httpx.Client(http2=True) as http:14 response = http.get(url)15 assert response.status_code == 20016 assert response.url == url17 assert response.content == b"Hello, world!"18 assert response.text == "Hello, world!"19 assert response.http_version == "HTTP/1.1"20 assert response.encoding is None21 assert response.request.url == url22 assert response.headers23 assert response.is_redirect is False24 assert repr(response) == "<Response [200 OK]>"25 assert response.elapsed > timedelta(0)262728@pytest.mark.parametrize(29 "url",30 [31 pytest.param("invalid://example.org", id="scheme-not-http(s)"),32 pytest.param("://example.org", id="no-scheme"),33 pytest.param("http://", id="no-host"),34 ],35)36def test_get_invalid_url(server, url):37 with httpx.Client() as client:38 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):39 client.get(url)404142def test_build_request(server):43 url = server.url.copy_with(path="/echo_headers")44 headers = {"Custom-header": "value"}4546 with httpx.Client() as client:47 request = client.build_request("GET", url)48 request.headers.update(headers)49 response = client.send(request)5051 assert response.status_code == 20052 assert response.url == url5354 assert response.json()["Custom-header"] == "value"555657def test_build_post_request(server):58 url = server.url.copy_with(path="/echo_headers")59 headers = {"Custom-header": "value"}6061 with httpx.Client() as client:62 request = client.build_request("POST", url)63 request.headers.update(headers)64 response = client.send(request)6566 assert response.status_code == 20067 assert response.url == url6869 assert response.json()["Content-length"] == "0"70 assert response.json()["Custom-header"] == "value"717273def test_post(server):74 with httpx.Client() as client:75 response = client.post(server.url, content=b"Hello, world!")76 assert response.status_code == 20077 assert response.reason_phrase == "OK"787980def test_post_json(server):81 with httpx.Client() as client:82 response = client.post(server.url, json={"text": "Hello, world!"})83 assert response.status_code == 20084 assert response.reason_phrase == "OK"858687def test_stream_response(server):88 with httpx.Client() as client:89 with client.stream("GET", server.url) as response:90 content = response.read()91 assert response.status_code == 20092 assert content == b"Hello, world!"939495def test_stream_iterator(server):96 body = b""9798 with httpx.Client() as client:99 with client.stream("GET", server.url) as response:100 for chunk in response.iter_bytes():101 body += chunk102103 assert response.status_code == 200104 assert body == b"Hello, world!"105106107def test_raw_iterator(server):108 body = b""109110 with httpx.Client() as client:111 with client.stream("GET", server.url) as response:112 for chunk in response.iter_raw():113 body += chunk114115 assert response.status_code == 200116 assert body == b"Hello, world!"117118119def test_raise_for_status(server):120 with httpx.Client() as client:121 for status_code in (200, 400, 404, 500, 505):122 response = client.request(123 "GET", server.url.copy_with(path=f"/status/{status_code}")124 )125 if 400 <= status_code < 600:126 with pytest.raises(httpx.HTTPStatusError) as exc_info:127 response.raise_for_status()128 assert exc_info.value.response == response129 assert exc_info.value.request.url.path == f"/status/{status_code}"130 else:131 assert response.raise_for_status() is None # type: ignore132133134def test_options(server):135 with httpx.Client() as client:136 response = client.options(server.url)137 assert response.status_code == 200138 assert response.reason_phrase == "OK"139140141def test_head(server):142 with httpx.Client() as client:143 response = client.head(server.url)144 assert response.status_code == 200145 assert response.reason_phrase == "OK"146147148def test_put(server):149 with httpx.Client() as client:150 response = client.put(server.url, content=b"Hello, world!")151 assert response.status_code == 200152 assert response.reason_phrase == "OK"153154155def test_patch(server):156 with httpx.Client() as client:157 response = client.patch(server.url, content=b"Hello, world!")158 assert response.status_code == 200159 assert response.reason_phrase == "OK"160161162def test_delete(server):163 with httpx.Client() as client:164 response = client.delete(server.url)165 assert response.status_code == 200166 assert response.reason_phrase == "OK"167168169def test_base_url(server):170 base_url = server.url171 with httpx.Client(base_url=base_url) as client:172 response = client.get("/")173 assert response.status_code == 200174 assert response.url == base_url175176177def test_merge_absolute_url():178 client = httpx.Client(base_url="https://www.example.com/")179 request = client.build_request("GET", "http://www.example.com/")180 assert request.url == "http://www.example.com/"181182183def test_merge_relative_url():184 client = httpx.Client(base_url="https://www.example.com/")185 request = client.build_request("GET", "/testing/123")186 assert request.url == "https://www.example.com/testing/123"187188189def test_merge_relative_url_with_path():190 client = httpx.Client(base_url="https://www.example.com/some/path")191 request = client.build_request("GET", "/testing/123")192 assert request.url == "https://www.example.com/some/path/testing/123"193194195def test_merge_relative_url_with_dotted_path():196 client = httpx.Client(base_url="https://www.example.com/some/path")197 request = client.build_request("GET", "../testing/123")198 assert request.url == "https://www.example.com/some/testing/123"199200201def test_pool_limits_deprecated():202 limits = httpx.Limits()203204 with pytest.warns(DeprecationWarning):205 httpx.Client(pool_limits=limits)206207 with pytest.warns(DeprecationWarning):208 httpx.AsyncClient(pool_limits=limits)209210211def test_context_managed_transport():212 class Transport(httpcore.SyncHTTPTransport):213 def __init__(self):214 self.events = []215216 def close(self):217 # The base implementation of httpcore.SyncHTTPTransport just218 # calls into `.close`, so simple transport cases can just override219 # this method for any cleanup, where more complex cases220 # might want to additionally override `__enter__`/`__exit__`.221 self.events.append("transport.close")222223 def __enter__(self):224 super().__enter__()225 self.events.append("transport.__enter__")226227 def __exit__(self, *args):228 super().__exit__(*args)229 self.events.append("transport.__exit__")230231 transport = Transport()232 with httpx.Client(transport=transport):233 pass234235 assert transport.events == [236 "transport.__enter__",237 "transport.close",238 "transport.__exit__",239 ]240241242def test_context_managed_transport_and_mount():243 class Transport(httpcore.SyncHTTPTransport):244 def __init__(self, name: str):245 self.name: str = name246 self.events: typing.List[str] = []247248 def close(self):249 # The base implementation of httpcore.SyncHTTPTransport just250 # calls into `.close`, so simple transport cases can just override251 # this method for any cleanup, where more complex cases252 # might want to additionally override `__enter__`/`__exit__`.253 self.events.append(f"{self.name}.close")254255 def __enter__(self):256 super().__enter__()257 self.events.append(f"{self.name}.__enter__")258259 def __exit__(self, *args):260 super().__exit__(*args)261 self.events.append(f"{self.name}.__exit__")262263 transport = Transport(name="transport")264 mounted = Transport(name="mounted")265 with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}):266 pass267268 assert transport.events == [269 "transport.__enter__",270 "transport.close",271 "transport.__exit__",272 ]273 assert mounted.events == [274 "mounted.__enter__",275 "mounted.close",276 "mounted.__exit__",277 ]278279280def hello_world(request):281 return httpx.Response(200, text="Hello, world!")282283284def test_client_closed_state_using_implicit_open():285 client = httpx.Client(transport=MockTransport(hello_world))286287 assert not client.is_closed288 client.get("http://example.com")289290 assert not client.is_closed291 client.close()292293 assert client.is_closed294 with pytest.raises(RuntimeError):295 client.get("http://example.com")296297298def test_client_closed_state_using_with_block():299 with httpx.Client(transport=MockTransport(hello_world)) as client:300 assert not client.is_closed301 client.get("http://example.com")302303 assert client.is_closed304 with pytest.raises(RuntimeError):305 client.get("http://example.com")306307308def echo_raw_headers(request: httpx.Request) -> httpx.Response:309 data = [310 (name.decode("ascii"), value.decode("ascii"))311 for name, value in request.headers.raw312 ]313 return httpx.Response(200, json=data)314315316def test_raw_client_header():317 """318 Set a header in the Client.319 """320 url = "http://example.org/echo_headers"321 headers = {"Example-Header": "example-value"}322323 client = httpx.Client(transport=MockTransport(echo_raw_headers), headers=headers)324 response = client.get(url)325326 assert response.status_code == 200327 assert response.json() == [328 ["Host", "example.org"],329 ["Accept", "*/*"],330 ["Accept-Encoding", "gzip, deflate, br"],331 ["Connection", "keep-alive"],332 ["User-Agent", f"python-httpx/{httpx.__version__}"],333 ["Example-Header", "example-value"],334 ]335336337def unmounted(request: httpx.Request) -> httpx.Response:338 data = {"app": "unmounted"}339 return httpx.Response(200, json=data)340341342def mounted(request: httpx.Request) -> httpx.Response:343 data = {"app": "mounted"}344 return httpx.Response(200, json=data)345346347def test_mounted_transport():348 transport = MockTransport(unmounted)349 mounts = {"custom://": MockTransport(mounted)}350351 client = httpx.Client(transport=transport, mounts=mounts)352353 response = client.get("https://www.example.com")354 assert response.status_code == 200355 assert response.json() == {"app": "unmounted"}356357 response = client.get("custom://www.example.com")358 assert response.status_code == 200359 assert response.json() == {"app": "mounted"}360361362def test_all_mounted_transport():363 mounts = {"all://": MockTransport(mounted)}364365 client = httpx.Client(mounts=mounts)366367 response = client.get("https://www.example.com")368 assert response.status_code == 200369 assert response.json() == {"app": "mounted"}