Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

610 lines · 19.4 KiB · Python

Last changed by

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

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

line 20why, one step back
20

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

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

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

line 22why, one step back
22

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

line 23why, one step back
23

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 32why, one step back
32class MockTransport:

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 37why, one step back
37 def _request(

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

line 38why, one step back
38 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

lines 55–72why, one step back
55class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):
56 async def request(57 self, *args, **kwargs58 ) -> typing.Tuple[59 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream60 ]:61 return self._request(*args, **kwargs)626364class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):65 def request(66 self, *args, **kwargs67 ) -> typing.Tuple[68 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream69 ]:70 return self._request(*args, **kwargs)7172

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

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

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

lines 74–86why, one step back
74 def __init__(
75 self,76 algorithm: str = "SHA-256",77 send_response_after_attempt: int = 1,78 qop: str = "auth",79 regenerate_nonce: bool = True,80 ) -> None:81 self.algorithm = algorithm82 self.send_response_after_attempt = send_response_after_attempt83 self.qop = qop84 self._regenerate_nonce = regenerate_nonce85 self._response_count = 086

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 88why, one step back
88 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

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

line 100why, one step back
100

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 104why, one step back
104

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 105why, one step back
105 def challenge_send(

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

line 136why, one step back
136 ]

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 137why, one step back
137 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 138–139why, one step back
138
139

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

lines 140–185why, one step back
140class RepeatAuth(Auth):
141 """142 A mock authentication scheme that requires clients to send143 the request a fixed number of times, and then send a last request containing144 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers145 of intermediate responses.146 """147148 requires_request_body = True149150 def __init__(self, repeat: int):151 self.repeat = repeat152153 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:154 nonces = []155156 for index in range(self.repeat):157 request.headers["Authorization"] = f"Repeat {index}"158 response = yield request159 nonces.append(response.headers["www-authenticate"])160161 key = ".".join(nonces)162 request.headers["Authorization"] = f"Repeat {key}"163 yield request164165166class ResponseBodyAuth(Auth):167 """168 A mock authentication scheme that requires clients to send an 'Authorization'169 header, then send back the contents of the response in the 'Authorization'170 header.171 """172173 requires_response_body = True174175 def __init__(self, token):176 self.token = token177178 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:179 request.headers["Authorization"] = self.token180 response = yield request181 data = response.text182 request.headers["Authorization"] = data183 yield request184185

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

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

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

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

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

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

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

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

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

lines 192–198why, one step back
192 response = await client.get(url, auth=auth)
193194 assert response.status_code == 200195 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}196197198@pytest.mark.asyncio

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

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

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

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

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

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

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

lines 203–209why, one step back
203 response = await client.get(url)
204205 assert response.status_code == 200206 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}207208209@pytest.mark.asyncio

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

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

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

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

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

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

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

lines 215–221why, one step back
215 response = await client.get(url)
216217 assert response.status_code == 200218 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}219220221@pytest.mark.asyncio

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

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

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

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

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

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

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

lines 226–228why, one step back
226 request.headers["Authorization"] = "Token 123"
227 return request228

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

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

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

lines 230–236why, one step back
230 response = await client.get(url, auth=auth)
231232 assert response.status_code == 200233 assert response.json() == {"auth": "Token 123"}234235236@pytest.mark.asyncio

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

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

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

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

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

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

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

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

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

lines 242–250why, one step back
242 response = await client.get(url)
243244 assert response.status_code == 200245 assert response.json() == {246 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"247 }248249250@pytest.mark.asyncio

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

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

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

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

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

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

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

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

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

lines 256–262why, one step back
256 response = await client.get(url, headers={"Authorization": "Override"})
257258 assert response.status_code == 200259 assert response.json() == {"auth": "Override"}260261262@pytest.mark.asyncio

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

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

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

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

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

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

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

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

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

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

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

lines 269–272why, one step back
269
270 assert response.status_code == 200271 assert response.json() == {"auth": None}272

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

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

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

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

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

lines 275–281why, one step back
275
276 assert response.status_code == 200277 assert response.json() == {278 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"279 }280281

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

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

line 306why, one step back
306 )

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

lines 307–311why, one step back
307 with pytest.raises(TypeError):
308 await client.get(url)309310311@pytest.mark.asyncio

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

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

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

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

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

lines 317–320why, one step back
317 response = await client.get(url, auth=auth)
318319 assert response.status_code == 200320 assert response.json() == {"auth": None}

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

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

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

lines 322–324why, one step back
322
323324@pytest.mark.asyncio

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

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

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

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

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

line 332why, one step back
332 )

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

lines 333–336why, one step back
333 response = await client.get(url, auth=auth)
334335 assert response.status_code == 200336 assert response.json() == {"auth": None}

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

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

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

lines 338–340why, one step back
338
339340@pytest.mark.asyncio

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

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

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

line 345why, one step back
345 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 346–349why, one step back
346 response = await client.get(url, auth=auth)
347348 assert response.status_code == 401349 assert response.json() == {"auth": None}

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

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

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

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

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

