test_auth.py
This file
Path
tests/client/test_auth.py
729 lines · 23.1 KiB · Python
Last changed by
Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
History of this fileTake it
The walk stopped after 200 commits: lines older than a82adcc point at it.
Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
lines 1–6why, one step back1"""2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncioUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 7–8why, one step back7import hashlib8import osAdd support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
line 9why, one step back9import threadingUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 10–11why, one step back10import typing11Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 12why, one step back12import httpcoreUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 13–14why, one step back13import pytest14Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 15why, one step back15import httpxUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 16–18why, one step back16from httpx import (17 URL,18 Auth,Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 19why, one step back19 BasicAuth,Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 20–25why, one step back20 DigestAuth,21 ProtocolError,22 Request,23 RequestBodyUnavailable,24 Response,25)Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 26why, one step back26from httpx._content_streams import ContentStream, JSONStreamUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 27why, one step back27Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 28why, one step back28from ..common import FIXTURES_DIRUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 29why, one step back29Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 30why, one step back30Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 31–38why, one step back31def get_header_value(headers, key, default=None):32 lookup = key.encode("ascii").lower()33 for header_key, header_value in headers:34 if header_key.lower() == lookup:35 return header_value.decode("ascii")36 return default3738Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 39why, one step back39class MockTransport:Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 40why, one step back40 def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 41–43why, one step back41 self.auth_header = auth_header42 self.status_code = status_code43Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 44why, one step back44 def _request(Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 45why, one step back45 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 46–49why, one step back46 method: bytes,47 url: typing.Tuple[bytes, bytes, int, bytes],48 headers: typing.List[typing.Tuple[bytes, bytes]],49 stream: ContentStream,Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722
line 50why, one step back50 timeout: typing.Mapping[str, typing.Optional[float]] = None,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 51–56why, one step back51 ) -> typing.Tuple[52 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream53 ]:54 authorization = get_header_value(headers, "Authorization")55 response_headers = (56 [(b"www-authenticate", self.auth_header)] if self.auth_header else []Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 57why, one step back57 )Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 58–59why, one step back58 response_stream = JSONStream({"auth": authorization})59 return b"HTTP/1.1", self.status_code, b"", response_headers, response_streamUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 60–61why, one step back6061Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 62–79why, one step back62class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):63 async def request(64 self, *args, **kwargs65 ) -> typing.Tuple[66 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream67 ]:68 return self._request(*args, **kwargs)697071class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):72 def request(73 self, *args, **kwargs74 ) -> typing.Tuple[75 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream76 ]:77 return self._request(*args, **kwargs)7879Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 80why, one step back80class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 81–93why, one step back81 def __init__(82 self,83 algorithm: str = "SHA-256",84 send_response_after_attempt: int = 1,85 qop: str = "auth",86 regenerate_nonce: bool = True,87 ) -> None:88 self.algorithm = algorithm89 self.send_response_after_attempt = send_response_after_attempt90 self.qop = qop91 self._regenerate_nonce = regenerate_nonce92 self._response_count = 093Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 94why, one step back94 async def request(Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 95why, one step back95 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 96why, one step back96 method: bytes,Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 97–99why, one step back97 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],98 headers: typing.List[typing.Tuple[bytes, bytes]] = None,99 stream: httpcore.AsyncByteStream = None,Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722
line 100why, one step back100 timeout: typing.Mapping[str, typing.Optional[float]] = None,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 101–103why, one step back101 ) -> typing.Tuple[102 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream103 ]:Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 104why, one step back104 if self._response_count < self.send_response_after_attempt:Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 105–106why, one step back105 assert headers is not None106 return self.challenge_send(method, headers)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 107why, one step back107Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 108–110why, one step back108 authorization = get_header_value(headers, "Authorization")109 body = JSONStream({"auth": authorization})110 return b"HTTP/1.1", 200, b"", [], bodyUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 111why, one step back111Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 112why, one step back112 def challenge_send(Use and pin black 20 (#1229)Florimond Mancabefore adoptionf5c27ec
line 113why, one step back113 self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]]Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 114–116why, one step back114 ) -> typing.Tuple[115 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream116 ]:Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 117–138why, one step back117 self._response_count += 1118 nonce = (119 hashlib.sha256(os.urandom(8)).hexdigest()120 if self._regenerate_nonce121 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"122 )123 challenge_data = {124 "nonce": nonce,125 "qop": self.qop,126 "opaque": (127 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"128 ),129 "algorithm": self.algorithm,130 "stale": "FALSE",131 }132 challenge_str = ", ".join(133 '{}="{}"'.format(key, value)134 for key, value in challenge_data.items()135 if value136 )137138 headers = [Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 139–142why, one step back139 (140 b"www-authenticate",141 b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),142 )Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 143why, one step back143 ]Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 144why, one step back144 return b"HTTP/1.1", 401, b"", headers, ContentStream()Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 145–146why, one step back145146Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 147–192why, one step back147class RepeatAuth(Auth):148 """149 A mock authentication scheme that requires clients to send150 the request a fixed number of times, and then send a last request containing151 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers152 of intermediate responses.153 """154155 requires_request_body = True156157 def __init__(self, repeat: int):158 self.repeat = repeat159160 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:161 nonces = []162163 for index in range(self.repeat):164 request.headers["Authorization"] = f"Repeat {index}"165 response = yield request166 nonces.append(response.headers["www-authenticate"])167168 key = ".".join(nonces)169 request.headers["Authorization"] = f"Repeat {key}"170 yield request171172173class ResponseBodyAuth(Auth):174 """175 A mock authentication scheme that requires clients to send an 'Authorization'176 header, then send back the contents of the response in the 'Authorization'177 header.178 """179180 requires_response_body = True181182 def __init__(self, token):183 self.token = token184185 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:186 request.headers["Authorization"] = self.token187 response = yield request188 data = response.text189 request.headers["Authorization"] = data190 yield request191192Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
lines 193–217why, one step back193class SyncOrAsyncAuth(Auth):194 """195 A mock authentication scheme that uses a different implementation for the196 sync and async cases.197 """198199 def __init__(self) -> None:200 self._lock = threading.Lock()201 self._async_lock = asyncio.Lock()202203 def sync_auth_flow(204 self, request: Request205 ) -> typing.Generator[Request, Response, None]:206 with self._lock:207 request.headers["Authorization"] = "sync-auth"208 yield request209210 async def async_auth_flow(211 self, request: Request212 ) -> typing.AsyncGenerator[Request, Response]:213 async with self._async_lock:214 request.headers["Authorization"] = "async-auth"215 yield request216217Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 218–222why, one step back218@pytest.mark.asyncio219async def test_basic_auth() -> None:220 url = "https://example.org/"221 auth = ("tomchristie", "password123")222Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 223–224why, one step back223 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:224 response = await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 225–233why, one step back225226 assert response.status_code == 200227 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}228229230@pytest.mark.asyncio231async def test_basic_auth_in_url() -> None:232 url = "https://tomchristie:password123@example.org/"233Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 234–235why, one step back234 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:235 response = await client.get(url)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 236–245why, one step back236237 assert response.status_code == 200238 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}239240241@pytest.mark.asyncio242async def test_basic_auth_on_session() -> None:243 url = "https://example.org/"244 auth = ("tomchristie", "password123")245Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 246–247why, one step back246 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:247 response = await client.get(url)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 248–260why, one step back248249 assert response.status_code == 200250 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}251252253@pytest.mark.asyncio254async def test_custom_auth() -> None:255 url = "https://example.org/"256257 def auth(request: Request) -> Request:258 request.headers["Authorization"] = "Token 123"259 return request260Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 261–262why, one step back261 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:262 response = await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 263–269why, one step back263264 assert response.status_code == 200265 assert response.json() == {"auth": "Token 123"}266267268@pytest.mark.asyncio269async def test_netrc_auth() -> None:Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 270why, one step back270 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 271–272why, one step back271 url = "http://netrcexample.org"272Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 273–274why, one step back273 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:274 response = await client.get(url)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 275–283why, one step back275276 assert response.status_code == 200277 assert response.json() == {278 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"279 }280281282@pytest.mark.asyncio283async def test_auth_header_has_priority_over_netrc() -> None:Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 284why, one step back284 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 285–286why, one step back285 url = "http://netrcexample.org"286Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 287–288why, one step back287 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:288 response = await client.get(url, headers={"Authorization": "Override"})Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 289–295why, one step back289290 assert response.status_code == 200291 assert response.json() == {"auth": "Override"}292293294@pytest.mark.asyncio295async def test_trust_env_auth() -> None:Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 296why, one step back296 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 297–298why, one step back297 url = "http://netrcexample.org"298Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 299–302why, one step back299 async with httpx.AsyncClient(300 transport=AsyncMockTransport(), trust_env=False301 ) as client:302 response = await client.get(url)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 303–306why, one step back303304 assert response.status_code == 200305 assert response.json() == {"auth": None}306Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 307–310why, one step back307 async with httpx.AsyncClient(308 transport=AsyncMockTransport(), trust_env=True309 ) as client:310 response = await client.get(url)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 311–317why, one step back311312 assert response.status_code == 200313 assert response.json() == {314 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"315 }316317Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0
lines 318–322why, one step back318@pytest.mark.asyncio319async def test_auth_disable_per_request() -> None:320 url = "https://example.org/"321 auth = ("tomchristie", "password123")322Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 323–324why, one step back323 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:324 response = await client.get(url, auth=None)Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0
lines 325–329why, one step back325326 assert response.status_code == 200327 assert response.json() == {"auth": None}328329Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 330–341why, one step back330def test_auth_hidden_url() -> None:331 url = "http://example-username:example-password@example.org/"332 expected = "URL('http://example-username:[secure]@example.org/')"333 assert url == URL(url)334 assert expected == repr(URL(url))335336337@pytest.mark.asyncio338async def test_auth_hidden_header() -> None:339 url = "https://example.org/"340 auth = ("example-username", "example-password")341Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 342–343why, one step back342 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:343 response = await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 344–348why, one step back344345 assert "'authorization': '[secure]'" in str(response.request.headers)346347348@pytest.mark.asyncioAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 349why, one step back349async def test_auth_property() -> None:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 350–351why, one step back350 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:351 assert client.auth is NoneAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 352why, one step back352Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 353–354why, one step back353 client.auth = ("tomchristie", "password123") # type: ignore354 assert isinstance(client.auth, BasicAuth)Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 355why, one step back355Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 356–359why, one step back356 url = "https://example.org/"357 response = await client.get(url)358 assert response.status_code == 200359 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
lines 360–363why, one step back360361362@pytest.mark.asyncio363async def test_auth_invalid_type() -> None:Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 364why, one step back364 with pytest.raises(TypeError):Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 365why, one step back365 client = httpx.AsyncClient(Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
lines 366–369why, one step back366 transport=AsyncMockTransport(),367 auth="not a tuple, not a callable", # type: ignore368 )369Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 370–372why, one step back370 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:371 with pytest.raises(TypeError):372 await client.get(auth="not a tuple, not a callable") # type: ignoreAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 373why, one step back373Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 374–375why, one step back374 with pytest.raises(TypeError):375 client.auth = "not a tuple, not a callable" # type: ignoreAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 376why, one step back376Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 377–382why, one step back377378@pytest.mark.asyncio379async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:380 url = "https://example.org/"381 auth = DigestAuth(username="tomchristie", password="password123")382Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 383–384why, one step back383 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:384 response = await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 385–390why, one step back385386 assert response.status_code == 200387 assert response.json() == {"auth": None}388 assert len(response.history) == 0389390Handle multiple auth headers correctly (#1240)Tom Christiebefore adoption33d339a
lines 391–405why, one step back391def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:392 url = "https://example.org/"393 auth = DigestAuth(username="tomchristie", password="password123")394 auth_header = b"Token ..."395396 client = httpx.Client(397 transport=SyncMockTransport(auth_header=auth_header, status_code=401)398 )399 response = client.get(url, auth=auth)400401 assert response.status_code == 401402 assert response.json() == {"auth": None}403 assert len(response.history) == 0404405Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 406–409why, one step back406@pytest.mark.asyncio407async def test_digest_auth_200_response_including_digest_auth_header() -> None:408 url = "https://example.org/"409 auth = DigestAuth(username="tomchristie", password="password123")Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 410why, one step back410 auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 411why, one step back411Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 412why, one step back412 async with httpx.AsyncClient(Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 413why, one step back413 transport=AsyncMockTransport(auth_header=auth_header, status_code=200)Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 414–415why, one step back414 ) as client:415 response = await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 416–426why, one step back416417 assert response.status_code == 200418 assert response.json() == {"auth": None}419 assert len(response.history) == 0420421422@pytest.mark.asyncio423async def test_digest_auth_401_response_without_digest_auth_header() -> None:424 url = "https://example.org/"425 auth = DigestAuth(username="tomchristie", password="password123")426Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 427–430why, one step back427 async with httpx.AsyncClient(428 transport=AsyncMockTransport(auth_header=b"", status_code=401)429 ) as client:430 response = await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 431–456why, one step back431432 assert response.status_code == 401433 assert response.json() == {"auth": None}434 assert len(response.history) == 0435436437@pytest.mark.parametrize(438 "algorithm,expected_hash_length,expected_response_length",439 [440 ("MD5", 64, 32),441 ("MD5-SESS", 64, 32),442 ("SHA", 64, 40),443 ("SHA-SESS", 64, 40),444 ("SHA-256", 64, 64),445 ("SHA-256-SESS", 64, 64),446 ("SHA-512", 64, 128),447 ("SHA-512-SESS", 64, 128),448 ],449)450@pytest.mark.asyncio451async def test_digest_auth(452 algorithm: str, expected_hash_length: int, expected_response_length: int453) -> None:454 url = "https://example.org/"455 auth = DigestAuth(username="tomchristie", password="password123")456Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 457–460why, one step back457 async with httpx.AsyncClient(458 transport=MockDigestAuthTransport(algorithm=algorithm)459 ) as client:460 response = await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 461–488why, one step back461462 assert response.status_code == 200463 assert len(response.history) == 1464465 authorization = typing.cast(dict, response.json())["auth"]466 scheme, _, fields = authorization.partition(" ")467 assert scheme == "Digest"468469 response_fields = [field.strip() for field in fields.split(",")]470 digest_data = dict(field.split("=") for field in response_fields)471472 assert digest_data["username"] == '"tomchristie"'473 assert digest_data["realm"] == '"httpx@example.org"'474 assert "nonce" in digest_data475 assert digest_data["uri"] == '"/"'476 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes477 assert len(digest_data["opaque"]) == expected_hash_length + 2478 assert digest_data["algorithm"] == algorithm479 assert digest_data["qop"] == "auth"480 assert digest_data["nc"] == "00000001"481 assert len(digest_data["cnonce"]) == 16 + 2482483484@pytest.mark.asyncio485async def test_digest_auth_no_specified_qop() -> None:486 url = "https://example.org/"487 auth = DigestAuth(username="tomchristie", password="password123")488Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 489–490why, one step back489 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop="")) as client:490 response = await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 491–519why, one step back491492 assert response.status_code == 200493 assert len(response.history) == 1494495 authorization = typing.cast(dict, response.json())["auth"]496 scheme, _, fields = authorization.partition(" ")497 assert scheme == "Digest"498499 response_fields = [field.strip() for field in fields.split(",")]500 digest_data = dict(field.split("=") for field in response_fields)501502 assert "qop" not in digest_data503 assert "nc" not in digest_data504 assert "cnonce" not in digest_data505 assert digest_data["username"] == '"tomchristie"'506 assert digest_data["realm"] == '"httpx@example.org"'507 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes508 assert digest_data["uri"] == '"/"'509 assert len(digest_data["response"]) == 64 + 2510 assert len(digest_data["opaque"]) == 64 + 2511 assert digest_data["algorithm"] == "SHA-256"512513514@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))515@pytest.mark.asyncio516async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:517 url = "https://example.org/"518 auth = DigestAuth(username="tomchristie", password="password123")519Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 520–521why, one step back520 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop=qop)) as client:521 response = await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 522–531why, one step back522523 assert response.status_code == 200524 assert len(response.history) == 1525526527@pytest.mark.asyncio528async def test_digest_auth_qop_auth_int_not_implemented() -> None:529 url = "https://example.org/"530 auth = DigestAuth(username="tomchristie", password="password123")531Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 532–536why, one step back532 async with httpx.AsyncClient(533 transport=MockDigestAuthTransport(qop="auth-int")534 ) as client:535 with pytest.raises(NotImplementedError):536 await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 537–543why, one step back537538539@pytest.mark.asyncio540async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:541 url = "https://example.org/"542 auth = DigestAuth(username="tomchristie", password="password123")543Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 544–548why, one step back544 async with httpx.AsyncClient(545 transport=MockDigestAuthTransport(qop="not-auth")546 ) as client:547 with pytest.raises(ProtocolError):548 await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 549–555why, one step back549550551@pytest.mark.asyncio552async def test_digest_auth_incorrect_credentials() -> None:553 url = "https://example.org/"554 auth = DigestAuth(username="tomchristie", password="password123")555Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 556why, one step back556 async with httpx.AsyncClient(Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 557why, one step back557 transport=MockDigestAuthTransport(send_response_after_attempt=2)Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 558–559why, one step back558 ) as client:559 response = await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 560–567why, one step back560561 assert response.status_code == 401562 assert len(response.history) == 1563564565@pytest.mark.parametrize(566 "auth_header",567 [Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 568–569why, one step back568 b'Digest realm="httpx@example.org", qop="auth"', # missing fields569 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields listUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 570–572why, one step back570 ],571)572@pytest.mark.asyncioIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 573why, one step back573async def test_async_digest_auth_raises_protocol_error_on_malformed_header(Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 574why, one step back574 auth_header: bytes,Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 575–577why, one step back575) -> None:576 url = "https://example.org/"577 auth = DigestAuth(username="tomchristie", password="password123")Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 578why, one step back578 async with httpx.AsyncClient(Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 579why, one step back579 transport=AsyncMockTransport(auth_header=auth_header, status_code=401)Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 580–582why, one step back580 ) as client:581 with pytest.raises(ProtocolError):582 await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 583–584why, one step back583584Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 585–596why, one step back585@pytest.mark.parametrize(586 "auth_header",587 [588 b'Digest realm="httpx@example.org", qop="auth"', # missing fields589 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list590 ],591)592def test_sync_digest_auth_raises_protocol_error_on_malformed_header(593 auth_header: bytes,594) -> None:595 url = "https://example.org/"596 auth = DigestAuth(username="tomchristie", password="password123")Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 597–598why, one step back597598 with httpx.Client(Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 599why, one step back599 transport=SyncMockTransport(auth_header=auth_header, status_code=401)Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 600–602why, one step back600 ) as client:601 with pytest.raises(ProtocolError):602 client.get(url, auth=auth)Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 603–604why, one step back603604Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 605why, one step back605@pytest.mark.asyncioIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 606why, one step back606async def test_async_auth_history() -> None:Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 607–610why, one step back607 """608 Test that intermediate requests sent as part of an authentication flow609 are recorded in the response history.610 """Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 611–612why, one step back611 url = "https://example.org/"612 auth = RepeatAuth(repeat=2)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 613why, one step back613Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 614–618why, one step back614 async with httpx.AsyncClient(615 transport=AsyncMockTransport(auth_header=b"abc")616 ) as client:617 response = await client.get(url, auth=auth)618Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 619–620why, one step back619 assert response.status_code == 200620 assert response.json() == {"auth": "Repeat abc.abc"}Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 621why, one step back621Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 622–625why, one step back622 assert len(response.history) == 2623 resp1, resp2 = response.history624 assert resp1.json() == {"auth": "Repeat 0"}625 assert resp2.json() == {"auth": "Repeat 1"}Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 626why, one step back626Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 627–628why, one step back627 assert len(resp2.history) == 1628 assert resp2.history == [resp1]Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 629why, one step back629Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 630why, one step back630 assert len(resp1.history) == 0Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 631–632why, one step back631632Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 633–637why, one step back633def test_sync_auth_history() -> None:634 """635 Test that intermediate requests sent as part of an authentication flow636 are recorded in the response history.637 """Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 638–640why, one step back638 url = "https://example.org/"639 auth = RepeatAuth(repeat=2)640Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 641–643why, one step back641 with httpx.Client(transport=SyncMockTransport(auth_header=b"abc")) as client:642 response = client.get(url, auth=auth)643Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 644–663why, one step back644 assert response.status_code == 200645 assert response.json() == {"auth": "Repeat abc.abc"}646647 assert len(response.history) == 2648 resp1, resp2 = response.history649 assert resp1.json() == {"auth": "Repeat 0"}650 assert resp2.json() == {"auth": "Repeat 1"}651652 assert len(resp2.history) == 1653 assert resp2.history == [resp1]654655 assert len(resp1.history) == 0656657658@pytest.mark.asyncio659async def test_digest_auth_unavailable_streaming_body():660 url = "https://example.org/"661 auth = DigestAuth(username="tomchristie", password="password123")662663 async def streaming_body():Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 664why, one step back664 yield b"Example request body" # pragma: nocoverUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 665why, one step back665Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 666–668why, one step back666 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:667 with pytest.raises(RequestBodyUnavailable):668 await client.post(url, data=streaming_body(), auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 669–671why, one step back669670671@pytest.mark.asyncioIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
line 672why, one step back672async def test_async_auth_reads_response_body() -> None:Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 673–676why, one step back673 """674 Test that we can read the response body in an auth flow if `requires_response_body`675 is set.676 """Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 677–678why, one step back677 url = "https://example.org/"678 auth = ResponseBodyAuth("xyz")Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 679–680why, one step back679 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:680 response = await client.get(url, auth=auth)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 681why, one step back681Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 682–683why, one step back682 assert response.status_code == 200683 assert response.json() == {"auth": '{"auth": "xyz"}'}Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 684–685why, one step back684685Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 686–690why, one step back686def test_sync_auth_reads_response_body() -> None:687 """688 Test that we can read the response body in an auth flow if `requires_response_body`689 is set.690 """Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 691–693why, one step back691 url = "https://example.org/"692 auth = ResponseBodyAuth("xyz")693Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 694–696why, one step back694 with httpx.Client(transport=SyncMockTransport()) as client:695 response = client.get(url, auth=auth)696Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 697–698why, one step back697 assert response.status_code == 200698 assert response.json() == {"auth": '{"auth": "xyz"}'}Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
lines 699–729why, one step back699700701@pytest.mark.asyncio702async def test_async_auth() -> None:703 """704 Test that we can use an auth implementation specific to the async case, to705 support cases that require performing I/O or using concurrency primitives (such706 as checking a disk-based cache or fetching a token from a remote auth server).707 """708 url = "https://example.org/"709 auth = SyncOrAsyncAuth()710711 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:712 response = await client.get(url, auth=auth)713714 assert response.status_code == 200715 assert response.json() == {"auth": "async-auth"}716717718def test_sync_auth() -> None:719 """720 Test that we can use an auth implementation specific to the sync case.721 """722 url = "https://example.org/"723 auth = SyncOrAsyncAuth()724725 with httpx.Client(transport=SyncMockTransport()) as client:726 response = client.get(url, auth=auth)727728 assert response.status_code == 200729 assert response.json() == {"auth": "sync-auth"}