test_client.py
This file
Path
tests/client/test_client.py
403 lines · 12.1 KiB · Python
Last changed by
Drop 'Response(on_close=...)' from API (#1572)Tom Christiebefore adoption073a328
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–116why, 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!"115116Drop 'Response(on_close=...)' from API (#1572)Tom Christiebefore adoption073a328
lines 117–126why, one step back117def test_cannot_stream_async_request(server):118 async def hello_world(): # pragma: nocover119 yield b"Hello, "120 yield b"world!"121122 with httpx.Client() as client:123 with pytest.raises(RuntimeError):124 client.post(server.url, content=hello_world())125126Pin pytestTom Christiebefore adoption31e587c
lines 127–157why, one step back127def test_raise_for_status(server):128 with httpx.Client() as client:129 for status_code in (200, 400, 404, 500, 505):130 response = client.request(131 "GET", server.url.copy_with(path=f"/status/{status_code}")132 )133 if 400 <= status_code < 600:134 with pytest.raises(httpx.HTTPStatusError) as exc_info:135 response.raise_for_status()136 assert exc_info.value.response == response137 assert exc_info.value.request.url.path == f"/status/{status_code}"138 else:139 assert response.raise_for_status() is None # type: ignore140141142def test_options(server):143 with httpx.Client() as client:144 response = client.options(server.url)145 assert response.status_code == 200146 assert response.reason_phrase == "OK"147148149def test_head(server):150 with httpx.Client() as client:151 response = client.head(server.url)152 assert response.status_code == 200153 assert response.reason_phrase == "OK"154155156def test_put(server):157 with httpx.Client() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 158why, one step back158 response = client.put(server.url, content=b"Hello, world!")Pin pytestTom Christiebefore adoption31e587c
lines 159–164why, one step back159 assert response.status_code == 200160 assert response.reason_phrase == "OK"161162163def test_patch(server):164 with httpx.Client() as client:Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 165why, one step back165 response = client.patch(server.url, content=b"Hello, world!")Pin pytestTom Christiebefore adoption31e587c
lines 166–184why, one step back166 assert response.status_code == 200167 assert response.reason_phrase == "OK"168169170def test_delete(server):171 with httpx.Client() as client:172 response = client.delete(server.url)173 assert response.status_code == 200174 assert response.reason_phrase == "OK"175176177def test_base_url(server):178 base_url = server.url179 with httpx.Client(base_url=base_url) as client:180 response = client.get("/")181 assert response.status_code == 200182 assert response.url == base_url183184Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6
line 185why, one step back185def test_merge_absolute_url():Drop HSTS Preloading (#1110)Florimond Mancabefore adoption78cf16a
line 186why, one step back186 client = httpx.Client(base_url="https://www.example.com/")Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6
line 187why, one step back187 request = client.build_request("GET", "http://www.example.com/")Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209
line 188why, one step back188 assert request.url == "http://www.example.com/"Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6
lines 189–193why, one step back189190191def test_merge_relative_url():192 client = httpx.Client(base_url="https://www.example.com/")193 request = client.build_request("GET", "/testing/123")Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209
line 194why, one step back194 assert request.url == "https://www.example.com/testing/123"Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6
lines 195–199why, one step back195196197def test_merge_relative_url_with_path():198 client = httpx.Client(base_url="https://www.example.com/some/path")199 request = client.build_request("GET", "/testing/123")Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209
line 200why, one step back200 assert request.url == "https://www.example.com/some/path/testing/123"Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6
lines 201–205why, one step back201202203def test_merge_relative_url_with_dotted_path():204 client = httpx.Client(base_url="https://www.example.com/some/path")205 request = client.build_request("GET", "../testing/123")Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209
line 206why, one step back206 assert request.url == "https://www.example.com/some/testing/123"Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925
lines 207–208why, one step back207208Fix some cases of merging with base_url (#1532)Tom Christiebefore adoption6cb1672
lines 209–214why, one step back209def test_merge_relative_url_with_path_including_colon():210 client = httpx.Client(base_url="https://www.example.com/some/path")211 request = client.build_request("GET", "/testing:123")212 assert request.url == "https://www.example.com/some/path/testing:123"213214Properly encoded slashes when using `base_url` (#1407)Florimond Mancabefore adoption9005bd5
lines 215–224why, one step back215def test_merge_relative_url_with_encoded_slashes():216 client = httpx.Client(base_url="https://www.example.com/")217 request = client.build_request("GET", "/testing%2F123")218 assert request.url == "https://www.example.com/testing%2F123"219220 client = httpx.Client(base_url="https://www.example.com/base%2Fpath")221 request = client.build_request("GET", "/testing")222 assert request.url == "https://www.example.com/base%2Fpath/testing"223224Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925
lines 225–232why, one step back225def test_pool_limits_deprecated():226 limits = httpx.Limits()227228 with pytest.warns(DeprecationWarning):229 httpx.Client(pool_limits=limits)230231 with pytest.warns(DeprecationWarning):232 httpx.AsyncClient(pool_limits=limits)Context managed transports (#1218)Tom Christiebefore adoption534400e
lines 233–235why, one step back233234235def test_context_managed_transport():Transport API (#1522)Tom Christiebefore adoption1a6e254
line 236why, one step back236 class Transport(httpx.BaseTransport):Context managed transports (#1218)Tom Christiebefore adoption534400e
lines 237–240why, one step back237 def __init__(self):238 self.events = []239240 def close(self):Transport API (#1522)Tom Christiebefore adoption1a6e254
line 241why, one step back241 # The base implementation of httpx.BaseTransport justContext managed transports (#1218)Tom Christiebefore adoption534400e
lines 242–255why, one step back242 # calls into `.close`, so simple transport cases can just override243 # this method for any cleanup, where more complex cases244 # might want to additionally override `__enter__`/`__exit__`.245 self.events.append("transport.close")246247 def __enter__(self):248 super().__enter__()249 self.events.append("transport.__enter__")250251 def __exit__(self, *args):252 super().__exit__(*args)253 self.events.append("transport.__exit__")254255 transport = Transport()Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 256why, one step back256 with httpx.Client(transport=transport):Context managed transports (#1218)Tom Christiebefore adoption534400e
lines 257–263why, one step back257 pass258259 assert transport.events == [260 "transport.__enter__",261 "transport.close",262 "transport.__exit__",263 ]Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 264–265why, one step back264265Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 266why, one step back266def test_context_managed_transport_and_mount():Transport API (#1522)Tom Christiebefore adoption1a6e254
line 267why, one step back267 class Transport(httpx.BaseTransport):Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 268–272why, one step back268 def __init__(self, name: str):269 self.name: str = name270 self.events: typing.List[str] = []271272 def close(self):Transport API (#1522)Tom Christiebefore adoption1a6e254
line 273why, one step back273 # The base implementation of httpx.BaseTransport justAdd support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 274–303why, one step back274 # calls into `.close`, so simple transport cases can just override275 # this method for any cleanup, where more complex cases276 # might want to additionally override `__enter__`/`__exit__`.277 self.events.append(f"{self.name}.close")278279 def __enter__(self):280 super().__enter__()281 self.events.append(f"{self.name}.__enter__")282283 def __exit__(self, *args):284 super().__exit__(*args)285 self.events.append(f"{self.name}.__exit__")286287 transport = Transport(name="transport")288 mounted = Transport(name="mounted")289 with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}):290 pass291292 assert transport.events == [293 "transport.__enter__",294 "transport.close",295 "transport.__exit__",296 ]297 assert mounted.events == [298 "mounted.__enter__",299 "mounted.close",300 "mounted.__exit__",301 ]302303Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 304–305why, one step back304def hello_world(request):305 return httpx.Response(200, text="Hello, world!")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 306–307why, one step back306307Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 308why, one step back308def test_client_closed_state_using_implicit_open():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 309why, one step back309 client = httpx.Client(transport=httpx.MockTransport(hello_world))Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 310why, one step back310Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 311why, one step back311 assert not client.is_closedIssue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 312–314why, one step back312 client.get("http://example.com")313314 assert not client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 315why, one step back315 client.close()Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 316why, one step back316Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 317–319why, one step back317 assert client.is_closed318 with pytest.raises(RuntimeError):319 client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 320why, one step back320Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 321–322why, one step back321322def test_client_closed_state_using_with_block():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 323why, one step back323 with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 324why, one step back324 assert not client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 325why, one step back325 client.get("http://example.com")Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 326–327why, one step back326327 assert client.is_closedTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 328–329why, one step back328 with pytest.raises(RuntimeError):329 client.get("http://example.com")Preserve header casing (#1338)Tom Christiebefore adoptionc725387
lines 330–346why, one step back330331332def echo_raw_headers(request: httpx.Request) -> httpx.Response:333 data = [334 (name.decode("ascii"), value.decode("ascii"))335 for name, value in request.headers.raw336 ]337 return httpx.Response(200, json=data)338339340def test_raw_client_header():341 """342 Set a header in the Client.343 """344 url = "http://example.org/echo_headers"345 headers = {"Example-Header": "example-value"}346Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 347–349why, one step back347 client = httpx.Client(348 transport=httpx.MockTransport(echo_raw_headers), headers=headers349 )Preserve header casing (#1338)Tom Christiebefore adoptionc725387
lines 350–360why, one step back350 response = client.get(url)351352 assert response.status_code == 200353 assert response.json() == [354 ["Host", "example.org"],355 ["Accept", "*/*"],356 ["Accept-Encoding", "gzip, deflate, br"],357 ["Connection", "keep-alive"],358 ["User-Agent", f"python-httpx/{httpx.__version__}"],359 ["Example-Header", "example-value"],360 ]Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 361–373why, one step back361362363def unmounted(request: httpx.Request) -> httpx.Response:364 data = {"app": "unmounted"}365 return httpx.Response(200, json=data)366367368def mounted(request: httpx.Request) -> httpx.Response:369 data = {"app": "mounted"}370 return httpx.Response(200, json=data)371372373def test_mounted_transport():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 374–375why, one step back374 transport = httpx.MockTransport(unmounted)375 mounts = {"custom://": httpx.MockTransport(mounted)}Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 376–388why, one step back376377 client = httpx.Client(transport=transport, mounts=mounts)378379 response = client.get("https://www.example.com")380 assert response.status_code == 200381 assert response.json() == {"app": "unmounted"}382383 response = client.get("custom://www.example.com")384 assert response.status_code == 200385 assert response.json() == {"app": "mounted"}386387388def test_all_mounted_transport():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 389why, one step back389 mounts = {"all://": httpx.MockTransport(mounted)}Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 390–395why, one step back390391 client = httpx.Client(mounts=mounts)392393 response = client.get("https://www.example.com")394 assert response.status_code == 200395 assert response.json() == {"app": "mounted"}Fix extenstions typo in AsyncHTTPTransport (#1549)Jonas Lundbergbefore adoption52dd95f
lines 396–403why, one step back396397398def test_server_extensions(server):399 url = server.url.copy_with(path="/http_version_2")400 with httpx.Client(http2=True) as client:401 response = client.get(url)402 assert response.status_code == 200403 assert response.extensions["http_version"] == b"HTTP/1.1"