lines 367–369why, one step back
367async def test_digest_auth(
368 algorithm: str, expected_hash_length: int, expected_response_length: int369) -> None:

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

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

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

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

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

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

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

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

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

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

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

line 382why, one step back
382

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

line 383why, one step back
383 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 384–398why, one step back
384 digest_data = dict(field.split("=") for field in response_fields)
385386 assert digest_data["username"] == '"tomchristie"'387 assert digest_data["realm"] == '"httpx@example.org"'388 assert "nonce" in digest_data389 assert digest_data["uri"] == '"/"'390 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes391 assert len(digest_data["opaque"]) == expected_hash_length + 2392 assert digest_data["algorithm"] == algorithm393 assert digest_data["qop"] == "auth"394 assert digest_data["nc"] == "00000001"395 assert len(digest_data["cnonce"]) == 16 + 2396397398@pytest.mark.asyncio

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

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

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

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

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

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

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

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

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

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

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

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

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

line 412why, one step back
412

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

line 413why, one step back
413 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 414–429why, one step back
414 digest_data = dict(field.split("=") for field in response_fields)
415416 assert "qop" not in digest_data417 assert "nc" not in digest_data418 assert "cnonce" not in digest_data419 assert digest_data["username"] == '"tomchristie"'420 assert digest_data["realm"] == '"httpx@example.org"'421 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes422 assert digest_data["uri"] == '"/"'423 assert len(digest_data["response"]) == 64 + 2424 assert len(digest_data["opaque"]) == 64 + 2425 assert digest_data["algorithm"] == "SHA-256"426427428@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))429@pytest.mark.asyncio

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

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

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

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

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

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

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

line 436why, one step back
436

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

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

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

line 439why, one step back
439

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

line 440why, one step back
440

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

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

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

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

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

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

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

lines 446–451why, one step back
446
447 with pytest.raises(NotImplementedError):448 await client.get(url, auth=auth)449450451@pytest.mark.asyncio

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

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

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

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

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

lines 456–461why, one step back
456
457 with pytest.raises(ProtocolError):458 await client.get(url, auth=auth)459460461@pytest.mark.asyncio

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

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

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

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

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

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

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

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

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

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

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

lines 473–477why, one step back
473
474475@pytest.mark.parametrize(476 "auth_header",477 [

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 478–482why, one step back
478 b'Digest realm="httpx@example.org", qop="auth"', # missing fields
479 b'realm="httpx@example.org", qop="auth"', # not starting with Digest480 b'DigestZ realm="httpx@example.org", qop="auth"'481 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',482 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 483–485why, one step back
483 ],
484)485@pytest.mark.asyncio

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

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

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

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

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

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

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

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

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

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

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

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

line 493why, one step back
493 )

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

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

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

lines 497–498why, one step back
497
498

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

lines 499–521why, one step back
499@pytest.mark.parametrize(
500 "auth_header",501 [502 b'Digest realm="httpx@example.org", qop="auth"', # missing fields503 b'realm="httpx@example.org", qop="auth"', # not starting with Digest504 b'DigestZ realm="httpx@example.org", qop="auth"'505 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',506 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list507 ],508)509def test_sync_digest_auth_raises_protocol_error_on_malformed_header(510 auth_header: bytes,511) -> None:512 url = "https://example.org/"513 auth = DigestAuth(username="tomchristie", password="password123")514 client = Client(515 transport=SyncMockTransport(auth_header=auth_header, status_code=401)516 )517518 with pytest.raises(ProtocolError):519 client.get(url, auth=auth)520521

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

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

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

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

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

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

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

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

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

line 531why, one step back
531

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

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

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

line 535why, one step back
535

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

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

Public Auth API (#732)Tom Christiebefore adoption12dd157

line 540why, one step back
540

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

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

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

line 543why, one step back
543

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

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

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

lines 545–546why, one step back
545
546

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

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

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

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

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

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

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

line 555why, one step back
555

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

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

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

lines 557–568why, one step back
557 assert response.status_code == 200
558 assert response.json() == {"auth": "Repeat abc.abc"}559560 assert len(response.history) == 2561 resp1, resp2 = response.history562 assert resp1.json() == {"auth": "Repeat 0"}563 assert resp2.json() == {"auth": "Repeat 1"}564565 assert len(resp2.history) == 1566 assert resp2.history == [resp1]567568 assert len(resp1.history) == 0

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

lines 569–574why, one step back
569
570571@pytest.mark.asyncio572async def test_digest_auth_unavailable_streaming_body():573 url = "https://example.org/"574 auth = DigestAuth(username="tomchristie", password="password123")

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

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

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

lines 576–577why, one step back
576
577 async def streaming_body():

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

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

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

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

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

lines 582–584why, one step back
582
583584@pytest.mark.asyncio

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

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

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

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

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

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

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

line 593why, one step back
593

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

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

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

lines 597–598why, one step back
597
598

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

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

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

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

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

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

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

line 607why, one step back
607

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

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

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

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