Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

694 lines · 21.9 KiB · Python

Last changed by

Fix warning test case (#1322)Tom Christiebefore adoption320bfe1

History of this file

Take it

The walk stopped after 200 commits: lines older than 330a825 point at it.

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

lines 1–6why, one step back
1"""
2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncio

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 7–8why, one step back
7import hashlib
8import os

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

line 9why, one step back
9import threading

Pin isort version (#1053)Josep Cugatbefore adoption330a825

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

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

line 14why, one step back
14import httpx

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

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

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

line 16why, one step back
16from tests.utils import MockTransport

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 17why, one step back
17

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 19why, one step back
19

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

line 20why, one step back
20

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 21–22why, one step back
21class App:
22 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 23–25why, one step back
23 self.auth_header = auth_header
24 self.status_code = status_code25

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 26–28why, one step back
26 def __call__(self, request: httpx.Request) -> httpx.Response:
27 headers = {"www-authenticate": self.auth_header} if self.auth_header else {}28 data = {"auth": request.headers.get("Authorization")}

Support Response(text=...), Response(html=...), Response(json=...) (#1297)Tom Christiebefore adoptionf3c2941

line 29why, one step back
29 return httpx.Response(self.status_code, headers=headers, json=data)

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 30–31why, one step back
30
31

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 32why, one step back
32class DigestApp:

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 33–45why, one step back
33 def __init__(
34 self,35 algorithm: str = "SHA-256",36 send_response_after_attempt: int = 1,37 qop: str = "auth",38 regenerate_nonce: bool = True,39 ) -> None:40 self.algorithm = algorithm41 self.send_response_after_attempt = send_response_after_attempt42 self.qop = qop43 self._regenerate_nonce = regenerate_nonce44 self._response_count = 045

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 46why, one step back
46 def __call__(self, request: httpx.Request) -> httpx.Response:

Pin isort version (#1053)Josep Cugatbefore adoption330a825

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

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 48why, one step back
48 return self.challenge_send(request)

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 49why, one step back
49

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 50why, one step back
50 data = {"auth": request.headers.get("Authorization")}

Support Response(text=...), Response(html=...), Response(json=...) (#1297)Tom Christiebefore adoptionf3c2941

line 51why, one step back
51 return httpx.Response(200, json=data)

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 52why, one step back
52

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 53why, one step back
53 def challenge_send(self, request: httpx.Request) -> httpx.Response:

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 54–74why, one step back
54 self._response_count += 1
55 nonce = (56 hashlib.sha256(os.urandom(8)).hexdigest()57 if self._regenerate_nonce58 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"59 )60 challenge_data = {61 "nonce": nonce,62 "qop": self.qop,63 "opaque": (64 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"65 ),66 "algorithm": self.algorithm,67 "stale": "FALSE",68 }69 challenge_str = ", ".join(70 '{}="{}"'.format(key, value)71 for key, value in challenge_data.items()72 if value73 )74

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 75–78why, one step back
75 headers = {
76 "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',77 }78 return Response(401, headers=headers)

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 79–126why, one step back
79
8081class RepeatAuth(Auth):82 """83 A mock authentication scheme that requires clients to send84 the request a fixed number of times, and then send a last request containing85 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers86 of intermediate responses.87 """8889 requires_request_body = True9091 def __init__(self, repeat: int):92 self.repeat = repeat9394 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:95 nonces = []9697 for index in range(self.repeat):98 request.headers["Authorization"] = f"Repeat {index}"99 response = yield request100 nonces.append(response.headers["www-authenticate"])101102 key = ".".join(nonces)103 request.headers["Authorization"] = f"Repeat {key}"104 yield request105106107class ResponseBodyAuth(Auth):108 """109 A mock authentication scheme that requires clients to send an 'Authorization'110 header, then send back the contents of the response in the 'Authorization'111 header.112 """113114 requires_response_body = True115116 def __init__(self, token):117 self.token = token118119 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:120 request.headers["Authorization"] = self.token121 response = yield request122 data = response.text123 request.headers["Authorization"] = data124 yield request125126

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

lines 127–151why, one step back
127class SyncOrAsyncAuth(Auth):
128 """129 A mock authentication scheme that uses a different implementation for the130 sync and async cases.131 """132133 def __init__(self) -> None:134 self._lock = threading.Lock()135 self._async_lock = asyncio.Lock()136137 def sync_auth_flow(138 self, request: Request139 ) -> typing.Generator[Request, Response, None]:140 with self._lock:141 request.headers["Authorization"] = "sync-auth"142 yield request143144 async def async_auth_flow(145 self, request: Request146 ) -> typing.AsyncGenerator[Request, Response]:147 async with self._async_lock:148 request.headers["Authorization"] = "async-auth"149 yield request150151

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 152–155why, one step back
152@pytest.mark.asyncio
153async def test_basic_auth() -> None:154 url = "https://example.org/"155 auth = ("tomchristie", "password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 156why, one step back
156 app = App()

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 157why, one step back
157

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 160–165why, one step back
160
161 assert response.status_code == 200162 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}163164165@pytest.mark.asyncio

Fix stream unsetting auth (#1312)Tom Christiebefore adoptiond25f2bf

lines 166–175why, one step back
166async def test_basic_auth_with_stream() -> None:
167 """168 See: https://github.com/encode/httpx/pull/1312169 """170 url = "https://example.org/"171 auth = ("tomchristie", "password123")172 app = App()173174 async with httpx.AsyncClient(transport=MockTransport(app), auth=auth) as client:175 async with client.stream("GET", url) as response:

Fix warning test case (#1322)Tom Christiebefore adoption320bfe1

line 176why, one step back
176 await response.aread()

Fix stream unsetting auth (#1312)Tom Christiebefore adoptiond25f2bf

lines 177–182why, one step back
177
178 assert response.status_code == 200179 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}180181182@pytest.mark.asyncio

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 183–184why, one step back
183async def test_basic_auth_in_url() -> None:
184 url = "https://tomchristie:password123@example.org/"

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 185why, one step back
185 app = App()

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 186why, one step back
186

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 189–197why, one step back
189
190 assert response.status_code == 200191 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}192193194@pytest.mark.asyncio195async def test_basic_auth_on_session() -> None:196 url = "https://example.org/"197 auth = ("tomchristie", "password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 198why, one step back
198 app = App()

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 199why, one step back
199

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 202–209why, one step back
202
203 assert response.status_code == 200204 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}205206207@pytest.mark.asyncio208async def test_custom_auth() -> None:209 url = "https://example.org/"

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 210why, one step back
210 app = App()

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 211–215why, one step back
211
212 def auth(request: Request) -> Request:213 request.headers["Authorization"] = "Token 123"214 return request215

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 218–224why, one step back
218
219 assert response.status_code == 200220 assert response.json() == {"auth": "Token 123"}221222223@pytest.mark.asyncio224async def test_netrc_auth() -> None:

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 226why, one step back
226 url = "http://netrcexample.org"

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 227why, one step back
227 app = App()

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 228why, one step back
228

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 231–239why, one step back
231
232 assert response.status_code == 200233 assert response.json() == {234 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"235 }236237238@pytest.mark.asyncio239async def test_auth_header_has_priority_over_netrc() -> None:

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 241why, one step back
241 url = "http://netrcexample.org"

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 242why, one step back
242 app = App()

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 243why, one step back
243

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 246–252why, one step back
246
247 assert response.status_code == 200248 assert response.json() == {"auth": "Override"}249250251@pytest.mark.asyncio252async def test_trust_env_auth() -> None:

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 254why, one step back
254 url = "http://netrcexample.org"

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 255why, one step back
255 app = App()

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 256why, one step back
256

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

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

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

line 258why, one step back
258 transport=MockTransport(app), trust_env=False

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 261–264why, one step back
261
262 assert response.status_code == 200263 assert response.json() == {"auth": None}264

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

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

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

line 266why, one step back
266 transport=MockTransport(app), trust_env=True

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

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

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

lines 276–279why, one step back
276@pytest.mark.asyncio
277async def test_auth_disable_per_request() -> None:278 url = "https://example.org/"279 auth = ("tomchristie", "password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 280why, one step back
280 app = App()

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

line 281why, one step back
281

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

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

lines 284–288why, one step back
284
285 assert response.status_code == 200286 assert response.json() == {"auth": None}287288

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 289–299why, one step back
289def test_auth_hidden_url() -> None:
290 url = "http://example-username:example-password@example.org/"291 expected = "URL('http://example-username:[secure]@example.org/')"292 assert url == URL(url)293 assert expected == repr(URL(url))294295296@pytest.mark.asyncio297async def test_auth_hidden_header() -> None:298 url = "https://example.org/"299 auth = ("example-username", "example-password")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 300why, one step back
300 app = App()

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 301why, one step back
301

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 304–308why, one step back
304
305 assert "'authorization': '[secure]'" in str(response.request.headers)306307308@pytest.mark.asyncio

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

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

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 310–311why, one step back
310 app = App()
311

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

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

line 314why, one step back
314

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

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

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

line 317why, one step back
317

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

lines 318–321why, one step back
318 url = "https://example.org/"
319 response = await client.get(url)320 assert response.status_code == 200321 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}

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

lines 322–325why, one step back
322
323324@pytest.mark.asyncio325async def test_auth_invalid_type() -> None:

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 326–327why, one step back
326 app = App()
327

Pin isort version (#1053)Josep Cugatbefore adoption330a825

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

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

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

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

line 330why, one step back
330 transport=MockTransport(app),

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

lines 331–333why, one step back
331 auth="not a tuple, not a callable", # type: ignore
332 )333

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

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

line 337why, one step back
337

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

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

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

line 340why, one step back
340

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 341–345why, one step back
341
342@pytest.mark.asyncio343async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:344 url = "https://example.org/"345 auth = DigestAuth(username="tomchristie", password="password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 346why, one step back
346 app = App()

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 347why, one step back
347

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 350–355why, one step back
350
351 assert response.status_code == 200352 assert response.json() == {"auth": None}353 assert len(response.history) == 0354355

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

lines 356–358why, one step back
356def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:
357 url = "https://example.org/"358 auth = DigestAuth(username="tomchristie", password="password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 359–360why, one step back
359 auth_header = "Token ..."
360 app = App(auth_header=auth_header, status_code=401)

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

line 361why, one step back
361

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 362why, one step back
362 client = httpx.Client(transport=MockTransport(app))

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

lines 363–369why, one step back
363 response = client.get(url, auth=auth)
364365 assert response.status_code == 401366 assert response.json() == {"auth": None}367 assert len(response.history) == 0368369

Pin isort version (#1053)Josep Cugatbefore adoption330a825

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

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 374–375why, one step back
374 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'
375 app = App(auth_header=auth_header, status_code=200)

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 376why, one step back
376

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 379–388why, one step back
379
380 assert response.status_code == 200381 assert response.json() == {"auth": None}382 assert len(response.history) == 0383384385@pytest.mark.asyncio386async def test_digest_auth_401_response_without_digest_auth_header() -> None:387 url = "https://example.org/"388 auth = DigestAuth(username="tomchristie", password="password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 389why, one step back
389 app = App(auth_header="", status_code=401)

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 390why, one step back
390

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 393–417why, one step back
393
394 assert response.status_code == 401395 assert response.json() == {"auth": None}396 assert len(response.history) == 0397398399@pytest.mark.parametrize(400 "algorithm,expected_hash_length,expected_response_length",401 [402 ("MD5", 64, 32),403 ("MD5-SESS", 64, 32),404 ("SHA", 64, 40),405 ("SHA-SESS", 64, 40),406 ("SHA-256", 64, 64),407 ("SHA-256-SESS", 64, 64),408 ("SHA-512", 64, 128),409 ("SHA-512-SESS", 64, 128),410 ],411)412@pytest.mark.asyncio413async def test_digest_auth(414 algorithm: str, expected_hash_length: int, expected_response_length: int415) -> None:416 url = "https://example.org/"417 auth = DigestAuth(username="tomchristie", password="password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 418why, one step back
418 app = DigestApp(algorithm=algorithm)

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 419why, one step back
419

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 422–448why, one step back
422
423 assert response.status_code == 200424 assert len(response.history) == 1425426 authorization = typing.cast(dict, response.json())["auth"]427 scheme, _, fields = authorization.partition(" ")428 assert scheme == "Digest"429430 response_fields = [field.strip() for field in fields.split(",")]431 digest_data = dict(field.split("=") for field in response_fields)432433 assert digest_data["username"] == '"tomchristie"'434 assert digest_data["realm"] == '"httpx@example.org"'435 assert "nonce" in digest_data436 assert digest_data["uri"] == '"/"'437 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes438 assert len(digest_data["opaque"]) == expected_hash_length + 2439 assert digest_data["algorithm"] == algorithm440 assert digest_data["qop"] == "auth"441 assert digest_data["nc"] == "00000001"442 assert len(digest_data["cnonce"]) == 16 + 2443444445@pytest.mark.asyncio446async def test_digest_auth_no_specified_qop() -> None:447 url = "https://example.org/"448 auth = DigestAuth(username="tomchristie", password="password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 449why, one step back
449 app = DigestApp(qop="")

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 450why, one step back
450

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 453–480why, one step back
453
454 assert response.status_code == 200455 assert len(response.history) == 1456457 authorization = typing.cast(dict, response.json())["auth"]458 scheme, _, fields = authorization.partition(" ")459 assert scheme == "Digest"460461 response_fields = [field.strip() for field in fields.split(",")]462 digest_data = dict(field.split("=") for field in response_fields)463464 assert "qop" not in digest_data465 assert "nc" not in digest_data466 assert "cnonce" not in digest_data467 assert digest_data["username"] == '"tomchristie"'468 assert digest_data["realm"] == '"httpx@example.org"'469 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes470 assert digest_data["uri"] == '"/"'471 assert len(digest_data["response"]) == 64 + 2472 assert len(digest_data["opaque"]) == 64 + 2473 assert digest_data["algorithm"] == "SHA-256"474475476@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))477@pytest.mark.asyncio478async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:479 url = "https://example.org/"480 auth = DigestAuth(username="tomchristie", password="password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 481why, one step back
481 app = DigestApp(qop=qop)

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 482why, one step back
482

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 485–493why, one step back
485
486 assert response.status_code == 200487 assert len(response.history) == 1488489490@pytest.mark.asyncio491async def test_digest_auth_qop_auth_int_not_implemented() -> None:492 url = "https://example.org/"493 auth = DigestAuth(username="tomchristie", password="password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 494why, one step back
494 app = DigestApp(qop="auth-int")

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 495why, one step back
495

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 499–504why, one step back
499
500501@pytest.mark.asyncio502async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:503 url = "https://example.org/"504 auth = DigestAuth(username="tomchristie", password="password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 505why, one step back
505 app = DigestApp(qop="not-auth")

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 506why, one step back
506

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 510–515why, one step back
510
511512@pytest.mark.asyncio513async def test_digest_auth_incorrect_credentials() -> None:514 url = "https://example.org/"515 auth = DigestAuth(username="tomchristie", password="password123")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 516why, one step back
516 app = DigestApp(send_response_after_attempt=2)

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 517why, one step back
517

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 520–527why, one step back
520
521 assert response.status_code == 401522 assert len(response.history) == 1523524525@pytest.mark.parametrize(526 "auth_header",527 [

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 530–533why, one step back
530 ],
531)532@pytest.mark.asyncio533async def test_async_digest_auth_raises_protocol_error_on_malformed_header(

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 534why, one step back
534 auth_header: str,

Pin isort version (#1053)Josep Cugatbefore adoption330a825

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

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 538–539why, one step back
538 app = App(auth_header=auth_header, status_code=401)
539

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 543–547why, one step back
543
544545@pytest.mark.parametrize(546 "auth_header",547 [

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 550–552why, one step back
550 ],
551)552def test_sync_digest_auth_raises_protocol_error_on_malformed_header(

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 553why, one step back
553 auth_header: str,

Pin isort version (#1053)Josep Cugatbefore adoption330a825

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

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 557why, one step back
557 app = App(auth_header=auth_header, status_code=401)

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

line 558why, one step back
558

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 562–571why, one step back
562
563564@pytest.mark.asyncio565async def test_async_auth_history() -> None:566 """567 Test that intermediate requests sent as part of an authentication flow568 are recorded in the response history.569 """570 url = "https://example.org/"571 auth = RepeatAuth(repeat=2)

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 572why, one step back
572 app = App(auth_header="abc")

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 573why, one step back
573

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 577–597why, one step back
577 assert response.status_code == 200
578 assert response.json() == {"auth": "Repeat abc.abc"}579580 assert len(response.history) == 2581 resp1, resp2 = response.history582 assert resp1.json() == {"auth": "Repeat 0"}583 assert resp2.json() == {"auth": "Repeat 1"}584585 assert len(resp2.history) == 1586 assert resp2.history == [resp1]587588 assert len(resp1.history) == 0589590591def test_sync_auth_history() -> None:592 """593 Test that intermediate requests sent as part of an authentication flow594 are recorded in the response history.595 """596 url = "https://example.org/"597 auth = RepeatAuth(repeat=2)

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 598why, one step back
598 app = App(auth_header="abc")

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 599why, one step back
599

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 603–620why, one step back
603 assert response.status_code == 200
604 assert response.json() == {"auth": "Repeat abc.abc"}605606 assert len(response.history) == 2607 resp1, resp2 = response.history608 assert resp1.json() == {"auth": "Repeat 0"}609 assert resp2.json() == {"auth": "Repeat 1"}610611 assert len(resp2.history) == 1612 assert resp2.history == [resp1]613614 assert len(resp1.history) == 0615616617@pytest.mark.asyncio618async def test_digest_auth_unavailable_streaming_body():619 url = "https://example.org/"620 auth = DigestAuth(username="tomchristie", password="password123")

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

line 621why, one step back
621 app = DigestApp()

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 622–625why, one step back
622
623 async def streaming_body():624 yield b"Example request body" # pragma: nocover625

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 629–638why, one step back
629
630631@pytest.mark.asyncio632async def test_async_auth_reads_response_body() -> None:633 """634 Test that we can read the response body in an auth flow if `requires_response_body`635 is set.636 """637 url = "https://example.org/"638 auth = ResponseBodyAuth("xyz")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

lines 639–640why, one step back
639 app = App()
640

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

lines 643–654why, one step back
643
644 assert response.status_code == 200645 assert response.json() == {"auth": '{"auth": "xyz"}'}646647648def test_sync_auth_reads_response_body() -> None:649 """650 Test that we can read the response body in an auth flow if `requires_response_body`651 is set.652 """653 url = "https://example.org/"654 auth = ResponseBodyAuth("xyz")

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 655why, one step back
655 app = App()

Pin isort version (#1053)Josep Cugatbefore adoption330a825

line 656why, one step back
656

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

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

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

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

Pin isort version (#1053)Josep Cugatbefore adoption330a825

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

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

lines 662–672why, one step back
662
663664@pytest.mark.asyncio665async def test_async_auth() -> None:666 """667 Test that we can use an auth implementation specific to the async case, to668 support cases that require performing I/O or using concurrency primitives (such669 as checking a disk-based cache or fetching a token from a remote auth server).670 """671 url = "https://example.org/"672 auth = SyncOrAsyncAuth()

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 673why, one step back
673 app = App()

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

line 674why, one step back
674

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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

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

lines 676–687why, one step back
676 response = await client.get(url, auth=auth)
677678 assert response.status_code == 200679 assert response.json() == {"auth": "async-auth"}680681682def test_sync_auth() -> None:683 """684 Test that we can use an auth implementation specific to the sync case.685 """686 url = "https://example.org/"687 auth = SyncOrAsyncAuth()

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

line 688why, one step back
688 app = App()

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

line 689why, one step back
689

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

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

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

lines 691–694why, one step back
691 response = client.get(url, auth=auth)
692693 assert response.status_code == 200694 assert response.json() == {"auth": "sync-auth"}