test_auth.py
This file
Path
tests/client/test_auth.py
666 lines · 21.3 KiB · Python
Last changed by
Handle multiple auth headers correctly (#1240)Tom Christiebefore adoption33d339a
History of this fileTake it
The walk stopped after 200 commits: lines older than 5380417 point at it.
Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 1–4why, one step back1import hashlib2import os3import typing4Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 5why, one step back5import httpcoreDrop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 6–7why, one step back6import pytest7Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 8why, one step back8import httpxDrop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 9–11why, one step back9from httpx import (10 URL,11 Auth,Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 12why, one step back12 BasicAuth,Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 13–18why, one step back13 DigestAuth,14 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 backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 20why, one step back20Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 21why, one step back21from ..common import FIXTURES_DIRDrop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 22why, one step back22Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 23why, one step back23Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 24–31why, one step back24def get_header_value(headers, key, default=None):25 lookup = key.encode("ascii").lower()26 for header_key, header_value in headers:27 if header_key.lower() == lookup:28 return header_value.decode("ascii")29 return default3031Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 32why, one step back32class MockTransport:Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 33why, one step back33 def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 34–36why, one step back34 self.auth_header = auth_header35 self.status_code = status_code36Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 37why, one step back37 def _request(Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 38why, one step back38 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 39–42why, one step back39 method: bytes,40 url: typing.Tuple[bytes, bytes, int, bytes],41 headers: typing.List[typing.Tuple[bytes, bytes]],42 stream: ContentStream,Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722
line 43why, one step back43 timeout: typing.Mapping[str, typing.Optional[float]] = None,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 44–49why, one step back44 ) -> typing.Tuple[45 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream46 ]:47 authorization = get_header_value(headers, "Authorization")48 response_headers = (49 [(b"www-authenticate", self.auth_header)] if self.auth_header else []Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 50why, one step back50 )Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 51–52why, one step back51 response_stream = JSONStream({"auth": authorization})52 return b"HTTP/1.1", self.status_code, b"", response_headers, response_streamDrop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 53–54why, one step back5354Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 55–72why, one step back55class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):56 async def request(57 self, *args, **kwargs58 ) -> typing.Tuple[59 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream60 ]:61 return self._request(*args, **kwargs)626364class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):65 def request(66 self, *args, **kwargs67 ) -> typing.Tuple[68 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream69 ]:70 return self._request(*args, **kwargs)7172Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 73why, one step back73class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 74–86why, one step back74 def __init__(75 self,76 algorithm: str = "SHA-256",77 send_response_after_attempt: int = 1,78 qop: str = "auth",79 regenerate_nonce: bool = True,80 ) -> None:81 self.algorithm = algorithm82 self.send_response_after_attempt = send_response_after_attempt83 self.qop = qop84 self._regenerate_nonce = regenerate_nonce85 self._response_count = 086Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 87why, one step back87 async def request(Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 88why, one step back88 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 89why, one step back89 method: bytes,Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 90–92why, one step back90 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],91 headers: typing.List[typing.Tuple[bytes, bytes]] = None,92 stream: httpcore.AsyncByteStream = None,Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722
line 93why, one step back93 timeout: typing.Mapping[str, typing.Optional[float]] = None,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 94–96why, one step back94 ) -> typing.Tuple[95 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream96 ]:Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 97why, one step back97 if self._response_count < self.send_response_after_attempt:Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 98–99why, one step back98 assert headers is not None99 return self.challenge_send(method, headers)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 100why, one step back100Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 101–103why, one step back101 authorization = get_header_value(headers, "Authorization")102 body = JSONStream({"auth": authorization})103 return b"HTTP/1.1", 200, b"", [], bodyDrop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 104why, one step back104Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 105why, one step back105 def challenge_send(Use and pin black 20 (#1229)Florimond Mancabefore adoptionf5c27ec
line 106why, one step back106 self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]]Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 107–109why, one step back107 ) -> typing.Tuple[108 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream109 ]:Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 110–131why, one step back110 self._response_count += 1111 nonce = (112 hashlib.sha256(os.urandom(8)).hexdigest()113 if self._regenerate_nonce114 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"115 )116 challenge_data = {117 "nonce": nonce,118 "qop": self.qop,119 "opaque": (120 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"121 ),122 "algorithm": self.algorithm,123 "stale": "FALSE",124 }125 challenge_str = ", ".join(126 '{}="{}"'.format(key, value)127 for key, value in challenge_data.items()128 if value129 )130131 headers = [Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 132–135why, one step back132 (133 b"www-authenticate",134 b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),135 )Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 136why, one step back136 ]Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 137why, one step back137 return b"HTTP/1.1", 401, b"", headers, ContentStream()Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 138–139why, one step back138139Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 140–185why, one step back140class RepeatAuth(Auth):141 """142 A mock authentication scheme that requires clients to send143 the request a fixed number of times, and then send a last request containing144 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers145 of intermediate responses.146 """147148 requires_request_body = True149150 def __init__(self, repeat: int):151 self.repeat = repeat152153 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:154 nonces = []155156 for index in range(self.repeat):157 request.headers["Authorization"] = f"Repeat {index}"158 response = yield request159 nonces.append(response.headers["www-authenticate"])160161 key = ".".join(nonces)162 request.headers["Authorization"] = f"Repeat {key}"163 yield request164165166class ResponseBodyAuth(Auth):167 """168 A mock authentication scheme that requires clients to send an 'Authorization'169 header, then send back the contents of the response in the 'Authorization'170 header.171 """172173 requires_response_body = True174175 def __init__(self, token):176 self.token = token177178 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:179 request.headers["Authorization"] = self.token180 response = yield request181 data = response.text182 request.headers["Authorization"] = data183 yield request184185Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 186–190why, one step back186@pytest.mark.asyncio187async def test_basic_auth() -> None:188 url = "https://example.org/"189 auth = ("tomchristie", "password123")190Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 191–192why, one step back191 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:192 response = await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 193–201why, one step back193194 assert response.status_code == 200195 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}196197198@pytest.mark.asyncio199async def test_basic_auth_in_url() -> None:200 url = "https://tomchristie:password123@example.org/"201Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 202–203why, one step back202 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:203 response = await client.get(url)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 204–213why, one step back204205 assert response.status_code == 200206 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}207208209@pytest.mark.asyncio210async def test_basic_auth_on_session() -> None:211 url = "https://example.org/"212 auth = ("tomchristie", "password123")213Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 214–215why, one step back214 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:215 response = await client.get(url)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 216–228why, one step back216217 assert response.status_code == 200218 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}219220221@pytest.mark.asyncio222async def test_custom_auth() -> None:223 url = "https://example.org/"224225 def auth(request: Request) -> Request:226 request.headers["Authorization"] = "Token 123"227 return request228Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 229–230why, one step back229 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:230 response = await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 231–237why, one step back231232 assert response.status_code == 200233 assert response.json() == {"auth": "Token 123"}234235236@pytest.mark.asyncio237async def test_netrc_auth() -> None:Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 238why, one step back238 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 239–240why, one step back239 url = "http://netrcexample.org"240Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 241–242why, one step back241 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:242 response = await client.get(url)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 243–251why, one step back243244 assert response.status_code == 200245 assert response.json() == {246 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"247 }248249250@pytest.mark.asyncio251async def test_auth_header_has_priority_over_netrc() -> None:Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 252why, one step back252 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 253–254why, one step back253 url = "http://netrcexample.org"254Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 255–256why, one step back255 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:256 response = await client.get(url, headers={"Authorization": "Override"})Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 257–263why, one step back257258 assert response.status_code == 200259 assert response.json() == {"auth": "Override"}260261262@pytest.mark.asyncio263async def test_trust_env_auth() -> None:Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 264why, one step back264 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 265–266why, one step back265 url = "http://netrcexample.org"266Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 267–270why, one step back267 async with httpx.AsyncClient(268 transport=AsyncMockTransport(), trust_env=False269 ) as client:270 response = await client.get(url)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 271–274why, one step back271272 assert response.status_code == 200273 assert response.json() == {"auth": None}274Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 275–278why, one step back275 async with httpx.AsyncClient(276 transport=AsyncMockTransport(), trust_env=True277 ) as client:278 response = await client.get(url)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 279–285why, one step back279280 assert response.status_code == 200281 assert response.json() == {282 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"283 }284285Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0
lines 286–290why, one step back286@pytest.mark.asyncio287async def test_auth_disable_per_request() -> None:288 url = "https://example.org/"289 auth = ("tomchristie", "password123")290Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 291–292why, one step back291 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:292 response = await client.get(url, auth=None)Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0
lines 293–297why, one step back293294 assert response.status_code == 200295 assert response.json() == {"auth": None}296297Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 298–309why, one step back298def test_auth_hidden_url() -> None:299 url = "http://example-username:example-password@example.org/"300 expected = "URL('http://example-username:[secure]@example.org/')"301 assert url == URL(url)302 assert expected == repr(URL(url))303304305@pytest.mark.asyncio306async def test_auth_hidden_header() -> None:307 url = "https://example.org/"308 auth = ("example-username", "example-password")309Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 310–311why, one step back310 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:311 response = await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 312–316why, one step back312313 assert "'authorization': '[secure]'" in str(response.request.headers)314315316@pytest.mark.asyncioAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 317why, one step back317async def test_auth_property() -> None:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 318–319why, one step back318 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:319 assert client.auth is NoneAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 320why, one step back320Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 321–322why, one step back321 client.auth = ("tomchristie", "password123") # type: ignore322 assert isinstance(client.auth, BasicAuth)Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 323why, one step back323Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 324–327why, one step back324 url = "https://example.org/"325 response = await client.get(url)326 assert response.status_code == 200327 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
lines 328–331why, one step back328329330@pytest.mark.asyncio331async def test_auth_invalid_type() -> None:Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 332why, one step back332 with pytest.raises(TypeError):Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 333why, one step back333 client = httpx.AsyncClient(Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
lines 334–337why, one step back334 transport=AsyncMockTransport(),335 auth="not a tuple, not a callable", # type: ignore336 )337Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 338–340why, one step back338 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:339 with pytest.raises(TypeError):340 await client.get(auth="not a tuple, not a callable") # type: ignoreAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 341why, one step back341Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 342–343why, one step back342 with pytest.raises(TypeError):343 client.auth = "not a tuple, not a callable" # type: ignoreAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 344why, one step back344Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 345–350why, one step back345346@pytest.mark.asyncio347async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:348 url = "https://example.org/"349 auth = DigestAuth(username="tomchristie", password="password123")350Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 351–352why, one step back351 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:352 response = await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 353–358why, one step back353354 assert response.status_code == 200355 assert response.json() == {"auth": None}356 assert len(response.history) == 0357358Handle multiple auth headers correctly (#1240)Tom Christiebefore adoption33d339a
lines 359–373why, one step back359def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:360 url = "https://example.org/"361 auth = DigestAuth(username="tomchristie", password="password123")362 auth_header = b"Token ..."363364 client = httpx.Client(365 transport=SyncMockTransport(auth_header=auth_header, status_code=401)366 )367 response = client.get(url, auth=auth)368369 assert response.status_code == 401370 assert response.json() == {"auth": None}371 assert len(response.history) == 0372373Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 374–377why, one step back374@pytest.mark.asyncio375async def test_digest_auth_200_response_including_digest_auth_header() -> None:376 url = "https://example.org/"377 auth = DigestAuth(username="tomchristie", password="password123")Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 378why, one step back378 auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 379why, one step back379Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 380why, one step back380 async with httpx.AsyncClient(Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 381why, one step back381 transport=AsyncMockTransport(auth_header=auth_header, status_code=200)Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 382–383why, one step back382 ) as client:383 response = await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 384–394why, one step back384385 assert response.status_code == 200386 assert response.json() == {"auth": None}387 assert len(response.history) == 0388389390@pytest.mark.asyncio391async def test_digest_auth_401_response_without_digest_auth_header() -> None:392 url = "https://example.org/"393 auth = DigestAuth(username="tomchristie", password="password123")394Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 395–398why, one step back395 async with httpx.AsyncClient(396 transport=AsyncMockTransport(auth_header=b"", status_code=401)397 ) as client:398 response = await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 399–424why, one step back399400 assert response.status_code == 401401 assert response.json() == {"auth": None}402 assert len(response.history) == 0403404405@pytest.mark.parametrize(406 "algorithm,expected_hash_length,expected_response_length",407 [408 ("MD5", 64, 32),409 ("MD5-SESS", 64, 32),410 ("SHA", 64, 40),411 ("SHA-SESS", 64, 40),412 ("SHA-256", 64, 64),413 ("SHA-256-SESS", 64, 64),414 ("SHA-512", 64, 128),415 ("SHA-512-SESS", 64, 128),416 ],417)418@pytest.mark.asyncio419async def test_digest_auth(420 algorithm: str, expected_hash_length: int, expected_response_length: int421) -> None:422 url = "https://example.org/"423 auth = DigestAuth(username="tomchristie", password="password123")424Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 425–428why, one step back425 async with httpx.AsyncClient(426 transport=MockDigestAuthTransport(algorithm=algorithm)427 ) as client:428 response = await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 429–456why, one step back429430 assert response.status_code == 200431 assert len(response.history) == 1432433 authorization = typing.cast(dict, response.json())["auth"]434 scheme, _, fields = authorization.partition(" ")435 assert scheme == "Digest"436437 response_fields = [field.strip() for field in fields.split(",")]438 digest_data = dict(field.split("=") for field in response_fields)439440 assert digest_data["username"] == '"tomchristie"'441 assert digest_data["realm"] == '"httpx@example.org"'442 assert "nonce" in digest_data443 assert digest_data["uri"] == '"/"'444 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes445 assert len(digest_data["opaque"]) == expected_hash_length + 2446 assert digest_data["algorithm"] == algorithm447 assert digest_data["qop"] == "auth"448 assert digest_data["nc"] == "00000001"449 assert len(digest_data["cnonce"]) == 16 + 2450451452@pytest.mark.asyncio453async def test_digest_auth_no_specified_qop() -> None:454 url = "https://example.org/"455 auth = DigestAuth(username="tomchristie", password="password123")456Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 457–458why, one step back457 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop="")) as client:458 response = await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 459–487why, one step back459460 assert response.status_code == 200461 assert len(response.history) == 1462463 authorization = typing.cast(dict, response.json())["auth"]464 scheme, _, fields = authorization.partition(" ")465 assert scheme == "Digest"466467 response_fields = [field.strip() for field in fields.split(",")]468 digest_data = dict(field.split("=") for field in response_fields)469470 assert "qop" not in digest_data471 assert "nc" not in digest_data472 assert "cnonce" not in digest_data473 assert digest_data["username"] == '"tomchristie"'474 assert digest_data["realm"] == '"httpx@example.org"'475 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes476 assert digest_data["uri"] == '"/"'477 assert len(digest_data["response"]) == 64 + 2478 assert len(digest_data["opaque"]) == 64 + 2479 assert digest_data["algorithm"] == "SHA-256"480481482@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))483@pytest.mark.asyncio484async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:485 url = "https://example.org/"486 auth = DigestAuth(username="tomchristie", password="password123")487Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 488–489why, one step back488 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop=qop)) as client:489 response = await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 490–499why, one step back490491 assert response.status_code == 200492 assert len(response.history) == 1493494495@pytest.mark.asyncio496async def test_digest_auth_qop_auth_int_not_implemented() -> None:497 url = "https://example.org/"498 auth = DigestAuth(username="tomchristie", password="password123")499Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 500–504why, one step back500 async with httpx.AsyncClient(501 transport=MockDigestAuthTransport(qop="auth-int")502 ) as client:503 with pytest.raises(NotImplementedError):504 await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 505–511why, one step back505506507@pytest.mark.asyncio508async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:509 url = "https://example.org/"510 auth = DigestAuth(username="tomchristie", password="password123")511Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 512–516why, one step back512 async with httpx.AsyncClient(513 transport=MockDigestAuthTransport(qop="not-auth")514 ) as client:515 with pytest.raises(ProtocolError):516 await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 517–523why, one step back517518519@pytest.mark.asyncio520async def test_digest_auth_incorrect_credentials() -> None:521 url = "https://example.org/"522 auth = DigestAuth(username="tomchristie", password="password123")523Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 524why, one step back524 async with httpx.AsyncClient(Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 525why, one step back525 transport=MockDigestAuthTransport(send_response_after_attempt=2)Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 526–527why, one step back526 ) as client:527 response = await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 528–535why, one step back528529 assert response.status_code == 401530 assert len(response.history) == 1531532533@pytest.mark.parametrize(534 "auth_header",535 [Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 536–537why, one step back536 b'Digest realm="httpx@example.org", qop="auth"', # missing fields537 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields listDrop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 538–540why, one step back538 ],539)540@pytest.mark.asyncioIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 541why, one step back541async def test_async_digest_auth_raises_protocol_error_on_malformed_header(Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 542why, one step back542 auth_header: bytes,Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 543–545why, one step back543) -> None:544 url = "https://example.org/"545 auth = DigestAuth(username="tomchristie", password="password123")Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 546why, one step back546 async with httpx.AsyncClient(Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 547why, one step back547 transport=AsyncMockTransport(auth_header=auth_header, status_code=401)Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 548–550why, one step back548 ) as client:549 with pytest.raises(ProtocolError):550 await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 551–552why, one step back551552Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 553–564why, one step back553@pytest.mark.parametrize(554 "auth_header",555 [556 b'Digest realm="httpx@example.org", qop="auth"', # missing fields557 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list558 ],559)560def test_sync_digest_auth_raises_protocol_error_on_malformed_header(561 auth_header: bytes,562) -> None:563 url = "https://example.org/"564 auth = DigestAuth(username="tomchristie", password="password123")Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 565–566why, one step back565566 with httpx.Client(Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 567why, one step back567 transport=SyncMockTransport(auth_header=auth_header, status_code=401)Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 568–570why, one step back568 ) as client:569 with pytest.raises(ProtocolError):570 client.get(url, auth=auth)Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 571–572why, one step back571572Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 573why, one step back573@pytest.mark.asyncioIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 574why, one step back574async def test_async_auth_history() -> None:Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 575–578why, one step back575 """576 Test that intermediate requests sent as part of an authentication flow577 are recorded in the response history.578 """Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 579–580why, one step back579 url = "https://example.org/"580 auth = RepeatAuth(repeat=2)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 581why, one step back581Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 582–586why, one step back582 async with httpx.AsyncClient(583 transport=AsyncMockTransport(auth_header=b"abc")584 ) as client:585 response = await client.get(url, auth=auth)586Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 587–588why, one step back587 assert response.status_code == 200588 assert response.json() == {"auth": "Repeat abc.abc"}Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 589why, one step back589Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 590–593why, one step back590 assert len(response.history) == 2591 resp1, resp2 = response.history592 assert resp1.json() == {"auth": "Repeat 0"}593 assert resp2.json() == {"auth": "Repeat 1"}Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 594why, one step back594Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 595–596why, one step back595 assert len(resp2.history) == 1596 assert resp2.history == [resp1]Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 597why, one step back597Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 598why, one step back598 assert len(resp1.history) == 0Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 599–600why, one step back599600Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 601–605why, one step back601def test_sync_auth_history() -> None:602 """603 Test that intermediate requests sent as part of an authentication flow604 are recorded in the response history.605 """Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 606–608why, one step back606 url = "https://example.org/"607 auth = RepeatAuth(repeat=2)608Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 609–611why, one step back609 with httpx.Client(transport=SyncMockTransport(auth_header=b"abc")) as client:610 response = client.get(url, auth=auth)611Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 612–631why, one step back612 assert response.status_code == 200613 assert response.json() == {"auth": "Repeat abc.abc"}614615 assert len(response.history) == 2616 resp1, resp2 = response.history617 assert resp1.json() == {"auth": "Repeat 0"}618 assert resp2.json() == {"auth": "Repeat 1"}619620 assert len(resp2.history) == 1621 assert resp2.history == [resp1]622623 assert len(resp1.history) == 0624625626@pytest.mark.asyncio627async def test_digest_auth_unavailable_streaming_body():628 url = "https://example.org/"629 auth = DigestAuth(username="tomchristie", password="password123")630631 async def streaming_body():Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 632why, one step back632 yield b"Example request body" # pragma: nocoverDrop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 633why, one step back633Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 634–636why, one step back634 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:635 with pytest.raises(RequestBodyUnavailable):636 await client.post(url, data=streaming_body(), auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 637–639why, one step back637638639@pytest.mark.asyncioIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 640why, one step back640async def test_async_auth_reads_response_body() -> None:Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 641–644why, one step back641 """642 Test that we can read the response body in an auth flow if `requires_response_body`643 is set.644 """Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 645–646why, one step back645 url = "https://example.org/"646 auth = ResponseBodyAuth("xyz")Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 647–648why, one step back647 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:648 response = await client.get(url, auth=auth)Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
line 649why, one step back649Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 650–651why, one step back650 assert response.status_code == 200651 assert response.json() == {"auth": '{"auth": "xyz"}'}Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 652–653why, one step back652653Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 654–658why, one step back654def test_sync_auth_reads_response_body() -> None:655 """656 Test that we can read the response body in an auth flow if `requires_response_body`657 is set.658 """Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 659–661why, one step back659 url = "https://example.org/"660 auth = ResponseBodyAuth("xyz")661Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 662–664why, one step back662 with httpx.Client(transport=SyncMockTransport()) as client:663 response = client.get(url, auth=auth)664Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417
lines 665–666why, one step back665 assert response.status_code == 200666 assert response.json() == {"auth": '{"auth": "xyz"}'}