Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

608 lines · 19.3 KiB · Python

Last changed by

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

History of this file

Take it

The walk stopped after 200 commits: lines older than 1e23855 point at it.

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 1–2why, one step back
1import hashlib
2import os

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 3why, one step back
3import typing

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 4why, one step back
4

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 5why, one step back
5import httpcore

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 6–7why, one step back
6import pytest
7

Raise an exception in DigestAuth if non-replayable request is passed (#685)Kousik Mitrabefore adoption0ed0314

lines 8–10why, one step back
8from httpx import (
9 URL,10 AsyncClient,

Public Auth API (#732)Tom Christiebefore adoption12dd157

line 11why, one step back
11 Auth,

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

line 12why, one step back
12 Client,

Raise an exception in DigestAuth if non-replayable request is passed (#685)Kousik Mitrabefore adoption0ed0314

lines 13–18why, one step back
13 DigestAuth,
14 ProtocolError,15 Request,16 RequestBodyUnavailable,17 Response,18)

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 20–21why, one step back
20
21

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 22–29why, one step back
22def get_header_value(headers, key, default=None):
23 lookup = key.encode("ascii").lower()24 for header_key, header_value in headers:25 if header_key.lower() == lookup:26 return header_value.decode("ascii")27 return default2829

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

line 30why, one step back
30class MockTransport:

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 32–34why, one step back
32 self.auth_header = auth_header
33 self.status_code = status_code34

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

line 35why, one step back
35 def _request(

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 36why, one step back
36 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 37–47why, one step back
37 method: bytes,
38 url: typing.Tuple[bytes, bytes, int, bytes],39 headers: typing.List[typing.Tuple[bytes, bytes]],40 stream: ContentStream,41 timeout: typing.Dict[str, typing.Optional[float]] = None,42 ) -> typing.Tuple[43 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream44 ]:45 authorization = get_header_value(headers, "Authorization")46 response_headers = (47 [(b"www-authenticate", self.auth_header)] if self.auth_header else []

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 48why, one step back
48 )

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 51–52why, one step back
51
52

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

lines 53–70why, one step back
53class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):
54 async def request(55 self, *args, **kwargs56 ) -> typing.Tuple[57 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream58 ]:59 return self._request(*args, **kwargs)606162class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):63 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)6970

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

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 72–84why, one step back
72 def __init__(
73 self,74 algorithm: str = "SHA-256",75 send_response_after_attempt: int = 1,76 qop: str = "auth",77 regenerate_nonce: bool = True,78 ) -> None:79 self.algorithm = algorithm80 self.send_response_after_attempt = send_response_after_attempt81 self.qop = qop82 self._regenerate_nonce = regenerate_nonce83 self._response_count = 084

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 86why, one step back
86 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 91–94why, one step back
91 timeout: typing.Dict[str, typing.Optional[float]] = None,
92 ) -> typing.Tuple[93 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream94 ]:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 98why, one step back
98

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 102why, one step back
102

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 103why, one step back
103 def challenge_send(

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

lines 104–107why, one step back
104 self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]],
105 ) -> typing.Tuple[106 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream107 ]:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 108–129why, one step back
108 self._response_count += 1
109 nonce = (110 hashlib.sha256(os.urandom(8)).hexdigest()111 if self._regenerate_nonce112 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"113 )114 challenge_data = {115 "nonce": nonce,116 "qop": self.qop,117 "opaque": (118 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"119 ),120 "algorithm": self.algorithm,121 "stale": "FALSE",122 }123 challenge_str = ", ".join(124 '{}="{}"'.format(key, value)125 for key, value in challenge_data.items()126 if value127 )128129 headers = [

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 130–133why, one step back
130 (
131 b"www-authenticate",132 b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),133 )

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 134why, one step back
134 ]

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 136–137why, one step back
136
137

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

