Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

622 lines · 19.8 KiB · Python

Last changed by

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

History of this file

Take it

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 5why, one step back
5import httpcore

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 6–10why, one step back
6import pytest
78from httpx import (9 URL,10 AsyncClient,

Public Auth API (#732)Tom Christiebefore adoption12dd157

line 11why, one step back
11 Auth,

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

line 12why, one step back
12 Client,

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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:

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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(

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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 []

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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):

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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(

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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 ]:

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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)

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

line 104why, one step back
104

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 105why, one step back
105 def challenge_send(

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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 )

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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()

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

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

line 191why, one step back
191 client = AsyncClient(transport=AsyncMockTransport())

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 192–201why, one step back
192 response = await client.get(url, auth=auth)
193194 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

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

line 202why, one step back
202 client = AsyncClient(transport=AsyncMockTransport())

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 203–213why, one step back
203 response = await client.get(url)
204205 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

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

line 214why, one step back
214 client = AsyncClient(transport=AsyncMockTransport(), auth=auth)

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 215–228why, one step back
215 response = await client.get(url)
216217 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

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

line 229why, one step back
229 client = AsyncClient(transport=AsyncMockTransport())

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 230–237why, one step back
230 response = await client.get(url, auth=auth)
231232 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")

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

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

line 241why, one step back
241 client = AsyncClient(transport=AsyncMockTransport())

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 242–251why, one step back
242 response = await client.get(url)
243244 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")

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

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

line 255why, one step back
255 client = AsyncClient(transport=AsyncMockTransport())

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 256–263why, one step back
256 response = await client.get(url, headers={"Authorization": "Override"})
257258 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")

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

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

line 267why, one step back
267 client = AsyncClient(transport=AsyncMockTransport(), trust_env=False)

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 268–272why, one step back
268 response = await client.get(url)
269270 assert response.status_code == 200271 assert response.json() == {"auth": None}272

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

line 273why, one step back
273 client = AsyncClient(transport=AsyncMockTransport(), trust_env=True)

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 274–281why, one step back
274 response = await client.get(url)
275276 assert response.status_code == 200277 assert response.json() == {278 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"279 }280281

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

lines 282–293why, one step back
282@pytest.mark.asyncio
283async def test_auth_disable_per_request() -> None:284 url = "https://example.org/"285 auth = ("tomchristie", "password123")286287 client = AsyncClient(transport=AsyncMockTransport(), auth=auth)288 response = await client.get(url, auth=None)289290 assert response.status_code == 200291 assert response.json() == {"auth": None}292293

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 294–305why, one step back
294def test_auth_hidden_url() -> None:
295 url = "http://example-username:example-password@example.org/"296 expected = "URL('http://example-username:[secure]@example.org/')"297 assert url == URL(url)298 assert expected == repr(URL(url))299300301@pytest.mark.asyncio302async def test_auth_hidden_header() -> None:303 url = "https://example.org/"304 auth = ("example-username", "example-password")305

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

line 306why, one step back
306 client = AsyncClient(transport=AsyncMockTransport())

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 307–315why, one step back
307 response = await client.get(url, auth=auth)
308309 assert "'authorization': '[secure]'" in str(response.request.headers)310311312@pytest.mark.asyncio313async def test_auth_invalid_type() -> None:314 url = "https://example.org/"315 client = AsyncClient(

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

lines 316–317why, one step back
316 transport=AsyncMockTransport(),
317 auth="not a tuple, not a callable", # type: ignore

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 318–327why, one step back
318 )
319 with pytest.raises(TypeError):320 await client.get(url)321322323@pytest.mark.asyncio324async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:325 url = "https://example.org/"326 auth = DigestAuth(username="tomchristie", password="password123")327

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

line 328why, one step back
328 client = AsyncClient(transport=AsyncMockTransport())

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 329–339why, one step back
329 response = await client.get(url, auth=auth)
330331 assert response.status_code == 200332 assert response.json() == {"auth": None}333 assert len(response.history) == 0334335336@pytest.mark.asyncio337async def test_digest_auth_200_response_including_digest_auth_header() -> None:338 url = "https://example.org/"339 auth = DigestAuth(username="tomchristie", password="password123")

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 341–342why, one step back
341
342 client = AsyncClient(

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

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 344–356why, one step back
344 )
345 response = await client.get(url, auth=auth)346347 assert response.status_code == 200348 assert response.json() == {"auth": None}349 assert len(response.history) == 0350351352@pytest.mark.asyncio353async def test_digest_auth_401_response_without_digest_auth_header() -> None:354 url = "https://example.org/"355 auth = DigestAuth(username="tomchristie", password="password123")356

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

line 357why, one step back
357 client = AsyncClient(transport=AsyncMockTransport(auth_header=b"", status_code=401))

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 358–384why, one step back
358 response = await client.get(url, auth=auth)
359360 assert response.status_code == 401361 assert response.json() == {"auth": None}362 assert len(response.history) == 0363364365@pytest.mark.parametrize(366 "algorithm,expected_hash_length,expected_response_length",367 [368 ("MD5", 64, 32),369 ("MD5-SESS", 64, 32),370 ("SHA", 64, 40),371 ("SHA-SESS", 64, 40),372 ("SHA-256", 64, 64),373 ("SHA-256-SESS", 64, 64),374 ("SHA-512", 64, 128),375 ("SHA-512-SESS", 64, 128),376 ],377)378@pytest.mark.asyncio379async def test_digest_auth(380 algorithm: str, expected_hash_length: int, expected_response_length: int381) -> None:382 url = "https://example.org/"383 auth = DigestAuth(username="tomchristie", password="password123")384

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

line 385why, one step back
385 client = AsyncClient(transport=MockDigestAuthTransport(algorithm=algorithm))

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 386–414why, one step back
386 response = await client.get(url, auth=auth)
387388 assert response.status_code == 200389 assert len(response.history) == 1390391 authorization = typing.cast(dict, response.json())["auth"]392 scheme, _, fields = authorization.partition(" ")393 assert scheme == "Digest"394395 response_fields = [field.strip() for field in fields.split(",")]396 digest_data = dict(field.split("=") for field in response_fields)397398 assert digest_data["username"] == '"tomchristie"'399 assert digest_data["realm"] == '"httpx@example.org"'400 assert "nonce" in digest_data401 assert digest_data["uri"] == '"/"'402 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes403 assert len(digest_data["opaque"]) == expected_hash_length + 2404 assert digest_data["algorithm"] == algorithm405 assert digest_data["qop"] == "auth"406 assert digest_data["nc"] == "00000001"407 assert len(digest_data["cnonce"]) == 16 + 2408409410@pytest.mark.asyncio411async def test_digest_auth_no_specified_qop() -> None:412 url = "https://example.org/"413 auth = DigestAuth(username="tomchristie", password="password123")414

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

line 415why, one step back
415 client = AsyncClient(transport=MockDigestAuthTransport(qop=""))

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 416–445why, one step back
416 response = await client.get(url, auth=auth)
417418 assert response.status_code == 200419 assert len(response.history) == 1420421 authorization = typing.cast(dict, response.json())["auth"]422 scheme, _, fields = authorization.partition(" ")423 assert scheme == "Digest"424425 response_fields = [field.strip() for field in fields.split(",")]426 digest_data = dict(field.split("=") for field in response_fields)427428 assert "qop" not in digest_data429 assert "nc" not in digest_data430 assert "cnonce" not in digest_data431 assert digest_data["username"] == '"tomchristie"'432 assert digest_data["realm"] == '"httpx@example.org"'433 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes434 assert digest_data["uri"] == '"/"'435 assert len(digest_data["response"]) == 64 + 2436 assert len(digest_data["opaque"]) == 64 + 2437 assert digest_data["algorithm"] == "SHA-256"438439440@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))441@pytest.mark.asyncio442async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:443 url = "https://example.org/"444 auth = DigestAuth(username="tomchristie", password="password123")445

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

