Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

729 lines · 23.1 KiB · Python

Last changed by

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

History of this file

Take it

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

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

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

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 10–11why, one step back
10import typing
11

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 12why, one step back
12import httpcore

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 13–14why, one step back
13import pytest
14

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

line 15why, one step back
15import httpx

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 16–18why, one step back
16from httpx import (
17 URL,18 Auth,

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

line 19why, one step back
19 BasicAuth,

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 20–25why, one step back
20 DigestAuth,
21 ProtocolError,22 Request,23 RequestBodyUnavailable,24 Response,25)

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 26why, one step back
26from httpx._content_streams import ContentStream, JSONStream

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 27why, one step back
27

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 28why, one step back
28from ..common import FIXTURES_DIR

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 29why, one step back
29

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 30why, one step back
30

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 31–38why, one step back
31def get_header_value(headers, key, default=None):
32 lookup = key.encode("ascii").lower()33 for header_key, header_value in headers:34 if header_key.lower() == lookup:35 return header_value.decode("ascii")36 return default3738

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 39why, one step back
39class MockTransport:

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 40why, one step back
40 def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 41–43why, one step back
41 self.auth_header = auth_header
42 self.status_code = status_code43

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 44why, one step back
44 def _request(

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 45why, one step back
45 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 46–49why, one step back
46 method: bytes,
47 url: typing.Tuple[bytes, bytes, int, bytes],48 headers: typing.List[typing.Tuple[bytes, bytes]],49 stream: ContentStream,

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

line 50why, one step back
50 timeout: typing.Mapping[str, typing.Optional[float]] = None,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 51–56why, one step back
51 ) -> typing.Tuple[
52 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream53 ]:54 authorization = get_header_value(headers, "Authorization")55 response_headers = (56 [(b"www-authenticate", self.auth_header)] if self.auth_header else []

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 57why, one step back
57 )

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 58–59why, one step back
58 response_stream = JSONStream({"auth": authorization})
59 return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 60–61why, one step back
60
61

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 62–79why, one step back
62class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):
63 async def request(64 self, *args, **kwargs65 ) -> typing.Tuple[66 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream67 ]:68 return self._request(*args, **kwargs)697071class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):72 def request(73 self, *args, **kwargs74 ) -> typing.Tuple[75 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream76 ]:77 return self._request(*args, **kwargs)7879

Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100

line 80why, one step back
80class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 81–93why, one step back
81 def __init__(
82 self,83 algorithm: str = "SHA-256",84 send_response_after_attempt: int = 1,85 qop: str = "auth",86 regenerate_nonce: bool = True,87 ) -> None:88 self.algorithm = algorithm89 self.send_response_after_attempt = send_response_after_attempt90 self.qop = qop91 self._regenerate_nonce = regenerate_nonce92 self._response_count = 093

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 94why, one step back
94 async def request(

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 95why, one step back
95 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 96why, one step back
96 method: bytes,

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

lines 97–99why, one step back
97 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],
98 headers: typing.List[typing.Tuple[bytes, bytes]] = None,99 stream: httpcore.AsyncByteStream = None,

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

line 100why, one step back
100 timeout: typing.Mapping[str, typing.Optional[float]] = None,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 101–103why, one step back
101 ) -> typing.Tuple[
102 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream103 ]:

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 104why, one step back
104 if self._response_count < self.send_response_after_attempt:

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

lines 105–106why, one step back
105 assert headers is not None
106 return self.challenge_send(method, headers)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 107why, one step back
107

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 108–110why, one step back
108 authorization = get_header_value(headers, "Authorization")
109 body = JSONStream({"auth": authorization})110 return b"HTTP/1.1", 200, b"", [], body

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 111why, one step back
111

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 112why, one step back
112 def challenge_send(

Use and pin black 20 (#1229)Florimond Mancabefore adoptionf5c27ec

line 113why, one step back
113 self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]]

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

