Skip to content
Myr

test_client.py

This file

Path

tests/client/test_client.py

379 lines · 11.3 KiB · Python

Last changed by

Properly encoded slashes when using `base_url` (#1407)Florimond Mancabefore adoption9005bd5

History of this file

Take it

The walk stopped after 200 commits: lines older than 330a825 point at it.

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

line 1why, one step back
1import typing

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 2–3why, one step back
2from datetime import timedelta
3

Context managed transports (#1218)Tom Christiebefore adoption534400e

line 4why, one step back
4import httpcore

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 5–7why, one step back
5import pytest
67import httpx

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 8why, one step back
8from tests.utils import MockTransport

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 9–12why, one step back
9
1011def test_get(server):12 url = server.url

HTTP/2 becomes fully optional (#1140)Tom Christiebefore adoption8d9dfb5

line 13why, one step back
13 with httpx.Client(http2=True) as http:

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 14–19why, one step back
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"

Drop chardet (#1269)Tom Christiebefore adoptiond0fe113

line 20why, one step back
20 assert response.encoding is None

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 21–27why, one step back
21 assert response.request.url == url
22 assert response.headers23 assert response.is_redirect is False24 assert repr(response) == "<Response [200 OK]>"25 assert response.elapsed > timedelta(0)2627

Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef

lines 28–36why, one step back
28@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):

Drop `URL(allow_relative=bool)` (#1073)Tom Christiebefore adoption7e6e351

line 37why, one step back
37 with httpx.Client() as client:

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

line 38why, one step back
38 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):

Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef

line 39why, one step back
39 client.get(url)

Drop `URL(allow_relative=bool)` (#1073)Tom Christiebefore adoption7e6e351

lines 40–41why, one step back
40
41

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 42–74why, one step back
42def 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:

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 75why, one step back
75 response = client.post(server.url, content=b"Hello, world!")

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 76–125why, one step back
76 assert response.status_code == 200
77 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:

Raise HTTPStatusError in raise_from_status (#1072)François Voronbefore adoption27b0dbc

line 126why, one step back
126 with pytest.raises(httpx.HTTPStatusError) as exc_info:

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 127–149why, one step back
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:

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 150why, one step back
150 response = client.put(server.url, content=b"Hello, world!")

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 151–156why, one step back
151 assert response.status_code == 200
152 assert response.reason_phrase == "OK"153154155def test_patch(server):156 with httpx.Client() as client:

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 157why, one step back
157 response = client.patch(server.url, content=b"Hello, world!")

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 158–176why, one step back
158 assert response.status_code == 200
159 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_url175176

Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6

line 177why, one step back
177def test_merge_absolute_url():

Drop HSTS Preloading (#1110)Florimond Mancabefore adoption78cf16a

line 178why, one step back
178 client = httpx.Client(base_url="https://www.example.com/")

Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6

line 179why, one step back
179 request = client.build_request("GET", "http://www.example.com/")

Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209

line 180why, one step back
180 assert request.url == "http://www.example.com/"

Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6

lines 181–185why, one step back
181
182183def test_merge_relative_url():184 client = httpx.Client(base_url="https://www.example.com/")185 request = client.build_request("GET", "/testing/123")

Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209

line 186why, one step back
186 assert request.url == "https://www.example.com/testing/123"

Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6

lines 187–191why, one step back
187
188189def 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")

Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209

line 192why, one step back
192 assert request.url == "https://www.example.com/some/path/testing/123"

Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6

lines 193–197why, one step back
193
194195def 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")

Replace httpx.URL for str in tests (#1237)Eduardo Enriquezbefore adoptionaad8209

line 198why, one step back
198 assert request.url == "https://www.example.com/some/testing/123"

Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925

lines 199–200why, one step back
199
200

Properly encoded slashes when using `base_url` (#1407)Florimond Mancabefore adoption9005bd5

lines 201–210why, one step back
201def test_merge_relative_url_with_encoded_slashes():
202 client = httpx.Client(base_url="https://www.example.com/")203 request = client.build_request("GET", "/testing%2F123")204 assert request.url == "https://www.example.com/testing%2F123"205206 client = httpx.Client(base_url="https://www.example.com/base%2Fpath")207 request = client.build_request("GET", "/testing")208 assert request.url == "https://www.example.com/base%2Fpath/testing"209210

Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925

lines 211–218why, one step back
211def test_pool_limits_deprecated():
212 limits = httpx.Limits()213214 with pytest.warns(DeprecationWarning):215 httpx.Client(pool_limits=limits)216217 with pytest.warns(DeprecationWarning):218 httpx.AsyncClient(pool_limits=limits)

Context managed transports (#1218)Tom Christiebefore adoption534400e

lines 219–241why, one step back
219
220221def test_context_managed_transport():222 class Transport(httpcore.SyncHTTPTransport):223 def __init__(self):224 self.events = []225226 def close(self):227 # The base implementation of httpcore.SyncHTTPTransport just228 # calls into `.close`, so simple transport cases can just override229 # this method for any cleanup, where more complex cases230 # might want to additionally override `__enter__`/`__exit__`.231 self.events.append("transport.close")232233 def __enter__(self):234 super().__enter__()235 self.events.append("transport.__enter__")236237 def __exit__(self, *args):238 super().__exit__(*args)239 self.events.append("transport.__exit__")240241 transport = Transport()

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

line 242why, one step back
242 with httpx.Client(transport=transport):

Context managed transports (#1218)Tom Christiebefore adoption534400e

lines 243–249why, one step back
243 pass
244245 assert transport.events == [246 "transport.__enter__",247 "transport.close",248 "transport.__exit__",249 ]

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 250–251why, one step back
250
251

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 252–289why, one step back
252def test_context_managed_transport_and_mount():
253 class Transport(httpcore.SyncHTTPTransport):254 def __init__(self, name: str):255 self.name: str = name256 self.events: typing.List[str] = []257258 def close(self):259 # The base implementation of httpcore.SyncHTTPTransport just260 # calls into `.close`, so simple transport cases can just override261 # this method for any cleanup, where more complex cases262 # might want to additionally override `__enter__`/`__exit__`.263 self.events.append(f"{self.name}.close")264265 def __enter__(self):266 super().__enter__()267 self.events.append(f"{self.name}.__enter__")268269 def __exit__(self, *args):270 super().__exit__(*args)271 self.events.append(f"{self.name}.__exit__")272273 transport = Transport(name="transport")274 mounted = Transport(name="mounted")275 with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}):276 pass277278 assert transport.events == [279 "transport.__enter__",280 "transport.close",281 "transport.__exit__",282 ]283 assert mounted.events == [284 "mounted.__enter__",285 "mounted.close",286 "mounted.__exit__",287 ]288289

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

lines 290–291why, one step back
290def hello_world(request):
291 return httpx.Response(200, text="Hello, world!")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 292–293why, one step back
292
293

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

lines 294–295why, one step back
294def test_client_closed_state_using_implicit_open():
295 client = httpx.Client(transport=MockTransport(hello_world))

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 296why, one step back
296

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 297why, one step back
297 assert not client.is_closed

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 298–300why, one step back
298 client.get("http://example.com")
299300 assert not client.is_closed

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 301why, one step back
301 client.close()

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 302why, one step back
302

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

lines 303–305why, one step back
303 assert client.is_closed
304 with pytest.raises(RuntimeError):305 client.get("http://example.com")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 306why, one step back
306

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

lines 307–309why, one step back
307
308def test_client_closed_state_using_with_block():309 with httpx.Client(transport=MockTransport(hello_world)) as client:

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 310why, one step back
310 assert not client.is_closed

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

line 311why, one step back
311 client.get("http://example.com")

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 312–313why, one step back
312
313 assert client.is_closed

Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5

lines 314–315why, one step back
314 with pytest.raises(RuntimeError):
315 client.get("http://example.com")

Preserve header casing (#1338)Tom Christiebefore adoptionc725387

lines 316–344why, one step back
316
317318def echo_raw_headers(request: httpx.Request) -> httpx.Response:319 data = [320 (name.decode("ascii"), value.decode("ascii"))321 for name, value in request.headers.raw322 ]323 return httpx.Response(200, json=data)324325326def test_raw_client_header():327 """328 Set a header in the Client.329 """330 url = "http://example.org/echo_headers"331 headers = {"Example-Header": "example-value"}332333 client = httpx.Client(transport=MockTransport(echo_raw_headers), headers=headers)334 response = client.get(url)335336 assert response.status_code == 200337 assert response.json() == [338 ["Host", "example.org"],339 ["Accept", "*/*"],340 ["Accept-Encoding", "gzip, deflate, br"],341 ["Connection", "keep-alive"],342 ["User-Agent", f"python-httpx/{httpx.__version__}"],343 ["Example-Header", "example-value"],344 ]

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 345–379why, one step back
345
346347def unmounted(request: httpx.Request) -> httpx.Response:348 data = {"app": "unmounted"}349 return httpx.Response(200, json=data)350351352def mounted(request: httpx.Request) -> httpx.Response:353 data = {"app": "mounted"}354 return httpx.Response(200, json=data)355356357def test_mounted_transport():358 transport = MockTransport(unmounted)359 mounts = {"custom://": MockTransport(mounted)}360361 client = httpx.Client(transport=transport, mounts=mounts)362363 response = client.get("https://www.example.com")364 assert response.status_code == 200365 assert response.json() == {"app": "unmounted"}366367 response = client.get("custom://www.example.com")368 assert response.status_code == 200369 assert response.json() == {"app": "mounted"}370371372def test_all_mounted_transport():373 mounts = {"all://": MockTransport(mounted)}374375 client = httpx.Client(mounts=mounts)376377 response = client.get("https://www.example.com")378 assert response.status_code == 200379 assert response.json() == {"app": "mounted"}