Skip to content

Commit 92274fb

Browse files
[Communication Shared] Adding the mypy fixes (#42925)
* Adding the mypy fixes * addressing the comments * addressing comments * Make docs happy * Updated docstring references --------- Co-authored-by: antisch <[email protected]>
1 parent 48f4b19 commit 92274fb

File tree

80 files changed

+569
-602
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

80 files changed

+569
-602
lines changed

sdk/communication/azure-communication-callautomation/azure/communication/callautomation/_shared/auth_policy_utils.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,10 @@ def get_authentication_policy(
2828
:type credential: Union[TokenCredential, AsyncTokenCredential, AzureKeyCredential, str]
2929
:param bool decode_url: `True` if there is a need to decode the url. Default value is `False`
3030
:param bool is_async: For async clients there is a need to decode the url
31-
32-
:return: Either AsyncBearerTokenCredentialPolicy or BearerTokenCredentialPolicy or HMACCredentialsPolicy
31+
:return: The authentication policy to be used.
3332
:rtype: ~azure.core.pipeline.policies.AsyncBearerTokenCredentialPolicy or
34-
~azure.core.pipeline.policies.BearerTokenCredentialPolicy or
35-
~azure.communication.callautomation.shared.policy.HMACCredentialsPolicy
33+
~azure.core.pipeline.policies.BearerTokenCredentialPolicy or
34+
~.HMACCredentialsPolicy
3635
"""
3736

3837
if credential is None:

sdk/communication/azure-communication-callautomation/azure/communication/callautomation/_shared/models.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ def __init__(self, user_id: str, **kwargs: Any) -> None:
245245
:param str user_id: Microsoft Teams user id.
246246
:keyword bool is_anonymous: `True` if the identifier is anonymous. Default value is `False`.
247247
:keyword cloud: Cloud environment that the user belongs to. Default value is `PUBLIC`.
248-
:paramtype cloud: str or ~azure.communication.callautomation.CommunicationCloudEnvironment
248+
:paramtype cloud: str or :class:`~.CommunicationCloudEnvironment`
249249
:keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed from
250250
the other properties.
251251
"""
@@ -316,7 +316,7 @@ def __init__(self, app_id: str, **kwargs: Any) -> None:
316316
"""
317317
:param str app_id: Microsoft Teams application id.
318318
:keyword cloud: Cloud environment that the application belongs to. Default value is `PUBLIC`.
319-
:paramtype cloud: str or ~azure.communication.callautomation.CommunicationCloudEnvironment
319+
:paramtype cloud: str or :class:`~.CommunicationCloudEnvironment`
320320
:keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed
321321
from the other properties.
322322
"""
@@ -360,7 +360,7 @@ def __init__(self, bot_id, **kwargs):
360360
:keyword bool is_resource_account_configured: `False` if the identifier is global.
361361
Default value is `True` for tennantzed bots.
362362
:keyword cloud: Cloud environment that the bot belongs to. Default value is `PUBLIC`.
363-
:paramtype cloud: str or ~azure.communication.callautomation.CommunicationCloudEnvironment
363+
:paramtype cloud: str or :class:`~.CommunicationCloudEnvironment`
364364
"""
365365
warnings.warn(
366366
"The MicrosoftBotIdentifier is deprecated and has been replaced by MicrosoftTeamsAppIdentifier.",
@@ -398,7 +398,7 @@ def __init__(self, *, user_id: str, tenant_id: str, resource_id: str, **kwargs:
398398
:param str tenant_id: Tenant id associated with the user.
399399
:param str resource_id: The Communication Services resource id.
400400
:keyword cloud: Cloud environment that the user belongs to. Default value is `PUBLIC`.
401-
:paramtype cloud: str or ~azure.communication.callautomation.CommunicationCloudEnvironment
401+
:paramtype cloud: str or :class:`~.CommunicationCloudEnvironment`
402402
:keyword str raw_id: The raw ID of the identifier.
403403
If not specified, this value will be constructed from the other properties.
404404
"""
@@ -455,7 +455,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d
455455
456456
:param str raw_id: A raw ID to construct the CommunicationIdentifier from.
457457
:return: The CommunicationIdentifier parsed from the raw_id.
458-
:rtype: CommunicationIdentifier
458+
:rtype: :class:`~.CommunicationIdentifier`
459459
"""
460460
if raw_id.startswith(PHONE_NUMBER_PREFIX):
461461
return PhoneNumberIdentifier(value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id)

sdk/communication/azure-communication-chat/azure/communication/chat/_shared/auth_policy_utils.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
# license information.
55
# -------------------------------------------------------------------------
66

7-
from typing import Union
7+
from typing import Union, cast
88
from azure.core.credentials import TokenCredential, AzureKeyCredential
99
from azure.core.credentials_async import AsyncTokenCredential
1010
from azure.core.pipeline.policies import (
@@ -28,21 +28,22 @@ def get_authentication_policy(
2828
:type credential: Union[TokenCredential, AsyncTokenCredential, AzureKeyCredential, str]
2929
:param bool decode_url: `True` if there is a need to decode the url. Default value is `False`
3030
:param bool is_async: For async clients there is a need to decode the url
31-
32-
:return: Either AsyncBearerTokenCredentialPolicy or BearerTokenCredentialPolicy or HMACCredentialsPolicy
31+
:return: The authentication policy to be used.
3332
:rtype: ~azure.core.pipeline.policies.AsyncBearerTokenCredentialPolicy or
34-
~azure.core.pipeline.policies.BearerTokenCredentialPolicy or
35-
~azure.communication.chat.shared.policy.HMACCredentialsPolicy
33+
~azure.core.pipeline.policies.BearerTokenCredentialPolicy or
34+
~.HMACCredentialsPolicy
3635
"""
3736

3837
if credential is None:
3938
raise ValueError("Parameter 'credential' must not be None.")
4039
if hasattr(credential, "get_token"):
4140
if is_async:
4241
return AsyncBearerTokenCredentialPolicy(
43-
credential, "https://communication.azure.com//.default" # type: ignore
42+
cast(AsyncTokenCredential, credential), "https://communication.azure.com//.default"
4443
)
45-
return BearerTokenCredentialPolicy(credential, "https://communication.azure.com//.default") # type: ignore
44+
return BearerTokenCredentialPolicy(
45+
cast(TokenCredential, credential), "https://communication.azure.com//.default"
46+
)
4647
if isinstance(credential, (AzureKeyCredential, str)):
4748
return HMACCredentialsPolicy(endpoint, credential, decode_url=decode_url)
4849

sdk/communication/azure-communication-chat/azure/communication/chat/_shared/models.py

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -157,14 +157,16 @@ def __init__(self, value: str, **kwargs: Any) -> None:
157157
is_anonymous: bool
158158

159159
if raw_id is not None:
160-
phone_number = raw_id[len(PHONE_NUMBER_PREFIX):]
160+
phone_number = raw_id[len(PHONE_NUMBER_PREFIX) :]
161161
is_anonymous = phone_number == PHONE_NUMBER_ANONYMOUS_SUFFIX
162162
asserted_id_index = -1 if is_anonymous else phone_number.rfind("_") + 1
163163
has_asserted_id = 0 < asserted_id_index < len(phone_number)
164-
props = {"value": value, "is_anonymous": is_anonymous}
165164
if has_asserted_id:
166-
props["asserted_id"] = phone_number[asserted_id_index:]
167-
self.properties = PhoneNumberProperties(**props) # type: ignore
165+
self.properties = PhoneNumberProperties(
166+
value=value, is_anonymous=is_anonymous, asserted_id=phone_number[asserted_id_index:]
167+
)
168+
else:
169+
self.properties = PhoneNumberProperties(value=value, is_anonymous=is_anonymous)
168170
else:
169171
self.properties = PhoneNumberProperties(value=value)
170172
self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties)
@@ -183,6 +185,7 @@ def _format_raw_id(self, properties: PhoneNumberProperties) -> str:
183185
value = properties["value"]
184186
return f"{PHONE_NUMBER_PREFIX}{value}"
185187

188+
186189
class UnknownIdentifier:
187190
"""Represents an identifier of an unknown type.
188191
@@ -242,7 +245,7 @@ def __init__(self, user_id: str, **kwargs: Any) -> None:
242245
:param str user_id: Microsoft Teams user id.
243246
:keyword bool is_anonymous: `True` if the identifier is anonymous. Default value is `False`.
244247
:keyword cloud: Cloud environment that the user belongs to. Default value is `PUBLIC`.
245-
:paramtype cloud: str or ~azure.communication.chat.CommunicationCloudEnvironment
248+
:paramtype cloud: str or :class:`~.CommunicationCloudEnvironment`
246249
:keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed from
247250
the other properties.
248251
"""
@@ -313,7 +316,7 @@ def __init__(self, app_id: str, **kwargs: Any) -> None:
313316
"""
314317
:param str app_id: Microsoft Teams application id.
315318
:keyword cloud: Cloud environment that the application belongs to. Default value is `PUBLIC`.
316-
:paramtype cloud: str or ~azure.communication.chat.CommunicationCloudEnvironment
319+
:paramtype cloud: str or :class:`~.CommunicationCloudEnvironment`
317320
:keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed
318321
from the other properties.
319322
"""
@@ -357,7 +360,7 @@ def __init__(self, bot_id, **kwargs):
357360
:keyword bool is_resource_account_configured: `False` if the identifier is global.
358361
Default value is `True` for tennantzed bots.
359362
:keyword cloud: Cloud environment that the bot belongs to. Default value is `PUBLIC`.
360-
:paramtype cloud: str or ~azure.communication.chat.CommunicationCloudEnvironment
363+
:paramtype cloud: str or :class:`~.CommunicationCloudEnvironment`
361364
"""
362365
warnings.warn(
363366
"The MicrosoftBotIdentifier is deprecated and has been replaced by MicrosoftTeamsAppIdentifier.",
@@ -389,20 +392,13 @@ class TeamsExtensionUserIdentifier:
389392
raw_id: str
390393
"""The raw ID of the identifier."""
391394

392-
def __init__(
393-
self,
394-
*,
395-
user_id: str,
396-
tenant_id: str,
397-
resource_id: str,
398-
**kwargs: Any
399-
) -> None:
395+
def __init__(self, *, user_id: str, tenant_id: str, resource_id: str, **kwargs: Any) -> None:
400396
"""
401397
:param str user_id: Teams extension user id.
402398
:param str tenant_id: Tenant id associated with the user.
403399
:param str resource_id: The Communication Services resource id.
404400
:keyword cloud: Cloud environment that the user belongs to. Default value is `PUBLIC`.
405-
:paramtype cloud: str or ~azure.communication.chat.CommunicationCloudEnvironment
401+
:paramtype cloud: str or :class:`~.CommunicationCloudEnvironment`
406402
:keyword str raw_id: The raw ID of the identifier.
407403
If not specified, this value will be constructed from the other properties.
408404
"""
@@ -434,6 +430,7 @@ def _format_raw_id(self, properties: TeamsExtensionUserProperties) -> str:
434430
prefix = ACS_USER_PREFIX
435431
return f"{prefix}{properties['resource_id']}_{properties['tenant_id']}_{properties['user_id']}"
436432

433+
437434
def try_create_teams_extension_user(prefix: str, suffix: str) -> Optional[TeamsExtensionUserIdentifier]:
438435
segments = suffix.split("_")
439436
if len(segments) != 3:
@@ -449,6 +446,7 @@ def try_create_teams_extension_user(prefix: str, suffix: str) -> Optional[TeamsE
449446
raise ValueError("Invalid MRI")
450447
return TeamsExtensionUserIdentifier(user_id=user_id, tenant_id=tenant_id, resource_id=resource_id, cloud=cloud)
451448

449+
452450
def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: disable=too-many-return-statements
453451
"""
454452
Creates a CommunicationIdentifier from a given raw ID.
@@ -457,7 +455,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d
457455
458456
:param str raw_id: A raw ID to construct the CommunicationIdentifier from.
459457
:return: The CommunicationIdentifier parsed from the raw_id.
460-
:rtype: CommunicationIdentifier
458+
:rtype: :class:`~.CommunicationIdentifier`
461459
"""
462460
if raw_id.startswith(PHONE_NUMBER_PREFIX):
463461
return PhoneNumberIdentifier(value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id)

sdk/communication/azure-communication-chat/azure/communication/chat/_shared/policy.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,15 @@
55
# -------------------------------------------------------------------------
66

77
import hashlib
8-
import urllib
98
import base64
109
import hmac
11-
from urllib.parse import ParseResult, urlparse
10+
from urllib.parse import urlparse, unquote
1211
from typing import Union
12+
1313
from azure.core.credentials import AzureKeyCredential
1414
from azure.core.pipeline.policies import SansIOHTTPPolicy
15+
from azure.core.pipeline import PipelineRequest
16+
1517
from .utils import get_current_utc_time
1618

1719

@@ -41,9 +43,7 @@ def __init__(
4143
self._access_key = access_key
4244
self._decode_url = decode_url
4345

44-
def _compute_hmac(
45-
self, value # type: str
46-
):
46+
def _compute_hmac(self, value: str) -> str:
4747
if isinstance(self._access_key, AzureKeyCredential):
4848
decoded_secret = base64.b64decode(self._access_key.key)
4949
else:
@@ -53,11 +53,11 @@ def _compute_hmac(
5353

5454
return base64.b64encode(digest).decode("utf-8")
5555

56-
def _sign_request(self, request):
56+
def _sign_request(self, request: PipelineRequest) -> None:
5757
verb = request.http_request.method.upper()
5858

5959
# Get the path and query from url, which looks like https://host/path/query
60-
parsed_url: ParseResult = urlparse(request.http_request.url)
60+
parsed_url = urlparse(request.http_request.url)
6161
query_url = parsed_url.path
6262

6363
if parsed_url.query:
@@ -91,7 +91,7 @@ def _sign_request(self, request):
9191
pass
9292

9393
if self._decode_url:
94-
query_url = urllib.parse.unquote(query_url)
94+
query_url = unquote(query_url)
9595

9696
signed_headers = "x-ms-date;host;x-ms-content-sha256"
9797

@@ -114,7 +114,5 @@ def _sign_request(self, request):
114114

115115
request.http_request.headers.update(signature_header)
116116

117-
return request
118-
119-
def on_request(self, request):
117+
def on_request(self, request: PipelineRequest) -> None:
120118
self._sign_request(request)

sdk/communication/azure-communication-chat/azure/communication/chat/_shared/token_exchange.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import json
88
from typing import Any, List, Optional
9+
910
# pylint: disable=non-abstract-transport-import
1011
# pylint: disable=no-name-in-module
1112

@@ -21,7 +22,7 @@
2122

2223
class TokenExchangeClient:
2324
"""Represents a client that exchanges an Entra token for an Azure Communication Services (ACS) token.
24-
25+
2526
:param resource_endpoint: The endpoint URL of the resource to authenticate against.
2627
:param credential: The credential to use for token exchange.
2728
:param scopes: The scopes to request during the token exchange.
@@ -31,11 +32,8 @@ class TokenExchangeClient:
3132
# pylint: disable=C4748
3233
# pylint: disable=client-method-missing-type-annotations
3334
def __init__(
34-
self,
35-
resource_endpoint: str,
36-
credential: TokenCredential,
37-
scopes: Optional[List[str]] = None,
38-
**kwargs: Any):
35+
self, resource_endpoint: str, credential: TokenCredential, scopes: Optional[List[str]] = None, **kwargs: Any
36+
):
3937