lines 114–116why, one step back
114 ) -> typing.Tuple[
115 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream116 ]:

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 117–138why, one step back
117 self._response_count += 1
118 nonce = (119 hashlib.sha256(os.urandom(8)).hexdigest()120 if self._regenerate_nonce121 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"122 )123 challenge_data = {124 "nonce": nonce,125 "qop": self.qop,126 "opaque": (127 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"128 ),129 "algorithm": self.algorithm,130 "stale": "FALSE",131 }132 challenge_str = ", ".join(133 '{}="{}"'.format(key, value)134 for key, value in challenge_data.items()135 if value136 )137138 headers = [

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 139–142why, one step back
139 (
140 b"www-authenticate",141 b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),142 )

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 143why, one step back
143 ]

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 144why, one step back
144 return b"HTTP/1.1", 401, b"", headers, ContentStream()

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 145–146why, one step back
145
146

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 147–192why, one step back
147class RepeatAuth(Auth):
148 """149 A mock authentication scheme that requires clients to send150 the request a fixed number of times, and then send a last request containing151 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers152 of intermediate responses.153 """154155 requires_request_body = True156157 def __init__(self, repeat: int):158 self.repeat = repeat159160 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:161 nonces = []162163 for index in range(self.repeat):164 request.headers["Authorization"] = f"Repeat {index}"165 response = yield request166 nonces.append(response.headers["www-authenticate"])167168 key = ".".join(nonces)169 request.headers["Authorization"] = f"Repeat {key}"170 yield request171172173class ResponseBodyAuth(Auth):174 """175 A mock authentication scheme that requires clients to send an 'Authorization'176 header, then send back the contents of the response in the 'Authorization'177 header.178 """179180 requires_response_body = True181182 def __init__(self, token):183 self.token = token184185 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:186 request.headers["Authorization"] = self.token187 response = yield request188 data = response.text189 request.headers["Authorization"] = data190 yield request191192

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

lines 193–217why, one step back
193class SyncOrAsyncAuth(Auth):
194 """195 A mock authentication scheme that uses a different implementation for the196 sync and async cases.197 """198199 def __init__(self) -> None:200 self._lock = threading.Lock()201 self._async_lock = asyncio.Lock()202203 def sync_auth_flow(204 self, request: Request205 ) -> typing.Generator[Request, Response, None]:206 with self._lock:207 request.headers["Authorization"] = "sync-auth"208 yield request209210 async def async_auth_flow(211 self, request: Request212 ) -> typing.AsyncGenerator[Request, Response]:213 async with self._async_lock:214 request.headers["Authorization"] = "async-auth"215 yield request216217

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 218–222why, one step back
218@pytest.mark.asyncio
219async def test_basic_auth() -> None:220 url = "https://example.org/"221 auth = ("tomchristie", "password123")222

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

lines 223–224why, one step back
223 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
224 response = await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 225–233why, one step back
225
226 assert response.status_code == 200227 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}228229230@pytest.mark.asyncio231async def test_basic_auth_in_url() -> None:232 url = "https://tomchristie:password123@example.org/"233

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

lines 234–235why, one step back
234 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
235 response = await client.get(url)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 236–245why, one step back
236
237 assert response.status_code == 200238 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}239240241@pytest.mark.asyncio242async def test_basic_auth_on_session() -> None:243 url = "https://example.org/"244 auth = ("tomchristie", "password123")245

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

lines 246–247why, one step back
246 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:
247 response = await client.get(url)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 248–260why, one step back
248
249 assert response.status_code == 200250 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}251252253@pytest.mark.asyncio254async def test_custom_auth() -> None:255 url = "https://example.org/"256257 def auth(request: Request) -> Request:258 request.headers["Authorization"] = "Token 123"259 return request260

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

lines 261–262why, one step back
261 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
262 response = await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 263–269why, one step back
263
264 assert response.status_code == 200265 assert response.json() == {"auth": "Token 123"}266267268@pytest.mark.asyncio269async def test_netrc_auth() -> None:

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 270why, one step back
270 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 271–272why, one step back
271 url = "http://netrcexample.org"
272

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

