Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than 31e587c 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

Pin pytestTom Christiebefore adoption31e587c

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

Pin pytestTom Christiebefore adoption31e587c

lines 10–13why, one step back
10import typing
1112import pytest13

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 14why, one step back
14import httpx

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

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

Pin pytestTom Christiebefore adoption31e587c

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:

Pin pytestTom Christiebefore adoption31e587c

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)

Pin pytestTom Christiebefore adoption31e587c

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:

Pin pytestTom Christiebefore adoption31e587c

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:

Pin pytestTom Christiebefore adoption31e587c

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)

Pin pytestTom Christiebefore adoption31e587c

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)

Pin pytestTom Christiebefore adoption31e587c

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:

Pin pytestTom Christiebefore adoption31e587c

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)

Pin pytestTom Christiebefore adoption31e587c

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

Pin pytestTom Christiebefore adoption31e587c

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()

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 158why, one step back
158 response = await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

lines 159–164why, one step back
159
160 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

Pin pytestTom Christiebefore adoption31e587c

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()

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 189why, one step back
189 response = await client.get(url)

Pin pytestTom Christiebefore adoption31e587c

lines 190–198why, one step back
190
191 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()

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 204why, one step back
204 response = await client.get(url)

Pin pytestTom Christiebefore adoption31e587c

lines 205–212why, one step back
205
206 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()

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 220why, one step back
220 response = await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

lines 221–229why, one step back
221
222 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()

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 233why, one step back
233 response = await client.get(url)

Pin pytestTom Christiebefore adoption31e587c

lines 234–244why, one step back
234
235 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()

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 248why, one step back
248 response = await client.get(url, headers={"Authorization": "Override"})

Pin pytestTom Christiebefore adoption31e587c

lines 249–257why, one step back
249
250 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()

Pin pytestTom Christiebefore adoption31e587c

line 259why, one step back
259

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 260why, one step back
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

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 262–263why, one step back
262 ) as client:
263 response = await client.get(url)

Pin pytestTom Christiebefore adoption31e587c

lines 264–267why, one step back
264
265 assert response.status_code == 200266 assert response.json() == {"auth": None}267

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 268why, one step back
268 async with httpx.AsyncClient(

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

line 269why, one step back
269 transport=httpx.MockTransport(app), trust_env=True

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 270–271why, one step back
270 ) as client:
271 response = await client.get(url)

Pin pytestTom Christiebefore adoption31e587c

lines 272–278why, one step back
272
273 assert response.status_code == 200274 assert response.json() == {275 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"276 }277278

Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0

lines 279–282why, one step back
279@pytest.mark.asyncio
280async 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()

Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 288why, one step back
288 response = await client.get(url, auth=None)

Allow disabling auth per-request using `auth=None` (#1115)Florimond Mancabefore adoptiona4463d0

lines 289–293why, one step back
289
290 assert response.status_code == 200291 assert response.json() == {"auth": None}292293

Pin pytestTom Christiebefore adoption31e587c

lines 294–304why, one step back
294def 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()

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 308why, one step back
308 response = await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

lines 309–313why, one step back
309
310 assert "'authorization': '[secure]'" in str(response.request.headers)311312313@pytest.mark.asyncio

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

line 314why, one step back
314async 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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 318why, one step back
318 assert client.auth is None

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

line 319why, one step back
319

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 320–321why, one step back
320 client.auth = ("tomchristie", "password123") # type: ignore
321 assert isinstance(client.auth, BasicAuth)

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

line 322why, one step back
322

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 323–326why, one step back
323 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 back
327
328329@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

Pin pytestTom Christiebefore adoption31e587c

line 333why, one step back
333 with pytest.raises(TypeError):

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 334why, one step back
334 client = httpx.AsyncClient(

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

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

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 340–341why, one step back
340 with pytest.raises(TypeError):
341 await client.get(auth="not a tuple, not a callable") # type: ignore

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

line 342why, one step back
342

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 343–344why, one step back
343 with pytest.raises(TypeError):
344 client.auth = "not a tuple, not a callable" # type: ignore

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

line 345why, one step back
345

Pin pytestTom Christiebefore adoption31e587c

lines 346–350why, one step back
346
347@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()

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 354why, one step back
354 response = await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

lines 355–360why, one step back
355
356 assert response.status_code == 200357 assert response.json() == {"auth": None}358 assert len(response.history) == 0359360

Handle multiple auth headers correctly (#1240)Tom Christiebefore adoption33d339a

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

Handle multiple auth headers correctly (#1240)Tom Christiebefore adoption33d339a

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))

Handle multiple auth headers correctly (#1240)Tom Christiebefore adoption33d339a

lines 368–374why, 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) == 0373374

Pin pytestTom Christiebefore adoption31e587c

lines 375–378why, one step back
375@pytest.mark.asyncio
376async 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)

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 383why, one step back
383 response = await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

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

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 397why, one step back
397 response = await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

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

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 426why, one step back
426 response = await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

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

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 457why, one step back
457 response = await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

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

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 489why, one step back
489 response = await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

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

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 502–503why, one step back
502 with pytest.raises(NotImplementedError):
503 await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

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

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 513–514why, one step back
513 with pytest.raises(ProtocolError):
514 await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

lines 515–520why, one step back
515
516517@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)

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 524why, one step back
524 response = await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

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

Pin pytestTom Christiebefore adoption31e587c

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,

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 546–547why, one step back
546 with pytest.raises(ProtocolError):
547 await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

lines 548–552why, one step back
548
549550@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

Pin pytestTom Christiebefore adoption31e587c

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,

Pin pytestTom Christiebefore adoption31e587c

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)

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 565–566why, one step back
565 with pytest.raises(ProtocolError):
566 client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

lines 567–576why, one step back
567
568569@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")

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 580–581why, one step back
580 response = await client.get(url, auth=auth)
581

Pin pytestTom Christiebefore adoption31e587c

lines 582–602why, one step back
582 assert response.status_code == 200
583 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")

Pin pytestTom Christiebefore adoption31e587c

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:

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 606–607why, one step back
606 response = client.get(url, auth=auth)
607

Pin pytestTom Christiebefore adoption31e587c

lines 608–625why, one step back
608 assert response.status_code == 200
609 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 back
626 app = DigestApp()

Pin pytestTom Christiebefore adoption31e587c

lines 627–630why, one step back
627
628 async def streaming_body():629 yield b"Example request body" # pragma: nocover630

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

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

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

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

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

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

Pin pytestTom Christiebefore adoption31e587c

lines 634–643why, one step back
634
635636@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 back
644 app = App()
645

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

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

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

line 647why, one step back
647 response = await client.get(url, auth=auth)

Pin pytestTom Christiebefore adoption31e587c

lines 648–659why, one step back
648
649 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 back
660 app = App()

Pin pytestTom Christiebefore adoption31e587c

line 661why, one step back
661

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

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

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 663–664why, one step back
663 response = client.get(url, auth=auth)
664

Pin pytestTom Christiebefore adoption31e587c

lines 665–666why, one step back
665 assert response.status_code == 200
666 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 back
667
668669@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 back
678 app = App()

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

line 679why, one step back
679

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

line 680why, one step back
680 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 back
681 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 back
693 app = App()

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

line 694why, one step back
694

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

line 695why, one step back
695 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 back
696 response = client.get(url, auth=auth)
697698 assert response.status_code == 200699 assert response.json() == {"auth": "sync-auth"}