Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

605 lines · 19.2 KiB · Python

Last changed by

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

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

line 13why, one step back
13 DigestAuth,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 14why, one step back
14 Headers,

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

lines 21–22why, one step back
21
22

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 31why, one step back
31class MockTransport:

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 32why, one step back
32 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 33–35why, one step back
33 self.auth_header = auth_header
34 self.status_code = status_code35

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

line 36why, one step back
36 def _request(

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

line 37why, one step back
37 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 38–48why, one step back
38 method: bytes,
39 url: typing.Tuple[bytes, bytes, int, bytes],40 headers: typing.List[typing.Tuple[bytes, bytes]],41 stream: ContentStream,42 timeout: typing.Dict[str, typing.Optional[float]] = None,43 ) -> typing.Tuple[44 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream45 ]:46 authorization = get_header_value(headers, "Authorization")47 response_headers = (48 [(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 49why, one step back
49 )

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 50–51why, one step back
50 response_stream = JSONStream({"auth": authorization})
51 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 52–53why, one step back
52
53

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

lines 54–71why, one step back
54class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):
55 async def request(56 self, *args, **kwargs57 ) -> typing.Tuple[58 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream59 ]:60 return self._request(*args, **kwargs)616263class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):64 def request(65 self, *args, **kwargs66 ) -> typing.Tuple[67 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream68 ]:69 return self._request(*args, **kwargs)7071

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

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

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

lines 73–85why, one step back
73 def __init__(
74 self,75 algorithm: str = "SHA-256",76 send_response_after_attempt: int = 1,77 qop: str = "auth",78 regenerate_nonce: bool = True,79 ) -> None:80 self.algorithm = algorithm81 self.send_response_after_attempt = send_response_after_attempt82 self.qop = qop83 self._regenerate_nonce = regenerate_nonce84 self._response_count = 085

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 87why, one step back
87 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 88–95why, one step back
88 method: bytes,
89 url: typing.Tuple[bytes, bytes, int, bytes],90 headers: typing.List[typing.Tuple[bytes, bytes]],91 stream: ContentStream,92 timeout: typing.Dict[str, typing.Optional[float]] = None,93 ) -> typing.Tuple[94 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream95 ]:

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 97why, one step back
97 return self.challenge_send(method, url, headers, stream)

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

lines 103–105why, one step back
103 def challenge_send(
104 self, method: bytes, url: URL, headers: Headers, stream: ContentStream,105 ) -> typing.Tuple[int, bytes, Headers, ContentStream]:

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 132why, one step back
132 ]

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 133why, one step back
133 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 134–135why, one step back
134
135

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

lines 136–181why, one step back
136class RepeatAuth(Auth):
137 """138 A mock authentication scheme that requires clients to send139 the request a fixed number of times, and then send a last request containing140 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers141 of intermediate responses.142 """143144 requires_request_body = True145146 def __init__(self, repeat: int):147 self.repeat = repeat148149 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:150 nonces = []151152 for index in range(self.repeat):153 request.headers["Authorization"] = f"Repeat {index}"154 response = yield request155 nonces.append(response.headers["www-authenticate"])156157 key = ".".join(nonces)158 request.headers["Authorization"] = f"Repeat {key}"159 yield request160161162class ResponseBodyAuth(Auth):163 """164 A mock authentication scheme that requires clients to send an 'Authorization'165 header, then send back the contents of the response in the 'Authorization'166 header.167 """168169 requires_response_body = True170171 def __init__(self, token):172 self.token = token173174 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:175 request.headers["Authorization"] = self.token176 response = yield request177 data = response.text178 request.headers["Authorization"] = data179 yield request180181

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

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

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

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

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

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

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

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

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

lines 188–194why, one step back
188 response = await client.get(url, auth=auth)
189190 assert response.status_code == 200191 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}192193194@pytest.mark.asyncio

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

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

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

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

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

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

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

lines 199–205why, one step back
199 response = await client.get(url)
200201 assert response.status_code == 200202 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}203204205@pytest.mark.asyncio

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

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

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

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

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

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

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

lines 211–217why, one step back
211 response = await client.get(url)
212213 assert response.status_code == 200214 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}215216217@pytest.mark.asyncio

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

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

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

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

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

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

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

lines 222–224why, one step back
222 request.headers["Authorization"] = "Token 123"
223 return request224

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

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

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