lines 273–274why, one step back
273 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
274 response = await client.get(url)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 275–283why, one step back
275
276 assert response.status_code == 200277 assert response.json() == {278 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"279 }280281282@pytest.mark.asyncio283async def test_auth_header_has_priority_over_netrc() -> None:

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 284why, one step back
284 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 285–286why, one step back
285 url = "http://netrcexample.org"
286

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

lines 287–288why, one step back
287 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
288 response = await client.get(url, headers={"Authorization": "Override"})

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 289–295why, one step back
289
290 assert response.status_code == 200291 assert response.json() == {"auth": "Override"}292293294@pytest.mark.asyncio295async def test_trust_env_auth() -> None:

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 296why, one step back
296 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 297–298why, one step back
297 url = "http://netrcexample.org"
298

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

lines 299–302why, one step back
299 async with httpx.AsyncClient(
300 transport=AsyncMockTransport(), trust_env=False301 ) as client:302 response = await client.get(url)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 303–306why, one step back
303
304 assert response.status_code == 200305 assert response.json() == {"auth": None}306

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

lines 307–310why, one step back
307 async with httpx.AsyncClient(
308 transport=AsyncMockTransport(), trust_env=True309 ) as client:310 response = await client.get(url)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 311–317why, one step back
311
312 assert response.status_code == 200313 assert response.json() == {314 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"315 }316317

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

lines 318–322why, one step back
318@pytest.mark.asyncio
319async def test_auth_disable_per_request() -> None:320 url = "https://example.org/"321 auth = ("tomchristie", "password123")322

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

lines 323–324why, one step back
323 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:
324 response = await client.get(url, auth=None)

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

lines 325–329why, one step back
325
326 assert response.status_code == 200327 assert response.json() == {"auth": None}328329

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 330–341why, one step back
330def test_auth_hidden_url() -> None:
331 url = "http://example-username:example-password@example.org/"332 expected = "URL('http://example-username:[secure]@example.org/')"333 assert url == URL(url)334 assert expected == repr(URL(url))335336337@pytest.mark.asyncio338async def test_auth_hidden_header() -> None:339 url = "https://example.org/"340 auth = ("example-username", "example-password")341

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

lines 342–343why, one step back
342 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
343 response = await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 344–348why, one step back
344
345 assert "'authorization': '[secure]'" in str(response.request.headers)346347348@pytest.mark.asyncio

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

line 349why, one step back
349async def test_auth_property() -> None:

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

lines 350–351why, one step back
350 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
351 assert client.auth is None

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

line 352why, one step back
352

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

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

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

line 355why, one step back
355

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

lines 356–359why, one step back
356 url = "https://example.org/"
357 response = await client.get(url)358 assert response.status_code == 200359 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}

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

lines 360–363why, one step back
360
361362@pytest.mark.asyncio363async def test_auth_invalid_type() -> None:

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

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

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

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

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

lines 366–369why, one step back
366 transport=AsyncMockTransport(),
367 auth="not a tuple, not a callable", # type: ignore368 )369

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

lines 370–372why, one step back
370 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
371 with pytest.raises(TypeError):372 await client.get(auth="not a tuple, not a callable") # type: ignore

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

line 373why, one step back
373

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

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

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

line 376why, one step back
376

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 377–382why, one step back
377
378@pytest.mark.asyncio379async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:380 url = "https://example.org/"381 auth = DigestAuth(username="tomchristie", password="password123")382

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

lines 383–384why, one step back
383 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
384 response = await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 385–390why, one step back
385
386 assert response.status_code == 200387 assert response.json() == {"auth": None}388 assert len(response.history) == 0389390

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

lines 391–405why, one step back
391def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:
392 url = "https://example.org/"393 auth = DigestAuth(username="tomchristie", password="password123")394 auth_header = b"Token ..."395396 client = httpx.Client(397 transport=SyncMockTransport(auth_header=auth_header, status_code=401)398 )399 response = client.get(url, auth=auth)400401 assert response.status_code == 401402 assert response.json() == {"auth": None}403 assert len(response.history) == 0404405

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 406–409why, one step back
406@pytest.mark.asyncio
407async def test_digest_auth_200_response_including_digest_auth_header() -> None:408 url = "https://example.org/"409 auth = DigestAuth(username="tomchristie", password="password123")

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 410why, one step back
410 auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 411why, one step back
411

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

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

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 413why, one step back
413 transport=AsyncMockTransport(auth_header=auth_header, status_code=200)

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

lines 414–415why, one step back
414 ) as client:
415 response = await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 416–426why, one step back
416
417 assert response.status_code == 200418 assert response.json() == {"auth": None}419 assert len(response.history) == 0420421422@pytest.mark.asyncio423async def test_digest_auth_401_response_without_digest_auth_header() -> None:424 url = "https://example.org/"425 auth = DigestAuth(username="tomchristie", password="password123")426

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

