Skip to content

Commit a209c20

Browse files
authored
Run mypy in azure-identity CI (Azure#15832)
1 parent d50c779 commit a209c20

21 files changed

+121
-91
lines changed

eng/tox/mypy_hard_failure_packages.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
MYPY_HARD_FAILURE_OPTED = [
99
"azure-core",
1010
"azure-eventhub",
11+
"azure-identity",
1112
"azure-servicebus",
1213
"azure-ai-textanalytics",
1314
"azure-ai-formrecognizer",

sdk/identity/azure-identity/azure/identity/_authn_client.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,12 @@
3939
if TYPE_CHECKING:
4040
# pylint:disable=unused-import,ungrouped-imports
4141
from time import struct_time
42-
from typing import Any, Dict, Iterable, Mapping, Optional, Union
42+
from typing import Any, Dict, Iterable, List, Mapping, Optional, Union
4343
from azure.core.pipeline import PipelineResponse
4444
from azure.core.pipeline.transport import HttpTransport
45-
from azure.core.pipeline.policies import HTTPPolicy
45+
from azure.core.pipeline.policies import HTTPPolicy, SansIOHTTPPolicy
46+
47+
PolicyListType = List[Union[HTTPPolicy, SansIOHTTPPolicy]]
4648

4749

4850
class AuthnClientBase(ABC):
@@ -166,10 +168,9 @@ def _parse_app_service_expires_on(expires_on):
166168

167169
raise ValueError("'{}' doesn't match the expected format".format(expires_on))
168170

169-
# TODO: public, factor out of request_token
170171
def _prepare_request(
171172
self,
172-
method="POST", # type: Optional[str]
173+
method="POST", # type: str
173174
headers=None, # type: Optional[Mapping[str, str]]
174175
form_data=None, # type: Optional[Mapping[str, str]]
175176
params=None, # type: Optional[Dict[str, str]]
@@ -200,7 +201,7 @@ class AuthnClient(AuthnClientBase):
200201
def __init__(
201202
self,
202203
config=None, # type: Optional[Configuration]
203-
policies=None, # type: Optional[Iterable[HTTPPolicy]]
204+
policies=None, # type: Optional[PolicyListType]
204205
transport=None, # type: Optional[HttpTransport]
205206
**kwargs # type: Any
206207
):
@@ -217,13 +218,13 @@ def __init__(
217218
]
218219
if not transport:
219220
transport = RequestsTransport(**kwargs)
220-
self._pipeline = Pipeline(transport=transport, policies=policies)
221+
self._pipeline = Pipeline(transport=transport, policies=policies) # type: Pipeline
221222
super(AuthnClient, self).__init__(**kwargs)
222223

223224
def request_token(
224225
self,
225226
scopes, # type: Iterable[str]
226-
method="POST", # type: Optional[str]
227+
method="POST", # type: str
227228
headers=None, # type: Optional[Mapping[str, str]]
228229
form_data=None, # type: Optional[Mapping[str, str]]
229230
params=None, # type: Optional[Dict[str, str]]

sdk/identity/azure-identity/azure/identity/_credentials/app_service.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,14 @@ def __init__(self, **kwargs):
2525

2626
client_args = _get_client_args(**kwargs)
2727
if client_args:
28+
self._available = True
2829
self._client = ManagedIdentityClient(**client_args)
2930
else:
30-
self._client = None
31+
self._available = False
3132

3233
def get_token(self, *scopes, **kwargs):
3334
# type: (*str, **Any) -> AccessToken
34-
if not self._client:
35+
if not self._available:
3536
raise CredentialUnavailableError(
3637
message="App Service managed identity configuration not found in environment"
3738
)

sdk/identity/azure-identity/azure/identity/_credentials/azure_arc.py

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@
77
from typing import TYPE_CHECKING
88

99
from azure.core.exceptions import ClientAuthenticationError
10-
from azure.core.pipeline import PipelineRequest, PipelineResponse
11-
from azure.core.pipeline.transport import HttpRequest, HttpResponse
10+
from azure.core.pipeline.transport import HttpRequest
1211
from azure.core.pipeline.policies import (
1312
DistributedTracingPolicy,
1413
HttpLoggingPolicy,
@@ -28,6 +27,7 @@
2827
from typing import Any, List, Optional, Union
2928
from azure.core.configuration import Configuration
3029
from azure.core.credentials import AccessToken
30+
from azure.core.pipeline import PipelineRequest, PipelineResponse
3131
from azure.core.pipeline.policies import SansIOHTTPPolicy
3232

3333
PolicyType = Union[HTTPPolicy, SansIOHTTPPolicy]
@@ -40,24 +40,21 @@ def __init__(self, **kwargs):
4040

4141
url = os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT)
4242
imds = os.environ.get(EnvironmentVariables.IMDS_ENDPOINT)
43-
if not (url and imds):
44-
# Azure Arc managed identity isn't available in this environment
45-
self._client = None
46-
return
47-
48-
identity_config = kwargs.pop("_identity_config", None) or {}
49-
config = _get_configuration()
50-
51-
self._client = ManagedIdentityClient(
52-
_identity_config=identity_config,
53-
policies=_get_policies(config),
54-
request_factory=functools.partial(_get_request, url),
55-
**kwargs
56-
)
43+
self._available = url and imds
44+
if self._available:
45+
identity_config = kwargs.pop("_identity_config", None) or {}
46+
config = _get_configuration()
47+
48+
self._client = ManagedIdentityClient(
49+
_identity_config=identity_config,
50+
policies=_get_policies(config),
51+
request_factory=functools.partial(_get_request, url),
52+
**kwargs
53+
)
5754

5855
def get_token(self, *scopes, **kwargs):
5956
# type: (*str, **Any) -> AccessToken
60-
if not self._client:
57+
if not self._available:
6158
raise CredentialUnavailableError(
6259
message="Azure Arc managed identity configuration not found in environment"
6360
)
@@ -125,7 +122,7 @@ class ArcChallengeAuthPolicy(HTTPPolicy):
125122
"""Policy for handling Azure Arc's challenge authentication"""
126123

127124
def send(self, request):
128-
# type: (PipelineRequest) -> HttpResponse
125+
# type: (PipelineRequest) -> PipelineResponse
129126
request.http_request.headers["Metadata"] = "true"
130127
response = self.next.send(request)
131128

sdk/identity/azure-identity/azure/identity/_credentials/default.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@
2222
TYPE_CHECKING = False
2323

2424
if TYPE_CHECKING:
25-
from typing import Any
26-
from azure.core.credentials import AccessToken
25+
from typing import Any, List
26+
from azure.core.credentials import AccessToken, TokenCredential
2727

2828
_LOGGER = logging.getLogger(__name__)
2929

@@ -101,7 +101,7 @@ def __init__(self, **kwargs):
101101
exclude_cli_credential = kwargs.pop("exclude_cli_credential", False)
102102
exclude_interactive_browser_credential = kwargs.pop("exclude_interactive_browser_credential", True)
103103

104-
credentials = []
104+
credentials = [] # type: List[TokenCredential]
105105
if not exclude_environment_credential:
106106
credentials.append(EnvironmentCredential(authority=authority, **kwargs))
107107
if not exclude_managed_identity_credential:

sdk/identity/azure-identity/azure/identity/_credentials/managed_identity.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
if TYPE_CHECKING:
3434
# pylint:disable=unused-import
3535
from typing import Any, Optional, Type
36+
from azure.core.credentials import TokenCredential
3637

3738
_LOGGER = logging.getLogger(__name__)
3839

@@ -52,7 +53,7 @@ class ManagedIdentityCredential(object):
5253

5354
def __init__(self, **kwargs):
5455
# type: (**Any) -> None
55-
self._credential = None
56+
self._credential = None # type: Optional[TokenCredential]
5657
if os.environ.get(EnvironmentVariables.MSI_ENDPOINT):
5758
if os.environ.get(EnvironmentVariables.MSI_SECRET):
5859
_LOGGER.info("%s will use App Service managed identity", self.__class__.__name__)

sdk/identity/azure-identity/azure/identity/_credentials/service_fabric.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,14 @@ def __init__(self, **kwargs):
2525

2626
client_args = _get_client_args(**kwargs)
2727
if client_args:
28+
self._available = True
2829
self._client = ManagedIdentityClient(**client_args)
2930
else:
30-
self._client = None
31+
self._available = False
3132

3233
def get_token(self, *scopes, **kwargs):
3334
# type: (*str, **Any) -> AccessToken
34-
if not self._client:
35+
if not self._available:
3536
raise CredentialUnavailableError(
3637
message="Service Fabric managed identity configuration not found in environment"
3738
)

sdk/identity/azure-identity/azure/identity/_credentials/shared_cache.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,11 @@ def _acquire_token_silent(self, *scopes, **kwargs):
130130
# type: (*str, **Any) -> AccessToken
131131
"""Silently acquire a token from MSAL. Requires an AuthenticationRecord."""
132132

133+
# self._auth_record and ._app will not be None when this method is called by get_token
134+
# but should either be None anyway (and to satisfy mypy) we raise
135+
if self._app is None or self._auth_record is None:
136+
raise CredentialUnavailableError("Initialization failed")
137+
133138
result = None
134139

135140
accounts_for_user = self._app.get_accounts(username=self._auth_record.username)

sdk/identity/azure-identity/azure/identity/_internal/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ def get_default_authority():
3333

3434

3535
def validate_tenant_id(tenant_id):
36-
"""Raise ValueError if tenant_id is empty or contains a character invalid for a tenant id"""
3736
# type: (str) -> None
37+
"""Raise ValueError if tenant_id is empty or contains a character invalid for a tenant id"""
3838
if not tenant_id or any(c not in VALID_TENANT_ID_CHARACTERS for c in tenant_id):
3939
raise ValueError(
4040
"Invalid tenant id provided. You can locate your tenant id by following the instructions here: "

sdk/identity/azure-identity/azure/identity/_internal/get_token_mixin.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ class GetTokenMixin(ABC):
2626
def __init__(self, *args, **kwargs):
2727
# type: (*Any, **Any) -> None
2828
self._last_request_time = 0
29-
super(GetTokenMixin, self).__init__(*args, **kwargs)
29+
30+
# https://github.com/python/mypy/issues/5887
31+
super(GetTokenMixin, self).__init__(*args, **kwargs) # type: ignore
3032

3133
@abc.abstractmethod
3234
def _acquire_token_silently(self, *scopes):

0 commit comments

Comments
 (0)