lines 226–232why, one step back
226 response = await client.get(url, auth=auth)
227228 assert response.status_code == 200229 assert response.json() == {"auth": "Token 123"}230231232@pytest.mark.asyncio

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

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

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

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

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

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

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

lines 238–246why, one step back
238 response = await client.get(url)
239240 assert response.status_code == 200241 assert response.json() == {242 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"243 }244245246@pytest.mark.asyncio

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

line 247why, one step back
247async 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 248–250why, one step back
248 os.environ["NETRC"] = "tests/.netrc"
249 url = "http://netrcexample.org"250

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

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

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

lines 252–258why, one step back
252 response = await client.get(url, headers={"Authorization": "Override"})
253254 assert response.status_code == 200255 assert response.json() == {"auth": "Override"}256257258@pytest.mark.asyncio

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

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

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

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

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

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

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

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

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

lines 265–268why, one step back
265
266 assert response.status_code == 200267 assert response.json() == {"auth": None}268

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

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

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

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

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

lines 271–277why, one step back
271
272 assert response.status_code == 200273 assert response.json() == {274 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"275 }276277

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

line 300why, one step back
300 transport=AsyncMockTransport(), auth="not a tuple, not a callable",

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

line 301why, one step back
301 )

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

lines 302–306why, one step back
302 with pytest.raises(TypeError):
303 await client.get(url)304305306@pytest.mark.asyncio

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

line 307why, one step back
307async 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 308–310why, one step back
308 url = "https://example.org/"
309 auth = DigestAuth(username="tomchristie", password="password123")310

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

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

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

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

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

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

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

lines 317–319why, one step back
317
318319@pytest.mark.asyncio

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

line 320why, one step back
320async 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 321–322why, one step back
321 url = "https://example.org/"
322 auth = DigestAuth(username="tomchristie", password="password123")

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

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

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

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

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

line 327why, one step back
327 )

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

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

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

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

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

lines 333–335why, one step back
333
334335@pytest.mark.asyncio

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

line 336why, one step back
336async 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 337–339why, one step back
337 url = "https://example.org/"
338 auth = DigestAuth(username="tomchristie", password="password123")339

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

line 340why, one step back
340 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 341–344why, one step back
341 response = await client.get(url, auth=auth)
342343 assert response.status_code == 401344 assert response.json() == {"auth": None}

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

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

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

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

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

lines 362–364why, one step back
362async def test_digest_auth(
363 algorithm: str, expected_hash_length: int, expected_response_length: int364) -> None:

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

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

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

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

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

lines 369–371why, one step back
369 response = await client.get(url, auth=auth)
370371 assert response.status_code == 200

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

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

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

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

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

line 377why, one step back
377

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

line 378why, one step back
378 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 379–393why, one step back
379 digest_data = dict(field.split("=") for field in response_fields)
380381 assert digest_data["username"] == '"tomchristie"'382 assert digest_data["realm"] == '"httpx@example.org"'383 assert "nonce" in digest_data384 assert digest_data["uri"] == '"/"'385 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes386 assert len(digest_data["opaque"]) == expected_hash_length + 2387 assert digest_data["algorithm"] == algorithm388 assert digest_data["qop"] == "auth"389 assert digest_data["nc"] == "00000001"390 assert len(digest_data["cnonce"]) == 16 + 2391392393@pytest.mark.asyncio

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

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

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

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

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

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

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

lines 399–401why, one step back
399 response = await client.get(url, auth=auth)
400401 assert response.status_code == 200

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

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

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

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

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

line 407why, one step back
407

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

line 408why, one step back
408 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 409–424why, one step back
409 digest_data = dict(field.split("=") for field in response_fields)
410411 assert "qop" not in digest_data412 assert "nc" not in digest_data413 assert "cnonce" not in digest_data414 assert digest_data["username"] == '"tomchristie"'415 assert digest_data["realm"] == '"httpx@example.org"'416 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes417 assert digest_data["uri"] == '"/"'418 assert len(digest_data["response"]) == 64 + 2419 assert len(digest_data["opaque"]) == 64 + 2420 assert digest_data["algorithm"] == "SHA-256"421422423@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))424@pytest.mark.asyncio

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

line 425why, one step back
425async 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 426–428why, one step back
426 url = "https://example.org/"
427 auth = DigestAuth(username="tomchristie", password="password123")428

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

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

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

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

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