lines 427–430why, one step back
427 async with httpx.AsyncClient(
428 transport=AsyncMockTransport(auth_header=b"", status_code=401)429 ) as client:430 response = await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 431–456why, one step back
431
432 assert response.status_code == 401433 assert response.json() == {"auth": None}434 assert len(response.history) == 0435436437@pytest.mark.parametrize(438 "algorithm,expected_hash_length,expected_response_length",439 [440 ("MD5", 64, 32),441 ("MD5-SESS", 64, 32),442 ("SHA", 64, 40),443 ("SHA-SESS", 64, 40),444 ("SHA-256", 64, 64),445 ("SHA-256-SESS", 64, 64),446 ("SHA-512", 64, 128),447 ("SHA-512-SESS", 64, 128),448 ],449)450@pytest.mark.asyncio451async def test_digest_auth(452 algorithm: str, expected_hash_length: int, expected_response_length: int453) -> None:454 url = "https://example.org/"455 auth = DigestAuth(username="tomchristie", password="password123")456

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

lines 457–460why, one step back
457 async with httpx.AsyncClient(
458 transport=MockDigestAuthTransport(algorithm=algorithm)459 ) as client:460 response = await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 461–488why, one step back
461
462 assert response.status_code == 200463 assert len(response.history) == 1464465 authorization = typing.cast(dict, response.json())["auth"]466 scheme, _, fields = authorization.partition(" ")467 assert scheme == "Digest"468469 response_fields = [field.strip() for field in fields.split(",")]470 digest_data = dict(field.split("=") for field in response_fields)471472 assert digest_data["username"] == '"tomchristie"'473 assert digest_data["realm"] == '"httpx@example.org"'474 assert "nonce" in digest_data475 assert digest_data["uri"] == '"/"'476 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes477 assert len(digest_data["opaque"]) == expected_hash_length + 2478 assert digest_data["algorithm"] == algorithm479 assert digest_data["qop"] == "auth"480 assert digest_data["nc"] == "00000001"481 assert len(digest_data["cnonce"]) == 16 + 2482483484@pytest.mark.asyncio485async def test_digest_auth_no_specified_qop() -> None:486 url = "https://example.org/"487 auth = DigestAuth(username="tomchristie", password="password123")488

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

lines 489–490why, one step back
489 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop="")) as client:
490 response = await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 491–519why, one step back
491
492 assert response.status_code == 200493 assert len(response.history) == 1494495 authorization = typing.cast(dict, response.json())["auth"]496 scheme, _, fields = authorization.partition(" ")497 assert scheme == "Digest"498499 response_fields = [field.strip() for field in fields.split(",")]500 digest_data = dict(field.split("=") for field in response_fields)501502 assert "qop" not in digest_data503 assert "nc" not in digest_data504 assert "cnonce" not in digest_data505 assert digest_data["username"] == '"tomchristie"'506 assert digest_data["realm"] == '"httpx@example.org"'507 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes508 assert digest_data["uri"] == '"/"'509 assert len(digest_data["response"]) == 64 + 2510 assert len(digest_data["opaque"]) == 64 + 2511 assert digest_data["algorithm"] == "SHA-256"512513514@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))515@pytest.mark.asyncio516async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:517 url = "https://example.org/"518 auth = DigestAuth(username="tomchristie", password="password123")519

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