lines 138–183why, one step back
138class RepeatAuth(Auth):
139 """140 A mock authentication scheme that requires clients to send141 the request a fixed number of times, and then send a last request containing142 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers143 of intermediate responses.144 """145146 requires_request_body = True147148 def __init__(self, repeat: int):149 self.repeat = repeat150151 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:152 nonces = []153154 for index in range(self.repeat):155 request.headers["Authorization"] = f"Repeat {index}"156 response = yield request157 nonces.append(response.headers["www-authenticate"])158159 key = ".".join(nonces)160 request.headers["Authorization"] = f"Repeat {key}"161 yield request162163164class ResponseBodyAuth(Auth):165 """166 A mock authentication scheme that requires clients to send an 'Authorization'167 header, then send back the contents of the response in the 'Authorization'168 header.169 """170171 requires_response_body = True172173 def __init__(self, token):174 self.token = token175176 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:177 request.headers["Authorization"] = self.token178 response = yield request179 data = response.text180 request.headers["Authorization"] = data181 yield request182183

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

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

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 185why, one step back
185async def test_basic_auth() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 186–188why, one step back
186 url = "https://example.org/"
187 auth = ("tomchristie", "password123")188

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

line 189why, one step back
189 client = AsyncClient(transport=AsyncMockTransport())

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 190–196why, one step back
190 response = await client.get(url, auth=auth)
191192 assert response.status_code == 200193 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}194195196@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 197why, one step back
197async def test_basic_auth_in_url() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 198–199why, one step back
198 url = "https://tomchristie:password123@example.org/"
199

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

line 200why, one step back
200 client = AsyncClient(transport=AsyncMockTransport())

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 201–207why, one step back
201 response = await client.get(url)
202203 assert response.status_code == 200204 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}205206207@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 208why, one step back
208async def test_basic_auth_on_session() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 209–211why, one step back
209 url = "https://example.org/"
210 auth = ("tomchristie", "password123")211

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

line 212why, one step back
212 client = AsyncClient(transport=AsyncMockTransport(), auth=auth)

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 213–219why, one step back
213 response = await client.get(url)
214215 assert response.status_code == 200216 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}217218219@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 220why, one step back
220async def test_custom_auth() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 221–222why, one step back
221 url = "https://example.org/"
222

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 223why, one step back
223 def auth(request: Request) -> Request:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 224–226why, one step back
224 request.headers["Authorization"] = "Token 123"
225 return request226

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

line 227why, one step back
227 client = AsyncClient(transport=AsyncMockTransport())

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 228–234why, one step back
228 response = await client.get(url, auth=auth)
229230 assert response.status_code == 200231 assert response.json() == {"auth": "Token 123"}232233234@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 235why, one step back
235async def test_netrc_auth() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 236–238why, one step back
236 os.environ["NETRC"] = "tests/.netrc"
237 url = "http://netrcexample.org"238

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

