test_auth.py
This file
Path
tests/client/test_auth.py
706 lines · 22.3 KiB · Python
Last changed by
Transport API as plain `request -> response` method. (#1840)Tom Christiebefore adoptionff9813e
History of this fileTake it
The walk stopped after 200 commits: lines older than 32d37cf point at it.
Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 1–156why, one step back1"""2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncio7import hashlib8import os9import threading10import typing1112import pytest1314import httpx15from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, Response1617from ..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 }77 return Response(401, headers=headers)787980class RepeatAuth(Auth):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 = repeat9293 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:94 nonces = []9596 for index in range(self.repeat):97 request.headers["Authorization"] = f"Repeat {index}"98 response = yield request99 nonces.append(response.headers["www-authenticate"])100101 key = ".".join(nonces)102 request.headers["Authorization"] = f"Repeat {key}"103 yield request104105106class ResponseBodyAuth(Auth):107 """108 A mock authentication scheme that requires clients to send an 'Authorization'109 header, then send back the contents of the response in the 'Authorization'110 header.111 """112113 requires_response_body = True114115 def __init__(self, token):116 self.token = token117118 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:119 request.headers["Authorization"] = self.token120 response = yield request121 data = response.text122 request.headers["Authorization"] = data123 yield request124125126class SyncOrAsyncAuth(Auth):127 """128 A mock authentication scheme that uses a different implementation for the129 sync and async cases.130 """131132 def __init__(self) -> None:133 self._lock = threading.Lock()134 self._async_lock = asyncio.Lock()135136 def sync_auth_flow(137 self, request: Request138 ) -> typing.Generator[Request, Response, None]:139 with self._lock:140 request.headers["Authorization"] = "sync-auth"141 yield request142143 async def async_auth_flow(144 self, request: Request145 ) -> typing.AsyncGenerator[Request, Response]:146 async with self._async_lock:147 request.headers["Authorization"] = "async-auth"148 yield request149150151@pytest.mark.asyncio152async def test_basic_auth() -> None:153 url = "https://example.org/"154 auth = ("tomchristie", "password123")155 app = App()156Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 157why, one step back157 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 158–172why, one step back158 response = await client.get(url, auth=auth)159160 assert response.status_code == 200161 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}162163164@pytest.mark.asyncio165async def test_basic_auth_with_stream() -> None:166 """167 See: https://github.com/encode/httpx/pull/1312168 """169 url = "https://example.org/"170 auth = ("tomchristie", "password123")171 app = App()172Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 173–175why, one step back173 async with httpx.AsyncClient(174 transport=httpx.MockTransport(app), auth=auth175 ) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 176–187why, one step back176 async with client.stream("GET", url) as response:177 await response.aread()178179 assert response.status_code == 200180 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}181182183@pytest.mark.asyncio184async def test_basic_auth_in_url() -> None:185 url = "https://tomchristie:password123@example.org/"186 app = App()187Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 188why, one step back188 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 189–200why, one step back189 response = await client.get(url)190191 assert response.status_code == 200192 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}193194195@pytest.mark.asyncio196async def test_basic_auth_on_session() -> None:197 url = "https://example.org/"198 auth = ("tomchristie", "password123")199 app = App()200Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 201–203why, one step back201 async with httpx.AsyncClient(202 transport=httpx.MockTransport(app), auth=auth203 ) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 204–218why, one step back204 response = await client.get(url)205206 assert response.status_code == 200207 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}208209210@pytest.mark.asyncio211async def test_custom_auth() -> None:212 url = "https://example.org/"213 app = App()214215 def auth(request: Request) -> Request:216 request.headers["Authorization"] = "Token 123"217 return request218Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 219why, one step back219 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 220–231why, one step back220 response = await client.get(url, auth=auth)221222 assert response.status_code == 200223 assert response.json() == {"auth": "Token 123"}224225226@pytest.mark.asyncio227async def test_netrc_auth() -> None:228 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")229 url = "http://netrcexample.org"230 app = App()231Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 232why, one step back232 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 233–246why, one step back233 response = await client.get(url)234235 assert response.status_code == 200236 assert response.json() == {237 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"238 }239240241@pytest.mark.asyncio242async def test_auth_header_has_priority_over_netrc() -> None:243 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")244 url = "http://netrcexample.org"245 app = App()246Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 247why, one step back247 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 248–260why, one step back248 response = await client.get(url, headers={"Authorization": "Override"})249250 assert response.status_code == 200251 assert response.json() == {"auth": "Override"}252253254@pytest.mark.asyncio255async def test_trust_env_auth() -> None:256 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")257 url = "http://netrcexample.org"258 app = App()259260 async with httpx.AsyncClient(Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 261why, one step back261 transport=httpx.MockTransport(app), trust_env=FalseSmall namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 262–268why, one step back262 ) as client:263 response = await client.get(url)264265 assert response.status_code == 200266 assert response.json() == {"auth": None}267268 async with httpx.AsyncClient(Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 269why, one step back269 transport=httpx.MockTransport(app), trust_env=TrueSmall namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 270–284why, one step back270 ) as client:271 response = await client.get(url)272273 assert response.status_code == 200274 assert response.json() == {275 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"276 }277278279@pytest.mark.asyncio280async def test_auth_disable_per_request() -> None:281 url = "https://example.org/"282 auth = ("tomchristie", "password123")283 app = App()284Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 285–287why, one step back285 async with httpx.AsyncClient(286 transport=httpx.MockTransport(app), auth=auth287 ) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 288–306why, one step back288 response = await client.get(url, auth=None)289290 assert response.status_code == 200291 assert response.json() == {"auth": None}292293294def test_auth_hidden_url() -> None:295 url = "http://example-username:example-password@example.org/"296 expected = "URL('http://example-username:[secure]@example.org/')"297 assert url == URL(url)298 assert expected == repr(URL(url))299300301@pytest.mark.asyncio302async def test_auth_hidden_header() -> None:303 url = "https://example.org/"304 auth = ("example-username", "example-password")305 app = App()306Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 307why, one step back307 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 308–316why, one step back308 response = await client.get(url, auth=auth)309310 assert "'authorization': '[secure]'" in str(response.request.headers)311312313@pytest.mark.asyncio314async def test_auth_property() -> None:315 app = App()316Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 317why, one step back317 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 318–334why, one step back318 assert client.auth is None319320 client.auth = ("tomchristie", "password123") # type: ignore321 assert isinstance(client.auth, BasicAuth)322323 url = "https://example.org/"324 response = await client.get(url)325 assert response.status_code == 200326 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}327328329@pytest.mark.asyncio330async def test_auth_invalid_type() -> None:331 app = App()332333 with pytest.raises(TypeError):334 client = httpx.AsyncClient(Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 335why, one step back335 transport=httpx.MockTransport(app),Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 336–338why, one step back336 auth="not a tuple, not a callable", # type: ignore337 )338Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 339why, one step back339 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 340–352why, one step back340 with pytest.raises(TypeError):341 await client.get(auth="not a tuple, not a callable") # type: ignore342343 with pytest.raises(TypeError):344 client.auth = "not a tuple, not a callable" # type: ignore345346347@pytest.mark.asyncio348async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:349 url = "https://example.org/"350 auth = DigestAuth(username="tomchristie", password="password123")351 app = App()352Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 353why, one step back353 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 354–366why, one step back354 response = await client.get(url, auth=auth)355356 assert response.status_code == 200357 assert response.json() == {"auth": None}358 assert len(response.history) == 0359360361def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:362 url = "https://example.org/"363 auth = DigestAuth(username="tomchristie", password="password123")364 auth_header = "Token ..."365 app = App(auth_header=auth_header, status_code=401)366Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 367why, one step back367 client = httpx.Client(transport=httpx.MockTransport(app))Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 368–381why, one step back368 response = client.get(url, auth=auth)369370 assert response.status_code == 401371 assert response.json() == {"auth": None}372 assert len(response.history) == 0373374375@pytest.mark.asyncio376async def test_digest_auth_200_response_including_digest_auth_header() -> None:377 url = "https://example.org/"378 auth = DigestAuth(username="tomchristie", password="password123")379 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'380 app = App(auth_header=auth_header, status_code=200)381Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 382why, one step back382 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 383–395why, one step back383 response = await client.get(url, auth=auth)384385 assert response.status_code == 200386 assert response.json() == {"auth": None}387 assert len(response.history) == 0388389390@pytest.mark.asyncio391async def test_digest_auth_401_response_without_digest_auth_header() -> None:392 url = "https://example.org/"393 auth = DigestAuth(username="tomchristie", password="password123")394 app = App(auth_header="", status_code=401)395Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 396why, one step back396 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 397–424why, one step back397 response = await client.get(url, auth=auth)398399 assert response.status_code == 401400 assert response.json() == {"auth": None}401 assert len(response.history) == 0402403404@pytest.mark.parametrize(405 "algorithm,expected_hash_length,expected_response_length",406 [407 ("MD5", 64, 32),408 ("MD5-SESS", 64, 32),409 ("SHA", 64, 40),410 ("SHA-SESS", 64, 40),411 ("SHA-256", 64, 64),412 ("SHA-256-SESS", 64, 64),413 ("SHA-512", 64, 128),414 ("SHA-512-SESS", 64, 128),415 ],416)417@pytest.mark.asyncio418async def test_digest_auth(419 algorithm: str, expected_hash_length: int, expected_response_length: int420) -> None:421 url = "https://example.org/"422 auth = DigestAuth(username="tomchristie", password="password123")423 app = DigestApp(algorithm=algorithm)424Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 425why, one step back425 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 426–455why, one step back426 response = await client.get(url, auth=auth)427428 assert response.status_code == 200429 assert len(response.history) == 1430431 authorization = typing.cast(dict, response.json())["auth"]432 scheme, _, fields = authorization.partition(" ")433 assert scheme == "Digest"434435 response_fields = [field.strip() for field in fields.split(",")]436 digest_data = dict(field.split("=") for field in response_fields)437438 assert digest_data["username"] == '"tomchristie"'439 assert digest_data["realm"] == '"httpx@example.org"'440 assert "nonce" in digest_data441 assert digest_data["uri"] == '"/"'442 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes443 assert len(digest_data["opaque"]) == expected_hash_length + 2444 assert digest_data["algorithm"] == algorithm445 assert digest_data["qop"] == "auth"446 assert digest_data["nc"] == "00000001"447 assert len(digest_data["cnonce"]) == 16 + 2448449450@pytest.mark.asyncio451async def test_digest_auth_no_specified_qop() -> None:452 url = "https://example.org/"453 auth = DigestAuth(username="tomchristie", password="password123")454 app = DigestApp(qop="")455Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 456why, one step back456 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 457–487why, one step back457 response = await client.get(url, auth=auth)458459 assert response.status_code == 200460 assert len(response.history) == 1461462 authorization = typing.cast(dict, response.json())["auth"]463 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)468469 assert "qop" not in digest_data470 assert "nc" not in digest_data471 assert "cnonce" not in digest_data472 assert digest_data["username"] == '"tomchristie"'473 assert digest_data["realm"] == '"httpx@example.org"'474 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes475 assert digest_data["uri"] == '"/"'476 assert len(digest_data["response"]) == 64 + 2477 assert len(digest_data["opaque"]) == 64 + 2478 assert digest_data["algorithm"] == "SHA-256"479480481@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))482@pytest.mark.asyncio483async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:484 url = "https://example.org/"485 auth = DigestAuth(username="tomchristie", password="password123")486 app = DigestApp(qop=qop)487Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 488why, one step back488 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 489–500why, one step back489 response = await client.get(url, auth=auth)490491 assert response.status_code == 200492 assert len(response.history) == 1493494495@pytest.mark.asyncio496async def test_digest_auth_qop_auth_int_not_implemented() -> None:497 url = "https://example.org/"498 auth = DigestAuth(username="tomchristie", password="password123")499 app = DigestApp(qop="auth-int")500Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 501why, one step back501 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 502–511why, one step back502 with pytest.raises(NotImplementedError):503 await client.get(url, auth=auth)504505506@pytest.mark.asyncio507async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:508 url = "https://example.org/"509 auth = DigestAuth(username="tomchristie", password="password123")510 app = DigestApp(qop="not-auth")511Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 512why, one step back512 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 513–522why, one step back513 with pytest.raises(ProtocolError):514 await client.get(url, auth=auth)515516517@pytest.mark.asyncio518async def test_digest_auth_incorrect_credentials() -> None:519 url = "https://example.org/"520 auth = DigestAuth(username="tomchristie", password="password123")521 app = DigestApp(send_response_after_attempt=2)522Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 523why, one step back523 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 524–544why, one step back524 response = await client.get(url, auth=auth)525526 assert response.status_code == 401527 assert len(response.history) == 1528529530@pytest.mark.parametrize(531 "auth_header",532 [533 'Digest realm="httpx@example.org", qop="auth"', # missing fields534 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list535 ],536)537@pytest.mark.asyncio538async def test_async_digest_auth_raises_protocol_error_on_malformed_header(539 auth_header: str,540) -> None:541 url = "https://example.org/"542 auth = DigestAuth(username="tomchristie", password="password123")543 app = App(auth_header=auth_header, status_code=401)544Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 545why, one step back545 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 546–563why, one step back546 with pytest.raises(ProtocolError):547 await client.get(url, auth=auth)548549550@pytest.mark.parametrize(551 "auth_header",552 [553 'Digest realm="httpx@example.org", qop="auth"', # missing fields554 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list555 ],556)557def test_sync_digest_auth_raises_protocol_error_on_malformed_header(558 auth_header: str,559) -> None:560 url = "https://example.org/"561 auth = DigestAuth(username="tomchristie", password="password123")562 app = App(auth_header=auth_header, status_code=401)563Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 564why, one step back564 with httpx.Client(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 565–578why, one step back565 with pytest.raises(ProtocolError):566 client.get(url, auth=auth)567568569@pytest.mark.asyncio570async def test_async_auth_history() -> None:571 """572 Test that intermediate requests sent as part of an authentication flow573 are recorded in the response history.574 """575 url = "https://example.org/"576 auth = RepeatAuth(repeat=2)577 app = App(auth_header="abc")578Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 579why, one step back579 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 580–604why, one step back580 response = await client.get(url, auth=auth)581582 assert response.status_code == 200583 assert response.json() == {"auth": "Repeat abc.abc"}584585 assert len(response.history) == 2586 resp1, resp2 = response.history587 assert resp1.json() == {"auth": "Repeat 0"}588 assert resp2.json() == {"auth": "Repeat 1"}589590 assert len(resp2.history) == 1591 assert resp2.history == [resp1]592593 assert len(resp1.history) == 0594595596def test_sync_auth_history() -> None:597 """598 Test that intermediate requests sent as part of an authentication flow599 are recorded in the response history.600 """601 url = "https://example.org/"602 auth = RepeatAuth(repeat=2)603 app = App(auth_header="abc")604Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 605why, one step back605 with httpx.Client(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 606–621why, one step back606 response = client.get(url, auth=auth)607608 assert response.status_code == 200609 assert response.json() == {"auth": "Repeat abc.abc"}610611 assert len(response.history) == 2612 resp1, resp2 = response.history613 assert resp1.json() == {"auth": "Repeat 0"}614 assert resp2.json() == {"auth": "Repeat 1"}615616 assert len(resp2.history) == 1617 assert resp2.history == [resp1]618619 assert len(resp1.history) == 0620621Transport API as plain `request -> response` method. (#1840)Tom Christiebefore adoptionff9813e
lines 622–628why, one step back622class ConsumeBodyTransport(httpx.MockTransport):623 async def handle_async_request(self, request: Request) -> Response:624 assert isinstance(request.stream, httpx.AsyncByteStream)625 [_ async for _ in request.stream]626 return self.handler(request)627628Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 629–637why, one step back629@pytest.mark.asyncio630async def test_digest_auth_unavailable_streaming_body():631 url = "https://example.org/"632 auth = DigestAuth(username="tomchristie", password="password123")633 app = DigestApp()634635 async def streaming_body():636 yield b"Example request body" # pragma: nocover637Transport API as plain `request -> response` method. (#1840)Tom Christiebefore adoptionff9813e
line 638why, one step back638 async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
line 639why, one step back639 with pytest.raises(httpx.StreamConsumed):Escalate the distinction between data=... and content=... to be stricter (#1573)Tom Christiebefore adoption397aad9
line 640why, one step back640 await client.post(url, content=streaming_body(), auth=auth)Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 641–652why, one step back641642643@pytest.mark.asyncio644async def test_async_auth_reads_response_body() -> None:645 """646 Test that we can read the response body in an auth flow if `requires_response_body`647 is set.648 """649 url = "https://example.org/"650 auth = ResponseBodyAuth("xyz")651 app = App()652Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 653why, one step back653 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 654–668why, one step back654 response = await client.get(url, auth=auth)655656 assert response.status_code == 200657 assert response.json() == {"auth": '{"auth": "xyz"}'}658659660def test_sync_auth_reads_response_body() -> None:661 """662 Test that we can read the response body in an auth flow if `requires_response_body`663 is set.664 """665 url = "https://example.org/"666 auth = ResponseBodyAuth("xyz")667 app = App()668Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 669why, one step back669 with httpx.Client(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 670–686why, one step back670 response = client.get(url, auth=auth)671672 assert response.status_code == 200673 assert response.json() == {"auth": '{"auth": "xyz"}'}674675676@pytest.mark.asyncio677async def test_async_auth() -> None:678 """679 Test that we can use an auth implementation specific to the async case, to680 support cases that require performing I/O or using concurrency primitives (such681 as checking a disk-based cache or fetching a token from a remote auth server).682 """683 url = "https://example.org/"684 auth = SyncOrAsyncAuth()685 app = App()686Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 687why, one step back687 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 688–701why, one step back688 response = await client.get(url, auth=auth)689690 assert response.status_code == 200691 assert response.json() == {"auth": "async-auth"}692693694def test_sync_auth() -> None:695 """696 Test that we can use an auth implementation specific to the sync case.697 """698 url = "https://example.org/"699 auth = SyncOrAsyncAuth()700 app = App()701Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 702why, one step back702 with httpx.Client(transport=httpx.MockTransport(app)) as client:Small namedtuple refactor (#1329)Johannesbefore adoption32d37cf
lines 703–706why, one step back703 response = client.get(url, auth=auth)704705 assert response.status_code == 200706 assert response.json() == {"auth": "sync-auth"}