Skip to content
Myr

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

1 file+98 added−134 removed

modified:tests/client/test_auth.py+98 added-134 removed
3 unmodified lines
4Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncio7import hashlib8import json9import os10import threading11import typing1212import httpcore13import pytest1415import httpx16from httpx import (
5 unmodified lines
22 Request,23 RequestBodyUnavailable,24 Response,25)26from httpx._content_streams import ContentStream, JSONStream26from tests.utils import AsyncMockTransport, MockTransport2728from ..common import FIXTURES_DIR293031def 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 default373839class MockTransport:40 def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:31class App:32 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:33 self.auth_header = auth_header34 self.status_code = status_code3544 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)414262class 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)697071class 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)787980class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):43class DigestApp:44 def __init__(45 self,46 algorithm: str = "SHA-256",47 send_response_after_attempt: int = 1,
5 unmodified lines
53 self.qop = qop54 self._regenerate_nonce = regenerate_nonce55 self._response_count = 05694 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)60108 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)64112 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_nonce
13 unmodified lines
83 for key, value in challenge_data.items()84 if value85 )86138 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)919293class RepeatAuth(Auth):94 """
69 unmodified lines
164@pytest.mark.asyncio165async def test_basic_auth() -> None:166 url = "https://example.org/"167 auth = ("tomchristie", "password123")168 app = App()169223 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)172173 assert response.status_code == 200174 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
1 unmodified line
176177@pytest.mark.asyncio178async def test_basic_auth_in_url() -> None:179 url = "https://tomchristie:password123@example.org/"180 app = App()181234 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:182 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:183 response = await client.get(url)184185 assert response.status_code == 200186 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
2 unmodified lines
189@pytest.mark.asyncio190async def test_basic_auth_on_session() -> None:191 url = "https://example.org/"192 auth = ("tomchristie", "password123")193 app = App()194246 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)199200 assert response.status_code == 200201 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
1 unmodified line
203204@pytest.mark.asyncio205async def test_custom_auth() -> None:206 url = "https://example.org/"207 app = App()208209 def auth(request: Request) -> Request:210 request.headers["Authorization"] = "Token 123"211 return request212261 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)215216 assert response.status_code == 200217 assert response.json() == {"auth": "Token 123"}
2 unmodified lines
220@pytest.mark.asyncio221async def test_netrc_auth() -> None:222 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")223 url = "http://netrcexample.org"224 app = App()225273 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:226 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:227 response = await client.get(url)228229 assert response.status_code == 200230 assert response.json() == {
4 unmodified lines
235@pytest.mark.asyncio236async 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()240287 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"})243244 assert response.status_code == 200245 assert response.json() == {"auth": "Override"}
2 unmodified lines
248@pytest.mark.asyncio249async def test_trust_env_auth() -> None:250 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")251 url = "http://netrcexample.org"252 app = App()253254 async with httpx.AsyncClient(300 transport=AsyncMockTransport(), trust_env=False255 transport=AsyncMockTransport(app), trust_env=False256 ) as client:257 response = await client.get(url)258259 assert response.status_code == 200260 assert response.json() == {"auth": None}261262 async with httpx.AsyncClient(308 transport=AsyncMockTransport(), trust_env=True263 transport=AsyncMockTransport(app), trust_env=True264 ) as client:265 response = await client.get(url)266267 assert response.status_code == 200
5 unmodified lines
273@pytest.mark.asyncio274async def test_auth_disable_per_request() -> None:275 url = "https://example.org/"276 auth = ("tomchristie", "password123")277 app = App()278323 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)283284 assert response.status_code == 200285 assert response.json() == {"auth": None}
9 unmodified lines
295@pytest.mark.asyncio296async def test_auth_hidden_header() -> None:297 url = "https://example.org/"298 auth = ("example-username", "example-password")299 app = App()300342 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)303304 assert "'authorization': '[secure]'" in str(response.request.headers)305306307@pytest.mark.asyncio308async def test_auth_property() -> None:309 app = App()310350 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:311 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:312 assert client.auth is None313314 client.auth = ("tomchristie", "password123") # type: ignore315 assert isinstance(client.auth, BasicAuth)
5 unmodified lines
321322323@pytest.mark.asyncio324async def test_auth_invalid_type() -> None:325 app = App()326327 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 )332370 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: ignore336337 with pytest.raises(TypeError):
3 unmodified lines
341@pytest.mark.asyncio342async 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()346383 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)349350 assert response.status_code == 200351 assert response.json() == {"auth": None}
2 unmodified lines
354355def 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)360396 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)363364 assert response.status_code == 401365 assert response.json() == {"auth": None}
3 unmodified lines
369@pytest.mark.asyncio370async 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)375412 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)378379 assert response.status_code == 200380 assert response.json() == {"auth": None}
3 unmodified lines
384@pytest.mark.asyncio385async 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)389427 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)392393 assert response.status_code == 401394 assert response.json() == {"auth": None}
18 unmodified lines
413 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)418457 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)421422 assert response.status_code == 200423 assert len(response.history) == 1
20 unmodified lines
444@pytest.mark.asyncio445async def test_digest_auth_no_specified_qop() -> None:446 url = "https://example.org/"447 auth = DigestAuth(username="tomchristie", password="password123")448 app = DigestApp(qop="")449489 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)452453 assert response.status_code == 200454 assert len(response.history) == 1
21 unmodified lines
476@pytest.mark.asyncio477async 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)481520 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)484485 assert response.status_code == 200486 assert len(response.history) == 1
2 unmodified lines
489@pytest.mark.asyncio490async 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")494532 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)498499500@pytest.mark.asyncio501async 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")505544 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)509510511@pytest.mark.asyncio512async 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)516556 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)519520 assert response.status_code == 401521 assert len(response.history) == 1
1 unmodified line
523524@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.asyncio532async 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)538539 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:540 with pytest.raises(ProtocolError):541 await client.get(url, auth=auth)542543544@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)551def 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)557598 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)561562
4 unmodified lines
567 are recorded in the response history.568 """569 url = "https://example.org/"570 auth = RepeatAuth(repeat=2)571 app = App(auth_header="abc")572614 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)575576 assert response.status_code == 200577 assert response.json() == {"auth": "Repeat abc.abc"}
15 unmodified lines
593 are recorded in the response history.594 """595 url = "https://example.org/"596 auth = RepeatAuth(repeat=2)597 app = App(auth_header="abc")598641 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)601602 assert response.status_code == 200603 assert response.json() == {"auth": "Repeat abc.abc"}
12 unmodified lines
616@pytest.mark.asyncio617async def test_digest_auth_unavailable_streaming_body():618 url = "https://example.org/"619 auth = DigestAuth(username="tomchristie", password="password123")620 app = App()621622 async def streaming_body():623 yield b"Example request body" # pragma: nocover624666 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)628629
4 unmodified lines
634 is set.635 """636 url = "https://example.org/"637 auth = ResponseBodyAuth("xyz")638 app = App()639679 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)642643 assert response.status_code == 200644 assert response.json() == {"auth": '{"auth": "xyz"}'}
5 unmodified lines
650 is set.651 """652 url = "https://example.org/"653 auth = ResponseBodyAuth("xyz")654 app = App()655694 with httpx.Client(transport=SyncMockTransport()) as client:656 with httpx.Client(transport=MockTransport(app)) as client:657 response = client.get(url, auth=auth)658659 assert response.status_code == 200660 assert response.json() == {"auth": '{"auth": "xyz"}'}
7 unmodified lines
668 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()673711 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)676677 assert response.status_code == 200678 assert response.json() == {"auth": "async-auth"}
4 unmodified lines
683 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()688725 with httpx.Client(transport=SyncMockTransport()) as client:689 with httpx.Client(transport=MockTransport(app)) as client:690 response = client.get(url, auth=auth)691692 assert response.status_code == 200693 assert response.json() == {"auth": "sync-auth"}