Skip to content
Myr

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 file

Take it

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

Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee

lines 1–6why, one step back
1"""
2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncio

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 7–8why, one step back
7import hashlib
8import os

Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee

line 9why, one step back
9import threading

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 10–14why, one step back
10import typing
1112import pytest1314import httpx

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

line 15why, one step back
15from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, Response

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 16–19why, one step back
16
17from ..common import FIXTURES_DIR1819

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 20–21why, one step back
20class App:
21 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 22–24why, one step back
22 self.auth_header = auth_header
23 self.status_code = status_code24

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 25–27why, one step back
25 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 back
28 return httpx.Response(self.status_code, headers=headers, json=data)

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 29–30why, one step back
29
30

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 31why, one step back
31class DigestApp:

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 32–44why, one step back
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 = 044

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 45why, one step back
45 def __call__(self, request: httpx.Request) -> httpx.Response:

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 46why, one step back
46 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 back
47 return self.challenge_send(request)

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 48why, one step back
48

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 49why, one step back
49 data = {"auth": request.headers.get("Authorization")}

Support Response(text=...), Response(html=...), Response(json=...) (#1297)Tom Christiebefore adoptionf3c2941

line 50why, one step back
50 return httpx.Response(200, json=data)

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 51why, one step back
51

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 52why, one step back
52 def challenge_send(self, request: httpx.Request) -> httpx.Response:

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 53–73why, one step back
53 self._response_count += 1
54 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 )73

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 74–77why, one step back
74 headers = {
75 "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',76 }77 return Response(401, headers=headers)

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 78–125why, one step back
78
7980class 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 request124125

Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee

lines 126–150why, one step back
126class 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 request149150

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 151–154why, one step back
151@pytest.mark.asyncio
152async 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 back
155 app = App()

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 156why, one step back
156

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 158–164why, one step back
158 response = await client.get(url, auth=auth)
159160 assert response.status_code == 200161 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}162163164@pytest.mark.asyncio

Fix stream unsetting auth (#1312)Tom Christiebefore adoptiond25f2bf

lines 165–172why, one step back
165async 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()172

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

lines 173–175why, one step back
173 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 back
176 async with client.stream("GET", url) as response:

Fix warning test case (#1322)Tom Christiebefore adoption320bfe1

line 177why, one step back
177 await response.aread()

Fix stream unsetting auth (#1312)Tom Christiebefore adoptiond25f2bf

lines 178–183why, one step back
178
179 assert response.status_code == 200180 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}181182183@pytest.mark.asyncio

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 184–185why, one step back
184async 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 back
186 app = App()

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 187why, one step back
187

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 189–198why, one step back
189 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 199why, one step back
199 app = App()

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 200why, one step back
200

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

lines 201–203why, one step back
201 async with httpx.AsyncClient(
202 transport=httpx.MockTransport(app), auth=auth203 ) as client:

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 204–212why, one step back
204 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/"

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 213why, one step back
213 app = App()

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 214–218why, one step back
214
215 def auth(request: Request) -> Request:216 request.headers["Authorization"] = "Token 123"217 return request218

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 220–229why, one step back
220 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"

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 230why, one step back
230 app = App()

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 231why, one step back
231

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 233–244why, one step back
233 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"

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 245why, one step back
245 app = App()

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 246why, one step back
246

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 248–257why, one step back
248 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"

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 258why, one step back
258 app = App()

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 259–260why, one step back
259
260 async with httpx.AsyncClient(

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 261why, one step back
261 transport=httpx.MockTransport(app), trust_env=False

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 262–268why, one step back
262 ) 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 back
269 transport=httpx.MockTransport(app), trust_env=True

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 270–282why, one step back
270 ) 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 283why, one step back
283 app = App()

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 284why, one step back
284

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

lines 285–287why, one step back
285 async with httpx.AsyncClient(
286 transport=httpx.MockTransport(app), auth=auth287 ) as client:

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 288–304why, one step back
288 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 305why, one step back
305 app = App()

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 306why, one step back
306

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 308–314why, one step back
308 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:

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 315–316why, one step back
315 app = App()
316

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 318–330why, one step back
318 assert client.auth is None
319320 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:

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 331–332why, one step back
331 app = App()
332

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 333–334why, one step back
333 with pytest.raises(TypeError):
334 client = httpx.AsyncClient(

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 335why, one step back
335 transport=httpx.MockTransport(app),

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 336–338why, one step back
336 auth="not a tuple, not a callable", # type: ignore
337 )338

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 340–350why, one step back
340 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 351why, one step back
351 app = App()

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 352why, one step back
352

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 354–363why, one step back
354 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 364–365why, one step back
364 auth_header = "Token ..."
365 app = App(auth_header=auth_header, status_code=401)

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 366why, one step back
366

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 367why, one step back
367 client = httpx.Client(transport=httpx.MockTransport(app))

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 368–378why, one step back
368 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 379–380why, one step back
379 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'
380 app = App(auth_header=auth_header, status_code=200)

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 381why, one step back
381

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 383–393why, one step back
383 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 394why, one step back
394 app = App(auth_header="", status_code=401)

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 395why, one step back
395

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 397–422why, one step back
397 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 423why, one step back
423 app = DigestApp(algorithm=algorithm)

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 424why, one step back
424

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 426–453why, one step back
426 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 454why, one step back
454 app = DigestApp(qop="")

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 455why, one step back
455

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 457–485why, one step back
457 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 486why, one step back
486 app = DigestApp(qop=qop)

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 487why, one step back
487

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 489–498why, one step back
489 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 499why, one step back
499 app = DigestApp(qop="auth-int")

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 500why, one step back
500

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 502–509why, one step back
502 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 510why, one step back
510 app = DigestApp(qop="not-auth")

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 511why, one step back
511

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 513–520why, one step back
513 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 521why, one step back
521 app = DigestApp(send_response_after_attempt=2)

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 522why, one step back
522

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 524–532why, one step back
524 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 [

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 533–534why, one step back
533 'Digest realm="httpx@example.org", qop="auth"', # missing fields
534 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 535–538why, one step back
535 ],
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 back
539 auth_header: str,

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 540–542why, one step back
540) -> 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 back
543 app = App(auth_header=auth_header, status_code=401)
544

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 546–552why, one step back
546 with pytest.raises(ProtocolError):
547 await client.get(url, auth=auth)548549550@pytest.mark.parametrize(551 "auth_header",552 [

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 553–554why, one step back
553 'Digest realm="httpx@example.org", qop="auth"', # missing fields
554 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 555–557why, one step back
555 ],
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 back
558 auth_header: str,

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 559–561why, one step back
559) -> 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 back
562 app = App(auth_header=auth_header, status_code=401)

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 563why, one step back
563

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 564why, one step back
564 with httpx.Client(transport=httpx.MockTransport(app)) as client:

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 565–576why, one step back
565 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)

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 577why, one step back
577 app = App(auth_header="abc")

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 578why, one step back
578

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 580–602why, one step back
580 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)

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 603why, one step back
603 app = App(auth_header="abc")

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 604why, one step back
604

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 605why, one step back
605 with httpx.Client(transport=httpx.MockTransport(app)) as client:

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 606–621why, one step back
606 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) == 0620621

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

lines 622–628why, one step back
622class 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)627628

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 629–632why, one step back
629@pytest.mark.asyncio
630async def test_digest_auth_unavailable_streaming_body():631 url = "https://example.org/"632 auth = DigestAuth(username="tomchristie", password="password123")

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

line 633why, one step back
633 app = DigestApp()

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 634–637why, one step back
634
635 async def streaming_body():636 yield b"Example request body" # pragma: nocover637

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

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

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

line 639why, one step back
639 with pytest.raises(httpx.StreamConsumed):

Escalate the distinction between data=... and content=... to be stricter (#1573)Tom Christiebefore adoption397aad9

line 640why, one step back
640 await client.post(url, content=streaming_body(), auth=auth)

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 641–650why, one step back
641
642643@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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 651–652why, one step back
651 app = App()
652

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

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

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 654–666why, one step back
654 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")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 667why, one step back
667 app = App()

Header refinements (#1248)Tom Christiebefore adoption19b863a

line 668why, one step back
668

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 669why, one step back
669 with httpx.Client(transport=httpx.MockTransport(app)) as client:

Header refinements (#1248)Tom Christiebefore adoption19b863a

lines 670–673why, one step back
670 response = client.get(url, auth=auth)
671672 assert response.status_code == 200673 assert response.json() == {"auth": '{"auth": "xyz"}'}

Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee

lines 674–684why, one step back
674
675676@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()

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 685why, one step back
685 app = App()

Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee

line 686why, one step back
686

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 687why, one step back
687 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 688–699why, one step back
688 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()

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 700why, one step back
700 app = App()

Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee

line 701why, one step back
701

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 702why, one step back
702 with httpx.Client(transport=httpx.MockTransport(app)) as client:

Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee

lines 703–706why, one step back
703 response = client.get(url, auth=auth)
704705 assert response.status_code == 200706 assert response.json() == {"auth": "sync-auth"}