test_auth.py
This file
Path
tests/client/test_auth.py
699 lines · 22.1 KiB · Python
Last changed by
Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
History of this fileTake it
The walk stopped after 200 commits: lines older than 330a825 point at it.
Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
lines 1–6why, one step back1"""2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncioPin isort version (#1053)Josep Cugatbefore adoption330a825
lines 7–8why, one step back7import hashlib8import osAdd support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
line 9why, one step back9import threadingPin isort version (#1053)Josep Cugatbefore adoption330a825
lines 10–13why, one step back10import typing1112import pytest13Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 14why, one step back14import httpxDrop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 15why, one step back15from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, ResponsePin isort version (#1053)Josep Cugatbefore adoption330a825
line 16why, one step back16Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 17why, one step back17from ..common import FIXTURES_DIRPin isort version (#1053)Josep Cugatbefore adoption330a825
line 18why, one step back18Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 19why, one step back19Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
lines 20–21why, one step back20class App:21 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 22–24why, one step back22 self.auth_header = auth_header23 self.status_code = status_code24Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
lines 25–27why, one step back25 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")}Support Response(text=...), Response(html=...), Response(json=...) (#1297)Tom Christiebefore adoptionf3c2941
line 28why, one step back28 return httpx.Response(self.status_code, headers=headers, json=data)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 29–30why, one step back2930Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 31why, one step back31class DigestApp:Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 32–44why, one step back32 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 = 044Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 45why, one step back45 def __call__(self, request: httpx.Request) -> httpx.Response:Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 46why, one step back46 if self._response_count < self.send_response_after_attempt:Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 47why, one step back47 return self.challenge_send(request)Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 48why, one step back48Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 49why, one step back49 data = {"auth": request.headers.get("Authorization")}Support Response(text=...), Response(html=...), Response(json=...) (#1297)Tom Christiebefore adoptionf3c2941
line 50why, one step back50 return httpx.Response(200, json=data)Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 51why, one step back51Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 52why, one step back52 def challenge_send(self, request: httpx.Request) -> httpx.Response:Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 53–73why, one step back53 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 )73Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
lines 74–77why, one step back74 headers = {75 "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',76 }77 return Response(401, headers=headers)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 78–125why, one step back787980class 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 request124125Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
lines 126–150why, one step back126class 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 request149150Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 151–154why, one step back151@pytest.mark.asyncio152async def test_basic_auth() -> None:153 url = "https://example.org/"154 auth = ("tomchristie", "password123")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 155why, one step back155 app = App()Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 156why, one step back156Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 157why, one step back157 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 158why, one step back158 response = await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 159–164why, one step back159160 assert response.status_code == 200161 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}162163164@pytest.mark.asyncioFix stream unsetting auth (#1312)Tom Christiebefore adoptiond25f2bf
lines 165–172why, one step back165async 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:Fix stream unsetting auth (#1312)Tom Christiebefore adoptiond25f2bf
line 176why, one step back176 async with client.stream("GET", url) as response:Fix warning test case (#1322)Tom Christiebefore adoption320bfe1
line 177why, one step back177 await response.aread()Fix stream unsetting auth (#1312)Tom Christiebefore adoptiond25f2bf
lines 178–183why, one step back178179 assert response.status_code == 200180 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}181182183@pytest.mark.asyncioPin isort version (#1053)Josep Cugatbefore adoption330a825
lines 184–185why, one step back184async def test_basic_auth_in_url() -> None:185 url = "https://tomchristie:password123@example.org/"Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 186why, one step back186 app = App()Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 187why, one step back187Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 188why, one step back188 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 189why, one step back189 response = await client.get(url)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 190–198why, one step back190191 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")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 199why, one step back199 app = App()Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 200why, one step back200Add `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:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 204why, one step back204 response = await client.get(url)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 205–212why, one step back205206 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/"Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 213why, one step back213 app = App()Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 214–218why, one step back214215 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:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 220why, one step back220 response = await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 221–227why, one step back221222 assert response.status_code == 200223 assert response.json() == {"auth": "Token 123"}224225226@pytest.mark.asyncio227async def test_netrc_auth() -> None:Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 228why, one step back228 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 229why, one step back229 url = "http://netrcexample.org"Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 230why, one step back230 app = App()Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 231why, one step back231Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 232why, one step back232 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 233why, one step back233 response = await client.get(url)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 234–242why, one step back234235 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:Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 243why, one step back243 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 244why, one step back244 url = "http://netrcexample.org"Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 245why, one step back245 app = App()Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 246why, one step back246Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 247why, one step back247 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 248why, one step back248 response = await client.get(url, headers={"Authorization": "Override"})Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 249–255why, one step back249250 assert response.status_code == 200251 assert response.json() == {"auth": "Override"}252253254@pytest.mark.asyncio255async def test_trust_env_auth() -> None:Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
line 256why, one step back256 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 257why, one step back257 url = "http://netrcexample.org"Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 258why, one step back258 app = App()Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 259why, one step back259Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 260why, one step back260 async with httpx.AsyncClient(Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 261why, one step back261 transport=httpx.MockTransport(app), trust_env=FalseClosing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 262–263why, one step back262 ) as client:263 response = await client.get(url)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 264–267why, one step back264265 assert response.status_code == 200266 assert response.json() == {"auth": None}267Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 268why, one step back268 async with httpx.AsyncClient(Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 269why, one step back269 transport=httpx.MockTransport(app), trust_env=TrueClosing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 270–271why, one step back270 ) as client:271 response = await client.get(url)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 272–278why, one step back272273 assert response.status_code == 200274 assert response.json() == {275 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"276 }277278Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0
lines 279–282why, one step back279@pytest.mark.asyncio280async def test_auth_disable_per_request() -> None:281 url = "https://example.org/"282 auth = ("tomchristie", "password123")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 283why, one step back283 app = App()Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0
line 284why, one step back284Add `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:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 288why, one step back288 response = await client.get(url, auth=None)Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0
lines 289–293why, one step back289290 assert response.status_code == 200291 assert response.json() == {"auth": None}292293Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 294–304why, one step back294def 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")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 305why, one step back305 app = App()Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 306why, one step back306Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 307why, one step back307 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 308why, one step back308 response = await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 309–313why, one step back309310 assert "'authorization': '[secure]'" in str(response.request.headers)311312313@pytest.mark.asyncioAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 314why, one step back314async def test_auth_property() -> None:Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
lines 315–316why, one step back315 app = App()316Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 317why, one step back317 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 318why, one step back318 assert client.auth is NoneAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 319why, one step back319Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 320–321why, one step back320 client.auth = ("tomchristie", "password123") # type: ignore321 assert isinstance(client.auth, BasicAuth)Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 322why, one step back322Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 323–326why, one step back323 url = "https://example.org/"324 response = await client.get(url)325 assert response.status_code == 200326 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
lines 327–330why, one step back327328329@pytest.mark.asyncio330async def test_auth_invalid_type() -> None:Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
lines 331–332why, one step back331 app = App()332Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 333why, one step back333 with pytest.raises(TypeError):Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 334why, one step back334 client = httpx.AsyncClient(Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 335why, one step back335 transport=httpx.MockTransport(app),Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
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:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 340–341why, one step back340 with pytest.raises(TypeError):341 await client.get(auth="not a tuple, not a callable") # type: ignoreAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 342why, one step back342Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 343–344why, one step back343 with pytest.raises(TypeError):344 client.auth = "not a tuple, not a callable" # type: ignoreAdd `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6
line 345why, one step back345Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 346–350why, one step back346347@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")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 351why, one step back351 app = App()Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 352why, one step back352Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 353why, one step back353 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 354why, one step back354 response = await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 355–360why, one step back355356 assert response.status_code == 200357 assert response.json() == {"auth": None}358 assert len(response.history) == 0359360Handle multiple auth headers correctly (#1240)Tom Christiebefore adoption33d339a
lines 361–363why, one step back361def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:362 url = "https://example.org/"363 auth = DigestAuth(username="tomchristie", password="password123")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
lines 364–365why, one step back364 auth_header = "Token ..."365 app = App(auth_header=auth_header, status_code=401)Handle multiple auth headers correctly (#1240)Tom Christiebefore adoption33d339a
line 366why, one step back366Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 367why, one step back367 client = httpx.Client(transport=httpx.MockTransport(app))Handle multiple auth headers correctly (#1240)Tom Christiebefore adoption33d339a
lines 368–374why, 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) == 0373374Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 375–378why, one step back375@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")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
lines 379–380why, one step back379 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'380 app = App(auth_header=auth_header, status_code=200)Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 381why, one step back381Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 382why, one step back382 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 383why, one step back383 response = await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 384–393why, one step back384385 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")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 394why, one step back394 app = App(auth_header="", status_code=401)Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 395why, one step back395Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 396why, one step back396 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 397why, one step back397 response = await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 398–422why, one step back398399 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")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 423why, one step back423 app = DigestApp(algorithm=algorithm)Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 424why, one step back424Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 425why, one step back425 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 426why, one step back426 response = await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 427–453why, one step back427428 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")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 454why, one step back454 app = DigestApp(qop="")Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 455why, one step back455Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 456why, one step back456 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 457why, one step back457 response = await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 458–485why, one step back458459 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")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 486why, one step back486 app = DigestApp(qop=qop)Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 487why, one step back487Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 488why, one step back488 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 489why, one step back489 response = await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 490–498why, one step back490491 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")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 499why, one step back499 app = DigestApp(qop="auth-int")Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 500why, one step back500Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 501why, one step back501 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 502–503why, one step back502 with pytest.raises(NotImplementedError):503 await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 504–509why, one step back504505506@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")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 510why, one step back510 app = DigestApp(qop="not-auth")Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 511why, one step back511Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 512why, one step back512 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 513–514why, one step back513 with pytest.raises(ProtocolError):514 await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 515–520why, one step back515516517@pytest.mark.asyncio518async def test_digest_auth_incorrect_credentials() -> None:519 url = "https://example.org/"520 auth = DigestAuth(username="tomchristie", password="password123")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 521why, one step back521 app = DigestApp(send_response_after_attempt=2)Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 522why, one step back522Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 523why, one step back523 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 524why, one step back524 response = await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 525–532why, one step back525526 assert response.status_code == 401527 assert len(response.history) == 1528529530@pytest.mark.parametrize(531 "auth_header",532 [Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
lines 533–534why, one step back533 'Digest realm="httpx@example.org", qop="auth"', # missing fields534 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields listPin isort version (#1053)Josep Cugatbefore adoption330a825
lines 535–538why, one step back535 ],536)537@pytest.mark.asyncio538async def test_async_digest_auth_raises_protocol_error_on_malformed_header(Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 539why, one step back539 auth_header: str,Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 540–542why, one step back540) -> None:541 url = "https://example.org/"542 auth = DigestAuth(username="tomchristie", password="password123")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
lines 543–544why, one step back543 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:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 546–547why, one step back546 with pytest.raises(ProtocolError):547 await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 548–552why, one step back548549550@pytest.mark.parametrize(551 "auth_header",552 [Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
lines 553–554why, one step back553 'Digest realm="httpx@example.org", qop="auth"', # missing fields554 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields listPin isort version (#1053)Josep Cugatbefore adoption330a825
lines 555–557why, one step back555 ],556)557def test_sync_digest_auth_raises_protocol_error_on_malformed_header(Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 558why, one step back558 auth_header: str,Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 559–561why, one step back559) -> None:560 url = "https://example.org/"561 auth = DigestAuth(username="tomchristie", password="password123")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 562why, one step back562 app = App(auth_header=auth_header, status_code=401)Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 563why, one step back563Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 564why, one step back564 with httpx.Client(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 565–566why, one step back565 with pytest.raises(ProtocolError):566 client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 567–576why, one step back567568569@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)Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 577why, one step back577 app = App(auth_header="abc")Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 578why, one step back578Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 579why, one step back579 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 580–581why, one step back580 response = await client.get(url, auth=auth)581Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 582–602why, one step back582 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)Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 603why, one step back603 app = App(auth_header="abc")Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 604why, one step back604Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 605why, one step back605 with httpx.Client(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 606–607why, one step back606 response = client.get(url, auth=auth)607Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 608–625why, one step back608 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) == 0620621622@pytest.mark.asyncio623async def test_digest_auth_unavailable_streaming_body():624 url = "https://example.org/"625 auth = DigestAuth(username="tomchristie", password="password123")Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 626why, one step back626 app = DigestApp()Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 627–630why, one step back627628 async def streaming_body():629 yield b"Example request body" # pragma: nocover630Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 631why, one step back631 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 632why, one step back632 with pytest.raises(httpx.StreamConsumed):Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 633why, one step back633 await client.post(url, data=streaming_body(), auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 634–643why, one step back634635636@pytest.mark.asyncio637async def test_async_auth_reads_response_body() -> None:638 """639 Test that we can read the response body in an auth flow if `requires_response_body`640 is set.641 """642 url = "https://example.org/"643 auth = ResponseBodyAuth("xyz")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
lines 644–645why, one step back644 app = App()645Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 646why, one step back646 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
line 647why, one step back647 response = await client.get(url, auth=auth)Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 648–659why, one step back648649 assert response.status_code == 200650 assert response.json() == {"auth": '{"auth": "xyz"}'}651652653def test_sync_auth_reads_response_body() -> None:654 """655 Test that we can read the response body in an auth flow if `requires_response_body`656 is set.657 """658 url = "https://example.org/"659 auth = ResponseBodyAuth("xyz")Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 660why, one step back660 app = App()Pin isort version (#1053)Josep Cugatbefore adoption330a825
line 661why, one step back661Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 662why, one step back662 with httpx.Client(transport=httpx.MockTransport(app)) as client:Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 663–664why, one step back663 response = client.get(url, auth=auth)664Pin isort version (#1053)Josep Cugatbefore adoption330a825
lines 665–666why, one step back665 assert response.status_code == 200666 assert response.json() == {"auth": '{"auth": "xyz"}'}Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
lines 667–677why, one step back667668669@pytest.mark.asyncio670async def test_async_auth() -> None:671 """672 Test that we can use an auth implementation specific to the async case, to673 support cases that require performing I/O or using concurrency primitives (such674 as checking a disk-based cache or fetching a token from a remote auth server).675 """676 url = "https://example.org/"677 auth = SyncOrAsyncAuth()Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 678why, one step back678 app = App()Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
line 679why, one step back679Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 680why, one step back680 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
lines 681–692why, one step back681 response = await client.get(url, auth=auth)682683 assert response.status_code == 200684 assert response.json() == {"auth": "async-auth"}685686687def test_sync_auth() -> None:688 """689 Test that we can use an auth implementation specific to the sync case.690 """691 url = "https://example.org/"692 auth = SyncOrAsyncAuth()Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d
line 693why, one step back693 app = App()Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
line 694why, one step back694Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 695why, one step back695 with httpx.Client(transport=httpx.MockTransport(app)) as client:Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
lines 696–699why, one step back696 response = client.get(url, auth=auth)697698 assert response.status_code == 200699 assert response.json() == {"auth": "sync-auth"}