Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

766 lines · 24.5 KiB · Python

Last changed by

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

History of this file

Take it

The walk stopped after 200 commits: lines older than ecbece1 point at it.

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 1–10why, one step back
1"""
2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncio7import hashlib8import os9import threading10import typing

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 11why, one step back
11from urllib.request import parse_keqv_list

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 12–76why, one step back
12
13import pytest1415import httpx1617from ..common import FIXTURES_DIR181920class App:21 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:22 self.auth_header = auth_header23 self.status_code = status_code2425 def __call__(self, request: httpx.Request) -> httpx.Response:26 headers = {"www-authenticate": self.auth_header} if self.auth_header else {}27 data = {"auth": request.headers.get("Authorization")}28 return httpx.Response(self.status_code, headers=headers, json=data)293031class DigestApp:32 def __init__(33 self,34 algorithm: str = "SHA-256",35 send_response_after_attempt: int = 1,36 qop: str = "auth",37 regenerate_nonce: bool = True,38 ) -> None:39 self.algorithm = algorithm40 self.send_response_after_attempt = send_response_after_attempt41 self.qop = qop42 self._regenerate_nonce = regenerate_nonce43 self._response_count = 04445 def __call__(self, request: httpx.Request) -> httpx.Response:46 if self._response_count < self.send_response_after_attempt:47 return self.challenge_send(request)4849 data = {"auth": request.headers.get("Authorization")}50 return httpx.Response(200, json=data)5152 def challenge_send(self, request: httpx.Request) -> httpx.Response:53 self._response_count += 154 nonce = (55 hashlib.sha256(os.urandom(8)).hexdigest()56 if self._regenerate_nonce57 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"58 )59 challenge_data = {60 "nonce": nonce,61 "qop": self.qop,62 "opaque": (63 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"64 ),65 "algorithm": self.algorithm,66 "stale": "FALSE",67 }68 challenge_str = ", ".join(69 '{}="{}"'.format(key, value)70 for key, value in challenge_data.items()71 if value72 )7374 headers = {75 "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',76 }

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 77why, one step back
77 return httpx.Response(401, headers=headers)

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 78–79why, one step back
78
79

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 80why, one step back
80class RepeatAuth(httpx.Auth):

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 81–92why, one step back
81 """
82 A mock authentication scheme that requires clients to send83 the request a fixed number of times, and then send a last request containing84 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers85 of intermediate responses.86 """8788 requires_request_body = True8990 def __init__(self, repeat: int):91 self.repeat = repeat92

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

lines 93–95why, one step back
93 def auth_flow(
94 self, request: httpx.Request95 ) -> typing.Generator[httpx.Request, httpx.Response, None]:

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 96–107why, one step back
96 nonces = []
9798 for index in range(self.repeat):99 request.headers["Authorization"] = f"Repeat {index}"100 response = yield request101 nonces.append(response.headers["www-authenticate"])102103 key = ".".join(nonces)104 request.headers["Authorization"] = f"Repeat {key}"105 yield request106107

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 108why, one step back
108class ResponseBodyAuth(httpx.Auth):

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 109–116why, one step back
109 """
110 A mock authentication scheme that requires clients to send an 'Authorization'111 header, then send back the contents of the response in the 'Authorization'112 header.113 """114115 requires_response_body = True116

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 117why, one step back
117 def __init__(self, token: str) -> None:

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 118–119why, one step back
118 self.token = token
119

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

lines 120–122why, one step back
120 def auth_flow(
121 self, request: httpx.Request122 ) -> typing.Generator[httpx.Request, httpx.Response, None]:

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 123–129why, one step back
123 request.headers["Authorization"] = self.token
124 response = yield request125 data = response.text126 request.headers["Authorization"] = data127 yield request128129

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 130why, one step back
130class SyncOrAsyncAuth(httpx.Auth):

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 131–140why, one step back
131 """
132 A mock authentication scheme that uses a different implementation for the133 sync and async cases.134 """135136 def __init__(self) -> None:137 self._lock = threading.Lock()138 self._async_lock = asyncio.Lock()139140 def sync_auth_flow(

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

lines 141–142why, one step back
141 self, request: httpx.Request
142 ) -> typing.Generator[httpx.Request, httpx.Response, None]:

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 143–147why, one step back
143 with self._lock:
144 request.headers["Authorization"] = "sync-auth"145 yield request146147 async def async_auth_flow(

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

lines 148–149why, one step back
148 self, request: httpx.Request
149 ) -> typing.AsyncGenerator[httpx.Request, httpx.Response]:

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 150–157why, one step back
150 async with self._async_lock:
151 request.headers["Authorization"] = "async-auth"152 yield request153154155@pytest.mark.asyncio156async def test_basic_auth() -> None:157 url = "https://example.org/"

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 158why, one step back
158 auth = ("user", "password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 159–164why, one step back
159 app = App()
160161 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:162 response = await client.get(url, auth=auth)163164 assert response.status_code == 200

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 165why, one step back
165 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 166–173why, one step back
166
167168@pytest.mark.asyncio169async def test_basic_auth_with_stream() -> None:170 """171 See: https://github.com/encode/httpx/pull/1312172 """173 url = "https://example.org/"

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 174why, one step back
174 auth = ("user", "password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 175–183why, one step back
175 app = App()
176177 async with httpx.AsyncClient(178 transport=httpx.MockTransport(app), auth=auth179 ) as client:180 async with client.stream("GET", url) as response:181 await response.aread()182183 assert response.status_code == 200

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 184why, one step back
184 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 185–188why, one step back
185
186187@pytest.mark.asyncio188async def test_basic_auth_in_url() -> None:

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 189why, one step back
189 url = "https://user:password123@example.org/"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 190–195why, one step back
190 app = App()
191192 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:193 response = await client.get(url)194195 assert response.status_code == 200

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 196why, one step back
196 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 197–201why, one step back
197
198199@pytest.mark.asyncio200async def test_basic_auth_on_session() -> None:201 url = "https://example.org/"

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 202why, one step back
202 auth = ("user", "password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 203–210why, one step back
203 app = App()
204205 async with httpx.AsyncClient(206 transport=httpx.MockTransport(app), auth=auth207 ) as client:208 response = await client.get(url)209210 assert response.status_code == 200

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 211why, one step back
211 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 212–218why, one step back
212
213214@pytest.mark.asyncio215async def test_custom_auth() -> None:216 url = "https://example.org/"217 app = App()218

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 219why, one step back
219 def auth(request: httpx.Request) -> httpx.Request:

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 220–285why, one step back
220 request.headers["Authorization"] = "Token 123"
221 return request222223 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:224 response = await client.get(url, auth=auth)225226 assert response.status_code == 200227 assert response.json() == {"auth": "Token 123"}228229230@pytest.mark.asyncio231async def test_netrc_auth() -> None:232 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")233 url = "http://netrcexample.org"234 app = App()235236 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:237 response = await client.get(url)238239 assert response.status_code == 200240 assert response.json() == {241 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"242 }243244245@pytest.mark.asyncio246async def test_auth_header_has_priority_over_netrc() -> None:247 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")248 url = "http://netrcexample.org"249 app = App()250251 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:252 response = await client.get(url, headers={"Authorization": "Override"})253254 assert response.status_code == 200255 assert response.json() == {"auth": "Override"}256257258@pytest.mark.asyncio259async def test_trust_env_auth() -> None:260 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")261 url = "http://netrcexample.org"262 app = App()263264 async with httpx.AsyncClient(265 transport=httpx.MockTransport(app), trust_env=False266 ) as client:267 response = await client.get(url)268269 assert response.status_code == 200270 assert response.json() == {"auth": None}271272 async with httpx.AsyncClient(273 transport=httpx.MockTransport(app), trust_env=True274 ) as client:275 response = await client.get(url)276277 assert response.status_code == 200278 assert response.json() == {279 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"280 }281282283@pytest.mark.asyncio284async def test_auth_disable_per_request() -> None:285 url = "https://example.org/"

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 286why, one step back
286 auth = ("user", "password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 287–300why, one step back
287 app = App()
288289 async with httpx.AsyncClient(290 transport=httpx.MockTransport(app), auth=auth291 ) as client:292 response = await client.get(url, auth=None)293294 assert response.status_code == 200295 assert response.json() == {"auth": None}296297298def test_auth_hidden_url() -> None:299 url = "http://example-username:example-password@example.org/"300 expected = "URL('http://example-username:[secure]@example.org/')"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

lines 301–302why, one step back
301 assert url == httpx.URL(url)
302 assert expected == repr(httpx.URL(url))

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 303–323why, one step back
303
304305@pytest.mark.asyncio306async def test_auth_hidden_header() -> None:307 url = "https://example.org/"308 auth = ("example-username", "example-password")309 app = App()310311 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:312 response = await client.get(url, auth=auth)313314 assert "'authorization': '[secure]'" in str(response.request.headers)315316317@pytest.mark.asyncio318async def test_auth_property() -> None:319 app = App()320321 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:322 assert client.auth is None323

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 324why, one step back
324 client.auth = ("user", "password123") # type: ignore

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 325why, one step back
325 assert isinstance(client.auth, httpx.BasicAuth)

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 326–329why, one step back
326
327 url = "https://example.org/"328 response = await client.get(url)329 assert response.status_code == 200

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 330why, one step back
330 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 331–353why, one step back
331
332333@pytest.mark.asyncio334async def test_auth_invalid_type() -> None:335 app = App()336337 with pytest.raises(TypeError):338 client = httpx.AsyncClient(339 transport=httpx.MockTransport(app),340 auth="not a tuple, not a callable", # type: ignore341 )342343 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:344 with pytest.raises(TypeError):345 await client.get(auth="not a tuple, not a callable") # type: ignore346347 with pytest.raises(TypeError):348 client.auth = "not a tuple, not a callable" # type: ignore349350351@pytest.mark.asyncio352async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:353 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 354why, one step back
354 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 355–366why, one step back
355 app = App()
356357 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:358 response = await client.get(url, auth=auth)359360 assert response.status_code == 200361 assert response.json() == {"auth": None}362 assert len(response.history) == 0363364365def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:366 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 367why, one step back
367 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 368–381why, one step back
368 auth_header = "Token ..."
369 app = App(auth_header=auth_header, status_code=401)370371 client = httpx.Client(transport=httpx.MockTransport(app))372 response = client.get(url, auth=auth)373374 assert response.status_code == 401375 assert response.json() == {"auth": None}376 assert len(response.history) == 0377378379@pytest.mark.asyncio380async def test_digest_auth_200_response_including_digest_auth_header() -> None:381 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 382why, one step back
382 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 383–396why, one step back
383 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'
384 app = App(auth_header=auth_header, status_code=200)385386 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:387 response = await client.get(url, auth=auth)388389 assert response.status_code == 200390 assert response.json() == {"auth": None}391 assert len(response.history) == 0392393394@pytest.mark.asyncio395async def test_digest_auth_401_response_without_digest_auth_header() -> None:396 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 397why, one step back
397 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 398–425why, one step back
398 app = App(auth_header="", status_code=401)
399400 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:401 response = await client.get(url, auth=auth)402403 assert response.status_code == 401404 assert response.json() == {"auth": None}405 assert len(response.history) == 0406407408@pytest.mark.parametrize(409 "algorithm,expected_hash_length,expected_response_length",410 [411 ("MD5", 64, 32),412 ("MD5-SESS", 64, 32),413 ("SHA", 64, 40),414 ("SHA-SESS", 64, 40),415 ("SHA-256", 64, 64),416 ("SHA-256-SESS", 64, 64),417 ("SHA-512", 64, 128),418 ("SHA-512-SESS", 64, 128),419 ],420)421@pytest.mark.asyncio422async def test_digest_auth(423 algorithm: str, expected_hash_length: int, expected_response_length: int424) -> None:425 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 426why, one step back
426 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 427–434why, one step back
427 app = DigestApp(algorithm=algorithm)
428429 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:430 response = await client.get(url, auth=auth)431432 assert response.status_code == 200433 assert len(response.history) == 1434

Typing: always fill in generic type parameters (#2468)Adrian Garcia Badaraccobefore adoption1b4e7fb

line 435why, one step back
435 authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 436–441why, one step back
436 scheme, _, fields = authorization.partition(" ")
437 assert scheme == "Digest"438439 response_fields = [field.strip() for field in fields.split(",")]440 digest_data = dict(field.split("=") for field in response_fields)441

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 442why, one step back
442 assert digest_data["username"] == '"user"'

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 443–456why, one step back
443 assert digest_data["realm"] == '"httpx@example.org"'
444 assert "nonce" in digest_data445 assert digest_data["uri"] == '"/"'446 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes447 assert len(digest_data["opaque"]) == expected_hash_length + 2448 assert digest_data["algorithm"] == algorithm449 assert digest_data["qop"] == "auth"450 assert digest_data["nc"] == "00000001"451 assert len(digest_data["cnonce"]) == 16 + 2452453454@pytest.mark.asyncio455async def test_digest_auth_no_specified_qop() -> None:456 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 457why, one step back
457 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 458–465why, one step back
458 app = DigestApp(qop="")
459460 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:461 response = await client.get(url, auth=auth)462463 assert response.status_code == 200464 assert len(response.history) == 1465

Typing: always fill in generic type parameters (#2468)Adrian Garcia Badaraccobefore adoption1b4e7fb

line 466why, one step back
466 authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 467–475why, one step back
467 scheme, _, fields = authorization.partition(" ")
468 assert scheme == "Digest"469470 response_fields = [field.strip() for field in fields.split(",")]471 digest_data = dict(field.split("=") for field in response_fields)472473 assert "qop" not in digest_data474 assert "nc" not in digest_data475 assert "cnonce" not in digest_data

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

line 476why, one step back
476 assert digest_data["username"] == '"user"'

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 477–488why, one step back
477 assert digest_data["realm"] == '"httpx@example.org"'
478 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes479 assert digest_data["uri"] == '"/"'480 assert len(digest_data["response"]) == 64 + 2481 assert len(digest_data["opaque"]) == 64 + 2482 assert digest_data["algorithm"] == "SHA-256"483484485@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))486@pytest.mark.asyncio487async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:488 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 489why, one step back
489 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 490–501why, one step back
490 app = DigestApp(qop=qop)
491492 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:493 response = await client.get(url, auth=auth)494495 assert response.status_code == 200496 assert len(response.history) == 1497498499@pytest.mark.asyncio500async def test_digest_auth_qop_auth_int_not_implemented() -> None:501 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 502why, one step back
502 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 503–512why, one step back
503 app = DigestApp(qop="auth-int")
504505 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:506 with pytest.raises(NotImplementedError):507 await client.get(url, auth=auth)508509510@pytest.mark.asyncio511async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:512 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 513why, one step back
513 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 514–516why, one step back
514 app = DigestApp(qop="not-auth")
515516 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 517why, one step back
517 with pytest.raises(httpx.ProtocolError):

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 518–523why, one step back
518 await client.get(url, auth=auth)
519520521@pytest.mark.asyncio522async def test_digest_auth_incorrect_credentials() -> None:523 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 524why, one step back
524 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 525–533why, one step back
525 app = DigestApp(send_response_after_attempt=2)
526527 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:528 response = await client.get(url, auth=auth)529530 assert response.status_code == 401531 assert len(response.history) == 1532533

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

lines 534–536why, one step back
534@pytest.mark.asyncio
535async def test_digest_auth_reuses_challenge() -> None:536 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 537why, one step back
537 auth = httpx.DigestAuth(username="user", password="password123")

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

lines 538–553why, one step back
538 app = DigestApp()
539540 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:541 response_1 = await client.get(url, auth=auth)542 response_2 = await client.get(url, auth=auth)543544 assert response_1.status_code == 200545 assert response_2.status_code == 200546547 assert len(response_1.history) == 1548 assert len(response_2.history) == 0549550551@pytest.mark.asyncio552async def test_digest_auth_resets_nonce_count_after_401() -> None:553 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 554why, one step back
554 auth = httpx.DigestAuth(username="user", password="password123")

reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13

lines 555–589why, one step back
555 app = DigestApp()
556557 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:558 response_1 = await client.get(url, auth=auth)559 assert response_1.status_code == 200560 assert len(response_1.history) == 1561562 first_nonce = parse_keqv_list(563 response_1.request.headers["Authorization"].split(", ")564 )["nonce"]565 first_nc = parse_keqv_list(566 response_1.request.headers["Authorization"].split(", ")567 )["nc"]568569 # with this we now force a 401 on a subsequent (but initial) request570 app.send_response_after_attempt = 2571572 # we expect the client again to try to authenticate, i.e. the history length must be 1573 response_2 = await client.get(url, auth=auth)574 assert response_2.status_code == 200575 assert len(response_2.history) == 1576577 second_nonce = parse_keqv_list(578 response_2.request.headers["Authorization"].split(", ")579 )["nonce"]580 second_nc = parse_keqv_list(581 response_2.request.headers["Authorization"].split(", ")582 )["nc"]583584 assert first_nonce != second_nonce # ensures that the auth challenge was reset585 assert (586 first_nc == second_nc587 ) # ensures the nonce count is reset when the authentication failed588589

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 590–601why, one step back
590@pytest.mark.parametrize(
591 "auth_header",592 [593 'Digest realm="httpx@example.org", qop="auth"', # missing fields594 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list595 ],596)597@pytest.mark.asyncio598async def test_async_digest_auth_raises_protocol_error_on_malformed_header(599 auth_header: str,600) -> None:601 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 602why, one step back
602 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 603–605why, one step back
603 app = App(auth_header=auth_header, status_code=401)
604605 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 606why, one step back
606 with pytest.raises(httpx.ProtocolError):

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 607–620why, one step back
607 await client.get(url, auth=auth)
608609610@pytest.mark.parametrize(611 "auth_header",612 [613 'Digest realm="httpx@example.org", qop="auth"', # missing fields614 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list615 ],616)617def test_sync_digest_auth_raises_protocol_error_on_malformed_header(618 auth_header: str,619) -> None:620 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 621why, one step back
621 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 622–624why, one step back
622 app = App(auth_header=auth_header, status_code=401)
623624 with httpx.Client(transport=httpx.MockTransport(app)) as client:

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 625why, one step back
625 with pytest.raises(httpx.ProtocolError):

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 626–681why, one step back
626 client.get(url, auth=auth)
627628629@pytest.mark.asyncio630async def test_async_auth_history() -> None:631 """632 Test that intermediate requests sent as part of an authentication flow633 are recorded in the response history.634 """635 url = "https://example.org/"636 auth = RepeatAuth(repeat=2)637 app = App(auth_header="abc")638639 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:640 response = await client.get(url, auth=auth)641642 assert response.status_code == 200643 assert response.json() == {"auth": "Repeat abc.abc"}644645 assert len(response.history) == 2646 resp1, resp2 = response.history647 assert resp1.json() == {"auth": "Repeat 0"}648 assert resp2.json() == {"auth": "Repeat 1"}649650 assert len(resp2.history) == 1651 assert resp2.history == [resp1]652653 assert len(resp1.history) == 0654655656def test_sync_auth_history() -> None:657 """658 Test that intermediate requests sent as part of an authentication flow659 are recorded in the response history.660 """661 url = "https://example.org/"662 auth = RepeatAuth(repeat=2)663 app = App(auth_header="abc")664665 with httpx.Client(transport=httpx.MockTransport(app)) as client:666 response = client.get(url, auth=auth)667668 assert response.status_code == 200669 assert response.json() == {"auth": "Repeat abc.abc"}670671 assert len(response.history) == 2672 resp1, resp2 = response.history673 assert resp1.json() == {"auth": "Repeat 0"}674 assert resp2.json() == {"auth": "Repeat 1"}675676 assert len(resp2.history) == 1677 assert resp2.history == [resp1]678679 assert len(resp1.history) == 0680681

Transport API as plain `request -> response` method. (#1840)Tom Christiebefore adoptionff9813e

line 682why, one step back
682class ConsumeBodyTransport(httpx.MockTransport):

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 683why, one step back
683 async def handle_async_request(self, request: httpx.Request) -> httpx.Response:

Transport API as plain `request -> response` method. (#1840)Tom Christiebefore adoptionff9813e

lines 684–688why, one step back
684 assert isinstance(request.stream, httpx.AsyncByteStream)
685 [_ async for _ in request.stream]686 return self.handler(request)687688

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 689–691why, one step back
689@pytest.mark.asyncio
690async def test_digest_auth_unavailable_streaming_body():691 url = "https://example.org/"

Use consistent import style (#2493)Tom Christiebefore adoption7985f68

line 692why, one step back
692 auth = httpx.DigestAuth(username="user", password="password123")

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 693–694why, one step back
693 app = DigestApp()
694

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 695why, one step back
695 async def streaming_body() -> typing.AsyncIterator[bytes]:

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 696why, one step back
696 yield b"Example request body" # pragma: no cover

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

line 697why, one step back
697

Transport API as plain `request -> response` method. (#1840)Tom Christiebefore adoptionff9813e

line 698why, one step back
698 async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 699–766why, one step back
699 with pytest.raises(httpx.StreamConsumed):
700 await client.post(url, content=streaming_body(), auth=auth)701702703@pytest.mark.asyncio704async def test_async_auth_reads_response_body() -> None:705 """706 Test that we can read the response body in an auth flow if `requires_response_body`707 is set.708 """709 url = "https://example.org/"710 auth = ResponseBodyAuth("xyz")711 app = App()712713 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:714 response = await client.get(url, auth=auth)715716 assert response.status_code == 200717 assert response.json() == {"auth": '{"auth": "xyz"}'}718719720def test_sync_auth_reads_response_body() -> None:721 """722 Test that we can read the response body in an auth flow if `requires_response_body`723 is set.724 """725 url = "https://example.org/"726 auth = ResponseBodyAuth("xyz")727 app = App()728729 with httpx.Client(transport=httpx.MockTransport(app)) as client:730 response = client.get(url, auth=auth)731732 assert response.status_code == 200733 assert response.json() == {"auth": '{"auth": "xyz"}'}734735736@pytest.mark.asyncio737async def test_async_auth() -> None:738 """739 Test that we can use an auth implementation specific to the async case, to740 support cases that require performing I/O or using concurrency primitives (such741 as checking a disk-based cache or fetching a token from a remote auth server).742 """743 url = "https://example.org/"744 auth = SyncOrAsyncAuth()745 app = App()746747 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:748 response = await client.get(url, auth=auth)749750 assert response.status_code == 200751 assert response.json() == {"auth": "async-auth"}752753754def test_sync_auth() -> None:755 """756 Test that we can use an auth implementation specific to the sync case.757 """758 url = "https://example.org/"759 auth = SyncOrAsyncAuth()760 app = App()761762 with httpx.Client(transport=httpx.MockTransport(app)) as client:763 response = client.get(url, auth=auth)764765 assert response.status_code == 200766 assert response.json() == {"auth": "sync-auth"}