Skip to content

Commit

Permalink
[AppConfig] Run pyright (Azure#32016)
Browse files Browse the repository at this point in the history
  • Loading branch information
YalinLi0312 authored Sep 19, 2023
1 parent 8a7fbdb commit 24241c0
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 56 deletions.
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
# license information.
# -------------------------------------------------------------------------
import binascii
import sys
from typing import Any, Dict, List, Mapping, Optional, Union, cast
from typing_extensions import Literal
from azure.core import MatchConditions
from azure.core.paging import ItemPaged
from azure.core.credentials import TokenCredential
Expand Down Expand Up @@ -45,11 +45,6 @@
from ._sync_token import SyncTokenPolicy
from ._user_agent import USER_AGENT

if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports


class AzureAppConfigurationClient:
"""Represents a client that calls restful API of Azure App Configuration service.
Expand Down Expand Up @@ -86,7 +81,7 @@ def __init__(self, base_url: str, credential: TokenCredential, **kwargs: Any) ->
if pipeline is None:
aad_mode = not isinstance(credential, AppConfigConnectionStringCredential)
pipeline = self._create_appconfig_pipeline(
credential=credential, aad_mode=aad_mode, base_url=base_url, **kwargs
credential=credential, credential_scopes=self._credential_scopes, aad_mode=aad_mode, **kwargs
)

self._impl = AzureAppConfiguration(
Expand Down Expand Up @@ -118,15 +113,14 @@ def from_connection_string(cls, connection_string: str, **kwargs: Any) -> "Azure
**kwargs
)

def _create_appconfig_pipeline(self, credential, base_url=None, aad_mode=False, **kwargs):
def _create_appconfig_pipeline(self, credential, credential_scopes, aad_mode=False, **kwargs):
transport = kwargs.get("transport")
policies = kwargs.get("policies")

if policies is None: # [] is a valid policy list
if aad_mode:
scope = base_url.strip("/") + "/.default"
if hasattr(credential, "get_token"):
credential_policy = BearerTokenCredentialPolicy(credential, scope)
credential_policy = BearerTokenCredentialPolicy(credential, credential_scopes)
else:
raise TypeError(
"Please provide an instance from azure-identity "
Expand Down Expand Up @@ -241,7 +235,7 @@ def get_configuration_setting(
key="MyKey", label="MyLabel"
)
"""
error_map = {} # type: Dict[int, Any]
error_map: Dict[int, Any] = {}
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
if match_condition == MatchConditions.IfPresent:
Expand Down Expand Up @@ -290,7 +284,7 @@ def add_configuration_setting(self, configuration_setting: ConfigurationSetting,
added_config_setting = client.add_configuration_setting(config_setting)
"""
key_value = configuration_setting._to_generated()
custom_headers = CaseInsensitiveDict(kwargs.get("headers")) # type: Mapping[str, Any]
custom_headers: Mapping[str, Any] = CaseInsensitiveDict(kwargs.get("headers"))
error_map = {412: ResourceExistsError}
try:
key_value_added = self._impl.put_key_value(
Expand Down Expand Up @@ -346,8 +340,8 @@ def set_configuration_setting(
returned_config_setting = client.set_configuration_setting(config_setting)
"""
key_value = configuration_setting._to_generated()
custom_headers = CaseInsensitiveDict(kwargs.get("headers")) # type: Mapping[str, Any]
error_map = {409: ResourceReadOnlyError} # type: Dict[int, Any]
custom_headers: Mapping[str, Any] = CaseInsensitiveDict(kwargs.get("headers"))
error_map: Dict[int, Any] = {409: ResourceReadOnlyError}
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
if match_condition == MatchConditions.IfModified:
Expand Down Expand Up @@ -404,8 +398,8 @@ def delete_configuration_setting( # pylint:disable=delete-operation-wrong-retur
"""
etag = kwargs.pop("etag", None)
match_condition = kwargs.pop("match_condition", MatchConditions.Unconditionally)
custom_headers = CaseInsensitiveDict(kwargs.get("headers")) # type: Mapping[str, Any]
error_map = {409: ResourceReadOnlyError} # type: Dict[int, Any]
custom_headers: Mapping[str, Any] = CaseInsensitiveDict(kwargs.get("headers"))
error_map: Dict[int, Any] = {409: ResourceReadOnlyError}
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
if match_condition == MatchConditions.IfModified:
Expand Down Expand Up @@ -510,7 +504,7 @@ def set_read_only(
read_only_config_setting = client.set_read_only(config_setting)
read_only_config_setting = client.set_read_only(config_setting, read_only=False)
"""
error_map = {} # type: Dict[int, Any]
error_map: Dict[int, Any] = {}
match_condition = kwargs.pop("match_condition", MatchConditions.Unconditionally)
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
Expand Down Expand Up @@ -614,7 +608,7 @@ def archive_snapshot(
:rtype: ~azure.appconfiguration.Snapshot
:raises: :class:`~azure.core.exceptions.HttpResponseError`
"""
error_map = {} # type: Dict[int, Any]
error_map: Dict[int, Any] = {}
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
if match_condition == MatchConditions.IfModified:
Expand Down Expand Up @@ -657,7 +651,7 @@ def recover_snapshot(
:rtype: ~azure.appconfiguration.Snapshot
:raises: :class:`~azure.core.exceptions.HttpResponseError`
"""
error_map = {} # type: Dict[int, Any]
error_map: Dict[int, Any] = {}
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
if match_condition == MatchConditions.IfModified:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1912,7 +1912,7 @@ def deserialize_date(attr):
if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore
raise DeserializationError("Date must have only digits and -. Received: %s" % attr)
# This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception.
return isodate.parse_date(attr, defaultmonth=None, defaultday=None)
return isodate.parse_date(attr, defaultmonth=0, defaultday=0)

@staticmethod
def deserialize_time(attr):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
# Licensed under the MIT License.
# ------------------------------------
import json
import sys
from datetime import datetime
from typing import Any, Dict, List, Optional, Union, cast
from typing_extensions import Literal

from azure.core.rest import HttpResponse
from ._generated._serialization import Model
Expand All @@ -16,12 +16,6 @@
SnapshotStatus,
)

if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports


PolymorphicConfigurationSetting = Union[
"ConfigurationSetting", "SecretReferenceConfigurationSetting", "FeatureFlagConfigurationSetting"
]
Expand All @@ -38,7 +32,7 @@ class ConfigurationSetting(Model):
"""The key of the configuration setting."""
label: str
"""The label of the configuration setting."""
content_type: str
content_type: Optional[str]
"""The content_type of the configuration setting."""
last_modified: datetime
"""A date representing the last time the key-value was modified."""
Expand Down Expand Up @@ -67,7 +61,7 @@ def __init__(self, **kwargs: Any) -> None:
self.label = kwargs.get("label", None)
self.value = kwargs.get("value", None)
self.etag = kwargs.get("etag", None)
self.content_type = kwargs.get("content_type", self.content_type)
self.content_type = kwargs.get("content_type", None)
self.last_modified = kwargs.get("last_modified", None)
self.read_only = kwargs.get("read_only", None)
self.tags = kwargs.get("tags", {})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
# IN THE SOFTWARE.
#
# --------------------------------------------------------------------------
from typing import Any, Dict
from typing import Any, Dict, Optional
from threading import Lock
from azure.core.pipeline import PipelineRequest, PipelineResponse
from azure.core.pipeline.policies import SansIOHTTPPolicy
Expand Down Expand Up @@ -67,10 +67,10 @@ class SyncTokenPolicy(SansIOHTTPPolicy):

def __init__(self, **kwargs: Any) -> None: # pylint: disable=unused-argument
self._sync_token_header = "Sync-Token"
self._sync_tokens = {} # type: Dict[str, Any]
self._sync_tokens: Dict[str, Any] = {}
self._lock = Lock()

def on_request(self, request: PipelineRequest) -> None: # type: ignore # pylint: disable=arguments-differ
def on_request(self, request: PipelineRequest) -> None:
"""This is executed before sending the request to the next policy.
:param request: The PipelineRequest object.
:type request: ~azure.core.pipeline.PipelineRequest
Expand All @@ -80,7 +80,7 @@ def on_request(self, request: PipelineRequest) -> None: # type: ignore # pylint
if sync_token_header:
request.http_request.headers.update({self._sync_token_header: sync_token_header})

def on_response(self, request: PipelineRequest, response: PipelineResponse) -> None: # type: ignore # pylint: disable=arguments-differ
def on_response(self, request: PipelineRequest, response: PipelineResponse) -> None:
"""This is executed after the request comes back from the policy.
:param request: The PipelineRequest object.
Expand All @@ -104,7 +104,7 @@ def add_token(self, full_raw_tokens: str) -> None:
sync_token = SyncToken.from_sync_token_string(raw_token)
self._update_sync_token(sync_token)

def _update_sync_token(self, sync_token: SyncToken) -> None:
def _update_sync_token(self, sync_token: Optional[SyncToken]) -> None:
if not sync_token:
return
with self._lock:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
# license information.
# -------------------------------------------------------------------------
import binascii
import sys
from typing import Any, Dict, List, Mapping, Optional, Union, cast
from typing_extensions import Literal
from azure.core import MatchConditions
from azure.core.async_paging import AsyncItemPaged
from azure.core.credentials_async import AsyncTokenCredential
Expand Down Expand Up @@ -37,11 +37,6 @@
prep_if_none_match,
)

if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports


class AzureAppConfigurationClient:
"""Represents a client that calls restful API of Azure App Configuration service.
Expand Down Expand Up @@ -80,7 +75,7 @@ def __init__(self, base_url: str, credential: AsyncTokenCredential, **kwargs: An
if aad_mode:
if hasattr(credential, "get_token"):
credential_policy = AsyncBearerTokenCredentialPolicy(
credential, # type: ignore
credential,
credential_scopes,
)
else:
Expand Down Expand Up @@ -217,7 +212,7 @@ async def get_configuration_setting(
key="MyKey", label="MyLabel"
)
"""
error_map = {} # type: Dict[int, Any]
error_map: Dict[int, Any] = {}
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
if match_condition == MatchConditions.IfPresent:
Expand Down Expand Up @@ -270,7 +265,7 @@ async def add_configuration_setting(
added_config_setting = await async_client.add_configuration_setting(config_setting)
"""
key_value = configuration_setting._to_generated()
custom_headers = CaseInsensitiveDict(kwargs.get("headers")) # type: Mapping[str, Any]
custom_headers: Mapping[str, Any] = CaseInsensitiveDict(kwargs.get("headers"))
error_map = {412: ResourceExistsError}

try:
Expand Down Expand Up @@ -331,8 +326,8 @@ async def set_configuration_setting(
etag = kwargs.get("etag", configuration_setting.etag)

key_value = configuration_setting._to_generated()
custom_headers = CaseInsensitiveDict(kwargs.get("headers")) # type: Mapping[str, Any]
error_map = {409: ResourceReadOnlyError} # type: Dict[int, Any]
custom_headers: Mapping[str, Any] = CaseInsensitiveDict(kwargs.get("headers"))
error_map: Dict[int, Any] = {409: ResourceReadOnlyError}
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
if match_condition == MatchConditions.IfModified:
Expand Down Expand Up @@ -390,8 +385,8 @@ async def delete_configuration_setting(
"""
etag = kwargs.pop("etag", None)
match_condition = kwargs.pop("match_condition", MatchConditions.Unconditionally)
custom_headers = CaseInsensitiveDict(kwargs.get("headers")) # type: Mapping[str, Any]
error_map = {409: ResourceReadOnlyError} # type: Dict[int, Any]
custom_headers: Mapping[str, Any] = CaseInsensitiveDict(kwargs.get("headers"))
error_map: Dict[int, Any] = {409: ResourceReadOnlyError}
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
if match_condition == MatchConditions.IfModified:
Expand Down Expand Up @@ -499,7 +494,7 @@ async def set_read_only(
read_only_config_setting = await async_client.set_read_only(config_setting)
read_only_config_setting = await client.set_read_only(config_setting, read_only=False)
"""
error_map = {} # type: Dict[int, Any]
error_map: Dict[int, Any] = {}
match_condition = kwargs.pop("match_condition", MatchConditions.Unconditionally)
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
Expand Down Expand Up @@ -603,7 +598,7 @@ async def archive_snapshot(
:rtype: ~azure.appconfiguration.Snapshot
:raises: :class:`~azure.core.exceptions.HttpResponseError`
"""
error_map = {} # type: Dict[int, Any]
error_map: Dict[int, Any] = {}
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
if match_condition == MatchConditions.IfModified:
Expand Down Expand Up @@ -646,7 +641,7 @@ async def recover_snapshot(
:rtype: ~azure.appconfiguration.Snapshot
:raises: :class:`~azure.core.exceptions.HttpResponseError`
"""
error_map = {} # type: Dict[int, Any]
error_map: Dict[int, Any] = {}
if match_condition == MatchConditions.IfNotModified:
error_map.update({412: ResourceModifiedError})
if match_condition == MatchConditions.IfModified:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
# IN THE SOFTWARE.
#
# --------------------------------------------------------------------------
from typing import Any, Dict
from typing import Any, Dict, Optional
from asyncio import Lock
from azure.core.pipeline import PipelineRequest, PipelineResponse
from azure.core.pipeline.policies import SansIOHTTPPolicy
Expand All @@ -39,10 +39,10 @@ class AsyncSyncTokenPolicy(SansIOHTTPPolicy):

def __init__(self, **kwargs: Any) -> None: # pylint: disable=unused-argument
self._sync_token_header = "Sync-Token"
self._sync_tokens = {} # type: Dict[str, Any]
self._sync_tokens: Dict[str, Any] = {}
self._lock = Lock()

async def on_request(self, request: PipelineRequest) -> None: # type: ignore # pylint: disable=arguments-differ, invalid-overridden-method
async def on_request(self, request: PipelineRequest) -> None: # pylint: disable=invalid-overridden-method
"""This is executed before sending the request to the next policy.
:param request: The PipelineRequest object.
Expand All @@ -53,7 +53,9 @@ async def on_request(self, request: PipelineRequest) -> None: # type: ignore #
if sync_token_header:
request.http_request.headers.update({self._sync_token_header: sync_token_header})

async def on_response(self, request: PipelineRequest, response: PipelineResponse) -> None: # type: ignore # pylint: disable=arguments-differ, invalid-overridden-method
async def on_response( # pylint: disable=invalid-overridden-method
self, request: PipelineRequest, response: PipelineResponse
) -> None:
"""This is executed after the request comes back from the policy.
:param request: The PipelineRequest object.
Expand All @@ -77,7 +79,7 @@ async def add_token(self, full_raw_tokens: str) -> None:
sync_token = SyncToken.from_sync_token_string(raw_token)
await self._update_sync_token(sync_token)

async def _update_sync_token(self, sync_token: SyncToken) -> None:
async def _update_sync_token(self, sync_token: Optional[SyncToken]) -> None:
if not sync_token:
return
async with self._lock:
Expand Down

0 comments on commit 24241c0

Please sign in to comment.