Skip to content
Myr

test_client.py

This file

Path

tests/client/test_client.py

400 lines · 12.0 KiB · Python

Last changed by

Stricter enforcement of either 'with httpx.Client() as client' or 'client = httpx.Client()' lifespan styles. (#1800)Tom Christiebefore adoption927c88d

History of this file

Take it

The walk stopped after 200 commits: lines older than 32d37cf point at it.

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

line 1why, one step back
1import typing

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

lines 2–116why, one step back
2from datetime import timedelta
34import pytest56import httpx789def test_get(server):10 url = server.url11 with httpx.Client(http2=True) as http:12 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"18 assert response.encoding is None19 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:36 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):37 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:73 response = client.post(server.url, content=b"Hello, world!")74 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!"115116

Drop 'Response(on_close=...)' from API (#1572)Tom Christiebefore adoption073a328

lines 117–126why, one step back
117def 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())125126

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

lines 127–208why, one step back
127def 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:158 response = client.put(server.url, content=b"Hello, world!")159 assert response.status_code == 200160 assert response.reason_phrase == "OK"161162163def test_patch(server):164 with httpx.Client() as client:165 response = client.patch(server.url, content=b"Hello, world!")166 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_url183184185def test_merge_absolute_url():186 client = httpx.Client(base_url="https://www.example.com/")187 request = client.build_request("GET", "http://www.example.com/")188 assert request.url == "http://www.example.com/"189190191def test_merge_relative_url():192 client = httpx.Client(base_url="https://www.example.com/")193 request = client.build_request("GET", "/testing/123")194 assert request.url == "https://www.example.com/testing/123"195196197def 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")200 assert request.url == "https://www.example.com/some/path/testing/123"201202203def 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")206 assert request.url == "https://www.example.com/some/testing/123"207208

Fix some cases of merging with base_url (#1532)Tom Christiebefore adoption6cb1672

lines 209–214why, one step back
209def 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"213214

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

lines 215–224why, one step back
215def 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"223224

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

line 225why, one step back
225def test_context_managed_transport():

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 226why, one step back
226 class Transport(httpx.BaseTransport):

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

lines 227–230why, one step back
227 def __init__(self):
228 self.events = []229230 def close(self):

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 231why, one step back
231 # The base implementation of httpx.BaseTransport just

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

lines 232–245why, one step back
232 # calls into `.close`, so simple transport cases can just override
233 # 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 back
246 with httpx.Client(transport=transport):

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

lines 247–255why, one step back
247 pass
248249 assert transport.events == [250 "transport.__enter__",251 "transport.close",252 "transport.__exit__",253 ]254255

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

line 256why, one step back
256def test_context_managed_transport_and_mount():

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 257why, one step back
257 class Transport(httpx.BaseTransport):

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

lines 258–262why, one step back
258 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 back
263 # The base implementation of httpx.BaseTransport just

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

lines 264–293why, one step back
264 # calls into `.close`, so simple transport cases can just override
265 # 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 ]292293

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

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

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

lines 296–297why, one step back
296
297

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

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

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

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

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

line 300why, one step back
300

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

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

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

lines 302–304why, one step back
302 client.get("http://example.com")
303304 assert not client.is_closed

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

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

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

line 306why, one step back
306

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

line 307why, one step back
307 assert client.is_closed

Stricter enforcement of either 'with httpx.Client() as client' or 'client = httpx.Client()' lifespan styles. (#1800)Tom Christiebefore adoption927c88d

lines 308–309why, one step back
308
309 # Once we're close we cannot make any more requests.

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

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

Stricter enforcement of either 'with httpx.Client() as client' or 'client = httpx.Client()' lifespan styles. (#1800)Tom Christiebefore adoption927c88d

lines 312–316why, one step back
312
313 # Once we're closed we cannot reopen the client.314 with pytest.raises(RuntimeError):315 with client:316 pass # pragma: nocover

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

line 317why, one step back
317

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

lines 318–319why, one step back
318
319def test_client_closed_state_using_with_block():

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

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

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

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

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

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

Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf

lines 323–324why, one step back
323
324 assert client.is_closed

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

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

Preserve header casing (#1338)Tom Christiebefore adoptionc725387

lines 327–343why, one step back
327
328329def echo_raw_headers(request: httpx.Request) -> httpx.Response:330 data = [331 (name.decode("ascii"), value.decode("ascii"))332 for name, value in request.headers.raw333 ]334 return httpx.Response(200, json=data)335336337def test_raw_client_header():338 """339 Set a header in the Client.340 """341 url = "http://example.org/echo_headers"342 headers = {"Example-Header": "example-value"}343

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

lines 344–346why, one step back
344 client = httpx.Client(
345 transport=httpx.MockTransport(echo_raw_headers), headers=headers346 )

Preserve header casing (#1338)Tom Christiebefore adoptionc725387

lines 347–357why, one step back
347 response = client.get(url)
348349 assert response.status_code == 200350 assert response.json() == [351 ["Host", "example.org"],352 ["Accept", "*/*"],353 ["Accept-Encoding", "gzip, deflate, br"],354 ["Connection", "keep-alive"],355 ["User-Agent", f"python-httpx/{httpx.__version__}"],356 ["Example-Header", "example-value"],357 ]

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

lines 358–370why, one step back
358
359360def unmounted(request: httpx.Request) -> httpx.Response:361 data = {"app": "unmounted"}362 return httpx.Response(200, json=data)363364365def mounted(request: httpx.Request) -> httpx.Response:366 data = {"app": "mounted"}367 return httpx.Response(200, json=data)368369370def test_mounted_transport():

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

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

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

lines 373–385why, one step back
373
374 client = httpx.Client(transport=transport, mounts=mounts)375376 response = client.get("https://www.example.com")377 assert response.status_code == 200378 assert response.json() == {"app": "unmounted"}379380 response = client.get("custom://www.example.com")381 assert response.status_code == 200382 assert response.json() == {"app": "mounted"}383384385def test_all_mounted_transport():

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

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

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

lines 387–392why, one step back
387
388 client = httpx.Client(mounts=mounts)389390 response = client.get("https://www.example.com")391 assert response.status_code == 200392 assert response.json() == {"app": "mounted"}

Fix extenstions typo in AsyncHTTPTransport (#1549)Jonas Lundbergbefore adoption52dd95f

lines 393–400why, one step back
393
394395def test_server_extensions(server):396 url = server.url.copy_with(path="/http_version_2")397 with httpx.Client(http2=True) as client:398 response = client.get(url)399 assert response.status_code == 200400 assert response.extensions["http_version"] == b"HTTP/1.1"