Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

657 lines · 21.2 KiB · Python

Last changed by

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

History of this file

Take it

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 1–4why, one step back
1import hashlib
2import os3import typing4

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 5why, one step back
5import httpcore

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 6–7why, one step back
6import pytest
7

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 8why, one step back
8import httpx

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 9–11why, one step back
9from httpx import (
10 URL,11 Auth,

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

line 12why, one step back
12 BasicAuth,

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 13–18why, one step back
13 DigestAuth,
14 ProtocolError,15 Request,16 RequestBodyUnavailable,17 Response,18)

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 19why, one step back
19from httpx._content_streams import ContentStream, JSONStream

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 20why, one step back
20

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 21why, one step back
21from ..common import FIXTURES_DIR

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 22why, one step back
22

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 23why, one step back
23

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 24–31why, one step back
24def get_header_value(headers, key, default=None):
25 lookup = key.encode("ascii").lower()26 for header_key, header_value in headers:27 if header_key.lower() == lookup:28 return header_value.decode("ascii")29 return default3031

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 32why, one step back
32class MockTransport:

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 33why, one step back
33 def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 34–36why, one step back
34 self.auth_header = auth_header
35 self.status_code = status_code36

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 37why, one step back
37 def _request(

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 38why, one step back
38 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 39–42why, one step back
39 method: bytes,
40 url: typing.Tuple[bytes, bytes, int, bytes],41 headers: typing.List[typing.Tuple[bytes, bytes]],42 stream: ContentStream,

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

line 43why, one step back
43 timeout: typing.Mapping[str, typing.Optional[float]] = None,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 44–49why, one step back
44 ) -> typing.Tuple[
45 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream46 ]:47 authorization = get_header_value(headers, "Authorization")48 response_headers = (49 [(b"www-authenticate", self.auth_header)] if self.auth_header else []

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 50why, one step back
50 )

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 51–52why, one step back
51 response_stream = JSONStream({"auth": authorization})
52 return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 53–54why, one step back
53
54

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 55–72why, one step back
55class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):
56 async def request(57 self, *args, **kwargs58 ) -> typing.Tuple[59 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream60 ]:61 return self._request(*args, **kwargs)626364class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):65 def request(66 self, *args, **kwargs67 ) -> typing.Tuple[68 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream69 ]:70 return self._request(*args, **kwargs)7172

Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100

line 73why, one step back
73class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 74–86why, one step back
74 def __init__(
75 self,76 algorithm: str = "SHA-256",77 send_response_after_attempt: int = 1,78 qop: str = "auth",79 regenerate_nonce: bool = True,80 ) -> None:81 self.algorithm = algorithm82 self.send_response_after_attempt = send_response_after_attempt83 self.qop = qop84 self._regenerate_nonce = regenerate_nonce85 self._response_count = 086

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 87why, one step back
87 async def request(

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 88why, one step back
88 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 89why, one step back
89 method: bytes,

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

lines 90–92why, one step back
90 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],
91 headers: typing.List[typing.Tuple[bytes, bytes]] = None,92 stream: httpcore.AsyncByteStream = None,

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

line 93why, one step back
93 timeout: typing.Mapping[str, typing.Optional[float]] = None,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 94–96why, one step back
94 ) -> typing.Tuple[
95 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream96 ]:

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 97why, one step back
97 if self._response_count < self.send_response_after_attempt:

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

lines 98–99why, one step back
98 assert headers is not None
99 return self.challenge_send(method, headers)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 100why, one step back
100

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 101–103why, one step back
101 authorization = get_header_value(headers, "Authorization")
102 body = JSONStream({"auth": authorization})103 return b"HTTP/1.1", 200, b"", [], body

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 104why, one step back
104

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 105why, one step back
105 def challenge_send(

Use and pin black 20 (#1229)Florimond Mancabefore adoptionf5c27ec

line 106why, one step back
106 self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]]

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

