test_auth.py
This file
Path
tests/client/test_auth.py
529 lines · 16.9 KiB · Python
Last changed by
Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
History of this fileTake it
The walk stopped after 200 commits: lines older than c38fd68 point at it.
Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 1–2why, one step back1import hashlib2import osType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 3why, one step back3import typingDrop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 4why, one step back4Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 5why, one step back5import httpcoreDrop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 6–7why, one step back6import pytest7Raise an exception in DigestAuth if non-replayable request is passed (#685)Kousik Mitrabefore adoption0ed0314
lines 8–10why, one step back8from httpx import (9 URL,10 AsyncClient,Public Auth API (#732)Tom Christiebefore adoption12dd157
line 11why, one step back11 Auth,Raise an exception in DigestAuth if non-replayable request is passed (#685)Kousik Mitrabefore adoption0ed0314
line 12why, one step back12 DigestAuth,Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 13why, one step back13 Headers,Raise an exception in DigestAuth if non-replayable request is passed (#685)Kousik Mitrabefore adoption0ed0314
lines 14–18why, one step back14 ProtocolError,15 Request,16 RequestBodyUnavailable,17 Response,18)Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 19why, one step back19from httpx._content_streams import ContentStream, JSONStreamDrop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 20–21why, one step back2021Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 22–29why, one step back22def get_header_value(headers, key, default=None):23 lookup = key.encode("ascii").lower()24 for header_key, header_value in headers:25 if header_key.lower() == lookup:26 return header_value.decode("ascii")27 return default2829Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 30why, one step back30class MockTransport(httpcore.AsyncHTTPTransport):Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 31why, one step back31 def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 32–34why, one step back32 self.auth_header = auth_header33 self.status_code = status_code34Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 35why, one step back35 async def request(Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 36why, one step back36 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 37–47why, one step back37 method: bytes,38 url: typing.Tuple[bytes, bytes, int, bytes],39 headers: typing.List[typing.Tuple[bytes, bytes]],40 stream: ContentStream,41 timeout: typing.Dict[str, typing.Optional[float]] = None,42 ) -> typing.Tuple[43 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream44 ]:45 authorization = get_header_value(headers, "Authorization")46 response_headers = (47 [(b"www-authenticate", self.auth_header)] if self.auth_header else []Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 48why, one step back48 )Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 49–50why, one step back49 response_stream = JSONStream({"auth": authorization})50 return b"HTTP/1.1", self.status_code, b"", response_headers, response_streamDrop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 51–52why, one step back5152Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 53why, one step back53class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 54–66why, one step back54 def __init__(55 self,56 algorithm: str = "SHA-256",57 send_response_after_attempt: int = 1,58 qop: str = "auth",59 regenerate_nonce: bool = True,60 ) -> None:61 self.algorithm = algorithm62 self.send_response_after_attempt = send_response_after_attempt63 self.qop = qop64 self._regenerate_nonce = regenerate_nonce65 self._response_count = 066Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 67why, one step back67 async def request(Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 68why, one step back68 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 69–76why, one step back69 method: bytes,70 url: typing.Tuple[bytes, bytes, int, bytes],71 headers: typing.List[typing.Tuple[bytes, bytes]],72 stream: ContentStream,73 timeout: typing.Dict[str, typing.Optional[float]] = None,74 ) -> typing.Tuple[75 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream76 ]:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 77why, one step back77 if self._response_count < self.send_response_after_attempt:Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 78why, one step back78 return self.challenge_send(method, url, headers, stream)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 79why, one step back79Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 80–82why, one step back80 authorization = get_header_value(headers, "Authorization")81 body = JSONStream({"auth": authorization})82 return b"HTTP/1.1", 200, b"", [], bodyDrop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 83why, one step back83Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 84–86why, one step back84 def challenge_send(85 self, method: bytes, url: URL, headers: Headers, stream: ContentStream,86 ) -> typing.Tuple[int, bytes, Headers, ContentStream]:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 87–108why, one step back87 self._response_count += 188 nonce = (89 hashlib.sha256(os.urandom(8)).hexdigest()90 if self._regenerate_nonce91 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"92 )93 challenge_data = {94 "nonce": nonce,95 "qop": self.qop,96 "opaque": (97 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"98 ),99 "algorithm": self.algorithm,100 "stale": "FALSE",101 }102 challenge_str = ", ".join(103 '{}="{}"'.format(key, value)104 for key, value in challenge_data.items()105 if value106 )107108 headers = [Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 109–112why, one step back109 (110 b"www-authenticate",111 b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),112 )Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 113why, one step back113 ]Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 114why, one step back114 return b"HTTP/1.1", 401, b"", headers, ContentStream()Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 115–117why, one step back115116117@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 118why, one step back118async def test_basic_auth() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 119–121why, one step back119 url = "https://example.org/"120 auth = ("tomchristie", "password123")121Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 122why, one step back122 client = AsyncClient(transport=MockTransport())Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 123–129why, one step back123 response = await client.get(url, auth=auth)124125 assert response.status_code == 200126 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}127128129@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 130why, one step back130async def test_basic_auth_in_url() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 131–132why, one step back131 url = "https://tomchristie:password123@example.org/"132Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 133why, one step back133 client = AsyncClient(transport=MockTransport())Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 134–140why, one step back134 response = await client.get(url)135136 assert response.status_code == 200137 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}138139140@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 141why, one step back141async def test_basic_auth_on_session() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 142–144why, one step back142 url = "https://example.org/"143 auth = ("tomchristie", "password123")144Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 145why, one step back145 client = AsyncClient(transport=MockTransport(), auth=auth)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 146–152why, one step back146 response = await client.get(url)147148 assert response.status_code == 200149 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}150151152@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 153why, one step back153async def test_custom_auth() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 154–155why, one step back154 url = "https://example.org/"155Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 156why, one step back156 def auth(request: Request) -> Request:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 157–159why, one step back157 request.headers["Authorization"] = "Token 123"158 return request159Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 160why, one step back160 client = AsyncClient(transport=MockTransport())Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 161–167why, one step back161 response = await client.get(url, auth=auth)162163 assert response.status_code == 200164 assert response.json() == {"auth": "Token 123"}165166167@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 168why, one step back168async def test_netrc_auth() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 169–171why, one step back169 os.environ["NETRC"] = "tests/.netrc"170 url = "http://netrcexample.org"171Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 172why, one step back172 client = AsyncClient(transport=MockTransport())Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 173–181why, one step back173 response = await client.get(url)174175 assert response.status_code == 200176 assert response.json() == {177 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"178 }179180181@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 182why, one step back182async def test_auth_header_has_priority_over_netrc() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 183–185why, one step back183 os.environ["NETRC"] = "tests/.netrc"184 url = "http://netrcexample.org"185Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 186why, one step back186 client = AsyncClient(transport=MockTransport())Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 187–193why, one step back187 response = await client.get(url, headers={"Authorization": "Override"})188189 assert response.status_code == 200190 assert response.json() == {"auth": "Override"}191192193@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 194why, one step back194async def test_trust_env_auth() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 195–197why, one step back195 os.environ["NETRC"] = "tests/.netrc"196 url = "http://netrcexample.org"197Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 198why, one step back198 client = AsyncClient(transport=MockTransport(), trust_env=False)No I/O auth (#644)Tom Christiebefore adoption6c69e09
line 199why, one step back199 response = await client.get(url)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 200–203why, one step back200201 assert response.status_code == 200202 assert response.json() == {"auth": None}203Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 204why, one step back204 client = AsyncClient(transport=MockTransport(), trust_env=True)No I/O auth (#644)Tom Christiebefore adoption6c69e09
line 205why, one step back205 response = await client.get(url)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 206–212why, one step back206207 assert response.status_code == 200208 assert response.json() == {209 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"210 }211212Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 213why, one step back213def test_auth_hidden_url() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 214–220why, one step back214 url = "http://example-username:example-password@example.org/"215 expected = "URL('http://example-username:[secure]@example.org/')"216 assert url == URL(url)217 assert expected == repr(URL(url))218219220@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 221why, one step back221async def test_auth_hidden_header() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 222–224why, one step back222 url = "https://example.org/"223 auth = ("example-username", "example-password")224Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 225why, one step back225 client = AsyncClient(transport=MockTransport())Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 226–231why, one step back226 response = await client.get(url, auth=auth)227228 assert "'authorization': '[secure]'" in str(response.request.headers)229230231@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 232why, one step back232async def test_auth_invalid_type() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 233why, one step back233 url = "https://example.org/"Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 234why, one step back234 client = AsyncClient(Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 235why, one step back235 transport=MockTransport(), auth="not a tuple, not a callable", # type: ignoreType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 236why, one step back236 )Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 237–241why, one step back237 with pytest.raises(TypeError):238 await client.get(url)239240241@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 242why, one step back242async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 243–245why, one step back243 url = "https://example.org/"244 auth = DigestAuth(username="tomchristie", password="password123")245Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 246why, one step back246 client = AsyncClient(transport=MockTransport())Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 247–250why, one step back247 response = await client.get(url, auth=auth)248249 assert response.status_code == 200250 assert response.json() == {"auth": None}Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
line 251why, one step back251 assert len(response.history) == 0Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 252–254why, one step back252253254@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 255why, one step back255async def test_digest_auth_200_response_including_digest_auth_header() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 256–257why, one step back256 url = "https://example.org/"257 auth = DigestAuth(username="tomchristie", password="password123")Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 258why, one step back258 auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 259why, one step back259Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 260why, one step back260 client = AsyncClient(Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 261why, one step back261 transport=MockTransport(auth_header=auth_header, status_code=200)Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 262why, one step back262 )Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 263–266why, one step back263 response = await client.get(url, auth=auth)264265 assert response.status_code == 200266 assert response.json() == {"auth": None}Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
line 267why, one step back267 assert len(response.history) == 0Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 268–270why, one step back268269270@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 271why, one step back271async def test_digest_auth_401_response_without_digest_auth_header() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 272–274why, one step back272 url = "https://example.org/"273 auth = DigestAuth(username="tomchristie", password="password123")274Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 275why, one step back275 client = AsyncClient(transport=MockTransport(auth_header=b"", status_code=401))Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 276–279why, one step back276 response = await client.get(url, auth=auth)277278 assert response.status_code == 401279 assert response.json() == {"auth": None}Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
line 280why, one step back280 assert len(response.history) == 0Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 281–296why, one step back281282283@pytest.mark.parametrize(284 "algorithm,expected_hash_length,expected_response_length",285 [286 ("MD5", 64, 32),287 ("MD5-SESS", 64, 32),288 ("SHA", 64, 40),289 ("SHA-SESS", 64, 40),290 ("SHA-256", 64, 64),291 ("SHA-256-SESS", 64, 64),292 ("SHA-512", 64, 128),293 ("SHA-512-SESS", 64, 128),294 ],295)296@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
lines 297–299why, one step back297async def test_digest_auth(298 algorithm: str, expected_hash_length: int, expected_response_length: int299) -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 300–302why, one step back300 url = "https://example.org/"301 auth = DigestAuth(username="tomchristie", password="password123")302Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 303why, one step back303 client = AsyncClient(transport=MockDigestAuthTransport(algorithm=algorithm))Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 304–306why, one step back304 response = await client.get(url, auth=auth)305306 assert response.status_code == 200Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
lines 307–308why, one step back307 assert len(response.history) == 1308Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
lines 309–311why, one step back309 authorization = typing.cast(dict, response.json())["auth"]310 scheme, _, fields = authorization.partition(" ")311 assert scheme == "Digest"Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 312why, one step back312Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 313why, one step back313 response_fields = [field.strip() for field in fields.split(",")]Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 314–328why, one step back314 digest_data = dict(field.split("=") for field in response_fields)315316 assert digest_data["username"] == '"tomchristie"'317 assert digest_data["realm"] == '"httpx@example.org"'318 assert "nonce" in digest_data319 assert digest_data["uri"] == '"/"'320 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes321 assert len(digest_data["opaque"]) == expected_hash_length + 2322 assert digest_data["algorithm"] == algorithm323 assert digest_data["qop"] == "auth"324 assert digest_data["nc"] == "00000001"325 assert len(digest_data["cnonce"]) == 16 + 2326327328@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 329why, one step back329async def test_digest_auth_no_specified_qop() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 330–332why, one step back330 url = "https://example.org/"331 auth = DigestAuth(username="tomchristie", password="password123")332Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 333why, one step back333 client = AsyncClient(transport=MockDigestAuthTransport(qop=""))Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 334–336why, one step back334 response = await client.get(url, auth=auth)335336 assert response.status_code == 200Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
lines 337–338why, one step back337 assert len(response.history) == 1338Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
lines 339–341why, one step back339 authorization = typing.cast(dict, response.json())["auth"]340 scheme, _, fields = authorization.partition(" ")341 assert scheme == "Digest"Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 342why, one step back342Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 343why, one step back343 response_fields = [field.strip() for field in fields.split(",")]Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 344–359why, one step back344 digest_data = dict(field.split("=") for field in response_fields)345346 assert "qop" not in digest_data347 assert "nc" not in digest_data348 assert "cnonce" not in digest_data349 assert digest_data["username"] == '"tomchristie"'350 assert digest_data["realm"] == '"httpx@example.org"'351 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes352 assert digest_data["uri"] == '"/"'353 assert len(digest_data["response"]) == 64 + 2354 assert len(digest_data["opaque"]) == 64 + 2355 assert digest_data["algorithm"] == "SHA-256"356357358@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))359@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 360why, one step back360async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 361–363why, one step back361 url = "https://example.org/"362 auth = DigestAuth(username="tomchristie", password="password123")363Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 364why, one step back364 client = AsyncClient(transport=MockDigestAuthTransport(qop=qop))Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
line 365why, one step back365 response = await client.get(url, auth=auth)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 366why, one step back366Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
lines 367–368why, one step back367 assert response.status_code == 200368 assert len(response.history) == 1Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 369why, one step back369Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
line 370why, one step back370Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 371why, one step back371@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 372why, one step back372async def test_digest_auth_qop_auth_int_not_implemented() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 373–374why, one step back373 url = "https://example.org/"374 auth = DigestAuth(username="tomchristie", password="password123")Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 375why, one step back375 client = AsyncClient(transport=MockDigestAuthTransport(qop="auth-int"))Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 376–381why, one step back376377 with pytest.raises(NotImplementedError):378 await client.get(url, auth=auth)379380381@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 382why, one step back382async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 383–384why, one step back383 url = "https://example.org/"384 auth = DigestAuth(username="tomchristie", password="password123")Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 385why, one step back385 client = AsyncClient(transport=MockDigestAuthTransport(qop="not-auth"))Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 386–391why, one step back386387 with pytest.raises(ProtocolError):388 await client.get(url, auth=auth)389390391@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 392why, one step back392async def test_digest_auth_incorrect_credentials() -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 393–395why, one step back393 url = "https://example.org/"394 auth = DigestAuth(username="tomchristie", password="password123")395Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
lines 396–398why, one step back396 client = AsyncClient(397 transport=MockDigestAuthTransport(send_response_after_attempt=2)398 )Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 399–401why, one step back399 response = await client.get(url, auth=auth)400401 assert response.status_code == 401Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
line 402why, one step back402 assert len(response.history) == 1Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 403–407why, one step back403404405@pytest.mark.parametrize(406 "auth_header",407 [Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 408–412why, one step back408 b'Digest realm="httpx@example.org", qop="auth"', # missing fields409 b'realm="httpx@example.org", qop="auth"', # not starting with Digest410 b'DigestZ realm="httpx@example.org", qop="auth"'411 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',412 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields listDrop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 413–415why, one step back413 ],414)415@pytest.mark.asyncioType-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 416why, one step back416async def test_digest_auth_raises_protocol_error_on_malformed_header(Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 417why, one step back417 auth_header: bytes,Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15
line 418why, one step back418) -> None:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 419–420why, one step back419 url = "https://example.org/"420 auth = DigestAuth(username="tomchristie", password="password123")Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 421why, one step back421 client = AsyncClient(Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 422why, one step back422 transport=MockTransport(auth_header=auth_header, status_code=401)Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 423why, one step back423 )Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 424–426why, one step back424425 with pytest.raises(ProtocolError):426 await client.get(url, auth=auth)Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
lines 427–443why, one step back427428429@pytest.mark.asyncio430async def test_auth_history() -> None:431 """432 Test that intermediate requests sent as part of an authentication flow433 are recorded in the response history.434 """435436 class RepeatAuth(Auth):437 """438 A mock authentication scheme that requires clients to send439 the request a fixed number of times, and then send a last request containing440 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers441 of intermediate responses.442 """443Public Auth API (#732)Tom Christiebefore adoption12dd157
lines 444–445why, one step back444 requires_request_body = True445Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
lines 446–448why, one step back446 def __init__(self, repeat: int):447 self.repeat = repeat448Public Auth API (#732)Tom Christiebefore adoption12dd157
lines 449–451why, one step back449 def auth_flow(450 self, request: Request451 ) -> typing.Generator[Request, Response, None]:Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
lines 452–464why, one step back452 nonces = []453454 for index in range(self.repeat):455 request.headers["Authorization"] = f"Repeat {index}"456 response = yield request457 nonces.append(response.headers["www-authenticate"])458459 key = ".".join(nonces)460 request.headers["Authorization"] = f"Repeat {key}"461 yield request462463 url = "https://example.org/"464 auth = RepeatAuth(repeat=2)Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 465why, one step back465 client = AsyncClient(transport=MockTransport(auth_header=b"abc"))Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
lines 466–479why, one step back466467 response = await client.get(url, auth=auth)468 assert response.status_code == 200469 assert response.json() == {"auth": "Repeat abc.abc"}470471 assert len(response.history) == 2472 resp1, resp2 = response.history473 assert resp1.json() == {"auth": "Repeat 0"}474 assert resp2.json() == {"auth": "Repeat 1"}475476 assert len(resp2.history) == 1477 assert resp2.history == [resp1]478479 assert len(resp1.history) == 0Raise an exception in DigestAuth if non-replayable request is passed (#685)Kousik Mitrabefore adoption0ed0314
lines 480–485why, one step back480481482@pytest.mark.asyncio483async def test_digest_auth_unavailable_streaming_body():484 url = "https://example.org/"485 auth = DigestAuth(username="tomchristie", password="password123")Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 486why, one step back486 client = AsyncClient(transport=MockTransport())Raise an exception in DigestAuth if non-replayable request is passed (#685)Kousik Mitrabefore adoption0ed0314
lines 487–488why, one step back487488 async def streaming_body():Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 489why, one step back489 yield b"Example request body" # pragma: nocoverRaise an exception in DigestAuth if non-replayable request is passed (#685)Kousik Mitrabefore adoption0ed0314
lines 490–492why, one step back490491 with pytest.raises(RequestBodyUnavailable):492 await client.post(url, data=streaming_body(), auth=auth)Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff
lines 493–524why, one step back493494495@pytest.mark.asyncio496async def test_auth_reads_response_body() -> None:497 """498 Test that we can read the response body in an auth flow if `requires_response_body`499 is set.500 """501502 class ResponseBodyAuth(Auth):503 """504 A mock authentication scheme that requires clients to send an 'Authorization'505 header, then send back the contents of the response in the 'Authorization'506 header.507 """508509 requires_response_body = True510511 def __init__(self, token):512 self.token = token513514 def auth_flow(515 self, request: Request516 ) -> typing.Generator[Request, Response, None]:517 request.headers["Authorization"] = self.token518 response = yield request519 data = response.text520 request.headers["Authorization"] = data521 yield request522523 url = "https://example.org/"524 auth = ResponseBodyAuth("xyz")Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 525why, one step back525 client = AsyncClient(transport=MockTransport())Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff
lines 526–529why, one step back526527 response = await client.get(url, auth=auth)528 assert response.status_code == 200529 assert response.json() == {"auth": '{"auth": "xyz"}'}