Refactor test_auth.py to use `MockTransport` class. (#1288)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Use tests.utils.MockTransport * Use tests.utils.MockTransport
authored by Tom Christie · committed by GitHub · parent 62c6c1c · Browse files · 1 file·+98 added−134 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+98 added−134 removed
- tests:+98 added−134 removed
Provenance
- Commit
2d6c30d- Tree
ebc9e3d- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
62c6c1c
1 file changed+98 added−134 removed
modified:tests/client/test_auth.py+98 added-134 removed
3 unmodified lines4 Unit tests for auth classes also exist in tests/test_auth.py5 """6 import asyncio7 import hashlib8+import json9 import os10 import threading11 import typing12 12-import httpcore13 import pytest14 15 import httpx16 from httpx import (5 unmodified lines22 Request,23 RequestBodyUnavailable,24 Response,25 )26-from httpx._content_streams import ContentStream, JSONStream26+from tests.utils import AsyncMockTransport, MockTransport27 28 from ..common import FIXTURES_DIR29 30 31-def get_header_value(headers, key, default=None):32- lookup = key.encode("ascii").lower()33- for header_key, header_value in headers:34- if header_key.lower() == lookup:35- return header_value.decode("ascii")36- return default37-38-39-class MockTransport:40- def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:31+class App:32+ def __init__(self, auth_header: str = "", status_code: int = 200) -> None:33 self.auth_header = auth_header34 self.status_code = status_code35 44- def _request(45- self,46- method: bytes,47- url: typing.Tuple[bytes, bytes, int, bytes],48- headers: typing.List[typing.Tuple[bytes, bytes]],49- stream: ContentStream,50- timeout: typing.Mapping[str, typing.Optional[float]] = None,51- ) -> typing.Tuple[52- bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream53- ]:54- authorization = get_header_value(headers, "Authorization")55- response_headers = (56- [(b"www-authenticate", self.auth_header)] if self.auth_header else []57- )58- response_stream = JSONStream({"auth": authorization})59- return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream36+ def __call__(self, request: httpx.Request) -> httpx.Response:37+ headers = {"www-authenticate": self.auth_header} if self.auth_header else {}38+ data = {"auth": request.headers.get("Authorization")}39+ content = json.dumps(data).encode("utf-8")40+ return httpx.Response(self.status_code, headers=headers, content=content)41 42 62-class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):63- async def request(64- self, *args, **kwargs65- ) -> typing.Tuple[66- bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream67- ]:68- return self._request(*args, **kwargs)69-70-71-class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):72- def request(73- self, *args, **kwargs74- ) -> typing.Tuple[75- bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream76- ]:77- return self._request(*args, **kwargs)78-79-80-class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):43+class DigestApp:44 def __init__(45 self,46 algorithm: str = "SHA-256",47 send_response_after_attempt: int = 1,5 unmodified lines53 self.qop = qop54 self._regenerate_nonce = regenerate_nonce55 self._response_count = 056 94- async def request(95- self,96- method: bytes,97- url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],98- headers: typing.List[typing.Tuple[bytes, bytes]] = None,99- stream: httpcore.AsyncByteStream = None,100- timeout: typing.Mapping[str, typing.Optional[float]] = None,101- ) -> typing.Tuple[102- bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream103- ]:57+ def __call__(self, request: httpx.Request) -> httpx.Response:58 if self._response_count < self.send_response_after_attempt:105- assert headers is not None106- return self.challenge_send(method, headers)59+ return self.challenge_send(request)60 108- authorization = get_header_value(headers, "Authorization")109- body = JSONStream({"auth": authorization})110- return b"HTTP/1.1", 200, b"", [], body61+ data = {"auth": request.headers.get("Authorization")}62+ content = json.dumps(data).encode("utf-8")63+ return httpx.Response(200, content=content)64 112- def challenge_send(113- self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]]114- ) -> typing.Tuple[115- bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream116- ]:65+ def challenge_send(self, request: httpx.Request) -> httpx.Response:66 self._response_count += 167 nonce = (68 hashlib.sha256(os.urandom(8)).hexdigest()69 if self._regenerate_nonce13 unmodified lines83 for key, value in challenge_data.items()84 if value85 )86 138- headers = [139- (140- b"www-authenticate",141- b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),142- )143- ]144- return b"HTTP/1.1", 401, b"", headers, ContentStream()87+ headers = {88+ "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',89+ }90+ return Response(401, headers=headers)91 92 93 class RepeatAuth(Auth):94 """69 unmodified lines164 @pytest.mark.asyncio165 async def test_basic_auth() -> None:166 url = "https://example.org/"167 auth = ("tomchristie", "password123")168+ app = App()169 223- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:170+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:171 response = await client.get(url, auth=auth)172 173 assert response.status_code == 200174 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}1 unmodified line176 177 @pytest.mark.asyncio178 async def test_basic_auth_in_url() -> None:179 url = "https://tomchristie:password123@example.org/"180+ app = App()181 234- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:182+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:183 response = await client.get(url)184 185 assert response.status_code == 200186 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}2 unmodified lines189 @pytest.mark.asyncio190 async def test_basic_auth_on_session() -> None:191 url = "https://example.org/"192 auth = ("tomchristie", "password123")193+ app = App()194 246- async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:195+ async with httpx.AsyncClient(196+ transport=AsyncMockTransport(app), auth=auth197+ ) as client:198 response = await client.get(url)199 200 assert response.status_code == 200201 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}1 unmodified line203 204 @pytest.mark.asyncio205 async def test_custom_auth() -> None:206 url = "https://example.org/"207+ app = App()208 209 def auth(request: Request) -> Request:210 request.headers["Authorization"] = "Token 123"211 return request212 261- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:213+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:214 response = await client.get(url, auth=auth)215 216 assert response.status_code == 200217 assert response.json() == {"auth": "Token 123"}2 unmodified lines220 @pytest.mark.asyncio221 async def test_netrc_auth() -> None:222 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")223 url = "http://netrcexample.org"224+ app = App()225 273- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:226+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:227 response = await client.get(url)228 229 assert response.status_code == 200230 assert response.json() == {4 unmodified lines235 @pytest.mark.asyncio236 async def test_auth_header_has_priority_over_netrc() -> None:237 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")238 url = "http://netrcexample.org"239+ app = App()240 287- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:241+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:242 response = await client.get(url, headers={"Authorization": "Override"})243 244 assert response.status_code == 200245 assert response.json() == {"auth": "Override"}2 unmodified lines248 @pytest.mark.asyncio249 async def test_trust_env_auth() -> None:250 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")251 url = "http://netrcexample.org"252+ app = App()253 254 async with httpx.AsyncClient(300- transport=AsyncMockTransport(), trust_env=False255+ transport=AsyncMockTransport(app), trust_env=False256 ) as client:257 response = await client.get(url)258 259 assert response.status_code == 200260 assert response.json() == {"auth": None}261 262 async with httpx.AsyncClient(308- transport=AsyncMockTransport(), trust_env=True263+ transport=AsyncMockTransport(app), trust_env=True264 ) as client:265 response = await client.get(url)266 267 assert response.status_code == 2005 unmodified lines273 @pytest.mark.asyncio274 async def test_auth_disable_per_request() -> None:275 url = "https://example.org/"276 auth = ("tomchristie", "password123")277+ app = App()278 323- async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:279+ async with httpx.AsyncClient(280+ transport=AsyncMockTransport(app), auth=auth281+ ) as client:282 response = await client.get(url, auth=None)283 284 assert response.status_code == 200285 assert response.json() == {"auth": None}9 unmodified lines295 @pytest.mark.asyncio296 async def test_auth_hidden_header() -> None:297 url = "https://example.org/"298 auth = ("example-username", "example-password")299+ app = App()300 342- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:301+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:302 response = await client.get(url, auth=auth)303 304 assert "'authorization': '[secure]'" in str(response.request.headers)305 306 307 @pytest.mark.asyncio308 async def test_auth_property() -> None:309+ app = App()310+350- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:311+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:312 assert client.auth is None313 314 client.auth = ("tomchristie", "password123") # type: ignore315 assert isinstance(client.auth, BasicAuth)5 unmodified lines321 322 323 @pytest.mark.asyncio324 async def test_auth_invalid_type() -> None:325+ app = App()326+327 with pytest.raises(TypeError):328 client = httpx.AsyncClient(366- transport=AsyncMockTransport(),329+ transport=AsyncMockTransport(app),330 auth="not a tuple, not a callable", # type: ignore331 )332 370- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:333+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:334 with pytest.raises(TypeError):335 await client.get(auth="not a tuple, not a callable") # type: ignore336 337 with pytest.raises(TypeError):3 unmodified lines341 @pytest.mark.asyncio342 async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:343 url = "https://example.org/"344 auth = DigestAuth(username="tomchristie", password="password123")345+ app = App()346 383- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:347+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:348 response = await client.get(url, auth=auth)349 350 assert response.status_code == 200351 assert response.json() == {"auth": None}2 unmodified lines354 355 def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:356 url = "https://example.org/"357 auth = DigestAuth(username="tomchristie", password="password123")394- auth_header = b"Token ..."358+ auth_header = "Token ..."359+ app = App(auth_header=auth_header, status_code=401)360 396- client = httpx.Client(397- transport=SyncMockTransport(auth_header=auth_header, status_code=401)398- )361+ client = httpx.Client(transport=MockTransport(app))362 response = client.get(url, auth=auth)363 364 assert response.status_code == 401365 assert response.json() == {"auth": None}3 unmodified lines369 @pytest.mark.asyncio370 async def test_digest_auth_200_response_including_digest_auth_header() -> None:371 url = "https://example.org/"372 auth = DigestAuth(username="tomchristie", password="password123")410- auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'373+ auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'374+ app = App(auth_header=auth_header, status_code=200)375 412- async with httpx.AsyncClient(413- transport=AsyncMockTransport(auth_header=auth_header, status_code=200)414- ) as client:376+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:377 response = await client.get(url, auth=auth)378 379 assert response.status_code == 200380 assert response.json() == {"auth": None}3 unmodified lines384 @pytest.mark.asyncio385 async def test_digest_auth_401_response_without_digest_auth_header() -> None:386 url = "https://example.org/"387 auth = DigestAuth(username="tomchristie", password="password123")388+ app = App(auth_header="", status_code=401)389 427- async with httpx.AsyncClient(428- transport=AsyncMockTransport(auth_header=b"", status_code=401)429- ) as client:390+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:391 response = await client.get(url, auth=auth)392 393 assert response.status_code == 401394 assert response.json() == {"auth": None}18 unmodified lines413 algorithm: str, expected_hash_length: int, expected_response_length: int414 ) -> None:415 url = "https://example.org/"416 auth = DigestAuth(username="tomchristie", password="password123")417+ app = DigestApp(algorithm=algorithm)418 457- async with httpx.AsyncClient(458- transport=MockDigestAuthTransport(algorithm=algorithm)459- ) as client:419+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:420 response = await client.get(url, auth=auth)421 422 assert response.status_code == 200423 assert len(response.history) == 120 unmodified lines444 @pytest.mark.asyncio445 async def test_digest_auth_no_specified_qop() -> None:446 url = "https://example.org/"447 auth = DigestAuth(username="tomchristie", password="password123")448+ app = DigestApp(qop="")449 489- async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop="")) as client:450+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:451 response = await client.get(url, auth=auth)452 453 assert response.status_code == 200454 assert len(response.history) == 121 unmodified lines476 @pytest.mark.asyncio477 async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:478 url = "https://example.org/"479 auth = DigestAuth(username="tomchristie", password="password123")480+ app = DigestApp(qop=qop)481 520- async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop=qop)) as client:482+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:483 response = await client.get(url, auth=auth)484 485 assert response.status_code == 200486 assert len(response.history) == 12 unmodified lines489 @pytest.mark.asyncio490 async def test_digest_auth_qop_auth_int_not_implemented() -> None:491 url = "https://example.org/"492 auth = DigestAuth(username="tomchristie", password="password123")493+ app = DigestApp(qop="auth-int")494 532- async with httpx.AsyncClient(533- transport=MockDigestAuthTransport(qop="auth-int")534- ) as client:495+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:496 with pytest.raises(NotImplementedError):497 await client.get(url, auth=auth)498 499 500 @pytest.mark.asyncio501 async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:502 url = "https://example.org/"503 auth = DigestAuth(username="tomchristie", password="password123")504+ app = DigestApp(qop="not-auth")505 544- async with httpx.AsyncClient(545- transport=MockDigestAuthTransport(qop="not-auth")546- ) as client:506+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:507 with pytest.raises(ProtocolError):508 await client.get(url, auth=auth)509 510 511 @pytest.mark.asyncio512 async def test_digest_auth_incorrect_credentials() -> None:513 url = "https://example.org/"514 auth = DigestAuth(username="tomchristie", password="password123")515+ app = DigestApp(send_response_after_attempt=2)516 556- async with httpx.AsyncClient(557- transport=MockDigestAuthTransport(send_response_after_attempt=2)558- ) as client:517+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:518 response = await client.get(url, auth=auth)519 520 assert response.status_code == 401521 assert len(response.history) == 11 unmodified line523 524 @pytest.mark.parametrize(525 "auth_header",526 [568- b'Digest realm="httpx@example.org", qop="auth"', # missing fields569- b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list527+ 'Digest realm="httpx@example.org", qop="auth"', # missing fields528+ 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list529 ],530 )531 @pytest.mark.asyncio532 async def test_async_digest_auth_raises_protocol_error_on_malformed_header(574- auth_header: bytes,533+ auth_header: str,534 ) -> None:535 url = "https://example.org/"536 auth = DigestAuth(username="tomchristie", password="password123")578- async with httpx.AsyncClient(579- transport=AsyncMockTransport(auth_header=auth_header, status_code=401)580- ) as client:537+ app = App(auth_header=auth_header, status_code=401)538+539+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:540 with pytest.raises(ProtocolError):541 await client.get(url, auth=auth)542 543 544 @pytest.mark.parametrize(545 "auth_header",546 [588- b'Digest realm="httpx@example.org", qop="auth"', # missing fields589- b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list547+ 'Digest realm="httpx@example.org", qop="auth"', # missing fields548+ 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list549 ],550 )551 def test_sync_digest_auth_raises_protocol_error_on_malformed_header(593- auth_header: bytes,552+ auth_header: str,553 ) -> None:554 url = "https://example.org/"555 auth = DigestAuth(username="tomchristie", password="password123")556+ app = App(auth_header=auth_header, status_code=401)557 598- with httpx.Client(599- transport=SyncMockTransport(auth_header=auth_header, status_code=401)600- ) as client:558+ with httpx.Client(transport=MockTransport(app)) as client:559 with pytest.raises(ProtocolError):560 client.get(url, auth=auth)561 562 4 unmodified lines567 are recorded in the response history.568 """569 url = "https://example.org/"570 auth = RepeatAuth(repeat=2)571+ app = App(auth_header="abc")572 614- async with httpx.AsyncClient(615- transport=AsyncMockTransport(auth_header=b"abc")616- ) as client:573+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:574 response = await client.get(url, auth=auth)575 576 assert response.status_code == 200577 assert response.json() == {"auth": "Repeat abc.abc"}15 unmodified lines593 are recorded in the response history.594 """595 url = "https://example.org/"596 auth = RepeatAuth(repeat=2)597+ app = App(auth_header="abc")598 641- with httpx.Client(transport=SyncMockTransport(auth_header=b"abc")) as client:599+ with httpx.Client(transport=MockTransport(app)) as client:600 response = client.get(url, auth=auth)601 602 assert response.status_code == 200603 assert response.json() == {"auth": "Repeat abc.abc"}12 unmodified lines616 @pytest.mark.asyncio617 async def test_digest_auth_unavailable_streaming_body():618 url = "https://example.org/"619 auth = DigestAuth(username="tomchristie", password="password123")620+ app = App()621 622 async def streaming_body():623 yield b"Example request body" # pragma: nocover624 666- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:625+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:626 with pytest.raises(RequestBodyUnavailable):627 await client.post(url, data=streaming_body(), auth=auth)628 629 4 unmodified lines634 is set.635 """636 url = "https://example.org/"637 auth = ResponseBodyAuth("xyz")638+ app = App()639+679- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:640+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:641 response = await client.get(url, auth=auth)642 643 assert response.status_code == 200644 assert response.json() == {"auth": '{"auth": "xyz"}'}5 unmodified lines650 is set.651 """652 url = "https://example.org/"653 auth = ResponseBodyAuth("xyz")654+ app = App()655 694- with httpx.Client(transport=SyncMockTransport()) as client:656+ with httpx.Client(transport=MockTransport(app)) as client:657 response = client.get(url, auth=auth)658 659 assert response.status_code == 200660 assert response.json() == {"auth": '{"auth": "xyz"}'}7 unmodified lines668 as checking a disk-based cache or fetching a token from a remote auth server).669 """670 url = "https://example.org/"671 auth = SyncOrAsyncAuth()672+ app = App()673 711- async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:674+ async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:675 response = await client.get(url, auth=auth)676 677 assert response.status_code == 200678 assert response.json() == {"auth": "async-auth"}4 unmodified lines683 Test that we can use an auth implementation specific to the sync case.684 """685 url = "https://example.org/"686 auth = SyncOrAsyncAuth()687+ app = App()688 725- with httpx.Client(transport=SyncMockTransport()) as client:689+ with httpx.Client(transport=MockTransport(app)) as client:690 response = client.get(url, auth=auth)691 692 assert response.status_code == 200693 assert response.json() == {"auth": "sync-auth"}