4038
self._resource_endpoint = resource_endpoint
4139
self._scopes = scopes or ["https://communication.azure.com/clients/.default"]
@@ -76,6 +74,5 @@ def _parse_access_token_from_response(self, response: PipelineResponse) -> Acces
7674
raise ValueError("Failed to parse access token from response") from ex
7775
else:
7876
raise HttpResponseError(
79-
message="Failed to exchange Entra token for ACS token",
80-
response=response.http_response
77+
message="Failed to exchange Entra token for ACS token", response=response.http_response
8178
)

sdk/communication/azure-communication-chat/azure/communication/chat/_shared/token_exchange_async.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import json
88
from typing import Any, Optional, List
9+
910
# pylint: disable=non-abstract-transport-import
1011
# pylint: disable=no-name-in-module
1112

@@ -35,7 +36,8 @@ def __init__(
3536
resource_endpoint: str,
3637
credential: AsyncTokenCredential,
3738
scopes: Optional[List[str]] = None,
38-
**kwargs: Any):
39+
**kwargs: Any
40+
):
3941

4042
self._resource_endpoint = resource_endpoint
4143
self._scopes = scopes or ["https://communication.azure.com/clients/.default"]
@@ -76,6 +78,5 @@ async def _parse_access_token_from_response(self, response: PipelineResponse) ->
7678
raise ValueError("Failed to parse access token from response") from ex
7779
else:
7880
raise HttpResponseError(
79-
message="Failed to exchange Entra token for ACS token",
80-
response=response.http_response
81+
message="Failed to exchange Entra token for ACS token", response=response.http_response
8182
)

