Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

643 lines · 20.4 KiB · Python

Last changed by

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

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,

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

line 12why, one step back
12 BasicAuth,

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

line 13why, one step back
13 Client,

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 21why, one step back
21

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

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

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

line 23why, one step back
23

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

line 24why, one step back
24

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 33why, one step back
33class MockTransport:

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 34why, one step back
34 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 35–37why, one step back
35 self.auth_header = auth_header
36 self.status_code = status_code37

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

line 38why, one step back
38 def _request(

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

line 39why, one step back
39 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 45–50why, one step back
45 ) -> typing.Tuple[
46 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream47 ]:48 authorization = get_header_value(headers, "Authorization")49 response_headers = (50 [(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 51why, one step back
51 )

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 52–53why, one step back
52 response_stream = JSONStream({"auth": authorization})
53 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 54–55why, one step back
54
55

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

lines 56–73why, one step back
56class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):
57 async def request(58 self, *args, **kwargs59 ) -> typing.Tuple[60 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream61 ]:62 return self._request(*args, **kwargs)636465class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):66 def request(67 self, *args, **kwargs68 ) -> typing.Tuple[69 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream70 ]:71 return self._request(*args, **kwargs)7273

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

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

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

lines 75–87why, one step back
75 def __init__(
76 self,77 algorithm: str = "SHA-256",78 send_response_after_attempt: int = 1,79 qop: str = "auth",80 regenerate_nonce: bool = True,81 ) -> None:82 self.algorithm = algorithm83 self.send_response_after_attempt = send_response_after_attempt84 self.qop = qop85 self._regenerate_nonce = regenerate_nonce86 self._response_count = 087

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 89why, one step back
89 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

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

line 101why, one step back
101

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 105why, one step back
105

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 106why, one step back
106 def challenge_send(

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 137why, one step back
137 ]

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 138why, one step back
138 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 139–140why, one step back
139
140

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

lines 141–186why, one step back
141class RepeatAuth(Auth):
142 """143 A mock authentication scheme that requires clients to send144 the request a fixed number of times, and then send a last request containing145 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers146 of intermediate responses.147 """148149 requires_request_body = True150151 def __init__(self, repeat: int):152 self.repeat = repeat153154 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:155 nonces = []156157 for index in range(self.repeat):158 request.headers["Authorization"] = f"Repeat {index}"159 response = yield request160 nonces.append(response.headers["www-authenticate"])161162 key = ".".join(nonces)163 request.headers["Authorization"] = f"Repeat {key}"164 yield request165166167class ResponseBodyAuth(Auth):168 """169 A mock authentication scheme that requires clients to send an 'Authorization'170 header, then send back the contents of the response in the 'Authorization'171 header.172 """173174 requires_response_body = True175176 def __init__(self, token):177 self.token = token178179 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:180 request.headers["Authorization"] = self.token181 response = yield request182 data = response.text183 request.headers["Authorization"] = data184 yield request185186

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

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

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

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

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

lines 193–202why, one step back
193 response = await client.get(url, auth=auth)
194195 assert response.status_code == 200196 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}197198199@pytest.mark.asyncio200async def test_basic_auth_in_url() -> None:201 url = "https://tomchristie:password123@example.org/"202

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

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

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

lines 204–214why, one step back
204 response = await client.get(url)
205206 assert response.status_code == 200207 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}208209210@pytest.mark.asyncio211async def test_basic_auth_on_session() -> None:212 url = "https://example.org/"213 auth = ("tomchristie", "password123")214

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

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

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

lines 216–229why, one step back
216 response = await client.get(url)
217218 assert response.status_code == 200219 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}220221222@pytest.mark.asyncio223async def test_custom_auth() -> None:224 url = "https://example.org/"225226 def auth(request: Request) -> Request:227 request.headers["Authorization"] = "Token 123"228 return request229

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

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

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

lines 231–238why, one step back
231 response = await client.get(url, auth=auth)
232233 assert response.status_code == 200234 assert response.json() == {"auth": "Token 123"}235236237@pytest.mark.asyncio238async def test_netrc_auth() -> None:

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

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

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

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

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

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

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