lines 520–521why, one step back
520 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop=qop)) as client:
521 response = await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 522–531why, one step back
522
523 assert response.status_code == 200524 assert len(response.history) == 1525526527@pytest.mark.asyncio528async def test_digest_auth_qop_auth_int_not_implemented() -> None:529 url = "https://example.org/"530 auth = DigestAuth(username="tomchristie", password="password123")531

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

lines 532–536why, one step back
532 async with httpx.AsyncClient(
533 transport=MockDigestAuthTransport(qop="auth-int")534 ) as client:535 with pytest.raises(NotImplementedError):536 await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 537–543why, one step back
537
538539@pytest.mark.asyncio540async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:541 url = "https://example.org/"542 auth = DigestAuth(username="tomchristie", password="password123")543

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

lines 544–548why, one step back
544 async with httpx.AsyncClient(
545 transport=MockDigestAuthTransport(qop="not-auth")546 ) as client:547 with pytest.raises(ProtocolError):548 await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 549–555why, one step back
549
550551@pytest.mark.asyncio552async def test_digest_auth_incorrect_credentials() -> None:553 url = "https://example.org/"554 auth = DigestAuth(username="tomchristie", password="password123")555

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

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

Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100

line 557why, one step back
557 transport=MockDigestAuthTransport(send_response_after_attempt=2)

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

lines 558–559why, one step back
558 ) as client:
559 response = await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 560–567why, one step back
560
561 assert response.status_code == 401562 assert len(response.history) == 1563564565@pytest.mark.parametrize(566 "auth_header",567 [

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 570–572why, one step back
570 ],
571)572@pytest.mark.asyncio

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 573why, one step back
573async def test_async_digest_auth_raises_protocol_error_on_malformed_header(

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 574why, one step back
574 auth_header: bytes,

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 575–577why, one step back
575) -> None:
576 url = "https://example.org/"577 auth = DigestAuth(username="tomchristie", password="password123")

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

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

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 579why, one step back
579 transport=AsyncMockTransport(auth_header=auth_header, status_code=401)

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