line 431why, one step back
431

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

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

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

line 435why, one step back
435

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

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

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

line 437why, one step back
437async 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 438–439why, one step back
438 url = "https://example.org/"
439 auth = DigestAuth(username="tomchristie", password="password123")

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

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

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

lines 441–446why, one step back
441
442 with pytest.raises(NotImplementedError):443 await client.get(url, auth=auth)444445446@pytest.mark.asyncio

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

line 447why, one step back
447async 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 448–449why, one step back
448 url = "https://example.org/"
449 auth = DigestAuth(username="tomchristie", password="password123")

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

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

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

lines 451–456why, one step back
451
452 with pytest.raises(ProtocolError):453 await client.get(url, auth=auth)454455456@pytest.mark.asyncio

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

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

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

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

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

lines 461–463why, one step back
461 client = AsyncClient(
462 transport=MockDigestAuthTransport(send_response_after_attempt=2)463 )

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

lines 464–466why, one step back
464 response = await client.get(url, auth=auth)
465466 assert response.status_code == 401

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

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

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

lines 468–472why, one step back
468
469470@pytest.mark.parametrize(471 "auth_header",472 [

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 473–477why, one step back
473 b'Digest realm="httpx@example.org", qop="auth"', # missing fields
474 b'realm="httpx@example.org", qop="auth"', # not starting with Digest475 b'DigestZ realm="httpx@example.org", qop="auth"'476 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',477 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 478–480why, one step back
478 ],
479)480@pytest.mark.asyncio

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

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

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

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

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

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

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

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

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

line 488why, one step back
488 )

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

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

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

lines 492–493why, one step back
492
493

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

lines 494–516why, one step back
494@pytest.mark.parametrize(
495 "auth_header",496 [497 b'Digest realm="httpx@example.org", qop="auth"', # missing fields498 b'realm="httpx@example.org", qop="auth"', # not starting with Digest499 b'DigestZ realm="httpx@example.org", qop="auth"'500 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',501 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list502 ],503)504def test_sync_digest_auth_raises_protocol_error_on_malformed_header(505 auth_header: bytes,506) -> None:507 url = "https://example.org/"508 auth = DigestAuth(username="tomchristie", password="password123")509 client = Client(510 transport=SyncMockTransport(auth_header=auth_header, status_code=401)511 )512513 with pytest.raises(ProtocolError):514 client.get(url, auth=auth)515516

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

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

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

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

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

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

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

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

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

line 526why, one step back
526

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

lines 527–529why, one step back
527 response = await client.get(url, auth=auth)
528 assert response.status_code == 200529 assert response.json() == {"auth": "Repeat abc.abc"}

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

line 530why, one step back
530

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

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

Public Auth API (#732)Tom Christiebefore adoption12dd157

line 535why, one step back
535

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

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

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

line 538why, one step back
538

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

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

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

lines 540–541why, one step back
540
541

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

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

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

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

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

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

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

line 550why, one step back
550

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

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

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

lines 552–563why, one step back
552 assert response.status_code == 200
553 assert response.json() == {"auth": "Repeat abc.abc"}554555 assert len(response.history) == 2556 resp1, resp2 = response.history557 assert resp1.json() == {"auth": "Repeat 0"}558 assert resp2.json() == {"auth": "Repeat 1"}559560 assert len(resp2.history) == 1561 assert resp2.history == [resp1]562563 assert len(resp1.history) == 0

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

lines 564–569why, one step back
564
565566@pytest.mark.asyncio567async def test_digest_auth_unavailable_streaming_body():568 url = "https://example.org/"569 auth = DigestAuth(username="tomchristie", password="password123")

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

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

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

lines 571–572why, one step back
571
572 async def streaming_body():

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

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

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

lines 574–576why, one step back
574
575 with pytest.raises(RequestBodyUnavailable):576 await client.post(url, data=streaming_body(), auth=auth)

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

lines 577–579why, one step back
577
578579@pytest.mark.asyncio

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

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

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

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

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

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

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

line 588why, one step back
588

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

lines 589–591why, one step back
589 response = await client.get(url, auth=auth)
590 assert response.status_code == 200591 assert response.json() == {"auth": '{"auth": "xyz"}'}

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

lines 592–593why, one step back
592
593

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

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

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

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

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

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

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

line 602why, one step back
602

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

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

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

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