test_auth.py
This file
Path
tests/client/test_auth.py
793 lines · 25.5 KiB · Python
Last changed by
fix type annotation for MockTransport (#2581)Adrian Garcia Badaraccobefore adoptionf0fd919
History of this fileTake it
The walk stopped after 200 commits: lines older than 70e7cd7 point at it.
Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 1–6why, one step back1"""2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import hashlibAdd `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
line 7why, one step back7import netrcBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
line 8why, one step back8import osAdd `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
line 9why, one step back9import sysBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 10–11why, one step back10import threading11import typingreuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 12why, one step back12from urllib.request import parse_keqv_listBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
line 13why, one step back13replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 14why, one step back14import anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 15–22why, one step back15import pytest1617import httpx1819from ..common import FIXTURES_DIR202122class App:Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 23–26why, one step back23 """24 A mock app to test auth credentials.25 """26Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 27–82why, one step back27 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:28 self.auth_header = auth_header29 self.status_code = status_code3031 def __call__(self, request: httpx.Request) -> httpx.Response:32 headers = {"www-authenticate": self.auth_header} if self.auth_header else {}33 data = {"auth": request.headers.get("Authorization")}34 return httpx.Response(self.status_code, headers=headers, json=data)353637class DigestApp:38 def __init__(39 self,40 algorithm: str = "SHA-256",41 send_response_after_attempt: int = 1,42 qop: str = "auth",43 regenerate_nonce: bool = True,44 ) -> None:45 self.algorithm = algorithm46 self.send_response_after_attempt = send_response_after_attempt47 self.qop = qop48 self._regenerate_nonce = regenerate_nonce49 self._response_count = 05051 def __call__(self, request: httpx.Request) -> httpx.Response:52 if self._response_count < self.send_response_after_attempt:53 return self.challenge_send(request)5455 data = {"auth": request.headers.get("Authorization")}56 return httpx.Response(200, json=data)5758 def challenge_send(self, request: httpx.Request) -> httpx.Response:59 self._response_count += 160 nonce = (61 hashlib.sha256(os.urandom(8)).hexdigest()62 if self._regenerate_nonce63 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"64 )65 challenge_data = {66 "nonce": nonce,67 "qop": self.qop,68 "opaque": (69 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"70 ),71 "algorithm": self.algorithm,72 "stale": "FALSE",73 }74 challenge_str = ", ".join(75 '{}="{}"'.format(key, value)76 for key, value in challenge_data.items()77 if value78 )7980 headers = {81 "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',82 }Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 83why, one step back83 return httpx.Response(401, headers=headers)Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 84–85why, one step back8485Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 86why, one step back86class RepeatAuth(httpx.Auth):Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 87–98why, one step back87 """88 A mock authentication scheme that requires clients to send89 the request a fixed number of times, and then send a last request containing90 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers91 of intermediate responses.92 """9394 requires_request_body = True9596 def __init__(self, repeat: int):97 self.repeat = repeat98Use consistent import style (#2493)Tom Christiebefore adoption7985f68
lines 99–101why, one step back99 def auth_flow(100 self, request: httpx.Request101 ) -> typing.Generator[httpx.Request, httpx.Response, None]:Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 102–113why, one step back102 nonces = []103104 for index in range(self.repeat):105 request.headers["Authorization"] = f"Repeat {index}"106 response = yield request107 nonces.append(response.headers["www-authenticate"])108109 key = ".".join(nonces)110 request.headers["Authorization"] = f"Repeat {key}"111 yield request112113Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 114why, one step back114class ResponseBodyAuth(httpx.Auth):Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 115–122why, one step back115 """116 A mock authentication scheme that requires clients to send an 'Authorization'117 header, then send back the contents of the response in the 'Authorization'118 header.119 """120121 requires_response_body = True122Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 123why, one step back123 def __init__(self, token: str) -> None:Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 124–125why, one step back124 self.token = token125Use consistent import style (#2493)Tom Christiebefore adoption7985f68
lines 126–128why, one step back126 def auth_flow(127 self, request: httpx.Request128 ) -> typing.Generator[httpx.Request, httpx.Response, None]:Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 129–135why, one step back129 request.headers["Authorization"] = self.token130 response = yield request131 data = response.text132 request.headers["Authorization"] = data133 yield request134135Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 136why, one step back136class SyncOrAsyncAuth(httpx.Auth):Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 137–143why, one step back137 """138 A mock authentication scheme that uses a different implementation for the139 sync and async cases.140 """141142 def __init__(self) -> None:143 self._lock = threading.Lock()replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 144why, one step back144 self._async_lock = anyio.Lock()Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 145–146why, one step back145146 def sync_auth_flow(Use consistent import style (#2493)Tom Christiebefore adoption7985f68
lines 147–148why, one step back147 self, request: httpx.Request148 ) -> typing.Generator[httpx.Request, httpx.Response, None]:Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 149–153why, one step back149 with self._lock:150 request.headers["Authorization"] = "sync-auth"151 yield request152153 async def async_auth_flow(Use consistent import style (#2493)Tom Christiebefore adoption7985f68
lines 154–155why, one step back154 self, request: httpx.Request155 ) -> typing.AsyncGenerator[httpx.Request, httpx.Response]:Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 156–160why, one step back156 async with self._async_lock:157 request.headers["Authorization"] = "async-auth"158 yield request159160replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 161why, one step back161@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 162–163why, one step back162async def test_basic_auth() -> None:163 url = "https://example.org/"reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 164why, one step back164 auth = ("user", "password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 165–170why, one step back165 app = App()166167 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:168 response = await client.get(url, auth=auth)169170 assert response.status_code == 200reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 171why, one step back171 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 172–173why, one step back172173replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 174why, one step back174@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 175–179why, one step back175async def test_basic_auth_with_stream() -> None:176 """177 See: https://github.com/encode/httpx/pull/1312178 """179 url = "https://example.org/"reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 180why, one step back180 auth = ("user", "password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 181–189why, one step back181 app = App()182183 async with httpx.AsyncClient(184 transport=httpx.MockTransport(app), auth=auth185 ) as client:186 async with client.stream("GET", url) as response:187 await response.aread()188189 assert response.status_code == 200reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 190why, one step back190 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 191–192why, one step back191192replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 193why, one step back193@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
line 194why, one step back194async def test_basic_auth_in_url() -> None:reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 195why, one step back195 url = "https://user:password123@example.org/"Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 196–201why, one step back196 app = App()197198 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:199 response = await client.get(url)200201 assert response.status_code == 200reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 202why, one step back202 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 203–204why, one step back203204replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 205why, one step back205@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 206–207why, one step back206async def test_basic_auth_on_session() -> None:207 url = "https://example.org/"reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 208why, one step back208 auth = ("user", "password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 209–216why, one step back209 app = App()210211 async with httpx.AsyncClient(212 transport=httpx.MockTransport(app), auth=auth213 ) as client:214 response = await client.get(url)215216 assert response.status_code == 200reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 217why, one step back217 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 218–219why, one step back218219replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 220why, one step back220@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 221–224why, one step back221async def test_custom_auth() -> None:222 url = "https://example.org/"223 app = App()224Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 225why, one step back225 def auth(request: httpx.Request) -> httpx.Request:Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 226–235why, one step back226 request.headers["Authorization"] = "Token 123"227 return request228229 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:230 response = await client.get(url, auth=auth)231232 assert response.status_code == 200233 assert response.json() == {"auth": "Token 123"}234235Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 236–241why, one step back236def test_netrc_auth_credentials_exist() -> None:237 """238 When netrc auth is being used and a request is made to a host that is239 in the netrc file, then the relevant credentials should be applied.240 """241 netrc_file = str(FIXTURES_DIR / ".netrc")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 242–243why, one step back242 url = "http://netrcexample.org"243 app = App()Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
line 244why, one step back244 auth = httpx.NetRCAuth(netrc_file)Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
line 245why, one step back245Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 246–247why, one step back246 with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:247 response = client.get(url)Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 248–254why, one step back248249 assert response.status_code == 200250 assert response.json() == {251 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"252 }253254Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 255–261why, one step back255def test_netrc_auth_credentials_do_not_exist() -> None:256 """257 When netrc auth is being used and a request is made to a host that is258 not in the netrc file, then no credentials should be applied.259 """260 netrc_file = str(FIXTURES_DIR / ".netrc")261 url = "http://example.org"Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
line 262why, one step back262 app = App()Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
line 263why, one step back263 auth = httpx.NetRCAuth(netrc_file)Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
line 264why, one step back264Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 265–266why, one step back265 with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:266 response = client.get(url)Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 267–268why, one step back267268 assert response.status_code == 200Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
line 269why, one step back269 assert response.json() == {"auth": None}Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 270–271why, one step back270271Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 272–284why, one step back272@pytest.mark.skipif(273 sys.version_info < (3, 11),274 reason="netrc files without a password are invalid with Python < 3.11",275)276def test_netrc_auth_nopassword() -> None: # pragma: no cover277 """278 Python has different netrc parsing behaviours with different versions.279 For Python 3.11+ a netrc file with no password is valid. In this case280 we want to check that we allow the netrc auth, and simply don't provide281 any credentials in the request.282 """283 netrc_file = str(FIXTURES_DIR / ".netrc-nopassword")284 url = "http://example.org"Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
line 285why, one step back285 app = App()Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
line 286why, one step back286 auth = httpx.NetRCAuth(netrc_file)Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
line 287why, one step back287Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 288–289why, one step back288 with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:289 response = client.get(url)Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 290–294why, one step back290291 assert response.status_code == 200292 assert response.json() == {"auth": None}293294Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 295–307why, one step back295@pytest.mark.skipif(296 sys.version_info >= (3, 11),297 reason="netrc files without a password are valid from Python >= 3.11",298)299def test_netrc_auth_nopassword_parse_error() -> None: # pragma: no cover300 """301 Python has different netrc parsing behaviours with different versions.302 For Python < 3.11 a netrc file with no password is invalid. In this case303 we want to allow the parse error to be raised.304 """305 netrc_file = str(FIXTURES_DIR / ".netrc-nopassword")306 with pytest.raises(netrc.NetrcParseError):307 httpx.NetRCAuth(netrc_file)Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 308–309why, one step back308309replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 310why, one step back310@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 311–312why, one step back311async def test_auth_disable_per_request() -> None:312 url = "https://example.org/"reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 313why, one step back313 auth = ("user", "password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 314–327why, one step back314 app = App()315316 async with httpx.AsyncClient(317 transport=httpx.MockTransport(app), auth=auth318 ) as client:319 response = await client.get(url, auth=None)320321 assert response.status_code == 200322 assert response.json() == {"auth": None}323324325def test_auth_hidden_url() -> None:326 url = "http://example-username:example-password@example.org/"327 expected = "URL('http://example-username:[secure]@example.org/')"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
lines 328–329why, one step back328 assert url == httpx.URL(url)329 assert expected == repr(httpx.URL(url))Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 330–331why, one step back330331replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 332why, one step back332@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 333–343why, one step back333async def test_auth_hidden_header() -> None:334 url = "https://example.org/"335 auth = ("example-username", "example-password")336 app = App()337338 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:339 response = await client.get(url, auth=auth)340341 assert "'authorization': '[secure]'" in str(response.request.headers)342343replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 344why, one step back344@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 345–350why, one step back345async def test_auth_property() -> None:346 app = App()347348 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:349 assert client.auth is None350reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 351why, one step back351 client.auth = ("user", "password123") # type: ignoreUse consistent import style (#2493)Tom Christiebefore adoption7985f68
line 352why, one step back352 assert isinstance(client.auth, httpx.BasicAuth)Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 353–356why, one step back353354 url = "https://example.org/"355 response = await client.get(url)356 assert response.status_code == 200reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 357why, one step back357 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 358–359why, one step back358359replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 360why, one step back360@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 361–377why, one step back361async def test_auth_invalid_type() -> None:362 app = App()363364 with pytest.raises(TypeError):365 client = httpx.AsyncClient(366 transport=httpx.MockTransport(app),367 auth="not a tuple, not a callable", # type: ignore368 )369370 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:371 with pytest.raises(TypeError):372 await client.get(auth="not a tuple, not a callable") # type: ignore373374 with pytest.raises(TypeError):375 client.auth = "not a tuple, not a callable" # type: ignore376377replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 378why, one step back378@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 379–380why, one step back379async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:380 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 381why, one step back381 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 382–393why, one step back382 app = App()383384 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:385 response = await client.get(url, auth=auth)386387 assert response.status_code == 200388 assert response.json() == {"auth": None}389 assert len(response.history) == 0390391392def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:393 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 394why, one step back394 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 395–405why, one step back395 auth_header = "Token ..."396 app = App(auth_header=auth_header, status_code=401)397398 client = httpx.Client(transport=httpx.MockTransport(app))399 response = client.get(url, auth=auth)400401 assert response.status_code == 401402 assert response.json() == {"auth": None}403 assert len(response.history) == 0404405replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 406why, one step back406@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 407–408why, one step back407async def test_digest_auth_200_response_including_digest_auth_header() -> None:408 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 409why, one step back409 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 410–420why, one step back410 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'411 app = App(auth_header=auth_header, status_code=200)412413 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:414 response = await client.get(url, auth=auth)415416 assert response.status_code == 200417 assert response.json() == {"auth": None}418 assert len(response.history) == 0419420replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 421why, one step back421@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 422–423why, one step back422async def test_digest_auth_401_response_without_digest_auth_header() -> None:423 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 424why, one step back424 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 425–447why, one step back425 app = App(auth_header="", status_code=401)426427 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:428 response = await client.get(url, auth=auth)429430 assert response.status_code == 401431 assert response.json() == {"auth": None}432 assert len(response.history) == 0433434435@pytest.mark.parametrize(436 "algorithm,expected_hash_length,expected_response_length",437 [438 ("MD5", 64, 32),439 ("MD5-SESS", 64, 32),440 ("SHA", 64, 40),441 ("SHA-SESS", 64, 40),442 ("SHA-256", 64, 64),443 ("SHA-256-SESS", 64, 64),444 ("SHA-512", 64, 128),445 ("SHA-512-SESS", 64, 128),446 ],447)replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 448why, one step back448@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 449–452why, one step back449async def test_digest_auth(450 algorithm: str, expected_hash_length: int, expected_response_length: int451) -> None:452 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 453why, one step back453 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 454–461why, one step back454 app = DigestApp(algorithm=algorithm)455456 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:457 response = await client.get(url, auth=auth)458459 assert response.status_code == 200460 assert len(response.history) == 1461Typing: always fill in generic type parameters (#2468)Adrian Garcia Badaraccobefore adoption1b4e7fb
line 462why, one step back462 authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 463–468why, one step back463 scheme, _, fields = authorization.partition(" ")464 assert scheme == "Digest"465466 response_fields = [field.strip() for field in fields.split(",")]467 digest_data = dict(field.split("=") for field in response_fields)468reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 469why, one step back469 assert digest_data["username"] == '"user"'Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 470–480why, one step back470 assert digest_data["realm"] == '"httpx@example.org"'471 assert "nonce" in digest_data472 assert digest_data["uri"] == '"/"'473 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes474 assert len(digest_data["opaque"]) == expected_hash_length + 2475 assert digest_data["algorithm"] == algorithm476 assert digest_data["qop"] == "auth"477 assert digest_data["nc"] == "00000001"478 assert len(digest_data["cnonce"]) == 16 + 2479480replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 481why, one step back481@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 482–483why, one step back482async def test_digest_auth_no_specified_qop() -> None:483 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 484why, one step back484 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 485–492why, one step back485 app = DigestApp(qop="")486487 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:488 response = await client.get(url, auth=auth)489490 assert response.status_code == 200491 assert len(response.history) == 1492Typing: always fill in generic type parameters (#2468)Adrian Garcia Badaraccobefore adoption1b4e7fb
line 493why, one step back493 authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 494–502why, one step back494 scheme, _, fields = authorization.partition(" ")495 assert scheme == "Digest"496497 response_fields = [field.strip() for field in fields.split(",")]498 digest_data = dict(field.split("=") for field in response_fields)499500 assert "qop" not in digest_data501 assert "nc" not in digest_data502 assert "cnonce" not in digest_datareuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
line 503why, one step back503 assert digest_data["username"] == '"user"'Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 504–512why, one step back504 assert digest_data["realm"] == '"httpx@example.org"'505 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes506 assert digest_data["uri"] == '"/"'507 assert len(digest_data["response"]) == 64 + 2508 assert len(digest_data["opaque"]) == 64 + 2509 assert digest_data["algorithm"] == "SHA-256"510511512@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 513why, one step back513@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 514–515why, one step back514async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:515 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 516why, one step back516 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 517–525why, one step back517 app = DigestApp(qop=qop)518519 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:520 response = await client.get(url, auth=auth)521522 assert response.status_code == 200523 assert len(response.history) == 1524525replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 526why, one step back526@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 527–528why, one step back527async def test_digest_auth_qop_auth_int_not_implemented() -> None:528 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 529why, one step back529 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 530–536why, one step back530 app = DigestApp(qop="auth-int")531532 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:533 with pytest.raises(NotImplementedError):534 await client.get(url, auth=auth)535536replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 537why, one step back537@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 538–539why, one step back538async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:539 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 540why, one step back540 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 541–543why, one step back541 app = DigestApp(qop="not-auth")542543 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 544why, one step back544 with pytest.raises(httpx.ProtocolError):Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 545–547why, one step back545 await client.get(url, auth=auth)546547replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 548why, one step back548@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 549–550why, one step back549async def test_digest_auth_incorrect_credentials() -> None:550 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 551why, one step back551 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 552–560why, one step back552 app = DigestApp(send_response_after_attempt=2)553554 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:555 response = await client.get(url, auth=auth)556557 assert response.status_code == 401558 assert len(response.history) == 1559560replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 561why, one step back561@pytest.mark.anyioreuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
lines 562–563why, one step back562async def test_digest_auth_reuses_challenge() -> None:563 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 564why, one step back564 auth = httpx.DigestAuth(username="user", password="password123")reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
lines 565–577why, one step back565 app = DigestApp()566567 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:568 response_1 = await client.get(url, auth=auth)569 response_2 = await client.get(url, auth=auth)570571 assert response_1.status_code == 200572 assert response_2.status_code == 200573574 assert len(response_1.history) == 1575 assert len(response_2.history) == 0576577replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 578why, one step back578@pytest.mark.anyioreuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
lines 579–580why, one step back579async def test_digest_auth_resets_nonce_count_after_401() -> None:580 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 581why, one step back581 auth = httpx.DigestAuth(username="user", password="password123")reuse the digest auth state to avoid unnecessary requests (#2463)rettierbefore adoption8327e13
lines 582–616why, one step back582 app = DigestApp()583584 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:585 response_1 = await client.get(url, auth=auth)586 assert response_1.status_code == 200587 assert len(response_1.history) == 1588589 first_nonce = parse_keqv_list(590 response_1.request.headers["Authorization"].split(", ")591 )["nonce"]592 first_nc = parse_keqv_list(593 response_1.request.headers["Authorization"].split(", ")594 )["nc"]595596 # with this we now force a 401 on a subsequent (but initial) request597 app.send_response_after_attempt = 2598599 # we expect the client again to try to authenticate, i.e. the history length must be 1600 response_2 = await client.get(url, auth=auth)601 assert response_2.status_code == 200602 assert len(response_2.history) == 1603604 second_nonce = parse_keqv_list(605 response_2.request.headers["Authorization"].split(", ")606 )["nonce"]607 second_nc = parse_keqv_list(608 response_2.request.headers["Authorization"].split(", ")609 )["nc"]610611 assert first_nonce != second_nonce # ensures that the auth challenge was reset612 assert (613 first_nc == second_nc614 ) # ensures the nonce count is reset when the authentication failed615616Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 617–623why, one step back617@pytest.mark.parametrize(618 "auth_header",619 [620 'Digest realm="httpx@example.org", qop="auth"', # missing fields621 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list622 ],623)replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 624why, one step back624@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 625–628why, one step back625async def test_async_digest_auth_raises_protocol_error_on_malformed_header(626 auth_header: str,627) -> None:628 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 629why, one step back629 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 630–632why, one step back630 app = App(auth_header=auth_header, status_code=401)631632 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 633why, one step back633 with pytest.raises(httpx.ProtocolError):Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 634–647why, one step back634 await client.get(url, auth=auth)635636637@pytest.mark.parametrize(638 "auth_header",639 [640 'Digest realm="httpx@example.org", qop="auth"', # missing fields641 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list642 ],643)644def test_sync_digest_auth_raises_protocol_error_on_malformed_header(645 auth_header: str,646) -> None:647 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 648why, one step back648 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 649–651why, one step back649 app = App(auth_header=auth_header, status_code=401)650651 with httpx.Client(transport=httpx.MockTransport(app)) as client:Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 652why, one step back652 with pytest.raises(httpx.ProtocolError):Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 653–655why, one step back653 client.get(url, auth=auth)654655replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 656why, one step back656@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 657–709why, one step back657async def test_async_auth_history() -> None:658 """659 Test that intermediate requests sent as part of an authentication flow660 are recorded in the response history.661 """662 url = "https://example.org/"663 auth = RepeatAuth(repeat=2)664 app = App(auth_header="abc")665666 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:667 response = await client.get(url, auth=auth)668669 assert response.status_code == 200670 assert response.json() == {"auth": "Repeat abc.abc"}671672 assert len(response.history) == 2673 resp1, resp2 = response.history674 assert resp1.json() == {"auth": "Repeat 0"}675 assert resp2.json() == {"auth": "Repeat 1"}676677 assert len(resp2.history) == 1678 assert resp2.history == [resp1]679680 assert len(resp1.history) == 0681682683def test_sync_auth_history() -> None:684 """685 Test that intermediate requests sent as part of an authentication flow686 are recorded in the response history.687 """688 url = "https://example.org/"689 auth = RepeatAuth(repeat=2)690 app = App(auth_header="abc")691692 with httpx.Client(transport=httpx.MockTransport(app)) as client:693 response = client.get(url, auth=auth)694695 assert response.status_code == 200696 assert response.json() == {"auth": "Repeat abc.abc"}697698 assert len(response.history) == 2699 resp1, resp2 = response.history700 assert resp1.json() == {"auth": "Repeat 0"}701 assert resp2.json() == {"auth": "Repeat 1"}702703 assert len(resp2.history) == 1704 assert resp2.history == [resp1]705706 assert len(resp1.history) == 0707708709class ConsumeBodyTransport(httpx.MockTransport):Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 710why, one step back710 async def handle_async_request(self, request: httpx.Request) -> httpx.Response:Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 711–712why, one step back711 assert isinstance(request.stream, httpx.AsyncByteStream)712 [_ async for _ in request.stream]fix type annotation for MockTransport (#2581)Adrian Garcia Badaraccobefore adoptionf0fd919
line 713why, one step back713 return self.handler(request) # type: ignore[return-value]Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 714–715why, one step back714715replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 716why, one step back716@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 717–718why, one step back717async def test_digest_auth_unavailable_streaming_body():718 url = "https://example.org/"Use consistent import style (#2493)Tom Christiebefore adoption7985f68
line 719why, one step back719 auth = httpx.DigestAuth(username="user", password="password123")Bump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 720–721why, one step back720 app = DigestApp()721Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 722why, one step back722 async def streaming_body() -> typing.AsyncIterator[bytes]:use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
line 723why, one step back723 yield b"Example request body" # pragma: no coverBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 724–729why, one step back724725 async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:726 with pytest.raises(httpx.StreamConsumed):727 await client.post(url, content=streaming_body(), auth=auth)728729replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 730why, one step back730@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 731–762why, one step back731async def test_async_auth_reads_response_body() -> None:732 """733 Test that we can read the response body in an auth flow if `requires_response_body`734 is set.735 """736 url = "https://example.org/"737 auth = ResponseBodyAuth("xyz")738 app = App()739740 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:741 response = await client.get(url, auth=auth)742743 assert response.status_code == 200744 assert response.json() == {"auth": '{"auth": "xyz"}'}745746747def test_sync_auth_reads_response_body() -> None:748 """749 Test that we can read the response body in an auth flow if `requires_response_body`750 is set.751 """752 url = "https://example.org/"753 auth = ResponseBodyAuth("xyz")754 app = App()755756 with httpx.Client(transport=httpx.MockTransport(app)) as client:757 response = client.get(url, auth=auth)758759 assert response.status_code == 200760 assert response.json() == {"auth": '{"auth": "xyz"}'}761762replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 763why, one step back763@pytest.mark.anyioBump pytest from 7.0.1 to 7.1.2 (#2196)dependabot[bot]before adoption70e7cd7
lines 764–793why, one step back764async def test_async_auth() -> None:765 """766 Test that we can use an auth implementation specific to the async case, to767 support cases that require performing I/O or using concurrency primitives (such768 as checking a disk-based cache or fetching a token from a remote auth server).769 """770 url = "https://example.org/"771 auth = SyncOrAsyncAuth()772 app = App()773774 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:775 response = await client.get(url, auth=auth)776777 assert response.status_code == 200778 assert response.json() == {"auth": "async-auth"}779780781def test_sync_auth() -> None:782 """783 Test that we can use an auth implementation specific to the sync case.784 """785 url = "https://example.org/"786 auth = SyncOrAsyncAuth()787 app = App()788789 with httpx.Client(transport=httpx.MockTransport(app)) as client:790 response = client.get(url, auth=auth)791792 assert response.status_code == 200793 assert response.json() == {"auth": "sync-auth"}