line 446why, one step back
446 client = AsyncClient(transport=MockDigestAuthTransport(qop=qop))

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 447–456why, one step back
447 response = await client.get(url, auth=auth)
448449 assert response.status_code == 200450 assert len(response.history) == 1451452453@pytest.mark.asyncio454async def test_digest_auth_qop_auth_int_not_implemented() -> None:455 url = "https://example.org/"456 auth = DigestAuth(username="tomchristie", password="password123")

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

line 457why, one step back
457 client = AsyncClient(transport=MockDigestAuthTransport(qop="auth-int"))

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 458–466why, one step back
458
459 with pytest.raises(NotImplementedError):460 await client.get(url, auth=auth)461462463@pytest.mark.asyncio464async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:465 url = "https://example.org/"466 auth = DigestAuth(username="tomchristie", password="password123")

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

line 467why, one step back
467 client = AsyncClient(transport=MockDigestAuthTransport(qop="not-auth"))

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 468–477why, one step back
468
469 with pytest.raises(ProtocolError):470 await client.get(url, auth=auth)471472473@pytest.mark.asyncio474async def test_digest_auth_incorrect_credentials() -> None:475 url = "https://example.org/"476 auth = DigestAuth(username="tomchristie", password="password123")477

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

lines 478–480why, one step back
478 client = AsyncClient(
479 transport=MockDigestAuthTransport(send_response_after_attempt=2)480 )

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 481–489why, one step back
481 response = await client.get(url, auth=auth)
482483 assert response.status_code == 401484 assert len(response.history) == 1485486487@pytest.mark.parametrize(488 "auth_header",489 [

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 490–494why, one step back
490 b'Digest realm="httpx@example.org", qop="auth"', # missing fields
491 b'realm="httpx@example.org", qop="auth"', # not starting with Digest492 b'DigestZ realm="httpx@example.org", qop="auth"'493 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',494 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 495–497why, one step back
495 ],
496)497@pytest.mark.asyncio

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 500–503why, one step back
500) -> None:
501 url = "https://example.org/"502 auth = DigestAuth(username="tomchristie", password="password123")503 client = AsyncClient(

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

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 505–510why, one step back
505 )
506507 with pytest.raises(ProtocolError):508 await client.get(url, auth=auth)509510

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