lines 107–109why, one step back
107 ) -> typing.Tuple[
108 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream109 ]:

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 110–131why, one step back
110 self._response_count += 1
111 nonce = (112 hashlib.sha256(os.urandom(8)).hexdigest()113 if self._regenerate_nonce114 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"115 )116 challenge_data = {117 "nonce": nonce,118 "qop": self.qop,119 "opaque": (120 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"121 ),122 "algorithm": self.algorithm,123 "stale": "FALSE",124 }125 challenge_str = ", ".join(126 '{}="{}"'.format(key, value)127 for key, value in challenge_data.items()128 if value129 )130131 headers = [

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 132–135why, one step back
132 (
133 b"www-authenticate",134 b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),135 )

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 136why, one step back
136 ]

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 137why, one step back
137 return b"HTTP/1.1", 401, b"", headers, ContentStream()

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 138–139why, one step back
138
139

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 140–185why, one step back
140class RepeatAuth(Auth):
141 """142 A mock authentication scheme that requires clients to send143 the request a fixed number of times, and then send a last request containing144 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers145 of intermediate responses.146 """147148 requires_request_body = True149150 def __init__(self, repeat: int):151 self.repeat = repeat152153 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:154 nonces = []155156 for index in range(self.repeat):157 request.headers["Authorization"] = f"Repeat {index}"158 response = yield request159 nonces.append(response.headers["www-authenticate"])160161 key = ".".join(nonces)162 request.headers["Authorization"] = f"Repeat {key}"163 yield request164165166class ResponseBodyAuth(Auth):167 """168 A mock authentication scheme that requires clients to send an 'Authorization'169 header, then send back the contents of the response in the 'Authorization'170 header.171 """172173 requires_response_body = True174175 def __init__(self, token):176 self.token = token177178 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:179 request.headers["Authorization"] = self.token180 response = yield request181 data = response.text182 request.headers["Authorization"] = data183 yield request184185

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 186–190why, one step back
186@pytest.mark.asyncio
187async def test_basic_auth() -> None:188 url = "https://example.org/"189 auth = ("tomchristie", "password123")190

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 191–192why, one step back
191 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
192 response = await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 193–201why, one step back
193
194 assert response.status_code == 200195 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}196197198@pytest.mark.asyncio199async def test_basic_auth_in_url() -> None:200 url = "https://tomchristie:password123@example.org/"201

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 202–203why, one step back
202 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
203 response = await client.get(url)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 204–213why, one step back
204
205 assert response.status_code == 200206 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}207208209@pytest.mark.asyncio210async def test_basic_auth_on_session() -> None:211 url = "https://example.org/"212 auth = ("tomchristie", "password123")213

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 214–215why, one step back
214 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:
215 response = await client.get(url)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 216–228why, one step back
216
217 assert response.status_code == 200218 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}219220221@pytest.mark.asyncio222async def test_custom_auth() -> None:223 url = "https://example.org/"224225 def auth(request: Request) -> Request:226 request.headers["Authorization"] = "Token 123"227 return request228

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 229–230why, one step back
229 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
230 response = await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 231–237why, one step back
231
232 assert response.status_code == 200233 assert response.json() == {"auth": "Token 123"}234235236@pytest.mark.asyncio237async def test_netrc_auth() -> None:

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 238why, one step back
238 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 239–240why, one step back
239 url = "http://netrcexample.org"
240

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 241–242why, one step back
241 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
242 response = await client.get(url)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 243–251why, one step back
243
244 assert response.status_code == 200245 assert response.json() == {246 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"247 }248249250@pytest.mark.asyncio251async def test_auth_header_has_priority_over_netrc() -> None:

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 252why, one step back
252 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 253–254why, one step back
253 url = "http://netrcexample.org"
254

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 255–256why, one step back
255 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
256 response = await client.get(url, headers={"Authorization": "Override"})

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 257–263why, one step back
257
258 assert response.status_code == 200259 assert response.json() == {"auth": "Override"}260261262@pytest.mark.asyncio263async def test_trust_env_auth() -> None:

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 264why, one step back
264 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 265–266why, one step back
265 url = "http://netrcexample.org"
266

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 267–270why, one step back
267 async with httpx.AsyncClient(
268 transport=AsyncMockTransport(), trust_env=False269 ) as client:270 response = await client.get(url)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 271–274why, one step back
271
272 assert response.status_code == 200273 assert response.json() == {"auth": None}274

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 275–278why, one step back
275 async with httpx.AsyncClient(
276 transport=AsyncMockTransport(), trust_env=True277 ) as client:278 response = await client.get(url)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 279–285why, one step back
279
280 assert response.status_code == 200281 assert response.json() == {282 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"283 }284285

Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0

lines 286–290why, one step back
286@pytest.mark.asyncio
287async def test_auth_disable_per_request() -> None:288 url = "https://example.org/"289 auth = ("tomchristie", "password123")290

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 291–292why, one step back
291 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:
292 response = await client.get(url, auth=None)

Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0

lines 293–297why, one step back
293
294 assert response.status_code == 200295 assert response.json() == {"auth": None}296297

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 298–309why, one step back
298def test_auth_hidden_url() -> None:
299 url = "http://example-username:example-password@example.org/"300 expected = "URL('http://example-username:[secure]@example.org/')"301 assert url == URL(url)302 assert expected == repr(URL(url))303304305@pytest.mark.asyncio306async def test_auth_hidden_header() -> None:307 url = "https://example.org/"308 auth = ("example-username", "example-password")309

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 310–311why, one step back
310 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
311 response = await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 312–316why, one step back
312
313 assert "'authorization': '[secure]'" in str(response.request.headers)314315316@pytest.mark.asyncio

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

line 317why, one step back
317async def test_auth_property() -> None:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 318–319why, one step back
318 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
319 assert client.auth is None

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

line 320why, one step back
320

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 321–322why, one step back
321 client.auth = ("tomchristie", "password123") # type: ignore
322 assert isinstance(client.auth, BasicAuth)

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

line 323why, one step back
323

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 324–327why, one step back
324 url = "https://example.org/"
325 response = await client.get(url)326 assert response.status_code == 200327 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

lines 328–331why, one step back
328
329330@pytest.mark.asyncio331async def test_auth_invalid_type() -> None:

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 332why, one step back
332 with pytest.raises(TypeError):

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 333why, one step back
333 client = httpx.AsyncClient(

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

lines 334–337why, one step back
334 transport=AsyncMockTransport(),
335 auth="not a tuple, not a callable", # type: ignore336 )337

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 338–340why, one step back
338 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
339 with pytest.raises(TypeError):340 await client.get(auth="not a tuple, not a callable") # type: ignore

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

line 341why, one step back
341

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 342–343why, one step back
342 with pytest.raises(TypeError):
343 client.auth = "not a tuple, not a callable" # type: ignore

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

line 344why, one step back
344

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 345–350why, one step back
345
346@pytest.mark.asyncio347async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:348 url = "https://example.org/"349 auth = DigestAuth(username="tomchristie", password="password123")350

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 351–352why, one step back
351 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
352 response = await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 353–362why, one step back
353
354 assert response.status_code == 200355 assert response.json() == {"auth": None}356 assert len(response.history) == 0357358359@pytest.mark.asyncio360async def test_digest_auth_200_response_including_digest_auth_header() -> None:361 url = "https://example.org/"362 auth = DigestAuth(username="tomchristie", password="password123")

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 363why, one step back
363 auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 364why, one step back
364

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 365why, one step back
365 async with httpx.AsyncClient(

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 366why, one step back
366 transport=AsyncMockTransport(auth_header=auth_header, status_code=200)

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 367–368why, one step back
367 ) as client:
368 response = await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 369–379why, one step back
369
370 assert response.status_code == 200371 assert response.json() == {"auth": None}372 assert len(response.history) == 0373374375@pytest.mark.asyncio376async def test_digest_auth_401_response_without_digest_auth_header() -> None:377 url = "https://example.org/"378 auth = DigestAuth(username="tomchristie", password="password123")379

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 380–383why, one step back
380 async with httpx.AsyncClient(
381 transport=AsyncMockTransport(auth_header=b"", status_code=401)382 ) as client:383 response = await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 384–409why, one step back
384
385 assert response.status_code == 401386 assert response.json() == {"auth": None}387 assert len(response.history) == 0388389390@pytest.mark.parametrize(391 "algorithm,expected_hash_length,expected_response_length",392 [393 ("MD5", 64, 32),394 ("MD5-SESS", 64, 32),395 ("SHA", 64, 40),396 ("SHA-SESS", 64, 40),397 ("SHA-256", 64, 64),398 ("SHA-256-SESS", 64, 64),399 ("SHA-512", 64, 128),400 ("SHA-512-SESS", 64, 128),401 ],402)403@pytest.mark.asyncio404async def test_digest_auth(405 algorithm: str, expected_hash_length: int, expected_response_length: int406) -> None:407 url = "https://example.org/"408 auth = DigestAuth(username="tomchristie", password="password123")409

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 410–413why, one step back
410 async with httpx.AsyncClient(
411 transport=MockDigestAuthTransport(algorithm=algorithm)412 ) as client:413 response = await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 414–441why, one step back
414
415 assert response.status_code == 200416 assert len(response.history) == 1417418 authorization = typing.cast(dict, response.json())["auth"]419 scheme, _, fields = authorization.partition(" ")420 assert scheme == "Digest"421422 response_fields = [field.strip() for field in fields.split(",")]423 digest_data = dict(field.split("=") for field in response_fields)424425 assert digest_data["username"] == '"tomchristie"'426 assert digest_data["realm"] == '"httpx@example.org"'427 assert "nonce" in digest_data428 assert digest_data["uri"] == '"/"'429 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes430 assert len(digest_data["opaque"]) == expected_hash_length + 2431 assert digest_data["algorithm"] == algorithm432 assert digest_data["qop"] == "auth"433 assert digest_data["nc"] == "00000001"434 assert len(digest_data["cnonce"]) == 16 + 2435436437@pytest.mark.asyncio438async def test_digest_auth_no_specified_qop() -> None:439 url = "https://example.org/"440 auth = DigestAuth(username="tomchristie", password="password123")441

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 442–443why, one step back
442 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop="")) as client:
443 response = await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 444–472why, one step back
444
445 assert response.status_code == 200446 assert len(response.history) == 1447448 authorization = typing.cast(dict, response.json())["auth"]449 scheme, _, fields = authorization.partition(" ")450 assert scheme == "Digest"451452 response_fields = [field.strip() for field in fields.split(",")]453 digest_data = dict(field.split("=") for field in response_fields)454455 assert "qop" not in digest_data456 assert "nc" not in digest_data457 assert "cnonce" not in digest_data458 assert digest_data["username"] == '"tomchristie"'459 assert digest_data["realm"] == '"httpx@example.org"'460 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes461 assert digest_data["uri"] == '"/"'462 assert len(digest_data["response"]) == 64 + 2463 assert len(digest_data["opaque"]) == 64 + 2464 assert digest_data["algorithm"] == "SHA-256"465466467@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))468@pytest.mark.asyncio469async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:470 url = "https://example.org/"471 auth = DigestAuth(username="tomchristie", password="password123")472

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 473–474why, one step back
473 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop=qop)) as client:
474 response = await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 475–484why, one step back
475
476 assert response.status_code == 200477 assert len(response.history) == 1478479480@pytest.mark.asyncio481async def test_digest_auth_qop_auth_int_not_implemented() -> None:482 url = "https://example.org/"483 auth = DigestAuth(username="tomchristie", password="password123")484

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 485–489why, one step back
485 async with httpx.AsyncClient(
486 transport=MockDigestAuthTransport(qop="auth-int")487 ) as client:488 with pytest.raises(NotImplementedError):489 await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 490–496why, one step back
490
491492@pytest.mark.asyncio493async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:494 url = "https://example.org/"495 auth = DigestAuth(username="tomchristie", password="password123")496

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 497–501why, one step back
497 async with httpx.AsyncClient(
498 transport=MockDigestAuthTransport(qop="not-auth")499 ) as client:500 with pytest.raises(ProtocolError):501 await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 502–508why, one step back
502
503504@pytest.mark.asyncio505async def test_digest_auth_incorrect_credentials() -> None:506 url = "https://example.org/"507 auth = DigestAuth(username="tomchristie", password="password123")508

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 509why, one step back
509 async with httpx.AsyncClient(

Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100

line 510why, one step back
510 transport=MockDigestAuthTransport(send_response_after_attempt=2)

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 511–512why, one step back
511 ) as client:
512 response = await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 513–520why, one step back
513
514 assert response.status_code == 401515 assert len(response.history) == 1516517518@pytest.mark.parametrize(519 "auth_header",520 [

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 521–525why, one step back
521 b'Digest realm="httpx@example.org", qop="auth"', # missing fields
522 b'realm="httpx@example.org", qop="auth"', # not starting with Digest523 b'DigestZ realm="httpx@example.org", qop="auth"'524 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',525 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 526–528why, one step back
526 ],
527)528@pytest.mark.asyncio

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 529why, one step back
529async def test_async_digest_auth_raises_protocol_error_on_malformed_header(

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 530why, one step back
530 auth_header: bytes,

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 531–533why, one step back
531) -> None:
532 url = "https://example.org/"533 auth = DigestAuth(username="tomchristie", password="password123")

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 534why, one step back
534 async with httpx.AsyncClient(

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 535why, one step back
535 transport=AsyncMockTransport(auth_header=auth_header, status_code=401)

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 536–538why, one step back
536 ) as client:
537 with pytest.raises(ProtocolError):538 await client.get(url, auth=auth)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 539–540why, one step back
539
540

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 541–555why, one step back
541@pytest.mark.parametrize(
542 "auth_header",543 [544 b'Digest realm="httpx@example.org", qop="auth"', # missing fields545 b'realm="httpx@example.org", qop="auth"', # not starting with Digest546 b'DigestZ realm="httpx@example.org", qop="auth"'547 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',548 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list549 ],550)551def test_sync_digest_auth_raises_protocol_error_on_malformed_header(552 auth_header: bytes,553) -> None:554 url = "https://example.org/"555 auth = DigestAuth(username="tomchristie", password="password123")

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 556–557why, one step back
556
557 with httpx.Client(

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 558why, one step back
558 transport=SyncMockTransport(auth_header=auth_header, status_code=401)

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 559–561why, one step back
559 ) as client:
560 with pytest.raises(ProtocolError):561 client.get(url, auth=auth)

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 562–563why, one step back
562
563

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 564why, one step back
564@pytest.mark.asyncio

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 565why, one step back
565async def test_async_auth_history() -> None:

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 566–569why, one step back
566 """
567 Test that intermediate requests sent as part of an authentication flow568 are recorded in the response history.569 """

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 570–571why, one step back
570 url = "https://example.org/"
571 auth = RepeatAuth(repeat=2)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 572why, one step back
572

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 573–577why, one step back
573 async with httpx.AsyncClient(
574 transport=AsyncMockTransport(auth_header=b"abc")575 ) as client:576 response = await client.get(url, auth=auth)577

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 578–579why, one step back
578 assert response.status_code == 200
579 assert response.json() == {"auth": "Repeat abc.abc"}

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 580why, one step back
580

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 581–584why, one step back
581 assert len(response.history) == 2
582 resp1, resp2 = response.history583 assert resp1.json() == {"auth": "Repeat 0"}584 assert resp2.json() == {"auth": "Repeat 1"}

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 585why, one step back
585

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 586–587why, one step back
586 assert len(resp2.history) == 1
587 assert resp2.history == [resp1]

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 588why, one step back
588

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 589why, one step back
589 assert len(resp1.history) == 0

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 590–591why, one step back
590
591

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 592–596why, one step back
592def test_sync_auth_history() -> None:
593 """594 Test that intermediate requests sent as part of an authentication flow595 are recorded in the response history.596 """

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 597–599why, one step back
597 url = "https://example.org/"
598 auth = RepeatAuth(repeat=2)599

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 600–602why, one step back
600 with httpx.Client(transport=SyncMockTransport(auth_header=b"abc")) as client:
601 response = client.get(url, auth=auth)602

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 603–622why, one step back
603 assert response.status_code == 200
604 assert response.json() == {"auth": "Repeat abc.abc"}605606 assert len(response.history) == 2607 resp1, resp2 = response.history608 assert resp1.json() == {"auth": "Repeat 0"}609 assert resp2.json() == {"auth": "Repeat 1"}610611 assert len(resp2.history) == 1612 assert resp2.history == [resp1]613614 assert len(resp1.history) == 0615616617@pytest.mark.asyncio618async def test_digest_auth_unavailable_streaming_body():619 url = "https://example.org/"620 auth = DigestAuth(username="tomchristie", password="password123")621622 async def streaming_body():

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

line 623why, one step back
623 yield b"Example request body" # pragma: nocover

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 624why, one step back
624

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 625–627why, one step back
625 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
626 with pytest.raises(RequestBodyUnavailable):627 await client.post(url, data=streaming_body(), auth=auth)

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

lines 628–630why, one step back
628
629630@pytest.mark.asyncio

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 631why, one step back
631async def test_async_auth_reads_response_body() -> None:

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

lines 632–635why, one step back
632 """
633 Test that we can read the response body in an auth flow if `requires_response_body`634 is set.635 """

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 636–637why, one step back
636 url = "https://example.org/"
637 auth = ResponseBodyAuth("xyz")

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 638–639why, one step back
638 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
639 response = await client.get(url, auth=auth)

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

line 640why, one step back
640

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 641–642why, one step back
641 assert response.status_code == 200
642 assert response.json() == {"auth": '{"auth": "xyz"}'}

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

lines 643–644why, one step back
643
644

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 645–649why, one step back
645def test_sync_auth_reads_response_body() -> None:
646 """647 Test that we can read the response body in an auth flow if `requires_response_body`648 is set.649 """

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

lines 650–652why, one step back
650 url = "https://example.org/"
651 auth = ResponseBodyAuth("xyz")652

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 653–655why, one step back
653 with httpx.Client(transport=SyncMockTransport()) as client:
654 response = client.get(url, auth=auth)655

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

lines 656–657why, one step back
656 assert response.status_code == 200
657 assert response.json() == {"auth": '{"auth": "xyz"}'}