line 239why, one step back
239 client = AsyncClient(transport=AsyncMockTransport())

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 240–248why, one step back
240 response = await client.get(url)
241242 assert response.status_code == 200243 assert response.json() == {244 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"245 }246247248@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 249why, one step back
249async def test_auth_header_has_priority_over_netrc() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 250–252why, one step back
250 os.environ["NETRC"] = "tests/.netrc"
251 url = "http://netrcexample.org"252

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

line 253why, one step back
253 client = AsyncClient(transport=AsyncMockTransport())

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 254–260why, one step back
254 response = await client.get(url, headers={"Authorization": "Override"})
255256 assert response.status_code == 200257 assert response.json() == {"auth": "Override"}258259260@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 261why, one step back
261async def test_trust_env_auth() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 262–264why, one step back
262 os.environ["NETRC"] = "tests/.netrc"
263 url = "http://netrcexample.org"264

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

line 265why, one step back
265 client = AsyncClient(transport=AsyncMockTransport(), trust_env=False)

No I/O auth (#644)Tom Christiebefore adoption6c69e09

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 267–270why, one step back
267
268 assert response.status_code == 200269 assert response.json() == {"auth": None}270

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

line 271why, one step back
271 client = AsyncClient(transport=AsyncMockTransport(), trust_env=True)

No I/O auth (#644)Tom Christiebefore adoption6c69e09

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 273–279why, one step back
273
274 assert response.status_code == 200275 assert response.json() == {276 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"277 }278279

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 280why, one step back
280def test_auth_hidden_url() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 281–287why, one step back
281 url = "http://example-username:example-password@example.org/"
282 expected = "URL('http://example-username:[secure]@example.org/')"283 assert url == URL(url)284 assert expected == repr(URL(url))285286287@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 288why, one step back
288async def test_auth_hidden_header() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 289–291why, one step back
289 url = "https://example.org/"
290 auth = ("example-username", "example-password")291

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

line 292why, one step back
292 client = AsyncClient(transport=AsyncMockTransport())

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 293–298why, one step back
293 response = await client.get(url, auth=auth)
294295 assert "'authorization': '[secure]'" in str(response.request.headers)296297298@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 299why, one step back
299async def test_auth_invalid_type() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 300why, one step back
300 url = "https://example.org/"

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 301why, one step back
301 client = AsyncClient(

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

lines 302–303why, one step back
302 transport=AsyncMockTransport(),
303 auth="not a tuple, not a callable", # type: ignore

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 304why, one step back
304 )

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 305–309why, one step back
305 with pytest.raises(TypeError):
306 await client.get(url)307308309@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 310why, one step back
310async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 311–313why, one step back
311 url = "https://example.org/"
312 auth = DigestAuth(username="tomchristie", password="password123")313

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

line 314why, one step back
314 client = AsyncClient(transport=AsyncMockTransport())

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 315–318why, one step back
315 response = await client.get(url, auth=auth)
316317 assert response.status_code == 200318 assert response.json() == {"auth": None}

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

line 319why, one step back
319 assert len(response.history) == 0

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 320–322why, one step back
320
321322@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 323why, one step back
323async def test_digest_auth_200_response_including_digest_auth_header() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 324–325why, one step back
324 url = "https://example.org/"
325 auth = DigestAuth(username="tomchristie", password="password123")

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 327why, one step back
327

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 328why, one step back
328 client = AsyncClient(

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

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

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 330why, one step back
330 )

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 331–334why, one step back
331 response = await client.get(url, auth=auth)
332333 assert response.status_code == 200334 assert response.json() == {"auth": None}

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

line 335why, one step back
335 assert len(response.history) == 0

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 336–338why, one step back
336
337338@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 339why, one step back
339async def test_digest_auth_401_response_without_digest_auth_header() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 340–342why, one step back
340 url = "https://example.org/"
341 auth = DigestAuth(username="tomchristie", password="password123")342

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

line 343why, one step back
343 client = AsyncClient(transport=AsyncMockTransport(auth_header=b"", status_code=401))

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 344–347why, one step back
344 response = await client.get(url, auth=auth)
345346 assert response.status_code == 401347 assert response.json() == {"auth": None}

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

line 348why, one step back
348 assert len(response.history) == 0

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 349–364why, one step back
349
350351@pytest.mark.parametrize(352 "algorithm,expected_hash_length,expected_response_length",353 [354 ("MD5", 64, 32),355 ("MD5-SESS", 64, 32),356 ("SHA", 64, 40),357 ("SHA-SESS", 64, 40),358 ("SHA-256", 64, 64),359 ("SHA-256-SESS", 64, 64),360 ("SHA-512", 64, 128),361 ("SHA-512-SESS", 64, 128),362 ],363)364@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

lines 365–367why, one step back
365async def test_digest_auth(
366 algorithm: str, expected_hash_length: int, expected_response_length: int367) -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 368–370why, one step back
368 url = "https://example.org/"
369 auth = DigestAuth(username="tomchristie", password="password123")370

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

line 371why, one step back
371 client = AsyncClient(transport=MockDigestAuthTransport(algorithm=algorithm))

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 372–374why, one step back
372 response = await client.get(url, auth=auth)
373374 assert response.status_code == 200

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

lines 375–376why, one step back
375 assert len(response.history) == 1
376

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

lines 377–379why, one step back
377 authorization = typing.cast(dict, response.json())["auth"]
378 scheme, _, fields = authorization.partition(" ")379 assert scheme == "Digest"

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 380why, one step back
380

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 381why, one step back
381 response_fields = [field.strip() for field in fields.split(",")]

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 382–396why, one step back
382 digest_data = dict(field.split("=") for field in response_fields)
383384 assert digest_data["username"] == '"tomchristie"'385 assert digest_data["realm"] == '"httpx@example.org"'386 assert "nonce" in digest_data387 assert digest_data["uri"] == '"/"'388 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes389 assert len(digest_data["opaque"]) == expected_hash_length + 2390 assert digest_data["algorithm"] == algorithm391 assert digest_data["qop"] == "auth"392 assert digest_data["nc"] == "00000001"393 assert len(digest_data["cnonce"]) == 16 + 2394395396@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 397why, one step back
397async def test_digest_auth_no_specified_qop() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 398–400why, one step back
398 url = "https://example.org/"
399 auth = DigestAuth(username="tomchristie", password="password123")400

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

line 401why, one step back
401 client = AsyncClient(transport=MockDigestAuthTransport(qop=""))

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 402–404why, one step back
402 response = await client.get(url, auth=auth)
403404 assert response.status_code == 200

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

lines 405–406why, one step back
405 assert len(response.history) == 1
406

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

lines 407–409why, one step back
407 authorization = typing.cast(dict, response.json())["auth"]
408 scheme, _, fields = authorization.partition(" ")409 assert scheme == "Digest"

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 410why, one step back
410

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 411why, one step back
411 response_fields = [field.strip() for field in fields.split(",")]

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 412–427why, one step back
412 digest_data = dict(field.split("=") for field in response_fields)
413414 assert "qop" not in digest_data415 assert "nc" not in digest_data416 assert "cnonce" not in digest_data417 assert digest_data["username"] == '"tomchristie"'418 assert digest_data["realm"] == '"httpx@example.org"'419 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes420 assert digest_data["uri"] == '"/"'421 assert len(digest_data["response"]) == 64 + 2422 assert len(digest_data["opaque"]) == 64 + 2423 assert digest_data["algorithm"] == "SHA-256"424425426@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))427@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 428why, one step back
428async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 429–431why, one step back
429 url = "https://example.org/"
430 auth = DigestAuth(username="tomchristie", password="password123")431

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

line 432why, one step back
432 client = AsyncClient(transport=MockDigestAuthTransport(qop=qop))

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 434why, one step back
434

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

lines 435–436why, one step back
435 assert response.status_code == 200
436 assert len(response.history) == 1

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 437why, one step back
437

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

line 438why, one step back
438

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

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

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 440why, one step back
440async def test_digest_auth_qop_auth_int_not_implemented() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 441–442why, one step back
441 url = "https://example.org/"
442 auth = DigestAuth(username="tomchristie", password="password123")

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

line 443why, one step back
443 client = AsyncClient(transport=MockDigestAuthTransport(qop="auth-int"))

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 444–449why, one step back
444
445 with pytest.raises(NotImplementedError):446 await client.get(url, auth=auth)447448449@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 450why, one step back
450async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 451–452why, one step back
451 url = "https://example.org/"
452 auth = DigestAuth(username="tomchristie", password="password123")

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

line 453why, one step back
453 client = AsyncClient(transport=MockDigestAuthTransport(qop="not-auth"))

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 454–459why, one step back
454
455 with pytest.raises(ProtocolError):456 await client.get(url, auth=auth)457458459@pytest.mark.asyncio

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 460why, one step back
460async def test_digest_auth_incorrect_credentials() -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 461–463why, one step back
461 url = "https://example.org/"
462 auth = DigestAuth(username="tomchristie", password="password123")463

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

lines 464–466why, one step back
464 client = AsyncClient(
465 transport=MockDigestAuthTransport(send_response_after_attempt=2)466 )

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 467–469why, one step back
467 response = await client.get(url, auth=auth)
468469 assert response.status_code == 401

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

line 470why, one step back
470 assert len(response.history) == 1

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 471–475why, one step back
471
472473@pytest.mark.parametrize(474 "auth_header",475 [

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 476–480why, one step back
476 b'Digest realm="httpx@example.org", qop="auth"', # missing fields
477 b'realm="httpx@example.org", qop="auth"', # not starting with Digest478 b'DigestZ realm="httpx@example.org", qop="auth"'479 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',480 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 481–483why, one step back
481 ],
482)483@pytest.mark.asyncio

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

line 486why, one step back
486) -> None:

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 487–488why, one step back
487 url = "https://example.org/"
488 auth = DigestAuth(username="tomchristie", password="password123")

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 489why, one step back
489 client = AsyncClient(

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

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

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 491why, one step back
491 )

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

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

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

lines 495–496why, one step back
495
496

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

lines 497–519why, one step back
497@pytest.mark.parametrize(
498 "auth_header",499 [500 b'Digest realm="httpx@example.org", qop="auth"', # missing fields501 b'realm="httpx@example.org", qop="auth"', # not starting with Digest502 b'DigestZ realm="httpx@example.org", qop="auth"'503 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',504 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list505 ],506)507def test_sync_digest_auth_raises_protocol_error_on_malformed_header(508 auth_header: bytes,509) -> None:510 url = "https://example.org/"511 auth = DigestAuth(username="tomchristie", password="password123")512 client = Client(513 transport=SyncMockTransport(auth_header=auth_header, status_code=401)514 )515516 with pytest.raises(ProtocolError):517 client.get(url, auth=auth)518519

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

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

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

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

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

lines 522–525why, one step back
522 """
523 Test that intermediate requests sent as part of an authentication flow524 are recorded in the response history.525 """

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

lines 526–528why, one step back
526 url = "https://example.org/"
527 auth = RepeatAuth(repeat=2)528 client = AsyncClient(transport=AsyncMockTransport(auth_header=b"abc"))

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

line 529why, one step back
529

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

lines 530–532why, one step back
530 response = await client.get(url, auth=auth)
531 assert response.status_code == 200532 assert response.json() == {"auth": "Repeat abc.abc"}

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

line 533why, one step back
533

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

lines 534–537why, one step back
534 assert len(response.history) == 2
535 resp1, resp2 = response.history536 assert resp1.json() == {"auth": "Repeat 0"}537 assert resp2.json() == {"auth": "Repeat 1"}

Public Auth API (#732)Tom Christiebefore adoption12dd157

line 538why, one step back
538

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

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

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

line 541why, one step back
541

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

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

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

lines 543–544why, one step back
543
544

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

lines 545–549why, one step back
545def test_sync_auth_history() -> None:
546 """547 Test that intermediate requests sent as part of an authentication flow548 are recorded in the response history.549 """

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

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

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

line 552why, one step back
552 client = Client(transport=SyncMockTransport(auth_header=b"abc"))

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

line 553why, one step back
553

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

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

Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c

lines 555–566why, one step back
555 assert response.status_code == 200
556 assert response.json() == {"auth": "Repeat abc.abc"}557558 assert len(response.history) == 2559 resp1, resp2 = response.history560 assert resp1.json() == {"auth": "Repeat 0"}561 assert resp2.json() == {"auth": "Repeat 1"}562563 assert len(resp2.history) == 1564 assert resp2.history == [resp1]565566 assert len(resp1.history) == 0

Raise an exception in DigestAuth if non-replayable request is passed (#685)Kousik Mitrabefore adoption0ed0314

lines 567–572why, one step back
567
568569@pytest.mark.asyncio570async def test_digest_auth_unavailable_streaming_body():571 url = "https://example.org/"572 auth = DigestAuth(username="tomchristie", password="password123")

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

line 573why, one step back
573 client = AsyncClient(transport=AsyncMockTransport())

Raise an exception in DigestAuth if non-replayable request is passed (#685)Kousik Mitrabefore adoption0ed0314

lines 574–575why, one step back
574
575 async def streaming_body():

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

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

Raise an exception in DigestAuth if non-replayable request is passed (#685)Kousik Mitrabefore adoption0ed0314

lines 577–579why, one step back
577
578 with pytest.raises(RequestBodyUnavailable):579 await client.post(url, data=streaming_body(), auth=auth)

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

lines 580–582why, one step back
580
581582@pytest.mark.asyncio

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

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

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

lines 584–587why, one step back
584 """
585 Test that we can read the response body in an auth flow if `requires_response_body`586 is set.587 """

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

lines 588–590why, one step back
588 url = "https://example.org/"
589 auth = ResponseBodyAuth("xyz")590 client = AsyncClient(transport=AsyncMockTransport())

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

line 591why, one step back
591

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

lines 592–594why, one step back
592 response = await client.get(url, auth=auth)
593 assert response.status_code == 200594 assert response.json() == {"auth": '{"auth": "xyz"}'}

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

lines 595–596why, one step back
595
596

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

lines 597–601why, one step back
597def test_sync_auth_reads_response_body() -> None:
598 """599 Test that we can read the response body in an auth flow if `requires_response_body`600 is set.601 """

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

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

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

line 604why, one step back
604 client = Client(transport=SyncMockTransport())

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

line 605why, one step back
605

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

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

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

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