lines 511–533why, one step back
511@pytest.mark.parametrize(
512 "auth_header",513 [514 b'Digest realm="httpx@example.org", qop="auth"', # missing fields515 b'realm="httpx@example.org", qop="auth"', # not starting with Digest516 b'DigestZ realm="httpx@example.org", qop="auth"'517 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',518 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list519 ],520)521def test_sync_digest_auth_raises_protocol_error_on_malformed_header(522 auth_header: bytes,523) -> None:524 url = "https://example.org/"525 auth = DigestAuth(username="tomchristie", password="password123")526 client = Client(527 transport=SyncMockTransport(auth_header=auth_header, status_code=401)528 )529530 with pytest.raises(ProtocolError):531 client.get(url, auth=auth)532533

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

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

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 536–539why, one step back
536 """
537 Test that intermediate requests sent as part of an authentication flow538 are recorded in the response history.539 """

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

lines 540–542why, one step back
540 url = "https://example.org/"
541 auth = RepeatAuth(repeat=2)542 client = AsyncClient(transport=AsyncMockTransport(auth_header=b"abc"))

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

line 543why, one step back
543

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

lines 544–546why, one step back
544 response = await client.get(url, auth=auth)
545 assert response.status_code == 200546 assert response.json() == {"auth": "Repeat abc.abc"}

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

line 547why, one step back
547

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

lines 548–551why, one step back
548 assert len(response.history) == 2
549 resp1, resp2 = response.history550 assert resp1.json() == {"auth": "Repeat 0"}551 assert resp2.json() == {"auth": "Repeat 1"}

Public Auth API (#732)Tom Christiebefore adoption12dd157

line 552why, one step back
552

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

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

line 555why, one step back
555

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

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 557–558why, one step back
557
558

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

lines 559–563why, one step back
559def test_sync_auth_history() -> None:
560 """561 Test that intermediate requests sent as part of an authentication flow562 are recorded in the response history.563 """

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

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

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

line 566why, one step back
566 client = Client(transport=SyncMockTransport(auth_header=b"abc"))

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

line 567why, one step back
567

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

line 568why, one step back
568 response = client.get(url, auth=auth)

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 569–586why, one step back
569 assert response.status_code == 200
570 assert response.json() == {"auth": "Repeat abc.abc"}571572 assert len(response.history) == 2573 resp1, resp2 = response.history574 assert resp1.json() == {"auth": "Repeat 0"}575 assert resp2.json() == {"auth": "Repeat 1"}576577 assert len(resp2.history) == 1578 assert resp2.history == [resp1]579580 assert len(resp1.history) == 0581582583@pytest.mark.asyncio584async def test_digest_auth_unavailable_streaming_body():585 url = "https://example.org/"586 auth = DigestAuth(username="tomchristie", password="password123")

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

line 587why, one step back
587 client = AsyncClient(transport=AsyncMockTransport())

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 588–589why, one step back
588
589 async def streaming_body():

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

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

Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0

lines 591–593why, one step back
591
592 with pytest.raises(RequestBodyUnavailable):593 await client.post(url, data=streaming_body(), auth=auth)

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

lines 594–596why, one step back
594
595596@pytest.mark.asyncio

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

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

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

lines 598–601why, one step back
598 """
599 Test that we can read the response body in an auth flow if `requires_response_body`600 is set.601 """

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

lines 602–604why, one step back
602 url = "https://example.org/"
603 auth = ResponseBodyAuth("xyz")604 client = AsyncClient(transport=AsyncMockTransport())

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

line 605why, one step back
605

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

lines 606–608why, one step back
606 response = await client.get(url, auth=auth)
607 assert response.status_code == 200608 assert response.json() == {"auth": '{"auth": "xyz"}'}

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

lines 609–610why, one step back
609
610

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

lines 611–615why, one step back
611def test_sync_auth_reads_response_body() -> None:
612 """613 Test that we can read the response body in an auth flow if `requires_response_body`614 is set.615 """

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

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

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

line 618why, one step back
618 client = Client(transport=SyncMockTransport())

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

line 619why, one step back
619

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

line 620why, one step back
620 response = client.get(url, auth=auth)

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

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