test_auth.py
This file
Path
tests/client/test_auth.py
795 lines · 25.5 KiB · Python
Last changed by
format (#3131)T-256before adoption0006ed0
History of this fileTake it
The walk stopped after 200 commits: lines older than 988809a point at it.
Bump coverage from 6.5.0 to 7.2.1 (#2614)dependabot[bot]before adoption988809a
lines 1–5why, one step back1"""2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""format (#3131)T-256before adoption0006ed0
line 6why, one step back6Bump coverage from 6.5.0 to 7.2.1 (#2614)dependabot[bot]before adoption988809a
lines 7–96why, one step back7import hashlib8import netrc9import os10import sys11import threading12import typing13from urllib.request import parse_keqv_list1415import anyio16import pytest1718import httpx1920from ..common import FIXTURES_DIR212223class App:24 """25 A mock app to test auth credentials.26 """2728 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:29 self.auth_header = auth_header30 self.status_code = status_code3132 def __call__(self, request: httpx.Request) -> httpx.Response:33 headers = {"www-authenticate": self.auth_header} if self.auth_header else {}34 data = {"auth": request.headers.get("Authorization")}35 return httpx.Response(self.status_code, headers=headers, json=data)363738class DigestApp:39 def __init__(40 self,41 algorithm: str = "SHA-256",42 send_response_after_attempt: int = 1,43 qop: str = "auth",44 regenerate_nonce: bool = True,45 ) -> None:46 self.algorithm = algorithm47 self.send_response_after_attempt = send_response_after_attempt48 self.qop = qop49 self._regenerate_nonce = regenerate_nonce50 self._response_count = 05152 def __call__(self, request: httpx.Request) -> httpx.Response:53 if self._response_count < self.send_response_after_attempt:54 return self.challenge_send(request)5556 data = {"auth": request.headers.get("Authorization")}57 return httpx.Response(200, json=data)5859 def challenge_send(self, request: httpx.Request) -> httpx.Response:60 self._response_count += 161 nonce = (62 hashlib.sha256(os.urandom(8)).hexdigest()63 if self._regenerate_nonce64 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"65 )66 challenge_data = {67 "nonce": nonce,68 "qop": self.qop,69 "opaque": (70 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"71 ),72 "algorithm": self.algorithm,73 "stale": "FALSE",74 }75 challenge_str = ", ".join(76 '{}="{}"'.format(key, value)77 for key, value in challenge_data.items()78 if value79 )8081 headers = {82 "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',83 }84 return httpx.Response(401, headers=headers)858687class RepeatAuth(httpx.Auth):88 """89 A mock authentication scheme that requires clients to send90 the request a fixed number of times, and then send a last request containing91 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers92 of intermediate responses.93 """9495 requires_request_body = True96add missing type hints to __init__(...) (#2938)Petr Belskiybefore adoption87f39f1
line 97why, one step back97 def __init__(self, repeat: int) -> None:Bump coverage from 6.5.0 to 7.2.1 (#2614)dependabot[bot]before adoption988809a
lines 98–599why, one step back98 self.repeat = repeat99100 def auth_flow(101 self, request: httpx.Request102 ) -> typing.Generator[httpx.Request, httpx.Response, None]:103 nonces = []104105 for index in range(self.repeat):106 request.headers["Authorization"] = f"Repeat {index}"107 response = yield request108 nonces.append(response.headers["www-authenticate"])109110 key = ".".join(nonces)111 request.headers["Authorization"] = f"Repeat {key}"112 yield request113114115class ResponseBodyAuth(httpx.Auth):116 """117 A mock authentication scheme that requires clients to send an 'Authorization'118 header, then send back the contents of the response in the 'Authorization'119 header.120 """121122 requires_response_body = True123124 def __init__(self, token: str) -> None:125 self.token = token126127 def auth_flow(128 self, request: httpx.Request129 ) -> typing.Generator[httpx.Request, httpx.Response, None]:130 request.headers["Authorization"] = self.token131 response = yield request132 data = response.text133 request.headers["Authorization"] = data134 yield request135136137class SyncOrAsyncAuth(httpx.Auth):138 """139 A mock authentication scheme that uses a different implementation for the140 sync and async cases.141 """142143 def __init__(self) -> None:144 self._lock = threading.Lock()145 self._async_lock = anyio.Lock()146147 def sync_auth_flow(148 self, request: httpx.Request149 ) -> typing.Generator[httpx.Request, httpx.Response, None]:150 with self._lock:151 request.headers["Authorization"] = "sync-auth"152 yield request153154 async def async_auth_flow(155 self, request: httpx.Request156 ) -> typing.AsyncGenerator[httpx.Request, httpx.Response]:157 async with self._async_lock:158 request.headers["Authorization"] = "async-auth"159 yield request160161162@pytest.mark.anyio163async def test_basic_auth() -> None:164 url = "https://example.org/"165 auth = ("user", "password123")166 app = App()167168 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:169 response = await client.get(url, auth=auth)170171 assert response.status_code == 200172 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}173174175@pytest.mark.anyio176async def test_basic_auth_with_stream() -> None:177 """178 See: https://github.com/encode/httpx/pull/1312179 """180 url = "https://example.org/"181 auth = ("user", "password123")182 app = App()183184 async with httpx.AsyncClient(185 transport=httpx.MockTransport(app), auth=auth186 ) as client:187 async with client.stream("GET", url) as response:188 await response.aread()189190 assert response.status_code == 200191 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}192193194@pytest.mark.anyio195async def test_basic_auth_in_url() -> None:196 url = "https://user:password123@example.org/"197 app = App()198199 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:200 response = await client.get(url)201202 assert response.status_code == 200203 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}204205206@pytest.mark.anyio207async def test_basic_auth_on_session() -> None:208 url = "https://example.org/"209 auth = ("user", "password123")210 app = App()211212 async with httpx.AsyncClient(213 transport=httpx.MockTransport(app), auth=auth214 ) as client:215 response = await client.get(url)216217 assert response.status_code == 200218 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}219220221@pytest.mark.anyio222async def test_custom_auth() -> None:223 url = "https://example.org/"224 app = App()225226 def auth(request: httpx.Request) -> httpx.Request:227 request.headers["Authorization"] = "Token 123"228 return request229230 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:231 response = await client.get(url, auth=auth)232233 assert response.status_code == 200234 assert response.json() == {"auth": "Token 123"}235236237def test_netrc_auth_credentials_exist() -> None:238 """239 When netrc auth is being used and a request is made to a host that is240 in the netrc file, then the relevant credentials should be applied.241 """242 netrc_file = str(FIXTURES_DIR / ".netrc")243 url = "http://netrcexample.org"244 app = App()245 auth = httpx.NetRCAuth(netrc_file)246247 with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:248 response = client.get(url)249250 assert response.status_code == 200251 assert response.json() == {252 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"253 }254255256def test_netrc_auth_credentials_do_not_exist() -> None:257 """258 When netrc auth is being used and a request is made to a host that is259 not in the netrc file, then no credentials should be applied.260 """261 netrc_file = str(FIXTURES_DIR / ".netrc")262 url = "http://example.org"263 app = App()264 auth = httpx.NetRCAuth(netrc_file)265266 with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:267 response = client.get(url)268269 assert response.status_code == 200270 assert response.json() == {"auth": None}271272273@pytest.mark.skipif(274 sys.version_info < (3, 11),275 reason="netrc files without a password are invalid with Python < 3.11",276)277def test_netrc_auth_nopassword() -> None: # pragma: no cover278 """279 Python has different netrc parsing behaviours with different versions.280 For Python 3.11+ a netrc file with no password is valid. In this case281 we want to check that we allow the netrc auth, and simply don't provide282 any credentials in the request.283 """284 netrc_file = str(FIXTURES_DIR / ".netrc-nopassword")285 url = "http://example.org"286 app = App()287 auth = httpx.NetRCAuth(netrc_file)288289 with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:290 response = client.get(url)291292 assert response.status_code == 200293 assert response.json() == {"auth": None}294295296@pytest.mark.skipif(297 sys.version_info >= (3, 11),298 reason="netrc files without a password are valid from Python >= 3.11",299)300def test_netrc_auth_nopassword_parse_error() -> None: # pragma: no cover301 """302 Python has different netrc parsing behaviours with different versions.303 For Python < 3.11 a netrc file with no password is invalid. In this case304 we want to allow the parse error to be raised.305 """306 netrc_file = str(FIXTURES_DIR / ".netrc-nopassword")307 with pytest.raises(netrc.NetrcParseError):308 httpx.NetRCAuth(netrc_file)309310311@pytest.mark.anyio312async def test_auth_disable_per_request() -> None:313 url = "https://example.org/"314 auth = ("user", "password123")315 app = App()316317 async with httpx.AsyncClient(318 transport=httpx.MockTransport(app), auth=auth319 ) as client:320 response = await client.get(url, auth=None)321322 assert response.status_code == 200323 assert response.json() == {"auth": None}324325326def test_auth_hidden_url() -> None:327 url = "http://example-username:example-password@example.org/"328 expected = "URL('http://example-username:[secure]@example.org/')"329 assert url == httpx.URL(url)330 assert expected == repr(httpx.URL(url))331332333@pytest.mark.anyio334async def test_auth_hidden_header() -> None:335 url = "https://example.org/"336 auth = ("example-username", "example-password")337 app = App()338339 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:340 response = await client.get(url, auth=auth)341342 assert "'authorization': '[secure]'" in str(response.request.headers)343344345@pytest.mark.anyio346async def test_auth_property() -> None:347 app = App()348349 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:350 assert client.auth is None351352 client.auth = ("user", "password123") # type: ignore353 assert isinstance(client.auth, httpx.BasicAuth)354355 url = "https://example.org/"356 response = await client.get(url)357 assert response.status_code == 200358 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}359360361@pytest.mark.anyio362async def test_auth_invalid_type() -> None:363 app = App()364365 with pytest.raises(TypeError):366 client = httpx.AsyncClient(367 transport=httpx.MockTransport(app),368 auth="not a tuple, not a callable", # type: ignore369 )370371 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:372 with pytest.raises(TypeError):373 await client.get(auth="not a tuple, not a callable") # type: ignore374375 with pytest.raises(TypeError):376 client.auth = "not a tuple, not a callable" # type: ignore377378379@pytest.mark.anyio380async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:381 url = "https://example.org/"382 auth = httpx.DigestAuth(username="user", password="password123")383 app = App()384385 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:386 response = await client.get(url, auth=auth)387388 assert response.status_code == 200389 assert response.json() == {"auth": None}390 assert len(response.history) == 0391392393def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:394 url = "https://example.org/"395 auth = httpx.DigestAuth(username="user", password="password123")396 auth_header = "Token ..."397 app = App(auth_header=auth_header, status_code=401)398399 client = httpx.Client(transport=httpx.MockTransport(app))400 response = client.get(url, auth=auth)401402 assert response.status_code == 401403 assert response.json() == {"auth": None}404 assert len(response.history) == 0405406407@pytest.mark.anyio408async def test_digest_auth_200_response_including_digest_auth_header() -> None:409 url = "https://example.org/"410 auth = httpx.DigestAuth(username="user", password="password123")411 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'412 app = App(auth_header=auth_header, status_code=200)413414 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:415 response = await client.get(url, auth=auth)416417 assert response.status_code == 200418 assert response.json() == {"auth": None}419 assert len(response.history) == 0420421422@pytest.mark.anyio423async def test_digest_auth_401_response_without_digest_auth_header() -> None:424 url = "https://example.org/"425 auth = httpx.DigestAuth(username="user", password="password123")426 app = App(auth_header="", status_code=401)427428 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:429 response = await client.get(url, auth=auth)430431 assert response.status_code == 401432 assert response.json() == {"auth": None}433 assert len(response.history) == 0434435436@pytest.mark.parametrize(437 "algorithm,expected_hash_length,expected_response_length",438 [439 ("MD5", 64, 32),440 ("MD5-SESS", 64, 32),441 ("SHA", 64, 40),442 ("SHA-SESS", 64, 40),443 ("SHA-256", 64, 64),444 ("SHA-256-SESS", 64, 64),445 ("SHA-512", 64, 128),446 ("SHA-512-SESS", 64, 128),447 ],448)449@pytest.mark.anyio450async def test_digest_auth(451 algorithm: str, expected_hash_length: int, expected_response_length: int452) -> None:453 url = "https://example.org/"454 auth = httpx.DigestAuth(username="user", password="password123")455 app = DigestApp(algorithm=algorithm)456457 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:458 response = await client.get(url, auth=auth)459460 assert response.status_code == 200461 assert len(response.history) == 1462463 authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]464 scheme, _, fields = authorization.partition(" ")465 assert scheme == "Digest"466467 response_fields = [field.strip() for field in fields.split(",")]468 digest_data = dict(field.split("=") for field in response_fields)469470 assert digest_data["username"] == '"user"'471 assert digest_data["realm"] == '"httpx@example.org"'472 assert "nonce" in digest_data473 assert digest_data["uri"] == '"/"'474 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes475 assert len(digest_data["opaque"]) == expected_hash_length + 2476 assert digest_data["algorithm"] == algorithm477 assert digest_data["qop"] == "auth"478 assert digest_data["nc"] == "00000001"479 assert len(digest_data["cnonce"]) == 16 + 2480481482@pytest.mark.anyio483async def test_digest_auth_no_specified_qop() -> None:484 url = "https://example.org/"485 auth = httpx.DigestAuth(username="user", password="password123")486 app = DigestApp(qop="")487488 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:489 response = await client.get(url, auth=auth)490491 assert response.status_code == 200492 assert len(response.history) == 1493494 authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]495 scheme, _, fields = authorization.partition(" ")496 assert scheme == "Digest"497498 response_fields = [field.strip() for field in fields.split(",")]499 digest_data = dict(field.split("=") for field in response_fields)500501 assert "qop" not in digest_data502 assert "nc" not in digest_data503 assert "cnonce" not in digest_data504 assert digest_data["username"] == '"user"'505 assert digest_data["realm"] == '"httpx@example.org"'506 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes507 assert digest_data["uri"] == '"/"'508 assert len(digest_data["response"]) == 64 + 2509 assert len(digest_data["opaque"]) == 64 + 2510 assert digest_data["algorithm"] == "SHA-256"511512513@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))514@pytest.mark.anyio515async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:516 url = "https://example.org/"517 auth = httpx.DigestAuth(username="user", password="password123")518 app = DigestApp(qop=qop)519520 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:521 response = await client.get(url, auth=auth)522523 assert response.status_code == 200524 assert len(response.history) == 1525526527@pytest.mark.anyio528async def test_digest_auth_qop_auth_int_not_implemented() -> None:529 url = "https://example.org/"530 auth = httpx.DigestAuth(username="user", password="password123")531 app = DigestApp(qop="auth-int")532533 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:534 with pytest.raises(NotImplementedError):535 await client.get(url, auth=auth)536537538@pytest.mark.anyio539async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:540 url = "https://example.org/"541 auth = httpx.DigestAuth(username="user", password="password123")542 app = DigestApp(qop="not-auth")543544 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:545 with pytest.raises(httpx.ProtocolError):546 await client.get(url, auth=auth)547548549@pytest.mark.anyio550async def test_digest_auth_incorrect_credentials() -> None:551 url = "https://example.org/"552 auth = httpx.DigestAuth(username="user", password="password123")553 app = DigestApp(send_response_after_attempt=2)554555 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:556 response = await client.get(url, auth=auth)557558 assert response.status_code == 401559 assert len(response.history) == 1560561562@pytest.mark.anyio563async def test_digest_auth_reuses_challenge() -> None:564 url = "https://example.org/"565 auth = httpx.DigestAuth(username="user", password="password123")566 app = DigestApp()567568 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:569 response_1 = await client.get(url, auth=auth)570 response_2 = await client.get(url, auth=auth)571572 assert response_1.status_code == 200573 assert response_2.status_code == 200574575 assert len(response_1.history) == 1576 assert len(response_2.history) == 0577578579@pytest.mark.anyio580async def test_digest_auth_resets_nonce_count_after_401() -> None:581 url = "https://example.org/"582 auth = httpx.DigestAuth(username="user", password="password123")583 app = DigestApp()584585 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:586 response_1 = await client.get(url, auth=auth)587 assert response_1.status_code == 200588 assert len(response_1.history) == 1589590 first_nonce = parse_keqv_list(591 response_1.request.headers["Authorization"].split(", ")592 )["nonce"]593 first_nc = parse_keqv_list(594 response_1.request.headers["Authorization"].split(", ")595 )["nc"]596597 # with this we now force a 401 on a subsequent (but initial) request598 app.send_response_after_attempt = 2599Ruff linter: Use the default line-length (#2922)T-256before adoptionfd60b18
lines 600–601why, one step back600 # we expect the client again to try to authenticate,601 # i.e. the history length must be 1Bump coverage from 6.5.0 to 7.2.1 (#2614)dependabot[bot]before adoption988809a
lines 602–795why, one step back602 response_2 = await client.get(url, auth=auth)603 assert response_2.status_code == 200604 assert len(response_2.history) == 1605606 second_nonce = parse_keqv_list(607 response_2.request.headers["Authorization"].split(", ")608 )["nonce"]609 second_nc = parse_keqv_list(610 response_2.request.headers["Authorization"].split(", ")611 )["nc"]612613 assert first_nonce != second_nonce # ensures that the auth challenge was reset614 assert (615 first_nc == second_nc616 ) # ensures the nonce count is reset when the authentication failed617618619@pytest.mark.parametrize(620 "auth_header",621 [622 'Digest realm="httpx@example.org", qop="auth"', # missing fields623 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list624 ],625)626@pytest.mark.anyio627async def test_async_digest_auth_raises_protocol_error_on_malformed_header(628 auth_header: str,629) -> None:630 url = "https://example.org/"631 auth = httpx.DigestAuth(username="user", password="password123")632 app = App(auth_header=auth_header, status_code=401)633634 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:635 with pytest.raises(httpx.ProtocolError):636 await client.get(url, auth=auth)637638639@pytest.mark.parametrize(640 "auth_header",641 [642 'Digest realm="httpx@example.org", qop="auth"', # missing fields643 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list644 ],645)646def test_sync_digest_auth_raises_protocol_error_on_malformed_header(647 auth_header: str,648) -> None:649 url = "https://example.org/"650 auth = httpx.DigestAuth(username="user", password="password123")651 app = App(auth_header=auth_header, status_code=401)652653 with httpx.Client(transport=httpx.MockTransport(app)) as client:654 with pytest.raises(httpx.ProtocolError):655 client.get(url, auth=auth)656657658@pytest.mark.anyio659async def test_async_auth_history() -> None:660 """661 Test that intermediate requests sent as part of an authentication flow662 are recorded in the response history.663 """664 url = "https://example.org/"665 auth = RepeatAuth(repeat=2)666 app = App(auth_header="abc")667668 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:669 response = await client.get(url, auth=auth)670671 assert response.status_code == 200672 assert response.json() == {"auth": "Repeat abc.abc"}673674 assert len(response.history) == 2675 resp1, resp2 = response.history676 assert resp1.json() == {"auth": "Repeat 0"}677 assert resp2.json() == {"auth": "Repeat 1"}678679 assert len(resp2.history) == 1680 assert resp2.history == [resp1]681682 assert len(resp1.history) == 0683684685def test_sync_auth_history() -> None:686 """687 Test that intermediate requests sent as part of an authentication flow688 are recorded in the response history.689 """690 url = "https://example.org/"691 auth = RepeatAuth(repeat=2)692 app = App(auth_header="abc")693694 with httpx.Client(transport=httpx.MockTransport(app)) as client:695 response = client.get(url, auth=auth)696697 assert response.status_code == 200698 assert response.json() == {"auth": "Repeat abc.abc"}699700 assert len(response.history) == 2701 resp1, resp2 = response.history702 assert resp1.json() == {"auth": "Repeat 0"}703 assert resp2.json() == {"auth": "Repeat 1"}704705 assert len(resp2.history) == 1706 assert resp2.history == [resp1]707708 assert len(resp1.history) == 0709710711class ConsumeBodyTransport(httpx.MockTransport):712 async def handle_async_request(self, request: httpx.Request) -> httpx.Response:713 assert isinstance(request.stream, httpx.AsyncByteStream)714 [_ async for _ in request.stream]715 return self.handler(request) # type: ignore[return-value]716717718@pytest.mark.anyio719async def test_digest_auth_unavailable_streaming_body():720 url = "https://example.org/"721 auth = httpx.DigestAuth(username="user", password="password123")722 app = DigestApp()723724 async def streaming_body() -> typing.AsyncIterator[bytes]:725 yield b"Example request body" # pragma: no cover726727 async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:728 with pytest.raises(httpx.StreamConsumed):729 await client.post(url, content=streaming_body(), auth=auth)730731732@pytest.mark.anyio733async def test_async_auth_reads_response_body() -> None:734 """735 Test that we can read the response body in an auth flow if `requires_response_body`736 is set.737 """738 url = "https://example.org/"739 auth = ResponseBodyAuth("xyz")740 app = App()741742 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:743 response = await client.get(url, auth=auth)744745 assert response.status_code == 200746 assert response.json() == {"auth": '{"auth": "xyz"}'}747748749def test_sync_auth_reads_response_body() -> None:750 """751 Test that we can read the response body in an auth flow if `requires_response_body`752 is set.753 """754 url = "https://example.org/"755 auth = ResponseBodyAuth("xyz")756 app = App()757758 with httpx.Client(transport=httpx.MockTransport(app)) as client:759 response = client.get(url, auth=auth)760761 assert response.status_code == 200762 assert response.json() == {"auth": '{"auth": "xyz"}'}763764765@pytest.mark.anyio766async def test_async_auth() -> None:767 """768 Test that we can use an auth implementation specific to the async case, to769 support cases that require performing I/O or using concurrency primitives (such770 as checking a disk-based cache or fetching a token from a remote auth server).771 """772 url = "https://example.org/"773 auth = SyncOrAsyncAuth()774 app = App()775776 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:777 response = await client.get(url, auth=auth)778779 assert response.status_code == 200780 assert response.json() == {"auth": "async-auth"}781782783def test_sync_auth() -> None:784 """785 Test that we can use an auth implementation specific to the sync case.786 """787 url = "https://example.org/"788 auth = SyncOrAsyncAuth()789 app = App()790791 with httpx.Client(transport=httpx.MockTransport(app)) as client:792 response = client.get(url, auth=auth)793794 assert response.status_code == 200795 assert response.json() == {"auth": "sync-auth"}