lines 243–252why, one step back
243 response = await client.get(url)
244245 assert response.status_code == 200246 assert response.json() == {247 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"248 }249250251@pytest.mark.asyncio252async def test_auth_header_has_priority_over_netrc() -> None:

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

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

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

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

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

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

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

lines 257–264why, one step back
257 response = await client.get(url, headers={"Authorization": "Override"})
258259 assert response.status_code == 200260 assert response.json() == {"auth": "Override"}261262263@pytest.mark.asyncio264async def test_trust_env_auth() -> None:

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

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

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

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

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

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

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

lines 269–273why, one step back
269 response = await client.get(url)
270271 assert response.status_code == 200272 assert response.json() == {"auth": None}273

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

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

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

lines 275–282why, one step back
275 response = await client.get(url)
276277 assert response.status_code == 200278 assert response.json() == {279 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"280 }281282

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

lines 283–294why, one step back
283@pytest.mark.asyncio
284async def test_auth_disable_per_request() -> None:285 url = "https://example.org/"286 auth = ("tomchristie", "password123")287288 client = AsyncClient(transport=AsyncMockTransport(), auth=auth)289 response = await client.get(url, auth=None)290291 assert response.status_code == 200292 assert response.json() == {"auth": None}293294

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

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

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

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

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

lines 308–313why, one step back
308 response = await client.get(url, auth=auth)
309310 assert "'authorization': '[secure]'" in str(response.request.headers)311312313@pytest.mark.asyncio

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

lines 314–320why, one step back
314async def test_auth_property() -> None:
315 client = AsyncClient(transport=AsyncMockTransport())316 assert client.auth is None317318 client.auth = ("tomchristie", "password123") # type: ignore319 assert isinstance(client.auth, BasicAuth)320

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

line 321why, one step back
321 url = "https://example.org/"

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

lines 322–328why, one step back
322 response = await client.get(url)
323 assert response.status_code == 200324 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}325326327@pytest.mark.asyncio328async def test_auth_invalid_type() -> None:

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

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

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

lines 330–341why, one step back
330 client = AsyncClient(
331 transport=AsyncMockTransport(),332 auth="not a tuple, not a callable", # type: ignore333 )334335 client = AsyncClient(transport=AsyncMockTransport())336337 with pytest.raises(TypeError):338 await client.get(auth="not a tuple, not a callable") # type: ignore339340 with pytest.raises(TypeError):341 client.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 342–348why, one step back
342
343344@pytest.mark.asyncio345async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:346 url = "https://example.org/"347 auth = DigestAuth(username="tomchristie", password="password123")348

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

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

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

lines 350–360why, one step back
350 response = await client.get(url, auth=auth)
351352 assert response.status_code == 200353 assert response.json() == {"auth": None}354 assert len(response.history) == 0355356357@pytest.mark.asyncio358async def test_digest_auth_200_response_including_digest_auth_header() -> None:359 url = "https://example.org/"360 auth = DigestAuth(username="tomchristie", password="password123")

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 361why, one step back
361 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 362–363why, one step back
362
363 client = AsyncClient(

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

line 364why, one step back
364 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 365–377why, one step back
365 )
366 response = await client.get(url, auth=auth)367368 assert response.status_code == 200369 assert response.json() == {"auth": None}370 assert len(response.history) == 0371372373@pytest.mark.asyncio374async def test_digest_auth_401_response_without_digest_auth_header() -> None:375 url = "https://example.org/"376 auth = DigestAuth(username="tomchristie", password="password123")377

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

line 378why, one step back
378 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 379–405why, one step back
379 response = await client.get(url, auth=auth)
380381 assert response.status_code == 401382 assert response.json() == {"auth": None}383 assert len(response.history) == 0384385386@pytest.mark.parametrize(387 "algorithm,expected_hash_length,expected_response_length",388 [389 ("MD5", 64, 32),390 ("MD5-SESS", 64, 32),391 ("SHA", 64, 40),392 ("SHA-SESS", 64, 40),393 ("SHA-256", 64, 64),394 ("SHA-256-SESS", 64, 64),395 ("SHA-512", 64, 128),396 ("SHA-512-SESS", 64, 128),397 ],398)399@pytest.mark.asyncio400async def test_digest_auth(401 algorithm: str, expected_hash_length: int, expected_response_length: int402) -> None:403 url = "https://example.org/"404 auth = DigestAuth(username="tomchristie", password="password123")405

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

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

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

lines 407–435why, one step back
407 response = await client.get(url, auth=auth)
408409 assert response.status_code == 200410 assert len(response.history) == 1411412 authorization = typing.cast(dict, response.json())["auth"]413 scheme, _, fields = authorization.partition(" ")414 assert scheme == "Digest"415416 response_fields = [field.strip() for field in fields.split(",")]417 digest_data = dict(field.split("=") for field in response_fields)418419 assert digest_data["username"] == '"tomchristie"'420 assert digest_data["realm"] == '"httpx@example.org"'421 assert "nonce" in digest_data422 assert digest_data["uri"] == '"/"'423 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes424 assert len(digest_data["opaque"]) == expected_hash_length + 2425 assert digest_data["algorithm"] == algorithm426 assert digest_data["qop"] == "auth"427 assert digest_data["nc"] == "00000001"428 assert len(digest_data["cnonce"]) == 16 + 2429430431@pytest.mark.asyncio432async def test_digest_auth_no_specified_qop() -> None:433 url = "https://example.org/"434 auth = DigestAuth(username="tomchristie", password="password123")435

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

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

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

lines 437–466why, one step back
437 response = await client.get(url, auth=auth)
438439 assert response.status_code == 200440 assert len(response.history) == 1441442 authorization = typing.cast(dict, response.json())["auth"]443 scheme, _, fields = authorization.partition(" ")444 assert scheme == "Digest"445446 response_fields = [field.strip() for field in fields.split(",")]447 digest_data = dict(field.split("=") for field in response_fields)448449 assert "qop" not in digest_data450 assert "nc" not in digest_data451 assert "cnonce" not in digest_data452 assert digest_data["username"] == '"tomchristie"'453 assert digest_data["realm"] == '"httpx@example.org"'454 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes455 assert digest_data["uri"] == '"/"'456 assert len(digest_data["response"]) == 64 + 2457 assert len(digest_data["opaque"]) == 64 + 2458 assert digest_data["algorithm"] == "SHA-256"459460461@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))462@pytest.mark.asyncio463async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:464 url = "https://example.org/"465 auth = DigestAuth(username="tomchristie", password="password123")466

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

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

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

