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 fileTake 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 back1import hashlib2import os3import typing4Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 5why, one step back5import httpcoreDrop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 6–10why, one step back6import pytest78from httpx import (9 URL,10 AsyncClient,Public Auth API (#732)Tom Christiebefore adoption12dd157
line 11why, one step back11 Auth,Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 12why, one step back12 BasicAuth,Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 13why, one step back13 Client,Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 14–19why, one step back14 DigestAuth,15 ProtocolError,16 Request,17 RequestBodyUnavailable,18 Response,19)Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 20why, one step back20from httpx._content_streams import ContentStream, JSONStreamDrop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
line 21why, one step back21Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 22why, one step back22from ..common import FIXTURES_DIRDrop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
line 23why, one step back23Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 24why, one step back24Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 25–32why, one step back25def 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 default3132Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 33why, one step back33class MockTransport:Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 34why, one step back34 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 back35 self.auth_header = auth_header36 self.status_code = status_code37Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 38why, one step back38 def _request(Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
line 39why, one step back39 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 40–43why, one step back40 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 back44 timeout: typing.Mapping[str, typing.Optional[float]] = None,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 45–50why, one step back45 ) -> 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 back51 )Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 52–53why, one step back52 response_stream = JSONStream({"auth": authorization})53 return b"HTTP/1.1", self.status_code, b"", response_headers, response_streamDrop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 54–55why, one step back5455Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 56–73why, one step back56class 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)7273Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 74why, one step back74class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 75–87why, one step back75 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 = 087Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 88why, one step back88 async def request(Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
line 89why, one step back89 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 90why, one step back90 method: bytes,Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 91–93why, one step back91 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 back94 timeout: typing.Mapping[str, typing.Optional[float]] = None,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 95–97why, one step back95 ) -> 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 back98 if self._response_count < self.send_response_after_attempt:Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 99–100why, one step back99 assert headers is not None100 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 back101Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 102–104why, one step back102 authorization = get_header_value(headers, "Authorization")103 body = JSONStream({"auth": authorization})104 return b"HTTP/1.1", 200, b"", [], bodyDrop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
line 105why, one step back105Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 106why, one step back106 def challenge_send(Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 107–110why, one step back107 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 back111 self._response_count += 1112 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 back133 (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 back137 ]Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 138why, one step back138 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 back139140Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 141–186why, one step back141class 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 request185186Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 187–191why, one step back187@pytest.mark.asyncio188async def test_basic_auth() -> None:189 url = "https://example.org/"190 auth = ("tomchristie", "password123")191Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 192why, one step back192 client = AsyncClient(transport=AsyncMockTransport())Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 193–202why, one step back193 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/"202Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 203why, one step back203 client = AsyncClient(transport=AsyncMockTransport())Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 204–214why, one step back204 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")214Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 215why, one step back215 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 back216 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 request229Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 230why, one step back230 client = AsyncClient(transport=AsyncMockTransport())Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 231–238why, one step back231 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 back239 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 back240 url = "http://netrcexample.org"241Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 242why, one step back242 client = AsyncClient(transport=AsyncMockTransport())Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 243–252why, one step back243 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 back253 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 back254 url = "http://netrcexample.org"255Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 256why, one step back256 client = AsyncClient(transport=AsyncMockTransport())Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 257–264why, one step back257 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 back265 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 back266 url = "http://netrcexample.org"267Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 268why, one step back268 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 back269 response = await client.get(url)270271 assert response.status_code == 200272 assert response.json() == {"auth": None}273Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 274why, one step back274 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 back275 response = await client.get(url)276277 assert response.status_code == 200278 assert response.json() == {279 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"280 }281282Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0
lines 283–294why, one step back283@pytest.mark.asyncio284async 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}293294Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 295–306why, one step back295def 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")306Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 307why, one step back307 client = AsyncClient(transport=AsyncMockTransport())Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 308–313why, one step back308 response = await client.get(url, auth=auth)309310 assert "'authorization': '[secure]'" in str(response.request.headers)311312313@pytest.mark.asyncioAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
lines 314–320why, one step back314async 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)320Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
line 321why, one step back321 url = "https://example.org/"Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
lines 322–328why, one step back322 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 back329 with pytest.raises(TypeError):Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
lines 330–341why, one step back330 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: ignoreDrop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 342–348why, one step back342343344@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")348Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 349why, one step back349 client = AsyncClient(transport=AsyncMockTransport())Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 350–360why, one step back350 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 back361 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 back362363 client = AsyncClient(Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 364why, one step back364 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 back365 )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")377Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 378why, one step back378 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 back379 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")405Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 406why, one step back406 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 back407 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")435Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 436why, one step back436 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 back437 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")466Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 467why, one step back467 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 back468 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 back478 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 back479480 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 back488 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 back489490 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")498Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
lines 499–501why, one step back499 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 back502 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 back511 b'Digest realm="httpx@example.org", qop="auth"', # missing fields512 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 listDrop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 516–518why, one step back516 ],517)518@pytest.mark.asyncioIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 519why, one step back519async def test_async_digest_auth_raises_protocol_error_on_malformed_header(Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 520why, one step back520 auth_header: bytes,Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 521–524why, one step back521) -> 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 back525 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 back526 )527528 with pytest.raises(ProtocolError):529 await client.get(url, auth=auth)530531Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 532–554why, one step back532@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)553554Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
line 555why, one step back555@pytest.mark.asyncioIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 556why, one step back556async 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 back557 """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 back561 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 back564Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 565–567why, one step back565 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 back568Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 569–572why, one step back569 assert len(response.history) == 2570 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 back573Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 574–575why, one step back574 assert len(resp2.history) == 1575 assert resp2.history == [resp1]Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
line 576why, one step back576Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 577why, one step back577 assert len(resp1.history) == 0Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 578–579why, one step back578579Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 580–584why, one step back580def 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 back585 url = "https://example.org/"586 auth = RepeatAuth(repeat=2)Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 587why, one step back587 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 back588Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 589why, one step back589 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 back590 assert response.status_code == 200591 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 back608 client = AsyncClient(transport=AsyncMockTransport())Drop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 609–610why, one step back609610 async def streaming_body():Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 611why, one step back611 yield b"Example request body" # pragma: nocoverDrop per-request 'cert'/'verify'/'trust_env', and 'stream=bool' arguments (#730)Tom Christiebefore adoptionc5037f0
lines 612–614why, one step back612613 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 back615616617@pytest.mark.asyncioIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 618why, one step back618async def test_async_auth_reads_response_body() -> None:Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff
lines 619–622why, one step back619 """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 back623 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 back626Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 627–629why, one step back627 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 back630631Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 632–636why, one step back632def 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 back637 url = "https://example.org/"638 auth = ResponseBodyAuth("xyz")Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 639why, one step back639 client = Client(transport=SyncMockTransport())Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff
line 640why, one step back640Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 641why, one step back641 response = client.get(url, auth=auth)Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff
lines 642–643why, one step back642 assert response.status_code == 200643 assert response.json() == {"auth": '{"auth": "xyz"}'}