sdk/communication/azure-communication-chat/azure/communication/chat/_shared/token_utils.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
def create_request_message(resource_endpoint: str, scopes: Optional[List[str]]) -> Any:
2323
from azure.core.pipeline.transport import HttpRequest
24+
2425
request_uri = create_request_uri(resource_endpoint, scopes)
2526
request = HttpRequest("POST", request_uri)
2627
request.headers["Accept"] = "application/json"
@@ -59,33 +60,32 @@ def parse_expires_on(expires_on, response):
5960
return expires_on_epoch
6061
except Exception as exc:
6162
raise HttpResponseError(
62-
message="Unknown format for expires_on field in access token response",
63-
response=response.http_response) from exc
63+
message="Unknown format for expires_on field in access token response", response=response.http_response
64+
) from exc
6465
else:
6566
raise HttpResponseError(
66-
message="Missing expires_on field in access token response",
67-
response=response.http_response)
67+
message="Missing expires_on field in access token response", response=response.http_response
68+
)
6869

6970

7071
def is_entra_token_cache_valid(entra_token_cache, request):
7172
current_entra_token = request.http_request.headers.get("Authorization", "")
72-
cache_valid = (
73-
entra_token_cache is not None and
74-
current_entra_token == entra_token_cache
75-
)
73+
cache_valid = entra_token_cache is not None and current_entra_token == entra_token_cache
7674
return cache_valid, current_entra_token
7775

7876

7977
def is_acs_token_cache_valid(response_cache):
80-
if (response_cache is None or response_cache.http_response is None or
81-
response_cache.http_response.status_code != 200):
78+
if (
79+
response_cache is None
80+
or response_cache.http_response is None
81+
or response_cache.http_response.status_code != 200
82+
):
8283
return False
8384
try:
8485
content = response_cache.http_response.text()
8586
data = json.loads(content)
8687
expires_on = data["accessToken"]["expiresOn"]
8788
expires_on_dt = isodate.parse_datetime(expires_on)
8889
return datetime.now(timezone.utc) < expires_on_dt
89-
except (KeyError, ValueError, json.JSONDecodeError):
90-
raise ValueError( # pylint: disable=W0707
91-
"Invalid token response")
90+
except (KeyError, ValueError, json.JSONDecodeError) as e:
91+
raise ValueError("Invalid token response") from e

0 commit comments

Comments
 (0)