lines 468–477why, one step back
468 response = await client.get(url, auth=auth)
469470 assert response.status_code == 200471 assert len(response.history) == 1472473474@pytest.mark.asyncio475async def test_digest_auth_qop_auth_int_not_implemented() -> None:476 url = "https://example.org/"477 auth = DigestAuth(username="tomchristie", password="password123")

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

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

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

lines 479–487why, one step back
479
480 with pytest.raises(NotImplementedError):481 await client.get(url, auth=auth)482483484@pytest.mark.asyncio485async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:486 url = "https://example.org/"487 auth = DigestAuth(username="tomchristie", password="password123")

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

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

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

lines 489–498why, one step back
489
490 with pytest.raises(ProtocolError):491 await client.get(url, auth=auth)492493494@pytest.mark.asyncio495async def test_digest_auth_incorrect_credentials() -> None:496 url = "https://example.org/"497 auth = DigestAuth(username="tomchristie", password="password123")498

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

lines 499–501why, one step back
499 client = AsyncClient(
500 transport=MockDigestAuthTransport(send_response_after_attempt=2)501 )

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

lines 502–510why, one step back
502 response = await client.get(url, auth=auth)
503504 assert response.status_code == 401505 assert len(response.history) == 1506507508@pytest.mark.parametrize(509 "auth_header",510 [

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 511–515why, one step back
511 b'Digest realm="httpx@example.org", qop="auth"', # missing fields
512 b'realm="httpx@example.org", qop="auth"', # not starting with Digest513 b'DigestZ realm="httpx@example.org", qop="auth"'514 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',515 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 516–518why, one step back
516 ],
517)518@pytest.mark.asyncio

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