lines 580–582why, one step back
580 ) as client:
581 with pytest.raises(ProtocolError):582 await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 583–584why, one step back
583
584

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 585–596why, one step back
585@pytest.mark.parametrize(
586 "auth_header",587 [588 b'Digest realm="httpx@example.org", qop="auth"', # missing fields589 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list590 ],591)592def test_sync_digest_auth_raises_protocol_error_on_malformed_header(593 auth_header: bytes,594) -> None:595 url = "https://example.org/"596 auth = DigestAuth(username="tomchristie", password="password123")

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

lines 597–598why, one step back
597
598 with httpx.Client(

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 599why, one step back
599 transport=SyncMockTransport(auth_header=auth_header, status_code=401)

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

lines 600–602why, one step back
600 ) as client:
601 with pytest.raises(ProtocolError):602 client.get(url, auth=auth)

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 603–604why, one step back
603
604

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 605why, one step back
605@pytest.mark.asyncio

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 606why, one step back
606async def test_async_auth_history() -> None:

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 607–610why, one step back
607 """
608 Test that intermediate requests sent as part of an authentication flow609 are recorded in the response history.610 """

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 611–612why, one step back
611 url = "https://example.org/"
612 auth = RepeatAuth(repeat=2)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 613why, one step back
613

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

lines 614–618why, one step back
614 async with httpx.AsyncClient(
615 transport=AsyncMockTransport(auth_header=b"abc")616 ) as client:617 response = await client.get(url, auth=auth)618

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 619–620why, one step back
619 assert response.status_code == 200
620 assert response.json() == {"auth": "Repeat abc.abc"}

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 621why, one step back
621

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 622–625why, one step back
622 assert len(response.history) == 2
623 resp1, resp2 = response.history624 assert resp1.json() == {"auth": "Repeat 0"}625 assert resp2.json() == {"auth": "Repeat 1"}

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 626why, one step back
626

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 627–628why, one step back
627 assert len(resp2.history) == 1
628 assert resp2.history == [resp1]

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 629why, one step back
629

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 630why, one step back
630 assert len(resp1.history) == 0

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 631–632why, one step back
631
632

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 633–637why, one step back
633def test_sync_auth_history() -> None:
634 """635 Test that intermediate requests sent as part of an authentication flow636 are recorded in the response history.637 """

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 638–640why, one step back
638 url = "https://example.org/"
639 auth = RepeatAuth(repeat=2)640

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

lines 641–643why, one step back
641 with httpx.Client(transport=SyncMockTransport(auth_header=b"abc")) as client:
642 response = client.get(url, auth=auth)643

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 644–663why, one step back
644 assert response.status_code == 200
645 assert response.json() == {"auth": "Repeat abc.abc"}646647 assert len(response.history) == 2648 resp1, resp2 = response.history649 assert resp1.json() == {"auth": "Repeat 0"}650 assert resp2.json() == {"auth": "Repeat 1"}651652 assert len(resp2.history) == 1653 assert resp2.history == [resp1]654655 assert len(resp1.history) == 0656657658@pytest.mark.asyncio659async def test_digest_auth_unavailable_streaming_body():660 url = "https://example.org/"661 auth = DigestAuth(username="tomchristie", password="password123")662663 async def streaming_body():

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

line 664why, one step back
664 yield b"Example request body" # pragma: nocover

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 665why, one step back
665

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

lines 666–668why, one step back
666 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
667 with pytest.raises(RequestBodyUnavailable):668 await client.post(url, data=streaming_body(), auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 669–671why, one step back
669
670671@pytest.mark.asyncio

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 672why, one step back
672async def test_async_auth_reads_response_body() -> None:

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 673–676why, one step back
673 """
674 Test that we can read the response body in an auth flow if `requires_response_body`675 is set.676 """

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 677–678why, one step back
677 url = "https://example.org/"
678 auth = ResponseBodyAuth("xyz")

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

lines 679–680why, one step back
679 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:
680 response = await client.get(url, auth=auth)

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

line 681why, one step back
681

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 682–683why, one step back
682 assert response.status_code == 200
683 assert response.json() == {"auth": '{"auth": "xyz"}'}

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 684–685why, one step back
684
685

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 686–690why, one step back
686def test_sync_auth_reads_response_body() -> None:
687 """688 Test that we can read the response body in an auth flow if `requires_response_body`689 is set.690 """

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 691–693why, one step back
691 url = "https://example.org/"
692 auth = ResponseBodyAuth("xyz")693

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

lines 694–696why, one step back
694 with httpx.Client(transport=SyncMockTransport()) as client:
695 response = client.get(url, auth=auth)696

Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc

lines 697–698why, one step back
697 assert response.status_code == 200
698 assert response.json() == {"auth": '{"auth": "xyz"}'}

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

lines 699–729why, one step back
699
700701@pytest.mark.asyncio702async def test_async_auth() -> None:703 """704 Test that we can use an auth implementation specific to the async case, to705 support cases that require performing I/O or using concurrency primitives (such706 as checking a disk-based cache or fetching a token from a remote auth server).707 """708 url = "https://example.org/"709 auth = SyncOrAsyncAuth()710711 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:712 response = await client.get(url, auth=auth)713714 assert response.status_code == 200715 assert response.json() == {"auth": "async-auth"}716717718def test_sync_auth() -> None:719 """720 Test that we can use an auth implementation specific to the sync case.721 """722 url = "https://example.org/"723 auth = SyncOrAsyncAuth()724725 with httpx.Client(transport=SyncMockTransport()) as client:726 response = client.get(url, auth=auth)727728 assert response.status_code == 200729 assert response.json() == {"auth": "sync-auth"}