test_client.py
This file
Path
tests/client/test_client.py
393 lines · 11.8 KiB · Python
Last changed by
Fix extenstions typo in AsyncHTTPTransport (#1549)Jonas Lundbergbefore adoption52dd95f
History of this fileTake it
The walk stopped after 200 commits: lines older than 31e587c point at it.
Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 1why, one step back1import typingPin pytestTom Christiebefore adoption31e587c
lines 2–10why, one step back2from datetime import timedelta34import pytest56import httpx789def test_get(server):10 url = server.urlHTTP/2 becomes fully optional (#1140)Tom Christiebefore adoption8d9dfb5
line 11why, one step back11 with httpx.Client(http2=True) as http:Pin pytestTom Christiebefore adoption31e587c
lines 12–17why, one step back12 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"Drop chardet (#1269)Tom Christiebefore adoptiond0fe113
line 18why, one step back18 assert response.encoding is NonePin pytestTom Christiebefore adoption31e587c
lines 19–35why, one step back19 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)242526@pytest.mark.parametrize(27 "url",28 [29 pytest.param("invalid://example.org", id="scheme-not-http(s)"),30 pytest.param("://example.org", id="no-scheme"),31 pytest.param("http://", id="no-host"),32 ],33)34def test_get_invalid_url(server, url):35 with httpx.Client() as client:Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722
line 36why, one step back36 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):Pin pytestTom Christiebefore adoption31e587c
lines 37–72why, one step back37 client.get(url)383940def test_build_request(server):41 url = server.url.copy_with(path="/echo_headers")42 headers = {"Custom-header": "value"}4344 with httpx.Client() as client:45 request = client.build_request("GET", url)46 request.headers.update(headers)47 response = client.send(request)4849 assert response.status_code == 20050 assert response.url == url5152 assert response.json()["Custom-header"] == "value"535455def test_build_post_request(server):56 url = server.url.copy_with(path="/echo_headers")57 headers = {"Custom-header": "value"}5859 with httpx.Client() as client:60 request = client.build_request("POST", url)61 request.headers.update(headers)62 response = client.send(request)6364 assert response.status_code == 20065 assert response.url == url6667 assert response.json()["Content-length"] == "0"68 assert response.json()["Custom-header"] == "value"697071def test_post(server):72 with httpx.Client() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 73why, one step back73 response = client.post(server.url, content=b"Hello, world!")Pin pytestTom Christiebefore adoption31e587c
lines 74–147why, one step back74 assert response.status_code == 20075 assert response.reason_phrase == "OK"767778def test_post_json(server):79 with httpx.Client() as client:80 response = client.post(server.url, json={"text": "Hello, world!"})81 assert response.status_code == 20082 assert response.reason_phrase == "OK"838485def test_stream_response(server):86 with httpx.Client() as client:87 with client.stream("GET", server.url) as response:88 content = response.read()89 assert response.status_code == 20090 assert content == b"Hello, world!"919293def test_stream_iterator(server):94 body = b""9596 with httpx.Client() as client:97 with client.stream("GET", server.url) as response:98 for chunk in response.iter_bytes():99 body += chunk100101 assert response.status_code == 200102 assert body == b"Hello, world!"103104105def test_raw_iterator(server):106 body = b""107108 with httpx.Client() as client:109 with client.stream("GET", server.url) as response:110 for chunk in response.iter_raw():111 body += chunk112113 assert response.status_code == 200114 assert body == b"Hello, world!"115116117def test_raise_for_status(server):118 with httpx.Client() as client:119 for status_code in (200, 400, 404, 500, 505):120 response = client.request(121 "GET", server.url.copy_with(path=f"/status/{status_code}")122 )123 if 400 <= status_code < 600:124 with pytest.raises(httpx.HTTPStatusError) as exc_info:125 response.raise_for_status()126 assert exc_info.value.response == response127 assert exc_info.value.request.url.path == f"/status/{status_code}"128 else:129 assert response.raise_for_status() is None # type: ignore130131132def test_options(server):133 with httpx.Client() as client:134 response = client.options(server.url)135 assert response.status_code == 200136 assert response.reason_phrase == "OK"137138139def test_head(server):140 with httpx.Client() as client:141 response = client.head(server.url)142 assert response.status_code == 200143 assert response.reason_phrase == "OK"144145146def test_put(server):147 with httpx.Client() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 148why, one step back148 response = client.put(server.url, content=b"Hello, world!")Pin pytestTom Christiebefore adoption31e587c
lines 149–154why, one step back149 assert response.status_code == 200150 assert response.reason_phrase == "OK"151152153def test_patch(server):154 with httpx.Client() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 155why, one step back155 response = client.patch(server.url, content=b"Hello, world!")Pin pytestTom Christiebefore adoption31e587c
lines 156–174why, one step back156 assert response.status_code == 200157 assert response.reason_phrase == "OK"158159160def test_delete(server):161 with httpx.Client() as client:162 response = client.delete(server.url)163 assert response.status_code == 200164 assert response.reason_phrase == "OK"165166167def test_base_url(server):168 base_url = server.url169 with httpx.Client(base_url=base_url) as client:170 response = client.get("/")171 assert response.status_code == 200172 assert response.url == base_url173174Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6
line 175why, one step back175def test_merge_absolute_url():Drop HSTS Preloading (#1110)Florimond Mancabefore adoption78cf16a
line 176why, one step back176 client = httpx.Client(base_url="https://www.example.com/")Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6
line 177why, one step back177 request = client.build_request("GET", "http://www.example.com/")Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209
line 178why, one step back178 assert request.url == "http://www.example.com/"Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6
lines 179–183why, one step back179180181def test_merge_relative_url():182 client = httpx.Client(base_url="https://www.example.com/")183 request = client.build_request("GET", "/testing/123")Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209
line 184why, one step back184 assert request.url == "https://www.example.com/testing/123"Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6
lines 185–189why, one step back185186187def test_merge_relative_url_with_path():188 client = httpx.Client(base_url="https://www.example.com/some/path")189 request = client.build_request("GET", "/testing/123")Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209
line 190why, one step back190 assert request.url == "https://www.example.com/some/path/testing/123"Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6
lines 191–195why, one step back191192193def test_merge_relative_url_with_dotted_path():194 client = httpx.Client(base_url="https://www.example.com/some/path")195 request = client.build_request("GET", "../testing/123")Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209
line 196why, one step back196 assert request.url == "https://www.example.com/some/testing/123"Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925
lines 197–198why, one step back197198Fix some cases of merging with base_url (#1532)Tom Christiebefore adoption6cb1672
lines 199–204why, one step back199def test_merge_relative_url_with_path_including_colon():200 client = httpx.Client(base_url="https://www.example.com/some/path")201 request = client.build_request("GET", "/testing:123")202 assert request.url == "https://www.example.com/some/path/testing:123"203204Properly encoded slashes when using `base_url` (#1407)Florimond Mancabefore adoption9005bd5
lines 205–214why, one step back205def test_merge_relative_url_with_encoded_slashes():206 client = httpx.Client(base_url="https://www.example.com/")207 request = client.build_request("GET", "/testing%2F123")208 assert request.url == "https://www.example.com/testing%2F123"209210 client = httpx.Client(base_url="https://www.example.com/base%2Fpath")211 request = client.build_request("GET", "/testing")212 assert request.url == "https://www.example.com/base%2Fpath/testing"213214Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925
lines 215–222why, one step back215def test_pool_limits_deprecated():216 limits = httpx.Limits()217218 with pytest.warns(DeprecationWarning):219 httpx.Client(pool_limits=limits)220221 with pytest.warns(DeprecationWarning):222 httpx.AsyncClient(pool_limits=limits)Context managed transports (#1218)Tom Christiebefore adoption534400e
lines 223–225why, one step back223224225def test_context_managed_transport():Transport API (#1522)Tom Christiebefore adoption1a6e254
line 226why, one step back226 class Transport(httpx.BaseTransport):Context managed transports (#1218)Tom Christiebefore adoption534400e
lines 227–230why, one step back227 def __init__(self):228 self.events = []229230 def close(self):Transport API (#1522)Tom Christiebefore adoption1a6e254
line 231why, one step back231 # The base implementation of httpx.BaseTransport justContext managed transports (#1218)Tom Christiebefore adoption534400e
lines 232–245why, one step back232 # calls into `.close`, so simple transport cases can just override233 # this method for any cleanup, where more complex cases234 # might want to additionally override `__enter__`/`__exit__`.235 self.events.append("transport.close")236237 def __enter__(self):238 super().__enter__()239 self.events.append("transport.__enter__")240241 def __exit__(self, *args):242 super().__exit__(*args)243 self.events.append("transport.__exit__")244245 transport = Transport()Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 246why, one step back246 with httpx.Client(transport=transport):Context managed transports (#1218)Tom Christiebefore adoption534400e
lines 247–253why, one step back247 pass248249 assert transport.events == [250 "transport.__enter__",251 "transport.close",252 "transport.__exit__",253 ]Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 254–255why, one step back254255Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 256why, one step back256def test_context_managed_transport_and_mount():Transport API (#1522)Tom Christiebefore adoption1a6e254
line 257why, one step back257 class Transport(httpx.BaseTransport):Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 258–262why, one step back258 def __init__(self, name: str):259 self.name: str = name260 self.events: typing.List[str] = []261262 def close(self):Transport API (#1522)Tom Christiebefore adoption1a6e254
line 263why, one step back263 # The base implementation of httpx.BaseTransport justAdd support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 264–293why, one step back264 # calls into `.close`, so simple transport cases can just override265 # this method for any cleanup, where more complex cases266 # might want to additionally override `__enter__`/`__exit__`.267 self.events.append(f"{self.name}.close")268269 def __enter__(self):270 super().__enter__()271 self.events.append(f"{self.name}.__enter__")272273 def __exit__(self, *args):274 super().__exit__(*args)275 self.events.append(f"{self.name}.__exit__")276277 transport = Transport(name="transport")278 mounted = Transport(name="mounted")279 with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}):280 pass281282 assert transport.events == [283 "transport.__enter__",284 "transport.close",285 "transport.__exit__",286 ]287 assert mounted.events == [288 "mounted.__enter__",289 "mounted.close",290 "mounted.__exit__",291 ]292293Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 294–295why, one step back294def hello_world(request):295 return httpx.Response(200, text="Hello, world!")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 296–297why, one step back296297Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 298why, one step back298def test_client_closed_state_using_implicit_open():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 299why, one step back299 client = httpx.Client(transport=httpx.MockTransport(hello_world))Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 300why, one step back300Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 301why, one step back301 assert not client.is_closedIssue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 302–304why, one step back302 client.get("http://example.com")303304 assert not client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 305why, one step back305 client.close()Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 306why, one step back306Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 307–309why, one step back307 assert client.is_closed308 with pytest.raises(RuntimeError):309 client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 310why, one step back310Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 311–312why, one step back311312def test_client_closed_state_using_with_block():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 313why, one step back313 with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 314why, one step back314 assert not client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 315why, one step back315 client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 316–317why, one step back316317 assert client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 318–319why, one step back318 with pytest.raises(RuntimeError):319 client.get("http://example.com")Preserve header casing (#1338)Tom Christiebefore adoptionc725387
lines 320–336why, one step back320321322def echo_raw_headers(request: httpx.Request) -> httpx.Response:323 data = [324 (name.decode("ascii"), value.decode("ascii"))325 for name, value in request.headers.raw326 ]327 return httpx.Response(200, json=data)328329330def test_raw_client_header():331 """332 Set a header in the Client.333 """334 url = "http://example.org/echo_headers"335 headers = {"Example-Header": "example-value"}336Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 337–339why, one step back337 client = httpx.Client(338 transport=httpx.MockTransport(echo_raw_headers), headers=headers339 )Preserve header casing (#1338)Tom Christiebefore adoptionc725387
lines 340–350why, one step back340 response = client.get(url)341342 assert response.status_code == 200343 assert response.json() == [344 ["Host", "example.org"],345 ["Accept", "*/*"],346 ["Accept-Encoding", "gzip, deflate, br"],347 ["Connection", "keep-alive"],348 ["User-Agent", f"python-httpx/{httpx.__version__}"],349 ["Example-Header", "example-value"],350 ]Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 351–363why, one step back351352353def unmounted(request: httpx.Request) -> httpx.Response:354 data = {"app": "unmounted"}355 return httpx.Response(200, json=data)356357358def mounted(request: httpx.Request) -> httpx.Response:359 data = {"app": "mounted"}360 return httpx.Response(200, json=data)361362363def test_mounted_transport():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 364–365why, one step back364 transport = httpx.MockTransport(unmounted)365 mounts = {"custom://": httpx.MockTransport(mounted)}Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 366–378why, one step back366367 client = httpx.Client(transport=transport, mounts=mounts)368369 response = client.get("https://www.example.com")370 assert response.status_code == 200371 assert response.json() == {"app": "unmounted"}372373 response = client.get("custom://www.example.com")374 assert response.status_code == 200375 assert response.json() == {"app": "mounted"}376377378def test_all_mounted_transport():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 379why, one step back379 mounts = {"all://": httpx.MockTransport(mounted)}Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 380–385why, one step back380381 client = httpx.Client(mounts=mounts)382383 response = client.get("https://www.example.com")384 assert response.status_code == 200385 assert response.json() == {"app": "mounted"}Fix extenstions typo in AsyncHTTPTransport (#1549)Jonas Lundbergbefore adoption52dd95f
lines 386–393why, one step back386387388def test_server_extensions(server):389 url = server.url.copy_with(path="/http_version_2")390 with httpx.Client(http2=True) as client:391 response = client.get(url)392 assert response.status_code == 200393 assert response.extensions["http_version"] == b"HTTP/1.1"