Skip to content
Myr

test_client.py

This file

Path

tests/client/test_client.py

380 lines · 11.3 KiB · Python

Last changed by

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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–11why, one step back
5import pytest
67import httpx8910def test_get(server):11 url = server.url

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

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

Drop chardet (#1269)Tom Christiebefore adoptiond0fe113

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 20–26why, one step back
20 assert response.request.url == url
21 assert response.headers22 assert response.is_redirect is False23 assert repr(response) == "<Response [200 OK]>"24 assert response.elapsed > timedelta(0)2526

Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef

lines 27–35why, one step back
27@pytest.mark.parametrize(
28 "url",29 [30 pytest.param("invalid://example.org", id="scheme-not-http(s)"),31 pytest.param("://example.org", id="no-scheme"),32 pytest.param("http://", id="no-host"),33 ],34)35def test_get_invalid_url(server, url):

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

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

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

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

Parameterize invalid URL tests (#1079)Tom Christiebefore adoption696c1ef

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

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

lines 39–40why, one step back
39
40

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 41–73why, one step back
41def test_build_request(server):
42 url = server.url.copy_with(path="/echo_headers")43 headers = {"Custom-header": "value"}4445 with httpx.Client() as client:46 request = client.build_request("GET", url)47 request.headers.update(headers)48 response = client.send(request)4950 assert response.status_code == 20051 assert response.url == url5253 assert response.json()["Custom-header"] == "value"545556def test_build_post_request(server):57 url = server.url.copy_with(path="/echo_headers")58 headers = {"Custom-header": "value"}5960 with httpx.Client() as client:61 request = client.build_request("POST", url)62 request.headers.update(headers)63 response = client.send(request)6465 assert response.status_code == 20066 assert response.url == url6768 assert response.json()["Content-length"] == "0"69 assert response.json()["Custom-header"] == "value"707172def test_post(server):73 with httpx.Client() as client:

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 75–124why, one step back
75 assert response.status_code == 200
76 assert response.reason_phrase == "OK"777879def test_post_json(server):80 with httpx.Client() as client:81 response = client.post(server.url, json={"text": "Hello, world!"})82 assert response.status_code == 20083 assert response.reason_phrase == "OK"848586def test_stream_response(server):87 with httpx.Client() as client:88 with client.stream("GET", server.url) as response:89 content = response.read()90 assert response.status_code == 20091 assert content == b"Hello, world!"929394def test_stream_iterator(server):95 body = b""9697 with httpx.Client() as client:98 with client.stream("GET", server.url) as response:99 for chunk in response.iter_bytes():100 body += chunk101102 assert response.status_code == 200103 assert body == b"Hello, world!"104105106def test_raw_iterator(server):107 body = b""108109 with httpx.Client() as client:110 with client.stream("GET", server.url) as response:111 for chunk in response.iter_raw():112 body += chunk113114 assert response.status_code == 200115 assert body == b"Hello, world!"116117118def test_raise_for_status(server):119 with httpx.Client() as client:120 for status_code in (200, 400, 404, 500, 505):121 response = client.request(122 "GET", server.url.copy_with(path=f"/status/{status_code}")123 )124 if 400 <= status_code < 600:

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 126–148why, one step back
126 response.raise_for_status()
127 assert exc_info.value.response == response128 assert exc_info.value.request.url.path == f"/status/{status_code}"129 else:130 assert response.raise_for_status() is None # type: ignore131132133def test_options(server):134 with httpx.Client() as client:135 response = client.options(server.url)136 assert response.status_code == 200137 assert response.reason_phrase == "OK"138139140def test_head(server):141 with httpx.Client() as client:142 response = client.head(server.url)143 assert response.status_code == 200144 assert response.reason_phrase == "OK"145146147def test_put(server):148 with httpx.Client() as client:

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 157–175why, one step back
157 assert response.status_code == 200
158 assert response.reason_phrase == "OK"159160161def test_delete(server):162 with httpx.Client() as client:163 response = client.delete(server.url)164 assert response.status_code == 200165 assert response.reason_phrase == "OK"166167168def test_base_url(server):169 base_url = server.url170 with httpx.Client(base_url=base_url) as client:171 response = client.get("/")172 assert response.status_code == 200173 assert response.url == base_url174175

Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6

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

Drop HSTS Preloading (#1110)Florimond Mancabefore adoption78cf16a

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

Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6

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

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

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

Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6

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

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

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

Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6

lines 186–190why, one step back
186
187188def test_merge_relative_url_with_path():189 client = httpx.Client(base_url="https://www.example.com/some/path")190 request = client.build_request("GET", "/testing/123")

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

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

Base URL improvements (#1130)Tom Christiebefore adoptiona3392c6

lines 192–196why, one step back
192
193194def test_merge_relative_url_with_dotted_path():195 client = httpx.Client(base_url="https://www.example.com/some/path")196 request = client.build_request("GET", "../testing/123")

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

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

Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925

lines 198–199why, one step back
198
199

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

lines 200–209why, one step back
200def test_merge_relative_url_with_encoded_slashes():
201 client = httpx.Client(base_url="https://www.example.com/")202 request = client.build_request("GET", "/testing%2F123")203 assert request.url == "https://www.example.com/testing%2F123"204205 client = httpx.Client(base_url="https://www.example.com/base%2Fpath")206 request = client.build_request("GET", "/testing")207 assert request.url == "https://www.example.com/base%2Fpath/testing"208209

Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925

lines 210–217why, one step back
210def test_pool_limits_deprecated():
211 limits = httpx.Limits()212213 with pytest.warns(DeprecationWarning):214 httpx.Client(pool_limits=limits)215216 with pytest.warns(DeprecationWarning):217 httpx.AsyncClient(pool_limits=limits)

Context managed transports (#1218)Tom Christiebefore adoption534400e

lines 218–240why, one step back
218
219220def test_context_managed_transport():221 class Transport(httpcore.SyncHTTPTransport):222 def __init__(self):223 self.events = []224225 def close(self):226 # The base implementation of httpcore.SyncHTTPTransport just227 # calls into `.close`, so simple transport cases can just override228 # this method for any cleanup, where more complex cases229 # might want to additionally override `__enter__`/`__exit__`.230 self.events.append("transport.close")231232 def __enter__(self):233 super().__enter__()234 self.events.append("transport.__enter__")235236 def __exit__(self, *args):237 super().__exit__(*args)238 self.events.append("transport.__exit__")239240 transport = Transport()

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

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

Context managed transports (#1218)Tom Christiebefore adoption534400e

lines 242–248why, one step back
242 pass
243244 assert transport.events == [245 "transport.__enter__",246 "transport.close",247 "transport.__exit__",248 ]

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

lines 249–250why, one step back
249
250

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

lines 251–288why, one step back
251def test_context_managed_transport_and_mount():
252 class Transport(httpcore.SyncHTTPTransport):253 def __init__(self, name: str):254 self.name: str = name255 self.events: typing.List[str] = []256257 def close(self):258 # The base implementation of httpcore.SyncHTTPTransport just259 # calls into `.close`, so simple transport cases can just override260 # this method for any cleanup, where more complex cases261 # might want to additionally override `__enter__`/`__exit__`.262 self.events.append(f"{self.name}.close")263264 def __enter__(self):265 super().__enter__()266 self.events.append(f"{self.name}.__enter__")267268 def __exit__(self, *args):269 super().__exit__(*args)270 self.events.append(f"{self.name}.__exit__")271272 transport = Transport(name="transport")273 mounted = Transport(name="mounted")274 with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}):275 pass276277 assert transport.events == [278 "transport.__enter__",279 "transport.close",280 "transport.__exit__",281 ]282 assert mounted.events == [283 "mounted.__enter__",284 "mounted.close",285 "mounted.__exit__",286 ]287288

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

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

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

lines 291–292why, one step back
291
292

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

line 293why, one step back
293def test_client_closed_state_using_implicit_open():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 294why, one step back
294 client = httpx.Client(transport=httpx.MockTransport(hello_world))

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

line 295why, one step back
295

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

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

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

lines 297–299why, one step back
297 client.get("http://example.com")
298299 assert not client.is_closed

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

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

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

line 301why, one step back
301

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

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

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

line 305why, one step back
305

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

lines 306–307why, one step back
306
307def test_client_closed_state_using_with_block():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 308why, one step back
308 with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:

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

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

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

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

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

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

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

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

Preserve header casing (#1338)Tom Christiebefore adoptionc725387

lines 315–331why, one step back
315
316317def echo_raw_headers(request: httpx.Request) -> httpx.Response:318 data = [319 (name.decode("ascii"), value.decode("ascii"))320 for name, value in request.headers.raw321 ]322 return httpx.Response(200, json=data)323324325def test_raw_client_header():326 """327 Set a header in the Client.328 """329 url = "http://example.org/echo_headers"330 headers = {"Example-Header": "example-value"}331

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

lines 332–334why, one step back
332 client = httpx.Client(
333 transport=httpx.MockTransport(echo_raw_headers), headers=headers334 )

Preserve header casing (#1338)Tom Christiebefore adoptionc725387

lines 335–345why, one step back
335 response = client.get(url)
336337 assert response.status_code == 200338 assert response.json() == [339 ["Host", "example.org"],340 ["Accept", "*/*"],341 ["Accept-Encoding", "gzip, deflate, br"],342 ["Connection", "keep-alive"],343 ["User-Agent", f"python-httpx/{httpx.__version__}"],344 ["Example-Header", "example-value"],345 ]

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

lines 346–358why, one step back
346
347348def unmounted(request: httpx.Request) -> httpx.Response:349 data = {"app": "unmounted"}350 return httpx.Response(200, json=data)351352353def mounted(request: httpx.Request) -> httpx.Response:354 data = {"app": "mounted"}355 return httpx.Response(200, json=data)356357358def test_mounted_transport():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

lines 359–360why, one step back
359 transport = httpx.MockTransport(unmounted)
360 mounts = {"custom://": httpx.MockTransport(mounted)}

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

lines 361–373why, one step back
361
362 client = httpx.Client(transport=transport, mounts=mounts)363364 response = client.get("https://www.example.com")365 assert response.status_code == 200366 assert response.json() == {"app": "unmounted"}367368 response = client.get("custom://www.example.com")369 assert response.status_code == 200370 assert response.json() == {"app": "mounted"}371372373def test_all_mounted_transport():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 374why, one step back
374 mounts = {"all://": httpx.MockTransport(mounted)}

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

lines 375–380why, one step back
375
376 client = httpx.Client(mounts=mounts)377378 response = client.get("https://www.example.com")379 assert response.status_code == 200380 assert response.json() == {"app": "mounted"}