Skip to content
Myr

Add `Client.auth` setter (#1185)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Florimond Manca · committed by GitHub · parent 34ba0e1 · Browse files · 3 files+62 added−20 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+62 added−20 removed

  • tests:+27 added−6 removed
  • other:+35 added−14 removed

3 files+62 added−20 removed

modified:docs/api.md+2 added-2 removed
modified:httpx/_client.py+33 added-12 removed
69 unmodified lines
70 trust_env: bool = True,71 ):72 self._base_url = self._enforce_trailing_slash(URL(base_url))7374 self.auth = auth74 self._auth = self._build_auth(auth)75 self._params = QueryParams(params)76 self._headers = Headers(headers)77 self._cookies = Cookies(cookies)78 self._timeout = Timeout(timeout)
38 unmodified lines
117 def timeout(self, timeout: TimeoutTypes) -> None:118 self._timeout = Timeout(timeout)119120 @property121 def auth(self) -> typing.Optional[Auth]:122 """123 Authentication class used when none is passed at the request-level.124125 See also [Authentication][0].126127 [0]: /quickstart/#authentication128 """129 return self._auth130131 @auth.setter132 def auth(self, auth: AuthTypes) -> None:133 self._auth = self._build_auth(auth)134135 @property136 def base_url(self) -> URL:137 """138 Base URL to use when sending requests with relative URLs.139 """
158 unmodified lines
298 merged_queryparams.update(params)299 return merged_queryparams300 return params301287 def _build_auth(302 def _build_auth(self, auth: AuthTypes) -> typing.Optional[Auth]:303 if auth is None:304 return None305 elif isinstance(auth, tuple):306 return BasicAuth(username=auth[0], password=auth[1])307 elif isinstance(auth, Auth):308 return auth309 elif callable(auth):310 return FunctionAuth(func=auth)311 else:312 raise TypeError('Invalid "auth" argument.')313314 def _build_request_auth(315 self, request: Request, auth: typing.Union[AuthTypes, UnsetType] = UNSET316 ) -> Auth:290 auth = self.auth if isinstance(auth, UnsetType) else auth317 auth = self._auth if isinstance(auth, UnsetType) else self._build_auth(auth)318319 if auth is not None:293 if isinstance(auth, tuple):294 return BasicAuth(username=auth[0], password=auth[1])295 elif isinstance(auth, Auth):296 return auth320 return auth297 elif callable(auth):298 return FunctionAuth(func=auth)299 raise TypeError('Invalid "auth" argument.')321322 username, password = request.url.username, request.url.password323 if username or password:324 return BasicAuth(username=username, password=password)
362 unmodified lines
687 [0]: /advanced/#request-instances688 """689 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)690670 auth = self._build_auth(request, auth)691 auth = self._build_request_auth(request, auth)692693 response = self._send_handling_redirects(694 request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,695 )
593 unmodified lines
1289 [0]: /advanced/#request-instances1290 """1291 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)12921272 auth = self._build_auth(request, auth)1293 auth = self._build_request_auth(request, auth)12941295 response = await self._send_handling_redirects(1296 request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,1297 )
404 unmodified lines
modified:tests/client/test_auth.py+27 added-6 removed
7 unmodified lines
8from httpx import (9 URL,10 AsyncClient,11 Auth,12 BasicAuth,13 Client,14 DigestAuth,15 ProtocolError,16 Request,
293 unmodified lines
310 assert "'authorization': '[secure]'" in str(response.request.headers)311312313@pytest.mark.asyncio313async def test_auth_invalid_type() -> None:314async def test_auth_property() -> None:315 client = AsyncClient(transport=AsyncMockTransport())316 assert client.auth is None317318 client.auth = ("tomchristie", "password123") # type: ignore319 assert isinstance(client.auth, BasicAuth)320321 url = "https://example.org/"315 client = AsyncClient(316 transport=AsyncMockTransport(),317 auth="not a tuple, not a callable", # type: ignore318 )322 response = await client.get(url)323 assert response.status_code == 200324 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}325326327@pytest.mark.asyncio328async def test_auth_invalid_type() -> None:329 with pytest.raises(TypeError):320 await client.get(url)330 client = AsyncClient(331 transport=AsyncMockTransport(),332 auth="not a tuple, not a callable", # type: ignore333 )334335 client = AsyncClient(transport=AsyncMockTransport())336337 with pytest.raises(TypeError):338 await client.get(auth="not a tuple, not a callable") # type: ignore339340 with pytest.raises(TypeError):341 client.auth = "not a tuple, not a callable" # type: ignore342343344@pytest.mark.asyncio345async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:346 url = "https://example.org/"347 auth = DigestAuth(username="tomchristie", password="password123")
296 unmodified lines