lines 521–524why, one step back
521) -> None:
522 url = "https://example.org/"523 auth = DigestAuth(username="tomchristie", password="password123")524 client = AsyncClient(

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

line 525why, one step back
525 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 526–531why, one step back
526 )
527528 with pytest.raises(ProtocolError):529 await client.get(url, auth=auth)530531

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

lines 532–554why, one step back
532@pytest.mark.parametrize(
533 "auth_header",534 [535 b'Digest realm="httpx@example.org", qop="auth"', # missing fields536 b'realm="httpx@example.org", qop="auth"', # not starting with Digest537 b'DigestZ realm="httpx@example.org", qop="auth"'538 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',539 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list540 ],541)542def test_sync_digest_auth_raises_protocol_error_on_malformed_header(543 auth_header: bytes,544) -> None:545 url = "https://example.org/"546 auth = DigestAuth(username="tomchristie", password="password123")547 client = Client(548 transport=SyncMockTransport(auth_header=auth_header, status_code=401)549 )550551 with pytest.raises(ProtocolError):552 client.get(url, auth=auth)553554

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

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

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

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

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

lines 557–560why, one step back
557 """
558 Test that intermediate requests sent as part of an authentication flow559 are recorded in the response history.560 """

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

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

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

line 564why, one step back
564

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

lines 565–567why, one step back
565 response = await client.get(url, auth=auth)
566 assert response.status_code == 200567 assert response.json() == {"auth": "Repeat abc.abc"}

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

line 568why, one step back
568

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

lines 569–572why, one step back
569 assert len(response.history) == 2
570 resp1, resp2 = response.history571 assert resp1.json() == {"auth": "Repeat 0"}572 assert resp2.json() == {"auth": "Repeat 1"}

Public Auth API (#732)Tom Christiebefore adoption12dd157

line 573why, one step back
573

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

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

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

line 576why, one step back
576

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

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

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

lines 578–579why, one step back
578
579

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

lines 580–584why, one step back
580def test_sync_auth_history() -> None:
581 """582 Test that intermediate requests sent as part of an authentication flow583 are recorded in the response history.584 """

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

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

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

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

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

line 588why, one step back
588

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

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

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

lines 590–607why, one step back
590 assert response.status_code == 200
591 assert response.json() == {"auth": "Repeat abc.abc"}592593 assert len(response.history) == 2594 resp1, resp2 = response.history595 assert resp1.json() == {"auth": "Repeat 0"}596 assert resp2.json() == {"auth": "Repeat 1"}597598 assert len(resp2.history) == 1599 assert resp2.history == [resp1]600601 assert len(resp1.history) == 0602603604@pytest.mark.asyncio605async def test_digest_auth_unavailable_streaming_body():606 url = "https://example.org/"607 auth = DigestAuth(username="tomchristie", password="password123")

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

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

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

lines 609–610why, one step back
609
610 async def streaming_body():

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

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

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

lines 612–614why, one step back
612
613 with pytest.raises(RequestBodyUnavailable):614 await client.post(url, data=streaming_body(), auth=auth)

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

lines 615–617why, one step back
615
616617@pytest.mark.asyncio

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

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

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

lines 619–622why, one step back
619 """
620 Test that we can read the response body in an auth flow if `requires_response_body`621 is set.622 """

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

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

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

line 626why, one step back
626

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

lines 627–629why, one step back
627 response = await client.get(url, auth=auth)
628 assert response.status_code == 200629 assert response.json() == {"auth": '{"auth": "xyz"}'}

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

lines 630–631why, one step back
630
631

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

lines 632–636why, one step back
632def test_sync_auth_reads_response_body() -> None:
633 """634 Test that we can read the response body in an auth flow if `requires_response_body`635 is set.636 """

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

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

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

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

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

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

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

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