diff --git a/sdk/communication/azure-communication-chat/azure/__init__.py b/sdk/communication/azure-communication-chat/azure/__init__.py index 69e3be50dac4..8db66d3d0f0f 100644 --- a/sdk/communication/azure-communication-chat/azure/__init__.py +++ b/sdk/communication/azure-communication-chat/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/communication/azure-communication-chat/azure/communication/__init__.py b/sdk/communication/azure-communication-chat/azure/communication/__init__.py index 69e3be50dac4..8db66d3d0f0f 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/__init__.py +++ b/sdk/communication/azure-communication-chat/azure/communication/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/__init__.py b/sdk/communication/azure-communication-chat/azure/communication/chat/__init__.py index b9136cb894d9..13a4160bf9c2 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/__init__.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/__init__.py @@ -1,13 +1,7 @@ from ._version import VERSION from ._chat_client import ChatClient from ._chat_thread_client import ChatThreadClient -from ._generated.models import ( - ChatAttachmentType, - SendChatMessageResult, - ChatThreadItem, - ChatMessageType, - ChatError -) +from ._generated.models import ChatAttachmentType, SendChatMessageResult, ChatThreadItem, ChatMessageType, ChatError from ._models import ( ChatAttachment, @@ -16,7 +10,7 @@ ChatThreadProperties, ChatMessageReadReceipt, ChatMessageContent, - CreateChatThreadResult + CreateChatThreadResult, ) from ._shared.user_credential import CommunicationTokenCredential @@ -32,36 +26,36 @@ MicrosoftTeamsAppProperties, MicrosoftTeamsUserIdentifier, MicrosoftTeamsUserProperties, - UnknownIdentifier + UnknownIdentifier, ) __all__ = [ - 'ChatClient', - 'ChatThreadClient', - 'ChatMessage', - 'ChatMessageContent', - 'ChatMessageReadReceipt', - 'SendChatMessageResult', - 'ChatThreadProperties', - 'ChatThreadItem', - 'ChatParticipant', - 'ChatMessageType', - 'ChatAttachment', - 'ChatAttachmentType', - 'CreateChatThreadResult', - 'ChatError', - 'CommunicationTokenCredential', - 'CommunicationIdentifier', - 'CommunicationIdentifierKind', - 'CommunicationUserIdentifier', - 'CommunicationUserProperties', - 'MicrosoftTeamsAppIdentifier', - 'MicrosoftTeamsAppProperties', - 'MicrosoftTeamsUserIdentifier', - 'MicrosoftTeamsUserProperties', - 'identifier_from_raw_id', - 'PhoneNumberIdentifier', - 'PhoneNumberProperties', - 'UnknownIdentifier' + "ChatClient", + "ChatThreadClient", + "ChatMessage", + "ChatMessageContent", + "ChatMessageReadReceipt", + "SendChatMessageResult", + "ChatThreadProperties", + "ChatThreadItem", + "ChatParticipant", + "ChatMessageType", + "ChatAttachment", + "ChatAttachmentType", + "CreateChatThreadResult", + "ChatError", + "CommunicationTokenCredential", + "CommunicationIdentifier", + "CommunicationIdentifierKind", + "CommunicationUserIdentifier", + "CommunicationUserProperties", + "MicrosoftTeamsAppIdentifier", + "MicrosoftTeamsAppProperties", + "MicrosoftTeamsUserIdentifier", + "MicrosoftTeamsUserProperties", + "identifier_from_raw_id", + "PhoneNumberIdentifier", + "PhoneNumberProperties", + "UnknownIdentifier", ] __version__ = VERSION diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/_chat_client.py b/sdk/communication/azure-communication-chat/azure/communication/chat/_chat_client.py index 48260cc8261f..10e533135443 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/_chat_client.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/_chat_client.py @@ -14,14 +14,11 @@ from ._shared.user_credential import CommunicationTokenCredential from ._generated import AzureCommunicationChatService from ._generated.models import CreateChatThreadRequest -from ._models import ( - ChatThreadProperties, - CreateChatThreadResult -) -from ._utils import ( # pylint: disable=unused-import +from ._models import ChatThreadProperties, CreateChatThreadResult +from ._utils import ( # pylint: disable=unused-import _to_utc_datetime, return_response, - CommunicationErrorResponseConverter + CommunicationErrorResponseConverter, ) from ._version import SDK_MONIKER @@ -31,7 +28,7 @@ from azure.core.paging import ItemPaged -class ChatClient(object): # pylint: disable=client-accepts-api-version-keyword +class ChatClient(object): # pylint: disable=client-accepts-api-version-keyword """A client to interact with the AzureCommunicationService Chat gateway. This client provides operations to create chat thread, delete chat thread, @@ -53,22 +50,22 @@ class ChatClient(object): # pylint: disable=client-accepts-api-version-keyword """ def __init__( - self, - endpoint, # type: str - credential, # type: CommunicationTokenCredential - **kwargs # type: Any + self, + endpoint, # type: str + credential, # type: CommunicationTokenCredential + **kwargs # type: Any ): # type: (...) -> None if not credential: raise ValueError("credential can not be None") try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError: - raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from + raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from - parsed_url = urlparse(endpoint.rstrip('/')) + parsed_url = urlparse(endpoint.rstrip("/")) if not parsed_url.netloc: raise ValueError("Invalid URL: {}".format(endpoint)) @@ -84,7 +81,8 @@ def __init__( @distributed_trace def get_chat_thread_client( - self, thread_id, # type: str + self, + thread_id, # type: str **kwargs # type: Any ): # type: (...) -> ChatThreadClient @@ -109,16 +107,12 @@ def get_chat_thread_client( if not thread_id: raise ValueError("thread_id cannot be None.") - return ChatThreadClient( - endpoint=self._endpoint, - credential=self._credential, - thread_id=thread_id, - **kwargs - ) + return ChatThreadClient(endpoint=self._endpoint, credential=self._credential, thread_id=thread_id, **kwargs) @distributed_trace def create_chat_thread( - self, topic, # type: str + self, + topic, # type: str **kwargs # type: Any ): # type: (...) -> CreateChatThreadResult @@ -151,11 +145,11 @@ def create_chat_thread( if not topic: raise ValueError("topic cannot be None.") - idempotency_token = kwargs.pop('idempotency_token', None) + idempotency_token = kwargs.pop("idempotency_token", None) if idempotency_token is None: idempotency_token = str(uuid4()) - thread_participants = kwargs.pop('thread_participants', None) + thread_participants = kwargs.pop("thread_participants", None) participants = [] if thread_participants is not None: participants = [m._to_generated() for m in thread_participants] # pylint:disable=protected-access @@ -163,33 +157,25 @@ def create_chat_thread( create_thread_request = CreateChatThreadRequest(topic=topic, participants=participants) create_chat_thread_result = self._client.chat.create_chat_thread( - create_chat_thread_request=create_thread_request, - repeatability_request_id=idempotency_token, - **kwargs) + create_chat_thread_request=create_thread_request, repeatability_request_id=idempotency_token, **kwargs + ) errors = None - if hasattr(create_chat_thread_result, 'invalid_participants'): + if hasattr(create_chat_thread_result, "invalid_participants"): errors = CommunicationErrorResponseConverter.convert( - participants=thread_participants or [], - chat_errors=create_chat_thread_result.invalid_participants + participants=thread_participants or [], chat_errors=create_chat_thread_result.invalid_participants ) - chat_thread_properties = ChatThreadProperties._from_generated( # pylint:disable=protected-access - create_chat_thread_result.chat_thread) - - create_chat_thread_result = CreateChatThreadResult( - chat_thread=chat_thread_properties, - errors=errors + chat_thread_properties = ChatThreadProperties._from_generated( # pylint:disable=protected-access + create_chat_thread_result.chat_thread ) - return create_chat_thread_result + create_chat_thread_result = CreateChatThreadResult(chat_thread=chat_thread_properties, errors=errors) + return create_chat_thread_result @distributed_trace - def list_chat_threads( - self, - **kwargs - ): + def list_chat_threads(self, **kwargs): # type: (...) -> ItemPaged[ChatThreadItem] """Gets the list of chat threads of a user. @@ -211,10 +197,7 @@ def list_chat_threads( results_per_page = kwargs.pop("results_per_page", None) start_time = kwargs.pop("start_time", None) - return self._client.chat.list_chat_threads( - max_page_size=results_per_page, - start_time=start_time, - **kwargs) + return self._client.chat.list_chat_threads(max_page_size=results_per_page, start_time=start_time, **kwargs) @distributed_trace def delete_chat_thread( diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/_chat_thread_client.py b/sdk/communication/azure-communication-chat/azure/communication/chat/_chat_thread_client.py index ad8f60088298..8d63a6d35b0a 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/_chat_thread_client.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/_chat_thread_client.py @@ -21,14 +21,9 @@ UpdateChatMessageRequest, UpdateChatThreadRequest, ChatMessageType, - SendChatMessageResult -) -from ._models import ( - ChatParticipant, - ChatMessage, - ChatMessageReadReceipt, - ChatThreadProperties + SendChatMessageResult, ) +from ._models import ChatParticipant, ChatMessage, ChatMessageReadReceipt, ChatThreadProperties from ._communication_identifier_serializer import serialize_identifier from ._utils import CommunicationErrorResponseConverter @@ -40,7 +35,7 @@ from azure.core.paging import ItemPaged -class ChatThreadClient(object): # pylint: disable=client-accepts-api-version-keyword +class ChatThreadClient(object): # pylint: disable=client-accepts-api-version-keyword """A client to interact with the AzureCommunicationService Chat gateway. Instances of this class is normally retrieved by ChatClient.get_chat_thread_client() @@ -70,11 +65,11 @@ class ChatThreadClient(object): # pylint: disable=client-accepts-api-version-key """ def __init__( - self, - endpoint, # type: str - credential, # type: CommunicationTokenCredential - thread_id, # type: str - **kwargs # type: Any + self, + endpoint, # type: str + credential, # type: CommunicationTokenCredential + thread_id, # type: str + **kwargs # type: Any ): # type: (...) -> None if not thread_id: @@ -84,12 +79,12 @@ def __init__( raise ValueError("credential can not be None") try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError: - raise ValueError("Host URL must be a string") # pylint: disable=raise-missing-from + raise ValueError("Host URL must be a string") # pylint: disable=raise-missing-from - parsed_url = urlparse(endpoint.rstrip('/')) + parsed_url = urlparse(endpoint.rstrip("/")) if not parsed_url.netloc: raise ValueError("Invalid URL: {}".format(endpoint)) @@ -116,8 +111,7 @@ def thread_id(self): @distributed_trace def get_properties( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> ChatThreadProperties """Gets the properties of the chat thread. @@ -139,7 +133,6 @@ def get_properties( chat_thread = self._client.chat_thread.get_chat_thread_properties(self._thread_id, **kwargs) return ChatThreadProperties._from_generated(chat_thread) # pylint:disable=protected-access - @distributed_trace def update_topic( self, @@ -168,9 +161,8 @@ def update_topic( update_topic_request = UpdateChatThreadRequest(topic=topic) return self._client.chat_thread.update_chat_thread_properties( - chat_thread_id=self._thread_id, - update_chat_thread_request=update_topic_request, - **kwargs) + chat_thread_id=self._thread_id, update_chat_thread_request=update_topic_request, **kwargs + ) @distributed_trace def send_read_receipt( @@ -201,14 +193,12 @@ def send_read_receipt( post_read_receipt_request = SendReadReceiptRequest(chat_message_id=message_id) return self._client.chat_thread.send_chat_read_receipt( - self._thread_id, - send_read_receipt_request=post_read_receipt_request, - **kwargs) + self._thread_id, send_read_receipt_request=post_read_receipt_request, **kwargs + ) @distributed_trace def list_read_receipts( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> ItemPaged[ChatMessageReadReceipt] """Gets read receipts for a thread. @@ -235,13 +225,15 @@ def list_read_receipts( self._thread_id, max_page_size=results_per_page, skip=skip, - cls=lambda objs: [ChatMessageReadReceipt._from_generated(x) for x in objs], # pylint:disable=protected-access - **kwargs) + cls=lambda objs: [ + ChatMessageReadReceipt._from_generated(x) for x in objs # pylint:disable=protected-access + ], + **kwargs + ) @distributed_trace def send_typing_notification( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None """Posts a typing event to a thread, on behalf of a user. @@ -265,9 +257,8 @@ def send_typing_notification( sender_display_name = kwargs.pop("sender_display_name", None) send_typing_notification_request = SendTypingNotificationRequest(sender_display_name=sender_display_name) return self._client.chat_thread.send_typing_notification( - chat_thread_id=self._thread_id, - send_typing_notification_request=send_typing_notification_request, - **kwargs) + chat_thread_id=self._thread_id, send_typing_notification_request=send_typing_notification_request, **kwargs + ) @distributed_trace def send_message( @@ -307,29 +298,27 @@ def send_message( chat_message_type = ChatMessageType.TEXT elif not isinstance(chat_message_type, ChatMessageType): try: - chat_message_type = ChatMessageType.__getattr__(chat_message_type) # pylint:disable=protected-access + chat_message_type = ChatMessageType.__getattr__(chat_message_type) # pylint:disable=protected-access except Exception: - raise ValueError( # pylint:disable=raise-missing-from - "chat_message_type: {message_type} is not acceptable".format(message_type=chat_message_type)) + raise ValueError( # pylint:disable=raise-missing-from + "chat_message_type: {message_type} is not acceptable".format(message_type=chat_message_type) + ) if chat_message_type not in [ChatMessageType.TEXT, ChatMessageType.HTML]: raise ValueError( - "chat_message_type: {message_type} can be only 'text' or 'html'".format(message_type=chat_message_type)) + "chat_message_type: {message_type} can be only 'text' or 'html'".format(message_type=chat_message_type) + ) sender_display_name = kwargs.pop("sender_display_name", None) metadata = kwargs.pop("metadata", None) create_message_request = SendChatMessageRequest( - content=content, - type=chat_message_type, - sender_display_name=sender_display_name, - metadata=metadata + content=content, type=chat_message_type, sender_display_name=sender_display_name, metadata=metadata ) send_chat_message_result = self._client.chat_thread.send_chat_message( - chat_thread_id=self._thread_id, - send_chat_message_request=create_message_request, - **kwargs) + chat_thread_id=self._thread_id, send_chat_message_request=create_message_request, **kwargs + ) return send_chat_message_result @distributed_trace @@ -364,8 +353,7 @@ def get_message( @distributed_trace def list_messages( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> ItemPaged[ChatMessage] """Gets a list of messages from a thread. @@ -394,7 +382,8 @@ def list_messages( max_page_size=results_per_page, start_time=start_time, cls=lambda objs: [ChatMessage._from_generated(x) for x in objs], # pylint:disable=protected-access - **kwargs) + **kwargs + ) return a @distributed_trace @@ -435,7 +424,8 @@ def update_message( chat_thread_id=self._thread_id, chat_message_id=message_id, update_chat_message_request=update_message_request, - **kwargs) + **kwargs + ) @distributed_trace def delete_message( @@ -465,14 +455,12 @@ def delete_message( raise ValueError("message_id cannot be None.") return self._client.chat_thread.delete_chat_message( - chat_thread_id=self._thread_id, - chat_message_id=message_id, - **kwargs) + chat_thread_id=self._thread_id, chat_message_id=message_id, **kwargs + ) @distributed_trace def list_participants( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> ItemPaged[ChatParticipant] """Gets the participants of a thread. @@ -501,8 +489,8 @@ def list_participants( max_page_size=results_per_page, skip=skip, cls=lambda objs: [ChatParticipant._from_generated(x) for x in objs], # pylint:disable=protected-access - **kwargs) - + **kwargs + ) @distributed_trace def add_participants( @@ -538,14 +526,12 @@ def add_participants( add_thread_participants_request = AddChatParticipantsRequest(participants=participants) add_chat_participants_result = self._client.chat_thread.add_chat_participants( - chat_thread_id=self._thread_id, - add_chat_participants_request=add_thread_participants_request, - **kwargs) + chat_thread_id=self._thread_id, add_chat_participants_request=add_thread_participants_request, **kwargs + ) - if hasattr(add_chat_participants_result, 'invalid_participants'): + if hasattr(add_chat_participants_result, "invalid_participants"): response = CommunicationErrorResponseConverter.convert( - participants=thread_participants, - chat_errors=add_chat_participants_result.invalid_participants + participants=thread_participants, chat_errors=add_chat_participants_result.invalid_participants ) return response @@ -579,7 +565,8 @@ def remove_participant( return self._client.chat_thread.remove_chat_participant( chat_thread_id=self._thread_id, participant_communication_identifier=serialize_identifier(identifier), - **kwargs) + **kwargs + ) def close(self): # type: () -> None diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/_communication_identifier_serializer.py b/sdk/communication/azure-communication-chat/azure/communication/chat/_communication_identifier_serializer.py index 26dc8a19eaea..6b08da1d07ea 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/_communication_identifier_serializer.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/_communication_identifier_serializer.py @@ -11,7 +11,7 @@ PhoneNumberIdentifier, MicrosoftTeamsUserIdentifier, UnknownIdentifier, - CommunicationIdentifierKind + CommunicationIdentifierKind, ) if TYPE_CHECKING: @@ -28,13 +28,15 @@ def serialize_identifier(identifier): :rtype: ~azure.communication.chat._generated.models.CommunicationIdentifierModel """ try: - request_model = {'raw_id': identifier.raw_id} + request_model = {"raw_id": identifier.raw_id} if identifier.kind and identifier.kind != CommunicationIdentifierKind.UNKNOWN: request_model[identifier.kind] = dict(identifier.properties) return request_model except AttributeError: - raise TypeError("Unsupported identifier type " + identifier.__class__.__name__) # pylint: disable=raise-missing-from + raise TypeError( # pylint: disable=raise-missing-from + "Unsupported identifier type " + identifier.__class__.__name__ + ) def deserialize_identifier(identifier_model): @@ -58,6 +60,6 @@ def deserialize_identifier(identifier_model): raw_id=raw_id, user_id=identifier_model.microsoft_teams_user.user_id, is_anonymous=identifier_model.microsoft_teams_user.is_anonymous, - cloud=identifier_model.microsoft_teams_user.cloud + cloud=identifier_model.microsoft_teams_user.cloud, ) return UnknownIdentifier(raw_id) diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/_models.py b/sdk/communication/azure-communication-chat/azure/communication/chat/_models.py index 7d5313d6b37d..c4bcf2d8d77a 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/_models.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/_models.py @@ -54,16 +54,17 @@ def _from_generated(cls, chat_thread_participant): return cls( identifier=deserialize_identifier(chat_thread_participant.communication_identifier), display_name=chat_thread_participant.display_name, - share_history_time=chat_thread_participant.share_history_time + share_history_time=chat_thread_participant.share_history_time, ) def _to_generated(self): return ChatParticipantAutorest( communication_identifier=serialize_identifier(self.identifier), display_name=self.display_name, - share_history_time=self.share_history_time + share_history_time=self.share_history_time, ) + class ChatAttachment: """An attachment in a chat message. @@ -81,15 +82,12 @@ class ChatAttachment: :vartype preview_url: str or None """ - def __init__( - self, - **kwargs: Any - ) -> None: - self.id = kwargs['id'] - self.attachment_type = kwargs['attachment_type'] - self.name = kwargs.get('name', None) - self.url = kwargs.get('url', None) - self.preview_url = kwargs.get('preview_url', None) + def __init__(self, **kwargs: Any) -> None: + self.id = kwargs["id"] + self.attachment_type = kwargs["attachment_type"] + self.name = kwargs.get("name", None) + self.url = kwargs.get("url", None) + self.preview_url = kwargs.get("preview_url", None) @classmethod def _from_generated(cls, chat_attachment): @@ -98,11 +96,11 @@ def _from_generated(cls, chat_attachment): attachment_type=chat_attachment.attachment_type, name=chat_attachment.name, url=chat_attachment.url, - preview_url=chat_attachment.preview_url + preview_url=chat_attachment.preview_url, ) -class ChatMessage: # pylint: disable=too-many-instance-attributes +class ChatMessage: # pylint: disable=too-many-instance-attributes """Chat message. Variables are only populated by the server, and will be ignored when sending a request. @@ -133,21 +131,18 @@ class ChatMessage: # pylint: disable=too-many-instance-attributes :vartype metadata: dict[str, str] or None """ - def __init__( - self, - **kwargs: Any - ) -> None: - self.id = kwargs['id'] - self.type = kwargs['type'] - self.sequence_id = kwargs['sequence_id'] - self.version = kwargs['version'] - self.content = kwargs['content'] - self.sender_display_name = kwargs['sender_display_name'] - self.created_on = kwargs['created_on'] - self.sender = kwargs['sender'] - self.deleted_on = kwargs['deleted_on'] - self.edited_on = kwargs['edited_on'] - self.metadata = kwargs.get('metadata') + def __init__(self, **kwargs: Any) -> None: + self.id = kwargs["id"] + self.type = kwargs["type"] + self.sequence_id = kwargs["sequence_id"] + self.version = kwargs["version"] + self.content = kwargs["content"] + self.sender_display_name = kwargs["sender_display_name"] + self.created_on = kwargs["created_on"] + self.sender = kwargs["sender"] + self.deleted_on = kwargs["deleted_on"] + self.edited_on = kwargs["edited_on"] + self.metadata = kwargs.get("metadata") @classmethod def _from_generated(cls, chat_message): @@ -159,7 +154,11 @@ def _from_generated(cls, chat_message): message_type = ChatMessageType(chat_message.type) except ValueError: message_type = chat_message.type - content = ChatMessageContent._from_generated(chat_message.content) if chat_message.content else None # pylint:disable=protected-access + content = ( + ChatMessageContent._from_generated(chat_message.content) # pylint:disable=protected-access + if chat_message.content + else None + ) return cls( id=chat_message.id, type=message_type, @@ -171,7 +170,7 @@ def _from_generated(cls, chat_message): sender=sender_communication_identifier, deleted_on=chat_message.deleted_on, edited_on=chat_message.edited_on, - metadata=chat_message.metadata + metadata=chat_message.metadata, ) @@ -192,23 +191,20 @@ class ChatMessageContent: :vartype attachments: List[~azure.communication.chat.ChatAttachment] """ - def __init__( - self, - **kwargs: Any - ) -> None: - self.message = kwargs.get('message', None) - self.topic = kwargs.get('topic', None) - self.participants = kwargs.get('participants', None) - self.initiator = kwargs.get('initiator', None) - self.attachments = kwargs.get('attachments', None) + def __init__(self, **kwargs: Any) -> None: + self.message = kwargs.get("message", None) + self.topic = kwargs.get("topic", None) + self.participants = kwargs.get("participants", None) + self.initiator = kwargs.get("initiator", None) + self.attachments = kwargs.get("attachments", None) @classmethod def _from_generated(cls, chat_message_content): participants_list = chat_message_content.participants if participants_list: participants = [ - ChatParticipant._from_generated(participant) for participant in # pylint:disable=protected-access - participants_list + ChatParticipant._from_generated(participant) # pylint:disable=protected-access + for participant in participants_list ] else: participants = [] @@ -216,8 +212,8 @@ def _from_generated(cls, chat_message_content): attachments_list = chat_message_content.attachments if attachments_list: attachments = [ - ChatAttachment._from_generated(attachment) for attachment in # pylint:disable=protected-access - attachments_list + ChatAttachment._from_generated(attachment) # pylint:disable=protected-access + for attachment in attachments_list ] else: attachments = [] @@ -232,7 +228,7 @@ def _from_generated(cls, chat_message_content): topic=chat_message_content.topic, participants=participants, initiator=initiator, - attachments=attachments + attachments=attachments, ) @@ -253,14 +249,11 @@ class ChatThreadProperties: # pylint:disable=protected-access - def __init__( - self, - **kwargs: Any - ) -> None: - self.id = kwargs['id'] - self.topic = kwargs.get('topic', None) - self.created_on = kwargs['created_on'] - self.created_by = kwargs['created_by'] + def __init__(self, **kwargs: Any) -> None: + self.id = kwargs["id"] + self.topic = kwargs.get("topic", None) + self.created_on = kwargs["created_on"] + self.created_by = kwargs["created_by"] @classmethod def _from_generated(cls, chat_thread): @@ -269,12 +262,7 @@ def _from_generated(cls, chat_thread): if created_by is not None: created_by = deserialize_identifier(chat_thread.created_by_communication_identifier) - return cls( - id=chat_thread.id, - topic=chat_thread.topic, - created_on=chat_thread.created_on, - created_by=created_by - ) + return cls(id=chat_thread.id, topic=chat_thread.topic, created_on=chat_thread.created_on, created_by=created_by) class ChatMessageReadReceipt: @@ -291,13 +279,10 @@ class ChatMessageReadReceipt: :vartype read_on: ~datetime.datetime """ - def __init__( - self, - **kwargs: Any - ) -> None: - self.sender = kwargs['sender'] - self.chat_message_id = kwargs['chat_message_id'] - self.read_on = kwargs['read_on'] + def __init__(self, **kwargs: Any) -> None: + self.sender = kwargs["sender"] + self.chat_message_id = kwargs["chat_message_id"] + self.read_on = kwargs["read_on"] @classmethod def _from_generated(cls, read_receipt): @@ -305,11 +290,8 @@ def _from_generated(cls, read_receipt): if sender is not None: sender = deserialize_identifier(read_receipt.sender_communication_identifier) - return cls( - sender=sender, - chat_message_id=read_receipt.chat_message_id, - read_on=read_receipt.read_on - ) + return cls(sender=sender, chat_message_id=read_receipt.chat_message_id, read_on=read_receipt.read_on) + class CreateChatThreadResult: """Result of the create chat thread operation. @@ -320,9 +302,6 @@ class CreateChatThreadResult: :vartype errors: List[Tuple[~azure.communication.chat.ChatParticipant, ~azure.communication.chat.ChatError]] or None """ - def __init__( - self, - **kwargs: Any - ) -> None: - self.chat_thread = kwargs['chat_thread'] - self.errors = kwargs.get('errors', None) + def __init__(self, **kwargs: Any) -> None: + self.chat_thread = kwargs["chat_thread"] + self.errors = kwargs.get("errors", None) diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/auth_policy_utils.py b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/auth_policy_utils.py index 3b0520c68412..76ee393bc94f 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/auth_policy_utils.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/auth_policy_utils.py @@ -43,9 +43,7 @@ def get_authentication_policy( return AsyncBearerTokenCredentialPolicy( credential, "https://communication.azure.com//.default" # type: ignore ) - return BearerTokenCredentialPolicy( - credential, "https://communication.azure.com//.default" # type: ignore - ) + return BearerTokenCredentialPolicy(credential, "https://communication.azure.com//.default") # type: ignore if isinstance(credential, (AzureKeyCredential, str)): return HMACCredentialsPolicy(endpoint, credential, decode_url=decode_url) diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/models.py b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/models.py index 7b646472045c..43875e1197e5 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/models.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/models.py @@ -14,8 +14,11 @@ class DeprecatedEnumMeta(CaseInsensitiveEnumMeta): def __getattribute__(cls, item): if item.upper() == "MICROSOFT_BOT": - warnings.warn("MICROSOFT_BOT is deprecated and has been replaced by \ - MICROSOFT_TEAMS_APP identifier.", DeprecationWarning) + warnings.warn( + "MICROSOFT_BOT is deprecated and has been replaced by \ + MICROSOFT_TEAMS_APP identifier.", + DeprecationWarning, + ) item = "MICROSOFT_TEAMS_APP" return super().__getattribute__(item) @@ -47,14 +50,17 @@ class CommunicationCloudEnvironment(str, Enum, metaclass=CaseInsensitiveEnumMeta @runtime_checkable class CommunicationIdentifier(Protocol): """Communication Identifier.""" + @property def raw_id(self) -> str: """The raw ID of the identifier.""" ... + @property def kind(self) -> CommunicationIdentifierKind: """The type of identifier.""" ... + @property def properties(self) -> Mapping[str, Any]: """The properties of the identifier.""" @@ -83,12 +89,14 @@ def properties(self) -> Mapping[str, Any]: class CommunicationUserProperties(TypedDict): """Dictionary of properties for a CommunicationUserIdentifier.""" + id: str """ID of the Communication user as returned from Azure Communication Identity.""" class CommunicationUserIdentifier: """Represents a user in Azure Communication Service.""" + kind: Literal[CommunicationIdentifierKind.COMMUNICATION_USER] = CommunicationIdentifierKind.COMMUNICATION_USER """The type of identifier.""" properties: CommunicationUserProperties @@ -116,12 +124,14 @@ def __eq__(self, other): class PhoneNumberProperties(TypedDict): """Dictionary of properties for a PhoneNumberIdentifier.""" + value: str """The phone number in E.164 format.""" class PhoneNumberIdentifier: """Represents a phone number.""" + kind: Literal[CommunicationIdentifierKind.PHONE_NUMBER] = CommunicationIdentifierKind.PHONE_NUMBER """The type of identifier.""" properties: PhoneNumberProperties @@ -165,6 +175,7 @@ class UnknownIdentifier: It is not advisable to rely on the `kind` property with a value `unknown`, as it could become a new or existing distinct type in the future. """ + kind: Literal[CommunicationIdentifierKind.UNKNOWN] = CommunicationIdentifierKind.UNKNOWN """The type of identifier.""" properties: Mapping[str, Any] @@ -188,6 +199,7 @@ def __eq__(self, other): class MicrosoftTeamsUserProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsUserIdentifier.""" + user_id: str """The id of the Microsoft Teams user. If the user isn't anonymous, the id is the AAD object id of the user.""" is_anonymous: bool @@ -198,6 +210,7 @@ class MicrosoftTeamsUserProperties(TypedDict): class MicrosoftTeamsUserIdentifier: """Represents an identifier for a Microsoft Teams user.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_USER] = CommunicationIdentifierKind.MICROSOFT_TEAMS_USER """The type of identifier.""" properties: MicrosoftTeamsUserProperties @@ -246,6 +259,7 @@ def _format_raw_id(self, properties: MicrosoftTeamsUserProperties) -> str: class MicrosoftTeamsAppProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsAppIdentifier.""" + app_id: str """The id of the Microsoft Teams application.""" cloud: Union[CommunicationCloudEnvironment, str] @@ -254,6 +268,7 @@ class MicrosoftTeamsAppProperties(TypedDict): class _botbackcompatdict(dict): """Backwards compatible properties.""" + def __getitem__(self, __key: Any) -> Any: try: return super().__getitem__(__key) @@ -267,6 +282,7 @@ def __getitem__(self, __key: Any) -> Any: class MicrosoftTeamsAppIdentifier: """Represents an identifier for a Microsoft Teams application.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_APP] = CommunicationIdentifierKind.MICROSOFT_TEAMS_APP """The type of identifier.""" properties: MicrosoftTeamsAppProperties @@ -282,10 +298,13 @@ def __init__(self, app_id: str, **kwargs: Any) -> None: :keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed from the other properties. """ - self.properties = cast(MicrosoftTeamsAppProperties, _botbackcompatdict( - app_id=app_id, - cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, - )) + self.properties = cast( + MicrosoftTeamsAppProperties, + _botbackcompatdict( + app_id=app_id, + cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, + ), + ) raw_id: Optional[str] = kwargs.get("raw_id") self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties) @@ -323,7 +342,7 @@ def __init__(self, bot_id, **kwargs): """ warnings.warn( "The MicrosoftBotIdentifier is deprecated and has been replaced by MicrosoftTeamsAppIdentifier.", - DeprecationWarning + DeprecationWarning, ) super().__init__(bot_id, **kwargs) @@ -339,9 +358,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d :rtype: CommunicationIdentifier """ if raw_id.startswith(PHONE_NUMBER_PREFIX): - return PhoneNumberIdentifier( - value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id - ) + return PhoneNumberIdentifier(value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id) segments = raw_id.split(":", maxsplit=2) if len(segments) < 3: @@ -350,9 +367,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d prefix = f"{segments[0]}:{segments[1]}:" suffix = segments[2] if prefix == TEAMS_USER_ANONYMOUS_PREFIX: - return MicrosoftTeamsUserIdentifier( - user_id=suffix, is_anonymous=True, raw_id=raw_id - ) + return MicrosoftTeamsUserIdentifier(user_id=suffix, is_anonymous=True, raw_id=raw_id) if prefix == TEAMS_USER_PUBLIC_CLOUD_PREFIX: return MicrosoftTeamsUserIdentifier( user_id=suffix, diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/policy.py b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/policy.py index 2fd2e7426c73..79aa48136fd3 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/policy.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/policy.py @@ -50,9 +50,7 @@ def _compute_hmac( else: decoded_secret = base64.b64decode(self._access_key) - digest = hmac.new( - decoded_secret, value.encode("utf-8"), hashlib.sha256 - ).digest() + digest = hmac.new(decoded_secret, value.encode("utf-8"), hashlib.sha256).digest() return base64.b64encode(digest).decode("utf-8") @@ -101,22 +99,10 @@ def _sign_request(self, request): utc_now = get_current_utc_time() if request.http_request.body is None: request.http_request.body = "" - content_digest = hashlib.sha256( - (request.http_request.body.encode("utf-8")) - ).digest() + content_digest = hashlib.sha256((request.http_request.body.encode("utf-8"))).digest() content_hash = base64.b64encode(content_digest).decode("utf-8") - string_to_sign = ( - verb - + "\n" - + query_url - + "\n" - + utc_now - + ";" - + self._host - + ";" - + content_hash - ) + string_to_sign = verb + "\n" + query_url + "\n" + utc_now + ";" + self._host + ";" + content_hash signature = self._compute_hmac(string_to_sign) @@ -124,10 +110,7 @@ def _sign_request(self, request): "x-ms-date": utc_now, "x-ms-content-sha256": content_hash, "x-ms-return-client-request-id": "true", - "Authorization": "HMAC-SHA256 SignedHeaders=" - + signed_headers - + "&Signature=" - + signature, + "Authorization": "HMAC-SHA256 SignedHeaders=" + signed_headers + "&Signature=" + signature, } request.http_request.headers.update(signature_header) diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/user_credential.py b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/user_credential.py index 4ca8378f6247..b6feb869d944 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/user_credential.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/user_credential.py @@ -39,9 +39,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._lock = Condition(Lock()) self._some_thread_refreshing = False @@ -55,9 +53,7 @@ def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -81,9 +77,7 @@ def _update_token_and_reschedule(self): try: new_token = self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -110,12 +104,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() if timespan <= TIMEOUT_MAX: self._timer = Timer(timespan, self._update_token_and_reschedule) self._timer.daemon = True diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/user_credential_async.py b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/user_credential_async.py index 2abd1a063d7a..2537ab7d5532 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/user_credential_async.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/user_credential_async.py @@ -41,9 +41,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._async_mutex = Lock() if sys.version_info[:3] == (3, 10, 0): @@ -62,9 +60,7 @@ async def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -88,9 +84,7 @@ async def _update_token_and_reschedule(self): try: new_token = await self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") async with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -117,12 +111,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() self._timer = AsyncTimer(timespan, self._update_token_and_reschedule) self._timer.start() diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/utils.py b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/utils.py index 47da8a283e5f..8576c31ddc56 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/utils.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/_shared/utils.py @@ -87,9 +87,7 @@ def create_access_token(token): payload = json.loads(padded_base64_payload) return AccessToken( token, - _convert_datetime_to_utc_int( - datetime.fromtimestamp(payload["exp"], TZ_UTC) - ), + _convert_datetime_to_utc_int(datetime.fromtimestamp(payload["exp"], TZ_UTC)), ) except ValueError as val_error: raise ValueError(token_parse_err_msg) from val_error diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/_utils.py b/sdk/communication/azure-communication-chat/azure/communication/chat/_utils.py index 611404fcfabb..c4dc8b52b098 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/_utils.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/_utils.py @@ -6,7 +6,7 @@ def _to_utc_datetime(value): - return value.strftime('%Y-%m-%dT%H:%M:%SZ') + return value.strftime("%Y-%m-%dT%H:%M:%SZ") def return_response(response, deserialized, _): # pylint: disable=unused-argument @@ -39,6 +39,7 @@ def convert(cls, participants, chat_errors): :return: A list of (ChatParticipant, ChatError) :rtype: list[(~azure.communication.chat.ChatParticipant, ~azure.communication.chat.ChatError)] """ + def create_dict(participants): # type: (...) -> Dict(str, ChatThreadParticipant) """ @@ -50,7 +51,7 @@ def create_dict(participants): """ result = {} for participant in participants: - result[participant.identifier.properties['id']] = participant + result[participant.identifier.properties["id"]] = participant return result _thread_participants_dict = create_dict(participants=participants) diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/aio/__init__.py b/sdk/communication/azure-communication-chat/azure/communication/chat/aio/__init__.py index ebda8b1a392f..7d42815d42e6 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/aio/__init__.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/aio/__init__.py @@ -5,8 +5,5 @@ from ._chat_client_async import ChatClient from ._chat_thread_client_async import ChatThreadClient from .._shared.user_credential_async import CommunicationTokenCredential -__all__ = [ - "ChatClient", - "ChatThreadClient", - "CommunicationTokenCredential" -] + +__all__ = ["ChatClient", "ChatThreadClient", "CommunicationTokenCredential"] diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/aio/_chat_client_async.py b/sdk/communication/azure-communication-chat/azure/communication/chat/aio/_chat_client_async.py index b2e59da2496b..8761951a38da 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/aio/_chat_client_async.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/aio/_chat_client_async.py @@ -19,24 +19,17 @@ from ._chat_thread_client_async import ChatThreadClient from .._shared.user_credential_async import CommunicationTokenCredential from .._generated.aio import AzureCommunicationChatService -from .._generated.models import ( - CreateChatThreadRequest, - ChatThreadItem -) -from .._models import ( - ChatThreadProperties, - ChatParticipant, - CreateChatThreadResult -) -from .._utils import ( # pylint: disable=unused-import +from .._generated.models import CreateChatThreadRequest, ChatThreadItem +from .._models import ChatThreadProperties, ChatParticipant, CreateChatThreadResult +from .._utils import ( # pylint: disable=unused-import _to_utc_datetime, return_response, - CommunicationErrorResponseConverter + CommunicationErrorResponseConverter, ) from .._version import SDK_MONIKER -class ChatClient(object): # pylint: disable=client-accepts-api-version-keyword +class ChatClient(object): # pylint: disable=client-accepts-api-version-keyword """A client to interact with the AzureCommunicationService Chat gateway. This client provides operations to create chat thread, delete chat thread, @@ -57,21 +50,17 @@ class ChatClient(object): # pylint: disable=client-accepts-api-version-keyword :caption: Creating the ChatClient from a URL and token. """ - def __init__( - self, endpoint: str, - credential: CommunicationTokenCredential, - **kwargs: Any - ) -> None: + def __init__(self, endpoint: str, credential: CommunicationTokenCredential, **kwargs: Any) -> None: if not credential: raise ValueError("credential can not be None") try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError: - raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from + raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from - parsed_url = urlparse(endpoint.rstrip('/')) + parsed_url = urlparse(endpoint.rstrip("/")) if not parsed_url.netloc: raise ValueError("Invalid URL: {}".format(endpoint)) @@ -82,13 +71,11 @@ def __init__( endpoint=self._endpoint, authentication_policy=AsyncBearerTokenCredentialPolicy(self._credential), sdk_moniker=SDK_MONIKER, - **kwargs) + **kwargs + ) @distributed_trace - def get_chat_thread_client( - self, thread_id: str, - **kwargs: Any - ) -> ChatThreadClient: + def get_chat_thread_client(self, thread_id: str, **kwargs: Any) -> ChatThreadClient: """ Get ChatThreadClient by providing a thread_id. @@ -110,18 +97,10 @@ def get_chat_thread_client( if not thread_id: raise ValueError("thread_id cannot be None.") - return ChatThreadClient( - endpoint=self._endpoint, - credential=self._credential, - thread_id=thread_id, - **kwargs - ) + return ChatThreadClient(endpoint=self._endpoint, credential=self._credential, thread_id=thread_id, **kwargs) @distributed_trace_async - async def create_chat_thread( - self, topic: str, - **kwargs - ) -> CreateChatThreadResult: + async def create_chat_thread(self, topic: str, **kwargs) -> CreateChatThreadResult: """Creates a chat thread. :param topic: Required. The thread topic. @@ -151,46 +130,37 @@ async def create_chat_thread( if not topic: raise ValueError("topic cannot be None.") - idempotency_token = kwargs.pop('idempotency_token', None) + idempotency_token = kwargs.pop("idempotency_token", None) if idempotency_token is None: idempotency_token = str(uuid4()) - thread_participants = kwargs.pop('thread_participants', None) + thread_participants = kwargs.pop("thread_participants", None) participants = [] if thread_participants is not None: participants = [m._to_generated() for m in thread_participants] # pylint:disable=protected-access - create_thread_request = \ - CreateChatThreadRequest(topic=topic, participants=participants) + create_thread_request = CreateChatThreadRequest(topic=topic, participants=participants) create_chat_thread_result = await self._client.chat.create_chat_thread( - create_chat_thread_request=create_thread_request, - repeatability_request_id=idempotency_token, - **kwargs) + create_chat_thread_request=create_thread_request, repeatability_request_id=idempotency_token, **kwargs + ) errors = None - if hasattr(create_chat_thread_result, 'invalid_participants'): + if hasattr(create_chat_thread_result, "invalid_participants"): errors = CommunicationErrorResponseConverter.convert( - participants=thread_participants or [], - chat_errors=create_chat_thread_result.invalid_participants + participants=thread_participants or [], chat_errors=create_chat_thread_result.invalid_participants ) - chat_thread = ChatThreadProperties._from_generated( # pylint:disable=protected-access - create_chat_thread_result.chat_thread) - - create_chat_thread_result = CreateChatThreadResult( - chat_thread=chat_thread, - errors=errors + chat_thread = ChatThreadProperties._from_generated( # pylint:disable=protected-access + create_chat_thread_result.chat_thread ) - return create_chat_thread_result + create_chat_thread_result = CreateChatThreadResult(chat_thread=chat_thread, errors=errors) + return create_chat_thread_result @distributed_trace - def list_chat_threads( - self, - **kwargs: Any - ) -> AsyncItemPaged[ChatThreadItem]: + def list_chat_threads(self, **kwargs: Any) -> AsyncItemPaged[ChatThreadItem]: """Gets the list of chat threads of a user. :keyword int results_per_page: The maximum number of chat threads to be returned per page. @@ -211,17 +181,10 @@ def list_chat_threads( results_per_page = kwargs.pop("results_per_page", None) start_time = kwargs.pop("start_time", None) - return self._client.chat.list_chat_threads( - max_page_size=results_per_page, - start_time=start_time, - **kwargs) + return self._client.chat.list_chat_threads(max_page_size=results_per_page, start_time=start_time, **kwargs) @distributed_trace_async - async def delete_chat_thread( - self, - thread_id: str, - **kwargs - ) -> None: + async def delete_chat_thread(self, thread_id: str, **kwargs) -> None: """Deletes a chat thread. :param thread_id: Required. Thread id to delete. diff --git a/sdk/communication/azure-communication-chat/azure/communication/chat/aio/_chat_thread_client_async.py b/sdk/communication/azure-communication-chat/azure/communication/chat/aio/_chat_thread_client_async.py index 5fb0ffa4b523..a4ac904ba28a 100644 --- a/sdk/communication/azure-communication-chat/azure/communication/chat/aio/_chat_thread_client_async.py +++ b/sdk/communication/azure-communication-chat/azure/communication/chat/aio/_chat_thread_client_async.py @@ -25,21 +25,16 @@ UpdateChatThreadRequest, SendChatMessageResult, ChatMessageType, - ChatError -) -from .._models import ( - ChatParticipant, - ChatMessage, - ChatMessageReadReceipt, - ChatThreadProperties + ChatError, ) +from .._models import ChatParticipant, ChatMessage, ChatMessageReadReceipt, ChatThreadProperties from .._shared.models import CommunicationIdentifier from .._communication_identifier_serializer import serialize_identifier from .._utils import CommunicationErrorResponseConverter from .._version import SDK_MONIKER -class ChatThreadClient(object): # pylint: disable=client-accepts-api-version-keyword +class ChatThreadClient(object): # pylint: disable=client-accepts-api-version-keyword """A client to interact with the AzureCommunicationService Chat gateway. Instances of this class is normally retrieved by ChatClient.get_chat_thread_client() @@ -68,13 +63,7 @@ class ChatThreadClient(object): # pylint: disable=client-accepts-api-version-key :caption: Creating the ChatThreadClient. """ - def __init__( - self, - endpoint: str, - credential: CommunicationTokenCredential, - thread_id: str, - **kwargs: Any - ) -> None: + def __init__(self, endpoint: str, credential: CommunicationTokenCredential, thread_id: str, **kwargs: Any) -> None: if not thread_id: raise ValueError("thread_id can not be None or empty") @@ -82,12 +71,12 @@ def __init__( raise ValueError("credential can not be None") try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError: - raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from + raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from - parsed_url = urlparse(endpoint.rstrip('/')) + parsed_url = urlparse(endpoint.rstrip("/")) if not parsed_url.netloc: raise ValueError("Invalid URL: {}".format(endpoint)) @@ -99,7 +88,8 @@ def __init__( endpoint=self._endpoint, authentication_policy=AsyncBearerTokenCredentialPolicy(self._credential), sdk_moniker=SDK_MONIKER, - **kwargs) + **kwargs + ) @property def thread_id(self) -> str: @@ -111,11 +101,7 @@ def thread_id(self) -> str: return self._thread_id @distributed_trace_async - async def get_properties( - self, - **kwargs - ) -> ChatThreadProperties: - + async def get_properties(self, **kwargs) -> ChatThreadProperties: """Gets the properties of the chat thread. :return: ChatThreadProperties @@ -135,13 +121,8 @@ async def get_properties( chat_thread = await self._client.chat_thread.get_chat_thread_properties(self._thread_id, **kwargs) return ChatThreadProperties._from_generated(chat_thread) # pylint:disable=protected-access - @distributed_trace_async - async def update_topic( - self, - topic: str = None, - **kwargs - ) -> None: + async def update_topic(self, topic: str = None, **kwargs) -> None: """Updates a thread's properties. :param topic: Thread topic. If topic is not specified, the update will succeed but @@ -163,16 +144,11 @@ async def update_topic( update_topic_request = UpdateChatThreadRequest(topic=topic) return await self._client.chat_thread.update_chat_thread_properties( - chat_thread_id=self._thread_id, - update_chat_thread_request=update_topic_request, - **kwargs) + chat_thread_id=self._thread_id, update_chat_thread_request=update_topic_request, **kwargs + ) @distributed_trace_async - async def send_read_receipt( - self, - message_id: str, - **kwargs - ) -> None: + async def send_read_receipt(self, message_id: str, **kwargs) -> None: """Posts a read receipt event to a chat thread, on behalf of a user. :param message_id: Required. Id of the latest message read by current user. @@ -195,15 +171,11 @@ async def send_read_receipt( post_read_receipt_request = SendReadReceiptRequest(chat_message_id=message_id) return await self._client.chat_thread.send_chat_read_receipt( - self._thread_id, - send_read_receipt_request=post_read_receipt_request, - **kwargs) + self._thread_id, send_read_receipt_request=post_read_receipt_request, **kwargs + ) @distributed_trace - def list_read_receipts( - self, - **kwargs: Any - ) -> AsyncItemPaged[ChatMessageReadReceipt]: + def list_read_receipts(self, **kwargs: Any) -> AsyncItemPaged[ChatMessageReadReceipt]: """Gets read receipts for a thread. :keyword int results_per_page: The maximum number of chat message read receipts to be returned per page. @@ -228,16 +200,14 @@ def list_read_receipts( self._thread_id, max_page_size=results_per_page, skip=skip, - cls=lambda objs: [ChatMessageReadReceipt._from_generated(x) for x in objs], # pylint:disable=protected-access - **kwargs) + cls=lambda objs: [ + ChatMessageReadReceipt._from_generated(x) for x in objs # pylint:disable=protected-access + ], + **kwargs + ) @distributed_trace_async - async def send_typing_notification( - self, - *, - sender_display_name: Optional[str] = None, - **kwargs - ) -> None: + async def send_typing_notification(self, *, sender_display_name: Optional[str] = None, **kwargs) -> None: """Posts a typing event to a thread, on behalf of a user. :keyword str sender_display_name: The display name of the typing notification sender. This property @@ -259,18 +229,11 @@ async def send_typing_notification( send_typing_notification_request = SendTypingNotificationRequest(sender_display_name=sender_display_name) return await self._client.chat_thread.send_typing_notification( - chat_thread_id=self._thread_id, - send_typing_notification_request=send_typing_notification_request, - **kwargs) + chat_thread_id=self._thread_id, send_typing_notification_request=send_typing_notification_request, **kwargs + ) @distributed_trace_async - async def send_message( - self, - content: str, - *, - metadata: Dict[str, str] = None, - **kwargs - ) -> SendChatMessageResult: + async def send_message(self, content: str, *, metadata: Dict[str, str] = None, **kwargs) -> SendChatMessageResult: """Sends a message to a thread. :param content: Required. Chat message content. @@ -304,34 +267,28 @@ async def send_message( try: chat_message_type = ChatMessageType.__getattr__(chat_message_type) # pylint:disable=protected-access except Exception: - raise ValueError( # pylint:disable=raise-missing-from - "chat_message_type: {message_type} is not acceptable".format(message_type=chat_message_type)) + raise ValueError( # pylint:disable=raise-missing-from + "chat_message_type: {message_type} is not acceptable".format(message_type=chat_message_type) + ) if chat_message_type not in [ChatMessageType.TEXT, ChatMessageType.HTML]: raise ValueError( - "chat_message_type: {message_type} can be only 'text' or 'html'".format(message_type=chat_message_type)) + "chat_message_type: {message_type} can be only 'text' or 'html'".format(message_type=chat_message_type) + ) sender_display_name = kwargs.pop("sender_display_name", None) create_message_request = SendChatMessageRequest( - content=content, - type=chat_message_type, - sender_display_name=sender_display_name, - metadata=metadata + content=content, type=chat_message_type, sender_display_name=sender_display_name, metadata=metadata ) send_chat_message_result = await self._client.chat_thread.send_chat_message( - chat_thread_id=self._thread_id, - send_chat_message_request=create_message_request, - **kwargs) + chat_thread_id=self._thread_id, send_chat_message_request=create_message_request, **kwargs + ) return send_chat_message_result @distributed_trace_async - async def get_message( - self, - message_id: str, - **kwargs - ) -> ChatMessage: + async def get_message(self, message_id: str, **kwargs) -> ChatMessage: """Gets a message by id. :param message_id: Required. The message id. @@ -356,10 +313,7 @@ async def get_message( return ChatMessage._from_generated(chat_message) # pylint:disable=protected-access @distributed_trace - def list_messages( - self, - **kwargs: Any - ) -> AsyncItemPaged[ChatMessage]: + def list_messages(self, **kwargs: Any) -> AsyncItemPaged[ChatMessage]: """Gets a list of messages from a thread. :keyword int results_per_page: The maximum number of messages to be returned per page. @@ -385,16 +339,12 @@ def list_messages( max_page_size=results_per_page, start_time=start_time, cls=lambda objs: [ChatMessage._from_generated(x) for x in objs], # pylint:disable=protected-access - **kwargs) + **kwargs + ) @distributed_trace_async async def update_message( - self, - message_id: str, - content: str = None, - *, - metadata: Dict[str, str] = None, - **kwargs + self, message_id: str, content: str = None, *, metadata: Dict[str, str] = None, **kwargs ) -> None: """Updates a message. @@ -424,14 +374,11 @@ async def update_message( chat_thread_id=self._thread_id, chat_message_id=message_id, update_chat_message_request=update_message_request, - **kwargs) + **kwargs + ) @distributed_trace_async - async def delete_message( - self, - message_id: str, - **kwargs - ) -> None: + async def delete_message(self, message_id: str, **kwargs) -> None: """Deletes a message. :param message_id: Required. The message id. @@ -453,15 +400,11 @@ async def delete_message( raise ValueError("message_id cannot be None.") return await self._client.chat_thread.delete_chat_message( - chat_thread_id=self._thread_id, - chat_message_id=message_id, - **kwargs) + chat_thread_id=self._thread_id, chat_message_id=message_id, **kwargs + ) @distributed_trace - def list_participants( - self, - **kwargs: Any - ) -> AsyncItemPaged[ChatParticipant]: + def list_participants(self, **kwargs: Any) -> AsyncItemPaged[ChatParticipant]: """Gets the participants of a thread. :keyword int results_per_page: The maximum number of participants to be returned per page. @@ -488,14 +431,12 @@ def list_participants( max_page_size=results_per_page, skip=skip, cls=lambda objs: [ChatParticipant._from_generated(x) for x in objs], # pylint:disable=protected-access - **kwargs) - + **kwargs + ) @distributed_trace_async async def add_participants( - self, - thread_participants: List[ChatParticipant], - **kwargs + self, thread_participants: List[ChatParticipant], **kwargs ) -> List[Tuple[ChatParticipant, ChatError]]: """Adds thread participants to a thread. If participants already exist, no change occurs. @@ -524,23 +465,17 @@ async def add_participants( add_thread_participants_request = AddChatParticipantsRequest(participants=participants) add_chat_participants_result = await self._client.chat_thread.add_chat_participants( - chat_thread_id=self._thread_id, - add_chat_participants_request=add_thread_participants_request, - **kwargs) + chat_thread_id=self._thread_id, add_chat_participants_request=add_thread_participants_request, **kwargs + ) - if hasattr(add_chat_participants_result, 'invalid_participants'): + if hasattr(add_chat_participants_result, "invalid_participants"): response = CommunicationErrorResponseConverter.convert( - participants=thread_participants, - chat_errors=add_chat_participants_result.invalid_participants + participants=thread_participants, chat_errors=add_chat_participants_result.invalid_participants ) return response @distributed_trace_async - async def remove_participant( - self, - identifier: CommunicationIdentifier, - **kwargs - ) -> None: + async def remove_participant(self, identifier: CommunicationIdentifier, **kwargs) -> None: """Remove a participant from a thread. :param identifier: Required. Identifier of the thread participant to remove from the thread. @@ -564,7 +499,8 @@ async def remove_participant( return await self._client.chat_thread.remove_chat_participant( chat_thread_id=self._thread_id, participant_communication_identifier=serialize_identifier(identifier), - **kwargs) + **kwargs + ) async def close(self) -> None: await self._client.close() diff --git a/sdk/communication/azure-communication-chat/samples/chat_client_sample.py b/sdk/communication/azure-communication-chat/samples/chat_client_sample.py index 050e12f8a8c5..ac7b43b698e9 100644 --- a/sdk/communication/azure-communication-chat/samples/chat_client_sample.py +++ b/sdk/communication/azure-communication-chat/samples/chat_client_sample.py @@ -1,4 +1,3 @@ - # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -28,6 +27,7 @@ class ChatClientSamples(object): from azure.communication.identity import CommunicationIdentityClient + connection_string = os.environ.get("COMMUNICATION_SAMPLES_CONNECTION_STRING", None) if not connection_string: raise ValueError("Set COMMUNICATION_SAMPLES_CONNECTION_STRING env before run this sample.") @@ -60,32 +60,26 @@ def create_thread(self): # [START create_thread] from datetime import datetime - from azure.communication.chat import( + from azure.communication.chat import ( ChatClient, ChatParticipant, CommunicationUserIdentifier, - CommunicationTokenCredential + CommunicationTokenCredential, ) # set `endpoint` to an existing ACS endpoint chat_client = ChatClient(endpoint, CommunicationTokenCredential(token)) topic = "test topic" - participants = [ChatParticipant( - identifier=user, - display_name='name', - share_history_time=datetime.utcnow() - )] + participants = [ChatParticipant(identifier=user, display_name="name", share_history_time=datetime.utcnow())] # creates a new chat_thread everytime create_chat_thread_result = chat_client.create_chat_thread(topic, thread_participants=participants) # creates a new chat_thread if not exists - idempotency_token = 'b66d6031-fdcc-41df-8306-e524c9f226b8' # unique identifier + idempotency_token = "b66d6031-fdcc-41df-8306-e524c9f226b8" # unique identifier create_chat_thread_result_w_repeatability_id = chat_client.create_chat_thread( - topic, - thread_participants=participants, - idempotency_token=idempotency_token + topic, thread_participants=participants, idempotency_token=idempotency_token ) # [END create_thread] @@ -109,7 +103,6 @@ def get_chat_thread_client(self): print("get_chat_thread_client succeeded with thread id: ", chat_thread_client.thread_id) - def list_threads(self): token = self.token endpoint = self.endpoint @@ -150,7 +143,7 @@ def clean_up(self): self.identity_client.delete_user(self.user) -if __name__ == '__main__': +if __name__ == "__main__": sample = ChatClientSamples() sample.create_chat_client() sample.create_thread() diff --git a/sdk/communication/azure-communication-chat/samples/chat_client_sample_async.py b/sdk/communication/azure-communication-chat/samples/chat_client_sample_async.py index 3ff971aa1e46..329e0f40a82a 100644 --- a/sdk/communication/azure-communication-chat/samples/chat_client_sample_async.py +++ b/sdk/communication/azure-communication-chat/samples/chat_client_sample_async.py @@ -1,4 +1,3 @@ - # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -28,6 +27,7 @@ class ChatClientSamplesAsync(object): from azure.communication.identity import CommunicationIdentityClient + connection_string = os.environ.get("COMMUNICATION_SAMPLES_CONNECTION_STRING", None) if not connection_string: raise ValueError("Set COMMUNICATION_SAMPLES_CONNECTION_STRING env before run this sample.") @@ -71,20 +71,17 @@ async def create_thread_async(self): async with chat_client: topic = "test topic" - participants = [ChatParticipant( - identifier=self.user, - display_name='name', - share_history_time=datetime.utcnow() - )] + participants = [ + ChatParticipant(identifier=self.user, display_name="name", share_history_time=datetime.utcnow()) + ] # creates a new chat_thread everytime create_chat_thread_result = await chat_client.create_chat_thread(topic, thread_participants=participants) # creates a new chat_thread if not exists - idempotency_token = 'b66d6031-fdcc-41df-8306-e524c9f226b8' # unique identifier + idempotency_token = "b66d6031-fdcc-41df-8306-e524c9f226b8" # unique identifier create_chat_thread_result_w_repeatability_id = await chat_client.create_chat_thread( - topic, - thread_participants=participants, - idempotency_token=idempotency_token) + topic, thread_participants=participants, idempotency_token=idempotency_token + ) # [END create_thread] self._thread_id = create_chat_thread_result.chat_thread.id @@ -107,7 +104,6 @@ def get_chat_thread_client(self): print("chat_thread_client created with thread id: ", chat_thread_client.thread_id) - async def list_threads_async(self): token = self.token endpoint = self.endpoint @@ -121,6 +117,7 @@ async def list_threads_async(self): async with chat_client: from datetime import datetime, timedelta + start_time = datetime.utcnow() - timedelta(days=2) chat_threads = chat_client.list_chat_threads(results_per_page=5, start_time=start_time) print("list_threads succeeded with results_per_page is 5, and were created since 2 days ago.") @@ -142,7 +139,7 @@ async def delete_thread_async(self): async with chat_client: # set `thread_id` to an existing chat thread id await chat_client.delete_chat_thread(thread_id) - # [END delete_thread] + # [END delete_thread] print("delete_thread succeeded") def clean_up(self): @@ -159,5 +156,6 @@ async def main(): await sample.delete_thread_async() sample.clean_up() -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.run(main()) diff --git a/sdk/communication/azure-communication-chat/samples/chat_thread_client_sample.py b/sdk/communication/azure-communication-chat/samples/chat_thread_client_sample.py index 158bc0539799..f4b816606145 100644 --- a/sdk/communication/azure-communication-chat/samples/chat_thread_client_sample.py +++ b/sdk/communication/azure-communication-chat/samples/chat_thread_client_sample.py @@ -28,10 +28,8 @@ class ChatThreadClientSamples(object): from azure.communication.identity import CommunicationIdentityClient - from azure.communication.chat import ( - ChatClient, - CommunicationTokenCredential - ) + from azure.communication.chat import ChatClient, CommunicationTokenCredential + connection_string = os.environ.get("COMMUNICATION_SAMPLES_CONNECTION_STRING", None) if not connection_string: raise ValueError("Set COMMUNICATION_SAMPLES_CONNECTION_STRING env before run this sample.") @@ -61,19 +59,16 @@ def create_chat_thread_client(self): ChatClient, ChatParticipant, CommunicationUserIdentifier, - CommunicationTokenCredential + CommunicationTokenCredential, ) + # retrieve `token` using CommunicationIdentityClient.get_token method # set `endpoint` to ACS service endpoint # create `user` using CommunicationIdentityClient.create_user method for new users; # else for existing users set `user` = CommunicationUserIdentifier(some_user_id) chat_client = ChatClient(endpoint, CommunicationTokenCredential(token)) topic = "test topic" - participants = [ChatParticipant( - identifier=user, - display_name='name', - share_history_time=datetime.utcnow() - )] + participants = [ChatParticipant(identifier=user, display_name="name", share_history_time=datetime.utcnow())] create_chat_thread_result = chat_client.create_chat_thread(topic, thread_participants=participants) chat_thread_client = chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id) # [END create_chat_thread_client] @@ -91,11 +86,15 @@ def get_chat_thread_properties(self): chat_client = ChatClient(endpoint, CommunicationTokenCredential(token)) chat_thread_client = chat_client.get_chat_thread_client(thread_id) chat_thread_properties = chat_thread_client.get_properties() - print('Expected Thread Id: ', thread_id, ' Actual Value: ', chat_thread_properties.id) + print("Expected Thread Id: ", thread_id, " Actual Value: ", chat_thread_properties.id) # [END get_thread] - print("get_chat_thread_properties succeeded, thread id: " + chat_thread.id + ", thread topic: " + chat_thread.topic) - + print( + "get_chat_thread_properties succeeded, thread id: " + + chat_thread.id + + ", thread topic: " + + chat_thread.topic + ) def update_topic(self): thread_id = self._thread_id @@ -127,15 +126,16 @@ def send_message(self): # Scenario 1: Send message without specifying chat_message_type send_message_result = chat_thread_client.send_message( - "Hello! My name is Fred Flinstone", - sender_display_name="Fred Flinstone") + "Hello! My name is Fred Flinstone", sender_display_name="Fred Flinstone" + ) send_message_result_id = send_message_result.id # Scenario 2: Send message specifying chat_message_type send_message_result_w_type = chat_thread_client.send_message( "Hello! My name is Wilma Flinstone", sender_display_name="Wilma Flinstone", - chat_message_type=ChatMessageType.TEXT) # equivalent to setting chat_message_type='text' + chat_message_type=ChatMessageType.TEXT, + ) # equivalent to setting chat_message_type='text' send_message_result_w_type_id = send_message_result_w_type.id # Verify message content print("First Message:", chat_thread_client.get_message(send_message_result_id).content.message) @@ -160,8 +160,7 @@ def get_message(self): print("Message received: ChatMessage: content=", chat_message.content.message, ", id=", chat_message.id) # [END get_message] - print("get_message succeeded, message id:", chat_message.id, \ - "content: ", chat_message.content.message) + print("get_message succeeded, message id:", chat_message.id, "content: ", chat_message.content.message) def list_messages(self): thread_id = self._thread_id @@ -272,7 +271,6 @@ def list_participants(self): # [END list_participants] print("list_participants succeeded") - def add_participants_w_check(self): # initially remove already added user thread_id = self._thread_id @@ -297,10 +295,7 @@ def decide_to_retry(error): # create `user` using CommunicationIdentityClient.create_user method for new users; # else for existing users set `user` = CommunicationUserIdentifier(some_user_id) - new_participant = ChatParticipant( - identifier=user, - display_name='name', - share_history_time=datetime.utcnow()) + new_participant = ChatParticipant(identifier=user, display_name="name", share_history_time=datetime.utcnow()) # create list containing one or more participants thread_participants = [new_participant] @@ -313,8 +308,6 @@ def decide_to_retry(error): # [END add_participants] print("add_participants_w_check succeeded") - - def remove_participant(self): thread_id = self._thread_id chat_client = self._chat_client @@ -332,14 +325,12 @@ def remove_participant(self): # add user1 and user2 to chat thread participant1 = ChatParticipant( - identifier=user1, - display_name='Fred Flinstone', - share_history_time=datetime.utcnow()) + identifier=user1, display_name="Fred Flinstone", share_history_time=datetime.utcnow() + ) participant2 = ChatParticipant( - identifier=user2, - display_name='Wilma Flinstone', - share_history_time=datetime.utcnow()) + identifier=user2, display_name="Wilma Flinstone", share_history_time=datetime.utcnow() + ) thread_participants = [participant1, participant2] chat_thread_client.add_participants(thread_participants) @@ -351,14 +342,16 @@ def remove_participant(self): for chat_thread_participant_page in chat_thread_participants.by_page(): for chat_thread_participant in chat_thread_participant_page: print("ChatParticipant: ", chat_thread_participant) - if chat_thread_participant.identifier.properties['id'] == user1.properties['id']: + if chat_thread_participant.identifier.properties["id"] == user1.properties["id"]: print("Found Fred!") chat_thread_client.remove_participant(chat_thread_participant.identifier) print("Fred has been removed from the thread...") break # Option 2: Directly remove Wilma Flinstone - unique_identifier = user2.properties['id'] # in real scenario the identifier would need to be retrieved from elsewhere + unique_identifier = user2.properties[ + "id" + ] # in real scenario the identifier would need to be retrieved from elsewhere chat_thread_client.remove_participant(CommunicationUserIdentifier(unique_identifier)) print("Wilma has been removed from the thread...") # [END remove_participant] @@ -386,7 +379,8 @@ def clean_up(self): self.identity_client.delete_user(self.user) self.identity_client.delete_user(self.new_user) -if __name__ == '__main__': + +if __name__ == "__main__": sample = ChatThreadClientSamples() sample.create_chat_thread_client() sample.update_topic() diff --git a/sdk/communication/azure-communication-chat/samples/chat_thread_client_sample_async.py b/sdk/communication/azure-communication-chat/samples/chat_thread_client_sample_async.py index 94cdb1fba83a..cee02eb226e3 100644 --- a/sdk/communication/azure-communication-chat/samples/chat_thread_client_sample_async.py +++ b/sdk/communication/azure-communication-chat/samples/chat_thread_client_sample_async.py @@ -58,16 +58,13 @@ async def create_chat_thread_client_async(self): from datetime import datetime from azure.communication.chat.aio import ChatClient, CommunicationTokenCredential from azure.communication.chat import ChatParticipant, CommunicationUserIdentifier + # set `endpoint` to an existing ACS endpoint chat_client = ChatClient(endpoint, CommunicationTokenCredential(token)) async with chat_client: topic = "test topic" - participants = [ChatParticipant( - identifier=user, - display_name='name', - share_history_time=datetime.utcnow() - )] + participants = [ChatParticipant(identifier=user, display_name="name", share_history_time=datetime.utcnow())] create_chat_thread_result = await chat_client.create_chat_thread(topic, thread_participants=participants) chat_thread_client = chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id) # [END create_chat_thread_client] @@ -90,11 +87,14 @@ async def get_chat_thread_properties_async(self): async with chat_thread_client: chat_thread_properties = chat_thread_client.get_properties() - print('Expected Thread Id: ', thread_id, ' Actual Value: ', chat_thread_properties.id) - # [END get_thread] - print("get_chat_thread_properties_async succeeded, thread id: " + chat_thread.id - + ", thread topic: " + chat_thread.topic) - + print("Expected Thread Id: ", thread_id, " Actual Value: ", chat_thread_properties.id) + # [END get_thread] + print( + "get_chat_thread_properties_async succeeded, thread id: " + + chat_thread.id + + ", thread topic: " + + chat_thread.topic + ) async def update_topic_async(self): thread_id = self._thread_id @@ -126,28 +126,32 @@ async def send_message_async(self): # [START send_message] from azure.communication.chat import ChatMessageType + async with chat_client: chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) async with chat_thread_client: # Scenario 1: Send message without specifying chat_message_type send_message_result = await chat_thread_client.send_message( - "Hello! My name is Fred Flinstone", - sender_display_name="Fred Flinstone", - metadata={"tags": "tags"}) + "Hello! My name is Fred Flinstone", sender_display_name="Fred Flinstone", metadata={"tags": "tags"} + ) send_message_result_id = send_message_result.id # Scenario 2: Send message specifying chat_message_type send_message_result_w_type = await chat_thread_client.send_message( "Hello! My name is Wilma Flinstone", sender_display_name="Wilma Flinstone", - chat_message_type=ChatMessageType.TEXT) # equivalent to setting chat_message_type='text' + chat_message_type=ChatMessageType.TEXT, + ) # equivalent to setting chat_message_type='text' send_message_result_w_type_id = send_message_result_w_type.id # Verify message content chat_message_1 = await chat_thread_client.get_message(send_message_result_id) print("First Message:", chat_message_1.content.message, chat_message_1.metadata) - print("Second Message:", (await chat_thread_client.get_message(send_message_result_w_type_id)).content.message) - # [END send_message] + print( + "Second Message:", + (await chat_thread_client.get_message(send_message_result_w_type_id)).content.message, + ) + # [END send_message] self._message_id = send_message_result_id print("send_message succeeded, message id:", self._message_id) print("send_message succeeded with type specified, message id:", send_message_result_w_type_id) @@ -176,6 +180,7 @@ async def list_messages_async(self): # [START list_messages] from datetime import datetime, timedelta + async with chat_client: # set `thread_id` to an existing thread id chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) @@ -281,7 +286,6 @@ async def list_participants_async(self): # [END list_participants] print("list_participants_async succeeded") - async def add_participants_w_check_async(self): thread_id = self._thread_id chat_client = self._chat_client @@ -300,10 +304,10 @@ def decide_to_retry(error): async with chat_thread_client: from azure.communication.chat import ChatParticipant from datetime import datetime + new_participant = ChatParticipant( - identifier=self.new_user, - display_name='name', - share_history_time=datetime.utcnow()) + identifier=self.new_user, display_name="name", share_history_time=datetime.utcnow() + ) thread_participants = [new_participant] result = await chat_thread_client.add_participants(thread_participants) @@ -335,14 +339,12 @@ async def remove_participant_async(self): async with chat_thread_client: # add user1 and user2 to chat thread participant1 = ChatParticipant( - identifier=user1, - display_name='Fred Flinstone', - share_history_time=datetime.utcnow()) + identifier=user1, display_name="Fred Flinstone", share_history_time=datetime.utcnow() + ) participant2 = ChatParticipant( - identifier=user2, - display_name='Wilma Flinstone', - share_history_time=datetime.utcnow()) + identifier=user2, display_name="Wilma Flinstone", share_history_time=datetime.utcnow() + ) thread_participants = [participant1, participant2] await chat_thread_client.add_participants(thread_participants) @@ -353,14 +355,16 @@ async def remove_participant_async(self): async for chat_thread_participant_page in chat_thread_participants.by_page(): async for chat_thread_participant in chat_thread_participant_page: print("ChatParticipant: ", chat_thread_participant) - if chat_thread_participant.identifier.properties['id'] == user1.properties['id']: + if chat_thread_participant.identifier.properties["id"] == user1.properties["id"]: print("Found Fred!") await chat_thread_client.remove_participant(chat_thread_participant.identifier) print("Fred has been removed from the thread...") break # Option 2: Directly remove Wilma Flinstone - unique_identifier = user2.properties['id'] # in real scenario the identifier would need to be retrieved from elsewhere + unique_identifier = user2.properties[ + "id" + ] # in real scenario the identifier would need to be retrieved from elsewhere await chat_thread_client.remove_participant(CommunicationUserIdentifier(unique_identifier)) print("Wilma has been removed from the thread...") # [END remove_participant] @@ -405,5 +409,6 @@ async def main(): await sample.send_typing_notification_async() sample.clean_up() -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.run(main()) diff --git a/sdk/communication/azure-communication-chat/samples/user_credential_sample.py b/sdk/communication/azure-communication-chat/samples/user_credential_sample.py index 055fd9e4d96a..4dc5c699e1a0 100644 --- a/sdk/communication/azure-communication-chat/samples/user_credential_sample.py +++ b/sdk/communication/azure-communication-chat/samples/user_credential_sample.py @@ -23,8 +23,9 @@ from azure.communication.chat import CommunicationTokenCredential from azure.communication.identity import CommunicationIdentityClient + class CommunicationTokenCredentialSamples(object): - + connection_string = os.environ.get("COMMUNICATION_SAMPLES_CONNECTION_STRING", None) if not connection_string: raise ValueError("Set COMMUNICATION_SAMPLES_CONNECTION_STRING env before running this sample.") @@ -35,7 +36,7 @@ class CommunicationTokenCredentialSamples(object): token = token_response.token def create_credential_with_static_token(self): - # For short-lived clients, refreshing the token upon expiry is not necessary + # For short-lived clients, refreshing the token upon expiry is not necessary # and `CommunicationTokenCredential` may be instantiated with a static token. with CommunicationTokenCredential(self.token) as credential: token_response = credential.get_token() @@ -45,26 +46,27 @@ def create_credential_with_refreshing_callback(self): # Alternatively, for long-lived clients, you can create a `CommunicationTokenCredential` with a callback to renew tokens if expired. # Here we assume that we have a function `fetch_token_from_server` that makes a network request to retrieve a token string for a user. # It's necessary that the `fetch_token_from_server` function returns a valid token (with an expiration date set in the future) at all times. - fetch_token_from_server = lambda: None - with CommunicationTokenCredential( - self.token, token_refresher=fetch_token_from_server) as credential: + fetch_token_from_server = lambda: None + with CommunicationTokenCredential(self.token, token_refresher=fetch_token_from_server) as credential: token_response = credential.get_token() print("Token issued with value: " + token_response.token) def create_credential_with_proactive_refreshing_callback(self): # Optionally, you can enable proactive token refreshing where a fresh token will be acquired as soon as the # previous token approaches expiry. Using this method, your requests are less likely to be blocked to acquire a fresh token - fetch_token_from_server = lambda: None + fetch_token_from_server = lambda: None with CommunicationTokenCredential( - self.token, token_refresher=fetch_token_from_server, proactive_refresh=True) as credential: + self.token, token_refresher=fetch_token_from_server, proactive_refresh=True + ) as credential: token_response = credential.get_token() print("Token issued with value: " + token_response.token) - + def clean_up(self): print("cleaning up: deleting created user.") self.identity_client.delete_user(self.user) - -if __name__ == '__main__': + + +if __name__ == "__main__": sample = CommunicationTokenCredentialSamples() sample.create_credential_with_static_token() sample.create_credential_with_refreshing_callback() diff --git a/sdk/communication/azure-communication-chat/samples/user_credential_sample_async.py b/sdk/communication/azure-communication-chat/samples/user_credential_sample_async.py index 60791cee875c..95da45db5aec 100644 --- a/sdk/communication/azure-communication-chat/samples/user_credential_sample_async.py +++ b/sdk/communication/azure-communication-chat/samples/user_credential_sample_async.py @@ -24,8 +24,9 @@ from azure.communication.chat.aio import CommunicationTokenCredential from azure.communication.identity import CommunicationIdentityClient + class CommunicationTokenCredentialSamples(object): - + connection_string = os.environ.get("COMMUNICATION_SAMPLES_CONNECTION_STRING", None) if not connection_string: raise ValueError("Set COMMUNICATION_SAMPLES_CONNECTION_STRING env before running this sample.") @@ -36,7 +37,7 @@ class CommunicationTokenCredentialSamples(object): token = token_response.token async def create_credential_with_static_token(self): - # For short-lived clients, refreshing the token upon expiry is not necessary + # For short-lived clients, refreshing the token upon expiry is not necessary # and `CommunicationTokenCredential` may be instantiated with a static token. async with CommunicationTokenCredential(self.token) as credential: token_response = await credential.get_token() @@ -46,25 +47,26 @@ async def create_credential_with_refreshing_callback(self): # Alternatively, for long-lived clients, you can create a `CommunicationTokenCredential` with a callback to renew tokens if expired. # Here we assume that we have a function `fetch_token_from_server` that makes a network request to retrieve a token string for a user. # It's necessary that the `fetch_token_from_server` function returns a valid token (with an expiration date set in the future) at all times. - fetch_token_from_server = lambda: None - async with CommunicationTokenCredential( - self.token, token_refresher=fetch_token_from_server) as credential: + fetch_token_from_server = lambda: None + async with CommunicationTokenCredential(self.token, token_refresher=fetch_token_from_server) as credential: token_response = await credential.get_token() print("Token issued with value: " + token_response.token) async def create_credential_with_proactive_refreshing_callback(self): # Optionally, you can enable proactive token refreshing where a fresh token will be acquired as soon as the # previous token approaches expiry. Using this method, your requests are less likely to be blocked to acquire a fresh token - fetch_token_from_server = lambda: None + fetch_token_from_server = lambda: None async with CommunicationTokenCredential( - self.token, token_refresher=fetch_token_from_server, proactive_refresh=True) as credential: + self.token, token_refresher=fetch_token_from_server, proactive_refresh=True + ) as credential: token_response = await credential.get_token() print("Token issued with value: " + token_response.token) - + def clean_up(self): print("cleaning up: deleting created user.") self.identity_client.delete_user(self.user) - + + async def main(): sample = CommunicationTokenCredentialSamples() await sample.create_credential_with_static_token() @@ -72,5 +74,6 @@ async def main(): await sample.create_credential_with_proactive_refreshing_callback() sample.clean_up() -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.run(main()) diff --git a/sdk/communication/azure-communication-chat/setup.py b/sdk/communication/azure-communication-chat/setup.py index 977faf887492..f493d261c27f 100644 --- a/sdk/communication/azure-communication-chat/setup.py +++ b/sdk/communication/azure-communication-chat/setup.py @@ -14,58 +14,59 @@ PACKAGE_PPRINT_NAME = "Communication Chat" # a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace('-', '/') +package_folder_path = PACKAGE_NAME.replace("-", "/") # a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace('-', '.') +namespace_name = PACKAGE_NAME.replace("-", ".") # Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) +with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: - raise RuntimeError('Cannot find version information') + raise RuntimeError("Cannot find version information") -with open('README.md', encoding='utf-8') as f: +with open("README.md", encoding="utf-8") as f: long_description = f.read() setup( name=PACKAGE_NAME, version=version, - description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), long_description=long_description, - long_description_content_type='text/markdown', - license='MIT License', - author='Microsoft Corporation', - author_email='azpysdkhelp@microsoft.com', - url='https://github.com/Azure/azure-sdk-for-python', + long_description_content_type="text/markdown", + license="MIT License", + author="Microsoft Corporation", + author_email="azpysdkhelp@microsoft.com", + url="https://github.com/Azure/azure-sdk-for-python", keywords="azure, azure sdk", classifiers=[ "Development Status :: 5 - Production/Stable", - 'Programming Language :: Python', + "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - 'License :: OSI Approved :: MIT License', + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: MIT License", ], zip_safe=False, - packages=find_packages(exclude=[ - 'tests', - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.communication' - ]), + packages=find_packages( + exclude=[ + "tests", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + "azure.communication", + ] + ), python_requires=">=3.8", include_package_data=True, package_data={ - 'pytyped': ['py.typed'], + "pytyped": ["py.typed"], }, install_requires=[ "isodate>=0.6.1", "azure-core>=1.29.5", "typing-extensions>=4.3.0", - ] + ], ) diff --git a/sdk/communication/azure-communication-chat/tests/_shared/utils.py b/sdk/communication/azure-communication-chat/tests/_shared/utils.py index 955346bee1a6..69a0d2586209 100644 --- a/sdk/communication/azure-communication-chat/tests/_shared/utils.py +++ b/sdk/communication/azure-communication-chat/tests/_shared/utils.py @@ -20,7 +20,7 @@ def create_token_credential(): from .fake_token_credential import FakeTokenCredential return FakeTokenCredential() - + return get_credential() @@ -32,7 +32,7 @@ def async_create_token_credential(): from .async_fake_token_credential import AsyncFakeTokenCredential return AsyncFakeTokenCredential() - + return get_credential(is_async=True) diff --git a/sdk/communication/azure-communication-chat/tests/chat_e2e_helper.py b/sdk/communication/azure-communication-chat/tests/chat_e2e_helper.py index b2872acbbd86..3f4318cb93c7 100644 --- a/sdk/communication/azure-communication-chat/tests/chat_e2e_helper.py +++ b/sdk/communication/azure-communication-chat/tests/chat_e2e_helper.py @@ -11,8 +11,9 @@ def get_connection_str(): if not is_live(): return "endpoint=https://sanitized.communication.azure.com/;accesskey=fake===" - return os.getenv('COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING') or \ - os.getenv('COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING') + return os.getenv("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING") or os.getenv( + "COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING" + ) # class ChatURIReplacer(RecordingProcessor): diff --git a/sdk/communication/azure-communication-chat/tests/conftest.py b/sdk/communication/azure-communication-chat/tests/conftest.py index e1e359b15288..be32de3276cd 100644 --- a/sdk/communication/azure-communication-chat/tests/conftest.py +++ b/sdk/communication/azure-communication-chat/tests/conftest.py @@ -27,6 +27,7 @@ from devtools_testutils import add_body_key_sanitizer + @pytest.fixture(scope="session", autouse=True) def add_sanitizers(test_proxy): # Two sanitizers for chatMessageId because it can be either top-level or nested in bodies diff --git a/sdk/communication/azure-communication-chat/tests/test_chat_client.py b/sdk/communication/azure-communication-chat/tests/test_chat_client.py index 0d1d1d73f101..e69aaed7472f 100644 --- a/sdk/communication/azure-communication-chat/tests/test_chat_client.py +++ b/sdk/communication/azure-communication-chat/tests/test_chat_client.py @@ -9,13 +9,8 @@ from azure.core.exceptions import HttpResponseError from azure.core.credentials import AccessToken from datetime import datetime, timezone -from azure.communication.chat import ( - ChatClient, - ChatParticipant -) -from azure.communication.chat._shared.models import( - CommunicationUserIdentifier -) +from azure.communication.chat import ChatClient, ChatParticipant +from azure.communication.chat._shared.models import CommunicationUserIdentifier from unittest_helpers import mock_response from datetime import datetime @@ -23,16 +18,20 @@ from unittest.mock import Mock, patch + def _convert_datetime_to_utc_int(input): return int(calendar.timegm(input.utctimetuple())) + class TestChatClient(unittest.TestCase): @classmethod - @patch('azure.communication.identity._shared.user_credential.CommunicationTokenCredential') + @patch("azure.communication.identity._shared.user_credential.CommunicationTokenCredential") def setUpClass(cls, credential): - credential.get_token = Mock(return_value=AccessToken( - "some_token", _convert_datetime_to_utc_int(datetime.now().replace(tzinfo=timezone.utc)) - )) + credential.get_token = Mock( + return_value=AccessToken( + "some_token", _convert_datetime_to_utc_int(datetime.now().replace(tzinfo=timezone.utc)) + ) + ) TestChatClient.credential = credential def test_create_chat_thread(self): @@ -41,122 +40,124 @@ def test_create_chat_thread(self): raised = False def mock_send(*_, **__): - return mock_response(status_code=201, json_payload={ - "chatThread": { - "id": thread_id, - "topic": "test topic", - "createdOn": "2020-12-03T21:09:17Z", - "createdBy": "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" - } - }) - + return mock_response( + status_code=201, + json_payload={ + "chatThread": { + "id": thread_id, + "topic": "test topic", + "createdOn": "2020-12-03T21:09:17Z", + "createdBy": "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041", + } + }, + ) + chat_client = ChatClient("https://endpoint", TestChatClient.credential, transport=Mock(send=mock_send)) - topic="test topic" + topic = "test topic" user = CommunicationUserIdentifier("8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041") - participants=[ChatParticipant( - identifier=user, - display_name='name', - share_history_time=datetime.utcnow() - )] + participants = [ChatParticipant(identifier=user, display_name="name", share_history_time=datetime.utcnow())] try: create_chat_thread_result = chat_client.create_chat_thread(topic, thread_participants=participants) except: raised = True raise - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") assert create_chat_thread_result.chat_thread.id == thread_id def test_create_chat_thread_w_repeatability_request_id(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" chat_thread_client = None raised = False - idempotency_token="b66d6031-fdcc-41df-8306-e524c9f226b8" + idempotency_token = "b66d6031-fdcc-41df-8306-e524c9f226b8" def mock_send(*_, **__): - return mock_response(status_code=201, json_payload={ - "chatThread": { - "id": thread_id, - "topic": "test topic", - "createdOn": "2020-12-03T21:09:17Z", - "createdBy": "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" - } - }) + return mock_response( + status_code=201, + json_payload={ + "chatThread": { + "id": thread_id, + "topic": "test topic", + "createdOn": "2020-12-03T21:09:17Z", + "createdBy": "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041", + } + }, + ) chat_client = ChatClient("https://endpoint", TestChatClient.credential, transport=Mock(send=mock_send)) topic = "test topic" user = CommunicationUserIdentifier("8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041") - participants = [ChatParticipant( - identifier=user, - display_name='name', - share_history_time=datetime.utcnow() - )] + participants = [ChatParticipant(identifier=user, display_name="name", share_history_time=datetime.utcnow())] try: - create_chat_thread_result = chat_client.create_chat_thread(topic=topic, - thread_participants=participants, - idempotency_token=idempotency_token) + create_chat_thread_result = chat_client.create_chat_thread( + topic=topic, thread_participants=participants, idempotency_token=idempotency_token + ) except: raised = True raise - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") assert create_chat_thread_result.chat_thread.id == thread_id def test_create_chat_thread_raises_error(self): def mock_send(*_, **__): return mock_response(status_code=400, json_payload={"msg": "some error"}) + chat_client = ChatClient("https://endpoint", TestChatClient.credential, transport=Mock(send=mock_send)) - topic="test topic", + topic = ("test topic",) user = CommunicationUserIdentifier("8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041") - thread_participants=[ChatParticipant( - identifier=user, - display_name='name', - share_history_time=datetime.utcnow() - )] - - self.assertRaises(HttpResponseError, chat_client.create_chat_thread, topic=topic, thread_participants=thread_participants) - + thread_participants = [ + ChatParticipant(identifier=user, display_name="name", share_history_time=datetime.utcnow()) + ] + + self.assertRaises( + HttpResponseError, chat_client.create_chat_thread, topic=topic, thread_participants=thread_participants + ) + def test_create_chat_thread_with_invalid_participant_raises_error(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" + def mock_send(*_, **__): - return mock_response(status_code=201, json_payload={ - "chatThread": { - "id": thread_id, - "topic": "Lunch", - "createdOn": "2020-06-06T05:55:41.6460000Z", - "createdByCommunicationIdentifier": { - "rawId": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10a", - "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10a" - } - } - }, - "invalidParticipants": [ - { - "target": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10c", - "code": "403", - "message": "Permissions check failed" + return mock_response( + status_code=201, + json_payload={ + "chatThread": { + "id": thread_id, + "topic": "Lunch", + "createdOn": "2020-06-06T05:55:41.6460000Z", + "createdByCommunicationIdentifier": { + "rawId": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10a", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10a" + }, + }, }, - { - "target": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10d", - "code": "404", - "message": "Not found" - } - ] - }) + "invalidParticipants": [ + { + "target": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10c", + "code": "403", + "message": "Permissions check failed", + }, + { + "target": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10d", + "code": "404", + "message": "Not found", + }, + ], + }, + ) + chat_client = ChatClient("https://endpoint", TestChatClient.credential, transport=Mock(send=mock_send)) - topic="test topic", + topic = ("test topic",) user = CommunicationUserIdentifier("57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041") - thread_participants=[ChatParticipant( - identifier=user, - display_name='name', - share_history_time=datetime.utcnow() - )] - + thread_participants = [ + ChatParticipant(identifier=user, display_name="name", share_history_time=datetime.utcnow()) + ] + create_chat_thread_result = chat_client.create_chat_thread(topic, thread_participants=thread_participants) assert create_chat_thread_result.errors is not None assert len(create_chat_thread_result.errors) is 2 @@ -167,6 +168,7 @@ def test_delete_chat_thread(self): def mock_send(*_, **__): return mock_response(status_code=204) + chat_client = ChatClient("https://endpoint", TestChatClient.credential, transport=Mock(send=mock_send)) try: @@ -174,7 +176,7 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") def test_list_chat_threads(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" @@ -182,6 +184,7 @@ def test_list_chat_threads(self): def mock_send(*_, **__): return mock_response(status_code=200, json_payload={"value": [{"id": thread_id}]}) + chat_client = ChatClient("https://endpoint", TestChatClient.credential, transport=Mock(send=mock_send)) chat_threads = None @@ -190,7 +193,7 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") for chat_thread_item_page in chat_threads.by_page(): l = list(chat_thread_item_page) assert len(l) == 1 @@ -203,5 +206,6 @@ def test_get_thread_client(self): assert chat_thread_client.thread_id == thread_id -if __name__ == '__main__': - unittest.main() \ No newline at end of file + +if __name__ == "__main__": + unittest.main() diff --git a/sdk/communication/azure-communication-chat/tests/test_chat_client_async.py b/sdk/communication/azure-communication-chat/tests/test_chat_client_async.py index 782e113874c4..bdef7744cd22 100644 --- a/sdk/communication/azure-communication-chat/tests/test_chat_client_async.py +++ b/sdk/communication/azure-communication-chat/tests/test_chat_client_async.py @@ -4,14 +4,10 @@ # license information. # ------------------------------------------------------------------------- from azure.core.credentials import AccessToken -from azure.communication.chat.aio import ( - ChatClient -) +from azure.communication.chat.aio import ChatClient from azure.communication.chat import ChatParticipant -from azure.communication.chat._shared.models import( - CommunicationUserIdentifier -) +from azure.communication.chat._shared.models import CommunicationUserIdentifier from unittest_helpers import mock_response from azure.core.exceptions import HttpResponseError from datetime import datetime, timezone @@ -22,6 +18,7 @@ import time import calendar + def _convert_datetime_to_utc_int(input): return int(calendar.timegm(input.utctimetuple())) @@ -29,6 +26,7 @@ def _convert_datetime_to_utc_int(input): async def mock_get_token(*_, **__): return AccessToken("some_token", _convert_datetime_to_utc_int(datetime.now().replace(tzinfo=timezone.utc))) + credential = Mock(spec_set=["get_token"], get_token=mock_get_token) @@ -37,68 +35,66 @@ async def test_create_chat_thread(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" async def mock_send(*_, **__): - return mock_response(status_code=201, json_payload={ - "chatThread": { - "id": thread_id, - "topic": "test topic", - "createdOn": "2020-12-03T21:09:17Z", - "createdBy": "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" - } - }) + return mock_response( + status_code=201, + json_payload={ + "chatThread": { + "id": thread_id, + "topic": "test topic", + "createdOn": "2020-12-03T21:09:17Z", + "createdBy": "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041", + } + }, + ) chat_client = ChatClient("https://endpoint", credential, transport=Mock(send=mock_send)) - topic="test topic" + topic = "test topic" user = CommunicationUserIdentifier("8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041") - participants=[ChatParticipant( - identifier=user, - display_name='name', - share_history_time=datetime.utcnow() - )] + participants = [ChatParticipant(identifier=user, display_name="name", share_history_time=datetime.utcnow())] create_chat_thread_result = await chat_client.create_chat_thread(topic, thread_participants=participants) assert create_chat_thread_result.chat_thread.id == thread_id + @pytest.mark.asyncio async def test_create_chat_thread_w_repeatability_request_id(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" idempotency_token = "b66d6031-fdcc-41df-8306-e524c9f226b8" + async def mock_send(*_, **__): - return mock_response(status_code=201, json_payload={ - "chatThread": { - "id": thread_id, - "topic": "test topic", - "createdOn": "2020-12-03T21:09:17Z", - "createdBy": "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" - } - }) + return mock_response( + status_code=201, + json_payload={ + "chatThread": { + "id": thread_id, + "topic": "test topic", + "createdOn": "2020-12-03T21:09:17Z", + "createdBy": "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041", + } + }, + ) chat_client = ChatClient("https://endpoint", credential, transport=Mock(send=mock_send)) - topic="test topic" + topic = "test topic" user = CommunicationUserIdentifier("8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041") - participants=[ChatParticipant( - identifier=user, - display_name='name', - share_history_time=datetime.utcnow() - )] - create_chat_thread_result = await chat_client.create_chat_thread(topic=topic, - thread_participants=participants, - idempotency_token=idempotency_token) + participants = [ChatParticipant(identifier=user, display_name="name", share_history_time=datetime.utcnow())] + create_chat_thread_result = await chat_client.create_chat_thread( + topic=topic, thread_participants=participants, idempotency_token=idempotency_token + ) assert create_chat_thread_result.chat_thread.id == thread_id + @pytest.mark.asyncio async def test_create_chat_thread_raises_error(): async def mock_send(*_, **__): return mock_response(status_code=400, json_payload={"msg": "some error"}) + chat_client = ChatClient("https://endpoint", credential, transport=Mock(send=mock_send)) - topic="test topic", + topic = ("test topic",) user = CommunicationUserIdentifier("8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041") - participants=[ChatParticipant( - identifier=user, - display_name='name', - share_history_time=datetime.utcnow() - )] + participants = [ChatParticipant(identifier=user, display_name="name", share_history_time=datetime.utcnow())] raised = False try: @@ -108,6 +104,7 @@ async def mock_send(*_, **__): assert raised == True + @pytest.mark.asyncio async def test_delete_chat_thread(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" @@ -115,6 +112,7 @@ async def test_delete_chat_thread(): async def mock_send(*_, **__): return mock_response(status_code=204) + chat_client = ChatClient("https://endpoint", credential, transport=Mock(send=mock_send)) raised = False @@ -125,6 +123,7 @@ async def mock_send(*_, **__): assert raised == False + @pytest.mark.asyncio async def test_list_chat_threads(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" @@ -132,6 +131,7 @@ async def test_list_chat_threads(): async def mock_send(*_, **__): return mock_response(status_code=200, json_payload={"value": [{"id": thread_id}]}) + chat_client = ChatClient("https://endpoint", credential, transport=Mock(send=mock_send)) chat_threads = None diff --git a/sdk/communication/azure-communication-chat/tests/test_chat_client_e2e.py b/sdk/communication/azure-communication-chat/tests/test_chat_client_e2e.py index 8516e2cf48b5..f342d07f5cb1 100644 --- a/sdk/communication/azure-communication-chat/tests/test_chat_client_e2e.py +++ b/sdk/communication/azure-communication-chat/tests/test_chat_client_e2e.py @@ -10,11 +10,7 @@ from uuid import uuid4 from azure.communication.identity import CommunicationIdentityClient -from azure.communication.chat import ( - ChatClient, - CommunicationTokenCredential, - ChatParticipant -) +from azure.communication.chat import ChatClient, CommunicationTokenCredential, ChatParticipant from azure.communication.chat._shared.utils import parse_connection_str from chat_e2e_helper import get_connection_str from _shared.utils import get_http_logging_policy @@ -35,9 +31,7 @@ def setup_method(self): # create ChatClient self.chat_client = ChatClient( - self.endpoint, - CommunicationTokenCredential(self.token), - http_logging_policy=get_http_logging_policy() + self.endpoint, CommunicationTokenCredential(self.token), http_logging_policy=get_http_logging_policy() ) def teardown_method(self): @@ -51,14 +45,12 @@ def _create_thread(self, idempotency_token=None): topic = "test topic" share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) - participants = [ChatParticipant( - identifier=self.user, - display_name='name', - share_history_time=share_history_time - )] - create_chat_thread_result = self.chat_client.create_chat_thread(topic, - thread_participants=participants, - idempotency_token=idempotency_token) + participants = [ + ChatParticipant(identifier=self.user, display_name="name", share_history_time=share_history_time) + ] + create_chat_thread_result = self.chat_client.create_chat_thread( + topic, thread_participants=participants, idempotency_token=idempotency_token + ) self.thread_id = create_chat_thread_result.chat_thread.id @pytest.mark.live_test_only @@ -71,9 +63,7 @@ def test_access_token_validation(self): # create ChatClient chat_client = ChatClient( - self.endpoint, - CommunicationTokenCredential(self.token), - http_logging_policy=get_http_logging_policy() + self.endpoint, CommunicationTokenCredential(self.token), http_logging_policy=get_http_logging_policy() ) raised = False try: @@ -91,7 +81,7 @@ def test_access_token_validation(self): for chat_thread_info in chat_threads_info_page: print("ChatThreadInfo: ", chat_thread_info) except: - raised = True + raised = True assert raised is False diff --git a/sdk/communication/azure-communication-chat/tests/test_chat_client_e2e_async.py b/sdk/communication/azure-communication-chat/tests/test_chat_client_e2e_async.py index 0aaa0725087f..c7bef5fba380 100644 --- a/sdk/communication/azure-communication-chat/tests/test_chat_client_e2e_async.py +++ b/sdk/communication/azure-communication-chat/tests/test_chat_client_e2e_async.py @@ -11,13 +11,8 @@ from uuid import uuid4 from azure.communication.identity import CommunicationIdentityClient -from azure.communication.chat.aio import ( - ChatClient, - CommunicationTokenCredential -) -from azure.communication.chat import ( - ChatParticipant -) +from azure.communication.chat.aio import ChatClient, CommunicationTokenCredential +from azure.communication.chat import ChatParticipant from azure.communication.chat._shared.utils import parse_connection_str from chat_e2e_helper import get_connection_str from _shared.utils import get_http_logging_policy @@ -38,9 +33,7 @@ def setup_method(self): # create ChatClient self.chat_client = ChatClient( - self.endpoint, - CommunicationTokenCredential(self.token), - http_logging_policy=get_http_logging_policy() + self.endpoint, CommunicationTokenCredential(self.token), http_logging_policy=get_http_logging_policy() ) def teardown_method(self): @@ -53,16 +46,14 @@ async def _create_thread(self, idempotency_token=None): topic = "test topic" share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) - participants = [ChatParticipant( - identifier=self.user, - display_name='name', - share_history_time=share_history_time - )] - create_chat_thread_result = await self.chat_client.create_chat_thread(topic, - thread_participants=participants, - idempotency_token=idempotency_token) + participants = [ + ChatParticipant(identifier=self.user, display_name="name", share_history_time=share_history_time) + ] + create_chat_thread_result = await self.chat_client.create_chat_thread( + topic, thread_participants=participants, idempotency_token=idempotency_token + ) self.thread_id = create_chat_thread_result.chat_thread.id - + @pytest.mark.live_test_only @pytest.mark.asyncio @recorded_by_proxy_async @@ -90,7 +81,7 @@ async def test_create_chat_thread_w_no_participants_async(self): # delete created users and chat threads if not self.is_playback(): await self.chat_client.delete_chat_thread(create_chat_thread_result.chat_thread.id) - + @pytest.mark.live_test_only @pytest.mark.asyncio @recorded_by_proxy_async @@ -107,7 +98,6 @@ async def test_create_chat_thread_w_repeatability_request_id_async(self): await self._create_thread(idempotency_token=idempotency_token) assert thread_id == self.thread_id - # delete created users and chat threads if not self.is_playback(): await self.chat_client.delete_chat_thread(self.thread_id) diff --git a/sdk/communication/azure-communication-chat/tests/test_chat_thread_client.py b/sdk/communication/azure-communication-chat/tests/test_chat_thread_client.py index c97bda3154fe..42fefe70409b 100644 --- a/sdk/communication/azure-communication-chat/tests/test_chat_thread_client.py +++ b/sdk/communication/azure-communication-chat/tests/test_chat_thread_client.py @@ -10,28 +10,26 @@ from datetime import datetime, timezone from azure.core.credentials import AccessToken from azure.core.exceptions import HttpResponseError -from azure.communication.chat import ( - ChatThreadClient, - ChatParticipant, - ChatMessageType -) -from azure.communication.chat._shared.models import( - CommunicationUserIdentifier -) +from azure.communication.chat import ChatThreadClient, ChatParticipant, ChatMessageType +from azure.communication.chat._shared.models import CommunicationUserIdentifier from unittest_helpers import mock_response from unittest.mock import Mock, patch + def _convert_datetime_to_utc_int(input): return int(calendar.timegm(input.utctimetuple())) + class TestChatThreadClient(unittest.TestCase): @classmethod - @patch('azure.communication.identity._shared.user_credential.CommunicationTokenCredential') + @patch("azure.communication.identity._shared.user_credential.CommunicationTokenCredential") def setUpClass(cls, credential): - credential.get_token = Mock(return_value=AccessToken( - "some_token", _convert_datetime_to_utc_int(datetime.now().replace(tzinfo=timezone.utc)) - )) + credential.get_token = Mock( + return_value=AccessToken( + "some_token", _convert_datetime_to_utc_int(datetime.now().replace(tzinfo=timezone.utc)) + ) + ) TestChatThreadClient.credential = credential def test_update_topic(self): @@ -40,7 +38,10 @@ def test_update_topic(self): def mock_send(*_, **__): return mock_response(status_code=204) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) topic = "update topic" try: @@ -48,36 +49,38 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") def test_send_message(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False def mock_send(*_, **__): return mock_response(status_code=201, json_payload={"id": message_id}) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) create_message_result = None try: - content='hello world' - sender_display_name='sender name' - metadata={ "tags": "tag" } + content = "hello world" + sender_display_name = "sender name" + metadata = {"tags": "tag"} create_message_result = chat_thread_client.send_message( - content=content, - sender_display_name=sender_display_name, - metadata=metadata) + content=content, sender_display_name=sender_display_name, metadata=metadata + ) create_message_result_id = create_message_result.id except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") assert create_message_result_id == message_id def test_send_message_w_type(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False message_str = "Hi I am Bob." @@ -86,131 +89,157 @@ def test_send_message_w_type(self): for chat_message_type in chat_message_types: def mock_send(*_, **__): - return mock_response(status_code=201, json_payload={ - "id": message_id, - "type": chat_message_type, - "sequenceId": "3", - "version": message_id, - "content": { - "message": message_str, - "topic": "Lunch Chat thread", - "participants": [ - { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b", - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ], - "initiator": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + return mock_response( + status_code=201, + json_payload={ + "id": message_id, + "type": chat_message_type, + "sequenceId": "3", + "version": message_id, + "content": { + "message": message_str, + "topic": "Lunch Chat thread", + "participants": [ + { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b", + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", + } + ], + "initiator": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b", + }, + "senderDisplayName": "Bob", + "createdOn": "2021-01-27T01:37:33Z", + "senderId": "8:acs:46849534-eb08-4ab7-bde7-c36928cd1547_00000007-e155-1f06-1db7-3a3a0d00004b", }, - "senderDisplayName": "Bob", - "createdOn": "2021-01-27T01:37:33Z", - "senderId": "8:acs:46849534-eb08-4ab7-bde7-c36928cd1547_00000007-e155-1f06-1db7-3a3a0d00004b" - }) + ) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, - transport=Mock(send=mock_send)) + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) try: - content='hello world' - sender_display_name='sender name' + content = "hello world" + sender_display_name = "sender name" create_message_result = chat_thread_client.send_message( - content=content, - chat_message_type=chat_message_type, - sender_display_name=sender_display_name) + content=content, chat_message_type=chat_message_type, sender_display_name=sender_display_name + ) create_message_result_id = create_message_result.id except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") assert create_message_result_id == message_id def test_send_message_w_invalid_type_throws_error(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False message_str = "Hi I am Bob." # the payload is irrelevant - it'll fail before def mock_send(*_, **__): - return mock_response(status_code=201, json_payload={ - "id": message_id - }) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + return mock_response(status_code=201, json_payload={"id": message_id}) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) create_message_result = None - chat_message_types = [ChatMessageType.PARTICIPANT_ADDED, ChatMessageType.PARTICIPANT_REMOVED, - ChatMessageType.TOPIC_UPDATED, "participant_added", "participant_removed", "topic_updated", - "ChatMessageType.TEXT", "ChatMessageType.HTML", - "ChatMessageType.PARTICIPANT_ADDED", "ChatMessageType.PARTICIPANT_REMOVED", - "ChatMessageType.TOPIC_UPDATED"] + chat_message_types = [ + ChatMessageType.PARTICIPANT_ADDED, + ChatMessageType.PARTICIPANT_REMOVED, + ChatMessageType.TOPIC_UPDATED, + "participant_added", + "participant_removed", + "topic_updated", + "ChatMessageType.TEXT", + "ChatMessageType.HTML", + "ChatMessageType.PARTICIPANT_ADDED", + "ChatMessageType.PARTICIPANT_REMOVED", + "ChatMessageType.TOPIC_UPDATED", + ] for chat_message_type in chat_message_types: try: - content='hello world' - sender_display_name='sender name' + content = "hello world" + sender_display_name = "sender name" create_message_result = chat_thread_client.send_message( - content=content, - chat_message_type=chat_message_type, - sender_display_name=sender_display_name) + content=content, chat_message_type=chat_message_type, sender_display_name=sender_display_name + ) except: raised = True - self.assertTrue(raised, 'Expected is excpetion raised') - + self.assertTrue(raised, "Expected is excpetion raised") def test_get_message(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False message_str = "Hi I am Bob." def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ - "id": message_id, - "type": "text", - "sequenceId": "3", - "version": message_id, - "content": { - "message": message_str, - "topic": "Lunch Chat thread", - "participants": [ - { - "communicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ], - "initiatorCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "attachments": [ - { - "id": "id", - "attachmentType": "image", - "name": "name.png", - "url": "https://endpoint/threads/chatThreadId/images/imageId/views/original", - "previewUrl": "https://endpoint/threads/chatThreadId/images/imageId/views/preview", + return mock_response( + status_code=200, + json_payload={ + "id": message_id, + "type": "text", + "sequenceId": "3", + "version": message_id, + "content": { + "message": message_str, + "topic": "Lunch Chat thread", + "participants": [ + { + "communicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, }, - { - "id": "id", - "attachmentType": "file", - "name": "name.pdf", - "previewUrl": "https://contoso.sharepoint.com/teams/TeamName/DocumentLibrary/FileName", - } - ] + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", + } + ], + "initiatorCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, }, - "senderDisplayName": "Bob", - "createdOn": "2021-01-27T01:37:33Z", - "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "deletedOn": "2021-01-27T01:37:33Z", - "editedOn": "2021-01-27T01:37:33Z", - "metadata": { - "tags": "tag" - } - }) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + "attachments": [ + { + "id": "id", + "attachmentType": "image", + "name": "name.png", + "url": "https://endpoint/threads/chatThreadId/images/imageId/views/original", + "previewUrl": "https://endpoint/threads/chatThreadId/images/imageId/views/preview", + }, + { + "id": "id", + "attachmentType": "file", + "name": "name.pdf", + "previewUrl": "https://contoso.sharepoint.com/teams/TeamName/DocumentLibrary/FileName", + }, + ], + }, + "senderDisplayName": "Bob", + "createdOn": "2021-01-27T01:37:33Z", + "senderCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "deletedOn": "2021-01-27T01:37:33Z", + "editedOn": "2021-01-27T01:37:33Z", + "metadata": {"tags": "tag"}, + }, + ) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) message = None try: @@ -218,7 +247,7 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") assert message.id == message_id assert message.content.message == message_str assert message.type == ChatMessageType.TEXT @@ -230,38 +259,60 @@ def mock_send(*_, **__): def test_list_messages(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" message_str = "Hi I am Bob." raised = False def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={"value": [{ - "id": message_id, - "type": "text", - "sequenceId": "3", - "version": message_id, - "content": { - "message": message_str, - "topic": "Lunch Chat thread", - "participants": [ - { - "communicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ], - "initiatorCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}} - }, - "senderDisplayName": "Bob", - "createdOn": "2021-01-27T01:37:33Z", - "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "deletedOn": "2021-01-27T01:37:33Z", - "editedOn": "2021-01-27T01:37:33Z" - }]}) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + return mock_response( + status_code=200, + json_payload={ + "value": [ + { + "id": message_id, + "type": "text", + "sequenceId": "3", + "version": message_id, + "content": { + "message": message_str, + "topic": "Lunch Chat thread", + "participants": [ + { + "communicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", + } + ], + "initiatorCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + }, + "senderDisplayName": "Bob", + "createdOn": "2021-01-27T01:37:33Z", + "senderCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "deletedOn": "2021-01-27T01:37:33Z", + "editedOn": "2021-01-27T01:37:33Z", + } + ] + }, + ) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) chat_messages = None try: @@ -269,7 +320,7 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") for chat_message in chat_messages.by_page(): l = list(chat_message) assert len(l) == 1 @@ -278,88 +329,120 @@ def mock_send(*_, **__): def test_list_messages_with_start_time(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" raised = False - message_id = '1596823919339' + message_id = "1596823919339" message_str = "Hi I am Bob." def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ - "value": [ - { - "id": message_id, - "type": "text", - "sequenceId": "2", - "version": message_id, - "content": { - "message": message_str, - "topic": "Lunch Chat thread", - "participants": [ - { - "communicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ], - "initiatorCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}} + return mock_response( + status_code=200, + json_payload={ + "value": [ + { + "id": message_id, + "type": "text", + "sequenceId": "2", + "version": message_id, + "content": { + "message": message_str, + "topic": "Lunch Chat thread", + "participants": [ + { + "communicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", + } + ], + "initiatorCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + }, + "senderDisplayName": "Bob", + "createdOn": "2021-01-27T01:37:33Z", + "senderCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "deletedOn": "2021-01-27T01:37:33Z", + "editedOn": "2021-01-27T01:37:33Z", }, - "senderDisplayName": "Bob", - "createdOn": "2021-01-27T01:37:33Z", - "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "deletedOn": "2021-01-27T01:37:33Z", - "editedOn": "2021-01-27T01:37:33Z" - }, - { - "id": message_id, - "type": "text", - "sequenceId": "3", - "version": message_id, - "content": { - "message": message_str, - "topic": "Lunch Chat thread", - "participants": [ - { - "communicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ], - "initiatorCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}} + { + "id": message_id, + "type": "text", + "sequenceId": "3", + "version": message_id, + "content": { + "message": message_str, + "topic": "Lunch Chat thread", + "participants": [ + { + "communicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", + } + ], + "initiatorCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + }, + "senderDisplayName": "Bob", + "createdOn": "2021-01-27T01:37:33Z", + "senderCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "deletedOn": "2021-01-27T01:37:33Z", + "editedOn": "2021-01-27T01:37:33Z", }, - "senderDisplayName": "Bob", - "createdOn": "2021-01-27T01:37:33Z", - "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "deletedOn": "2021-01-27T01:37:33Z", - "editedOn": "2021-01-27T01:37:33Z" - } - ]}) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + ] + }, + ) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) chat_messages = None try: - chat_messages = chat_thread_client.list_messages( - start_time=datetime(2020, 8, 17, 18, 0, 0) - ) + chat_messages = chat_thread_client.list_messages(start_time=datetime(2020, 8, 17, 18, 0, 0)) except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") for chat_message in chat_messages.by_page(): l = list(chat_message) assert len(l) == 2 def test_update_message_content(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False def mock_send(*_, **__): return mock_response(status_code=204) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) try: content = "updated message content" @@ -367,60 +450,72 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") def test_update_message_metadata(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False def mock_send(*_, **__): return mock_response(status_code=204) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) try: - metadata={ "tags": "tag" } + metadata = {"tags": "tag"} chat_thread_client.update_message(message_id, metadata=metadata) except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") def test_delete_message(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False def mock_send(*_, **__): return mock_response(status_code=204) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) try: chat_thread_client.delete_message(message_id) except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") def test_list_participants(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - participant_id="8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" + participant_id = "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" raised = False def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={"value": [ - { - "communicationIdentifier": { - "rawId": participant_id, - "communicationUser": { - "id": participant_id + return mock_response( + status_code=200, + json_payload={ + "value": [ + { + "communicationIdentifier": { + "rawId": participant_id, + "communicationUser": {"id": participant_id}, + }, + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", } - }, - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ]}) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + ] + }, + ) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) chat_thread_participants = None try: @@ -428,11 +523,11 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") for chat_thread_participant_page in chat_thread_participants.by_page(): l = list(chat_thread_participant_page) assert len(l) == 1 - l[0].identifier.properties['id'] = participant_id + l[0].identifier.properties["id"] = participant_id def test_list_participants_with_results_per_page(self): thread_id = "19:81181a8abbf54b5695f87a0042ddcba9@thread.v2" @@ -441,32 +536,33 @@ def test_list_participants_with_results_per_page(self): raised = False def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ - "value": [ - { - "communicationIdentifier": { - "rawId": participant_id_1, - "communicationUser": { - "id": participant_id_1 - } + return mock_response( + status_code=200, + json_payload={ + "value": [ + { + "communicationIdentifier": { + "rawId": participant_id_1, + "communicationUser": {"id": participant_id_1}, + }, + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", }, - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - }, - { - "communicationIdentifier": { - "rawId": participant_id_2, - "communicationUser": { - "id": participant_id_2 - } + { + "communicationIdentifier": { + "rawId": participant_id_2, + "communicationUser": {"id": participant_id_2}, + }, + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", }, - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ]}) + ] + }, + ) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, - transport=Mock(send=mock_send)) + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) chat_thread_participants = None try: @@ -474,25 +570,28 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") for chat_thread_participant_page in chat_thread_participants.by_page(): l = list(chat_thread_participant_page) assert len(l) == 2 - def test_add_participants(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - new_participant_id="8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" + new_participant_id = "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" raised = False def mock_send(*_, **__): return mock_response(status_code=201) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) new_participant = ChatParticipant( - identifier=CommunicationUserIdentifier(new_participant_id), - display_name='name', - share_history_time=datetime.utcnow()) + identifier=CommunicationUserIdentifier(new_participant_id), + display_name="name", + share_history_time=datetime.utcnow(), + ) participants = [new_participant] try: @@ -500,32 +599,34 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") self.assertTrue(len(result) == 0) def test_add_participants_w_failed_participants_returns_nonempty_list(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - new_participant_id="8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" + new_participant_id = "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" raised = False error_message = "some error message" def mock_send(*_, **__): - return mock_response(status_code=201,json_payload={ - "invalidParticipants": [ - { - "code": "string", - "message": error_message, - "target": new_participant_id, - "details": [] - } - ] - }) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + return mock_response( + status_code=201, + json_payload={ + "invalidParticipants": [ + {"code": "string", "message": error_message, "target": new_participant_id, "details": []} + ] + }, + ) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) new_participant = ChatParticipant( - identifier=CommunicationUserIdentifier(new_participant_id), - display_name='name', - share_history_time=datetime.utcnow()) + identifier=CommunicationUserIdentifier(new_participant_id), + display_name="name", + share_history_time=datetime.utcnow(), + ) participants = [new_participant] try: @@ -533,33 +634,35 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") self.assertTrue(len(result) == 1) failed_participant = result[0][0] communication_error = result[0][1] - self.assertEqual(new_participant.identifier.properties['id'], failed_participant.identifier.properties['id']) + self.assertEqual(new_participant.identifier.properties["id"], failed_participant.identifier.properties["id"]) self.assertEqual(new_participant.display_name, failed_participant.display_name) self.assertEqual(new_participant.share_history_time, failed_participant.share_history_time) self.assertEqual(error_message, communication_error.message) - def test_remove_participant(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - participant_id="8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" + participant_id = "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" raised = False def mock_send(*_, **__): return mock_response(status_code=204) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) try: chat_thread_client.remove_participant(identifier=CommunicationUserIdentifier(participant_id)) except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") def test_send_typing_notification(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" @@ -567,14 +670,17 @@ def test_send_typing_notification(self): def mock_send(*_, **__): return mock_response(status_code=200) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) try: chat_thread_client.send_typing_notification() except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") def test_send_typing_notification_with_sender_display_name(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" @@ -582,51 +688,58 @@ def test_send_typing_notification_with_sender_display_name(self): def mock_send(*_, **__): return mock_response(status_code=200) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) try: chat_thread_client.send_typing_notification(sender_display_name="John") except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") def test_send_read_receipt(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id="1596823919339" + message_id = "1596823919339" raised = False def mock_send(*_, **__): return mock_response(status_code=200) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) try: chat_thread_client.send_read_receipt(message_id) except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") def test_list_read_receipts(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id="1596823919339" + message_id = "1596823919339" raised = False def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ - "value": [ - { - "chatMessageId": message_id, - "senderCommunicationIdentifier": { - "rawId": "string", - "communicationUser": { - "id": "string" - } + return mock_response( + status_code=200, + json_payload={ + "value": [ + { + "chatMessageId": message_id, + "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": {"id": "string"}}, } - } - ] - }) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + ] + }, + ) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) read_receipts = None try: @@ -634,40 +747,37 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") for read_receipt_page in read_receipts.by_page(): l = list(read_receipt_page) assert len(l) == 1 def test_list_read_receipts_with_results_per_page(self): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id_1="1596823919339" - message_id_2="1596823919340" + message_id_1 = "1596823919339" + message_id_2 = "1596823919340" raised = False def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ - "value": [ - { - "chatMessageId": message_id_1, - "senderCommunicationIdentifier": { - "rawId": "string", - "communicationUser": { - "id": "string" - } - } - }, - { - "chatMessageId": message_id_2, - "senderCommunicationIdentifier": { - "rawId": "string", - "communicationUser": { - "id": "string" - } - } - } - ]}) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + return mock_response( + status_code=200, + json_payload={ + "value": [ + { + "chatMessageId": message_id_1, + "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": {"id": "string"}}, + }, + { + "chatMessageId": message_id_2, + "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": {"id": "string"}}, + }, + ] + }, + ) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) read_receipts = None try: @@ -675,7 +785,7 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") for read_receipt_page in read_receipts.by_page(): l = list(read_receipt_page) assert len(l) == 2 @@ -685,14 +795,20 @@ def test_get_properties(self): raised = False def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ - "id": thread_id, - "topic": "Lunch Chat thread", - "createdOn": "2020-10-30T10:50:50Z", - "deletedOn": "2020-10-30T10:50:50Z", - "createdByCommunicationIdentifier": {"rawId": "string", "communicationUser": {"id": "string"}} - }) - chat_thread_client = ChatThreadClient("https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send)) + return mock_response( + status_code=200, + json_payload={ + "id": thread_id, + "topic": "Lunch Chat thread", + "createdOn": "2020-10-30T10:50:50Z", + "deletedOn": "2020-10-30T10:50:50Z", + "createdByCommunicationIdentifier": {"rawId": "string", "communicationUser": {"id": "string"}}, + }, + ) + + chat_thread_client = ChatThreadClient( + "https://endpoint", TestChatThreadClient.credential, thread_id, transport=Mock(send=mock_send) + ) get_thread_result = None try: @@ -700,9 +816,9 @@ def mock_send(*_, **__): except: raised = True - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") assert get_thread_result.id == thread_id -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_async.py b/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_async.py index 3deacc0c97bc..c724bcd5e493 100644 --- a/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_async.py +++ b/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_async.py @@ -6,13 +6,8 @@ from azure.core.credentials import AccessToken from datetime import datetime, timezone from azure.communication.chat.aio import ChatThreadClient -from azure.communication.chat import ( - ChatParticipant, - ChatMessageType -) -from azure.communication.chat._shared.models import( - CommunicationUserIdentifier -) +from azure.communication.chat import ChatParticipant, ChatMessageType +from azure.communication.chat._shared.models import CommunicationUserIdentifier from unittest_helpers import mock_response from azure.core.exceptions import HttpResponseError @@ -22,6 +17,7 @@ import time import calendar + def _convert_datetime_to_utc_int(input): return int(calendar.timegm(input.utctimetuple())) @@ -29,6 +25,7 @@ def _convert_datetime_to_utc_int(input): async def mock_get_token(*_, **__): return AccessToken("some_token", _convert_datetime_to_utc_int(datetime.now().replace(tzinfo=timezone.utc))) + credential = Mock(spec_set=["get_token"], get_token=mock_get_token) @@ -39,6 +36,7 @@ async def test_update_topic(): async def mock_send(*_, **__): return mock_response(status_code=204) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) topic = "update topic" @@ -49,26 +47,27 @@ async def mock_send(*_, **__): assert raised == False + @pytest.mark.asyncio async def test_send_message(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False async def mock_send(*_, **__): return mock_response(status_code=201, json_payload={"id": message_id}) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) create_message_result_id = None try: - content='hello world' - sender_display_name='sender name' - metadata={ "tags": "tag" } + content = "hello world" + sender_display_name = "sender name" + metadata = {"tags": "tag"} create_message_result = await chat_thread_client.send_message( - content, - sender_display_name=sender_display_name, - metadata=metadata) + content, sender_display_name=sender_display_name, metadata=metadata + ) create_message_result_id = create_message_result.id except: raised = True @@ -76,10 +75,11 @@ async def mock_send(*_, **__): assert raised == False assert create_message_result_id == message_id + @pytest.mark.asyncio async def test_send_message_w_type(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False message_str = "Hi I am Bob." @@ -90,7 +90,9 @@ async def test_send_message_w_type(): for chat_message_type in chat_message_types: async def mock_send(*_, **__): - return mock_response(status_code=201, json_payload={ + return mock_response( + status_code=201, + json_payload={ "id": message_id, "type": chat_message_type, "sequenceId": "3", @@ -102,26 +104,26 @@ async def mock_send(*_, **__): { "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b", "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" + "shareHistoryTime": "2020-10-30T10:50:50Z", } ], - "initiator": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + "initiator": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b", }, "senderDisplayName": "Bob", "createdOn": "2021-01-27T01:37:33Z", - "senderId": "8:acs:46849534-eb08-4ab7-bde7-c36928cd1547_00000007-e155-1f06-1db7-3a3a0d00004b" - }) + "senderId": "8:acs:46849534-eb08-4ab7-bde7-c36928cd1547_00000007-e155-1f06-1db7-3a3a0d00004b", + }, + ) chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) try: - content='hello world' - sender_display_name='sender name' + content = "hello world" + sender_display_name = "sender name" create_message_result = await chat_thread_client.send_message( - content, - chat_message_type=chat_message_type, - sender_display_name=sender_display_name) + content, chat_message_type=chat_message_type, sender_display_name=sender_display_name + ) create_message_result_id = create_message_result.id except: raised = True @@ -129,34 +131,43 @@ async def mock_send(*_, **__): assert raised == False assert create_message_result_id == message_id + @pytest.mark.asyncio async def test_send_message_w_invalid_type_throws_error(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False # the payload is irrelevant - it'll fail before async def mock_send(*_, **__): return mock_response(status_code=201, json_payload={"id": message_id}) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) create_message_result_id = None - chat_message_types = [ChatMessageType.PARTICIPANT_ADDED, ChatMessageType.PARTICIPANT_REMOVED, - ChatMessageType.TOPIC_UPDATED, "participant_added", "participant_removed", "topic_updated", - "ChatMessageType.TEXT", "ChatMessageType.HTML", - "ChatMessageType.PARTICIPANT_ADDED", "ChatMessageType.PARTICIPANT_REMOVED", - "ChatMessageType.TOPIC_UPDATED"] + chat_message_types = [ + ChatMessageType.PARTICIPANT_ADDED, + ChatMessageType.PARTICIPANT_REMOVED, + ChatMessageType.TOPIC_UPDATED, + "participant_added", + "participant_removed", + "topic_updated", + "ChatMessageType.TEXT", + "ChatMessageType.HTML", + "ChatMessageType.PARTICIPANT_ADDED", + "ChatMessageType.PARTICIPANT_REMOVED", + "ChatMessageType.TOPIC_UPDATED", + ] for chat_message_type in chat_message_types: try: - content='hello world' - sender_display_name='sender name' + content = "hello world" + sender_display_name = "sender name" create_message_result = await chat_thread_client.send_message( - content, - chat_message_type=chat_message_type, - sender_display_name=sender_display_name) + content, chat_message_type=chat_message_type, sender_display_name=sender_display_name + ) except: raised = True @@ -166,40 +177,54 @@ async def mock_send(*_, **__): @pytest.mark.asyncio async def test_get_message(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False message_str = "Hi I am Bob." async def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ - "id": message_id, - "type": "text", - "sequenceId": "3", - "version": message_id, - "content": { - "message": message_str, - "topic": "Lunch Chat thread", - "participants": [ - { - "communicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ], - "initiatorCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}} - }, - "senderDisplayName": "Bob", - "createdOn": "2021-01-27T01:37:33Z", - "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "deletedOn": "2021-01-27T01:37:33Z", - "editedOn": "2021-01-27T01:37:33Z", - "metadata": { - "tags": "tag" + return mock_response( + status_code=200, + json_payload={ + "id": message_id, + "type": "text", + "sequenceId": "3", + "version": message_id, + "content": { + "message": message_str, + "topic": "Lunch Chat thread", + "participants": [ + { + "communicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", } - }) + ], + "initiatorCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + }, + "senderDisplayName": "Bob", + "createdOn": "2021-01-27T01:37:33Z", + "senderCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "deletedOn": "2021-01-27T01:37:33Z", + "editedOn": "2021-01-27T01:37:33Z", + "metadata": {"tags": "tag"}, + }, + ) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) message = None @@ -215,14 +240,19 @@ async def mock_send(*_, **__): assert message.metadata["tags"] == "tag" assert len(message.content.participants) > 0 + @pytest.mark.asyncio async def test_list_messages(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False async def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={"value": [{ + return mock_response( + status_code=200, + json_payload={ + "value": [ + { "id": message_id, "type": "text", "sequenceId": "3", @@ -232,22 +262,38 @@ async def mock_send(*_, **__): "topic": "Lunch Chat thread", "participants": [ { - "communicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, + "communicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" + "shareHistoryTime": "2020-10-30T10:50:50Z", } ], - "initiatorCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}} + "initiatorCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, }, "senderDisplayName": "Bob", "createdOn": "2021-01-27T01:37:33Z", - "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, + "senderCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, "deletedOn": "2021-01-27T01:37:33Z", - "editedOn": "2021-01-27T01:37:33Z" - }]}) + "editedOn": "2021-01-27T01:37:33Z", + } + ] + }, + ) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) chat_messages = None @@ -272,67 +318,95 @@ async def test_list_messages_with_start_time(): raised = False async def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ - "value": [ - { - "id": "message_id_1", - "type": "text", - "sequenceId": "3", - "version": "message_id_1", - "content": { - "message": "message_str", - "topic": "Lunch Chat thread", - "participants": [ - { - "communicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ], - "initiatorCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}} + return mock_response( + status_code=200, + json_payload={ + "value": [ + { + "id": "message_id_1", + "type": "text", + "sequenceId": "3", + "version": "message_id_1", + "content": { + "message": "message_str", + "topic": "Lunch Chat thread", + "participants": [ + { + "communicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", + } + ], + "initiatorCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + }, + "senderDisplayName": "Bob", + "createdOn": "2021-01-27T01:37:33Z", + "senderCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "deletedOn": "2021-01-27T01:37:33Z", + "editedOn": "2021-01-27T01:37:33Z", }, - "senderDisplayName": "Bob", - "createdOn": "2021-01-27T01:37:33Z", - "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "deletedOn": "2021-01-27T01:37:33Z", - "editedOn": "2021-01-27T01:37:33Z" - }, - { - "id": "message_id_2", - "type": "text", - "sequenceId": "3", - "version": "message_id_2", - "content": { - "message": "message_str", - "topic": "Lunch Chat thread", - "participants": [ - { - "communicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ], - "initiatorCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}} + { + "id": "message_id_2", + "type": "text", + "sequenceId": "3", + "version": "message_id_2", + "content": { + "message": "message_str", + "topic": "Lunch Chat thread", + "participants": [ + { + "communicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", + } + ], + "initiatorCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + }, + "senderDisplayName": "Bob", + "createdOn": "2021-01-27T01:37:33Z", + "senderCommunicationIdentifier": { + "rawId": "string", + "communicationUser": { + "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b" + }, + }, + "deletedOn": "2021-01-27T01:37:33Z", + "editedOn": "2021-01-27T01:37:33Z", }, - "senderDisplayName": "Bob", - "createdOn": "2021-01-27T01:37:33Z", - "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": { - "id": "8:acs:8540c0de-899f-5cce-acb5-3ec493af3800_0e59221d-0c1d-46ae-9544-c963ce56c10b"}}, - "deletedOn": "2021-01-27T01:37:33Z", - "editedOn": "2021-01-27T01:37:33Z" - }]}) + ] + }, + ) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) chat_messages = None try: - chat_messages = chat_thread_client.list_messages( - start_time=datetime(2020, 8, 17, 18, 0, 0) - ) + chat_messages = chat_thread_client.list_messages(start_time=datetime(2020, 8, 17, 18, 0, 0)) except: raised = True @@ -344,14 +418,16 @@ async def mock_send(*_, **__): assert len(items) == 2 + @pytest.mark.asyncio async def test_update_message_content(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False async def mock_send(*_, **__): return mock_response(status_code=204) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) try: @@ -362,32 +438,36 @@ async def mock_send(*_, **__): assert raised == False + @pytest.mark.asyncio async def test_update_message_metadata(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False async def mock_send(*_, **__): return mock_response(status_code=204) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) try: - metadata={ "tags": "tag" } + metadata = {"tags": "tag"} await chat_thread_client.update_message(message_id, metadata=metadata) except: raised = True assert raised == False + @pytest.mark.asyncio async def test_delete_message(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id='1596823919339' + message_id = "1596823919339" raised = False async def mock_send(*_, **__): return mock_response(status_code=204) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) try: @@ -397,25 +477,30 @@ async def mock_send(*_, **__): assert raised == False + @pytest.mark.asyncio async def test_list_participants(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - participant_id="8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" + participant_id = "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" raised = False async def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={"value": [ - { - "communicationIdentifier": { - "rawId": participant_id, - "communicationUser": { - "id": participant_id + return mock_response( + status_code=200, + json_payload={ + "value": [ + { + "communicationIdentifier": { + "rawId": participant_id, + "communicationUser": {"id": participant_id}, + }, + "displayName": "Bob", + "shareHistoryTime": "2020-10-30T10:50:50Z", } - }, - "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ]}) + ] + }, + ) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) chat_thread_participants = None @@ -432,6 +517,7 @@ async def mock_send(*_, **__): assert len(items) == 1 + @pytest.mark.asyncio async def test_list_participants_with_results_per_page(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" @@ -440,29 +526,30 @@ async def test_list_participants_with_results_per_page(): raised = False async def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ + return mock_response( + status_code=200, + json_payload={ "value": [ { "communicationIdentifier": { "rawId": participant_id_1, - "communicationUser": { - "id": participant_id_1 - } + "communicationUser": {"id": participant_id_1}, }, "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" + "shareHistoryTime": "2020-10-30T10:50:50Z", }, { "communicationIdentifier": { "rawId": participant_id_2, - "communicationUser": { - "id": participant_id_2 - } + "communicationUser": {"id": participant_id_2}, }, "displayName": "Bob", - "shareHistoryTime": "2020-10-30T10:50:50Z" - } - ]}) + "shareHistoryTime": "2020-10-30T10:50:50Z", + }, + ] + }, + ) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) chat_thread_participants = None @@ -483,17 +570,19 @@ async def mock_send(*_, **__): @pytest.mark.asyncio async def test_add_participants(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - new_participant_id="8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" + new_participant_id = "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" raised = False async def mock_send(*_, **__): return mock_response(status_code=201) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) new_participant = ChatParticipant( - identifier=CommunicationUserIdentifier(new_participant_id), - display_name='name', - share_history_time=datetime.utcnow()) + identifier=CommunicationUserIdentifier(new_participant_id), + display_name="name", + share_history_time=datetime.utcnow(), + ) participants = [new_participant] try: @@ -503,30 +592,31 @@ async def mock_send(*_, **__): assert raised == False + @pytest.mark.asyncio async def test_add_participants_w_failed_participants_returns_nonempty_list(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - new_participant_id="8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" + new_participant_id = "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" raised = False error_message = "some error message" async def mock_send(*_, **__): - return mock_response(status_code=201, json_payload={ - "invalidParticipants": [ - { - "code": "string", - "message": error_message, - "target": new_participant_id, - "details": [] - } - ] - }) + return mock_response( + status_code=201, + json_payload={ + "invalidParticipants": [ + {"code": "string", "message": error_message, "target": new_participant_id, "details": []} + ] + }, + ) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) new_participant = ChatParticipant( - identifier=CommunicationUserIdentifier(new_participant_id), - display_name='name', - share_history_time=datetime.utcnow()) + identifier=CommunicationUserIdentifier(new_participant_id), + display_name="name", + share_history_time=datetime.utcnow(), + ) participants = [new_participant] try: @@ -540,19 +630,21 @@ async def mock_send(*_, **__): failed_participant = result[0][0] communication_error = result[0][1] - assert new_participant.identifier.properties['id'] == failed_participant.identifier.properties['id'] + assert new_participant.identifier.properties["id"] == failed_participant.identifier.properties["id"] assert new_participant.display_name == failed_participant.display_name assert new_participant.share_history_time == failed_participant.share_history_time assert error_message == communication_error.message + @pytest.mark.asyncio async def test_remove_participant(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - participant_id="8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" + participant_id = "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041" raised = False async def mock_send(*_, **__): return mock_response(status_code=204) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) try: @@ -562,6 +654,7 @@ async def mock_send(*_, **__): assert raised == False + @pytest.mark.asyncio async def test_send_typing_notification(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" @@ -569,6 +662,7 @@ async def test_send_typing_notification(): async def mock_send(*_, **__): return mock_response(status_code=200) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) try: @@ -578,6 +672,7 @@ async def mock_send(*_, **__): assert raised == False + @pytest.mark.asyncio async def test_send_typing_notification_with_sender_display_name(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" @@ -585,6 +680,7 @@ async def test_send_typing_notification_with_sender_display_name(): async def mock_send(*_, **__): return mock_response(status_code=200) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) try: @@ -594,14 +690,16 @@ async def mock_send(*_, **__): assert raised == False + @pytest.mark.asyncio async def test_send_read_receipt(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id="1596823919339" + message_id = "1596823919339" raised = False async def mock_send(*_, **__): return mock_response(status_code=200) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) try: @@ -611,24 +709,26 @@ async def mock_send(*_, **__): assert raised == False + @pytest.mark.asyncio async def test_list_read_receipts(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" - message_id="1596823919339" + message_id = "1596823919339" raised = False async def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={"value": [ - { - "chatMessageId": message_id, - "senderCommunicationIdentifier": { - "rawId": "string", - "communicationUser": { - "id": "string" + return mock_response( + status_code=200, + json_payload={ + "value": [ + { + "chatMessageId": message_id, + "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": {"id": "string"}}, } - } - } - ]}) + ] + }, + ) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) read_receipts = None @@ -645,6 +745,7 @@ async def mock_send(*_, **__): assert len(items) == 1 + @pytest.mark.asyncio async def test_list_read_receipts_with_results_per_page(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" @@ -653,27 +754,22 @@ async def test_list_read_receipts_with_results_per_page(): raised = False async def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ - "value": [ - { - "chatMessageId": message_id_1, - "senderCommunicationIdentifier": { - "rawId": "string", - "communicationUser": { - "id": "string" - } - } - }, - { - "chatMessageId": message_id_2, - "senderCommunicationIdentifier": { - "rawId": "string", - "communicationUser": { - "id": "string" - } - } - } - ]}) + return mock_response( + status_code=200, + json_payload={ + "value": [ + { + "chatMessageId": message_id_1, + "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": {"id": "string"}}, + }, + { + "chatMessageId": message_id_2, + "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": {"id": "string"}}, + }, + ] + }, + ) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) read_receipts = None @@ -690,6 +786,7 @@ async def mock_send(*_, **__): assert len(items) == 2 + @pytest.mark.asyncio async def test_list_read_receipts_with_results_per_page_and_skip(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" @@ -697,18 +794,18 @@ async def test_list_read_receipts_with_results_per_page_and_skip(): raised = False async def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ - "value": [ - { - "chatMessageId": message_id_1, - "senderCommunicationIdentifier": { - "rawId": "string", - "communicationUser": { - "id": "string" - } + return mock_response( + status_code=200, + json_payload={ + "value": [ + { + "chatMessageId": message_id_1, + "senderCommunicationIdentifier": {"rawId": "string", "communicationUser": {"id": "string"}}, } - } - ]}) + ] + }, + ) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) read_receipts = None @@ -725,19 +822,24 @@ async def mock_send(*_, **__): assert len(items) == 1 + @pytest.mark.asyncio async def test_get_properties(): thread_id = "19:bcaebfba0d314c2aa3e920d38fa3df08@thread.v2" raised = False async def mock_send(*_, **__): - return mock_response(status_code=200, json_payload={ + return mock_response( + status_code=200, + json_payload={ "id": thread_id, "topic": "Lunch Chat thread", "createdOn": "2020-10-30T10:50:50Z", "deletedOn": "2020-10-30T10:50:50Z", - "createdByCommunicationIdentifier": {"rawId": "string", "communicationUser": {"id": "string"}} - }) + "createdByCommunicationIdentifier": {"rawId": "string", "communicationUser": {"id": "string"}}, + }, + ) + chat_thread_client = ChatThreadClient("https://endpoint", credential, thread_id, transport=Mock(send=mock_send)) get_thread_result = None diff --git a/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_e2e.py b/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_e2e.py index d027c214d12f..be06be00e178 100644 --- a/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_e2e.py +++ b/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_e2e.py @@ -9,12 +9,7 @@ from devtools_testutils import AzureRecordedTestCase, is_live, recorded_by_proxy from azure.communication.identity import CommunicationIdentityClient -from azure.communication.chat import ( - ChatClient, - ChatParticipant, - ChatMessageType, - CommunicationTokenCredential -) +from azure.communication.chat import ChatClient, ChatParticipant, ChatMessageType, CommunicationTokenCredential from azure.communication.chat._shared.utils import parse_connection_str from chat_e2e_helper import get_connection_str @@ -41,14 +36,12 @@ def setup_method(self): # create ChatClient self.chat_client = ChatClient( - self.endpoint, - CommunicationTokenCredential(self.token), - http_logging_policy=get_http_logging_policy() + self.endpoint, CommunicationTokenCredential(self.token), http_logging_policy=get_http_logging_policy() ) self.chat_client_new_user = ChatClient( - self.endpoint, + self.endpoint, CommunicationTokenCredential(self.token_new_user), - http_logging_policy=get_http_logging_policy() + http_logging_policy=get_http_logging_policy(), ) def teardown_method(self): @@ -58,42 +51,26 @@ def teardown_method(self): self.identity_client.delete_user(self.user) self.identity_client.delete_user(self.new_user) - def _create_thread( - self, - **kwargs - ): + def _create_thread(self, **kwargs): # create chat thread, and ChatThreadClient topic = "test topic" share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) - participants = [ChatParticipant( - identifier=self.user, - display_name='name', - share_history_time=share_history_time - )] + participants = [ + ChatParticipant(identifier=self.user, display_name="name", share_history_time=share_history_time) + ] create_chat_thread_result = self.chat_client.create_chat_thread(topic, thread_participants=participants) self.chat_thread_client = self.chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id) self.thread_id = self.chat_thread_client.thread_id - def _create_thread_w_two_users( - self, - **kwargs - ): + def _create_thread_w_two_users(self, **kwargs): # create chat thread, and ChatThreadClient topic = "test topic" share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) participants = [ - ChatParticipant( - identifier=self.user, - display_name='name', - share_history_time=share_history_time - ), - ChatParticipant( - identifier=self.new_user, - display_name='name', - share_history_time=share_history_time - ) + ChatParticipant(identifier=self.user, display_name="name", share_history_time=share_history_time), + ChatParticipant(identifier=self.new_user, display_name="name", share_history_time=share_history_time), ] create_chat_thread_result = self.chat_client.create_chat_thread(topic, thread_participants=participants) self.chat_thread_client = self.chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id) @@ -101,11 +78,9 @@ def _create_thread_w_two_users( def _send_message(self): # send a message - content = 'hello world' - sender_display_name = 'sender name' - create_message_result = self.chat_thread_client.send_message( - content, - sender_display_name=sender_display_name) + content = "hello world" + sender_display_name = "sender name" + create_message_result = self.chat_thread_client.send_message(content, sender_display_name=sender_display_name) message_id = create_message_result.id return message_id @@ -121,12 +96,10 @@ def test_update_topic(self): def test_send_message(self): self._create_thread() - content = 'hello world' - sender_display_name = 'sender name' + content = "hello world" + sender_display_name = "sender name" - create_message_result = self.chat_thread_client.send_message( - content, - sender_display_name=sender_display_name) + create_message_result = self.chat_thread_client.send_message(content, sender_display_name=sender_display_name) create_message_result_id = create_message_result.id assert create_message_result_id is not None @@ -139,7 +112,7 @@ def test_get_message(self): message = self.chat_thread_client.get_message(message_id) assert message.id == message_id assert message.type == ChatMessageType.TEXT - assert message.content.message == 'hello world' + assert message.content.message == "hello world" @pytest.mark.live_test_only @recorded_by_proxy @@ -179,9 +152,8 @@ def test_list_participants(self): share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) new_participant = ChatParticipant( - identifier=self.new_user, - display_name='name', - share_history_time=share_history_time) + identifier=self.new_user, display_name="name", share_history_time=share_history_time + ) self.chat_thread_client.add_participants([new_participant]) @@ -194,10 +166,9 @@ def test_list_participants(self): li = list(chat_thread_participant_page) assert len(li) <= 1 participant_count += len(li) - li[0].identifier.properties['id'] = self.user.properties['id'] + li[0].identifier.properties["id"] = self.user.properties["id"] assert participant_count == 1 - @pytest.mark.live_test_only @recorded_by_proxy def test_add_participants(self): @@ -206,9 +177,8 @@ def test_add_participants(self): share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) new_participant = ChatParticipant( - identifier=self.new_user, - display_name='name', - share_history_time=share_history_time) + identifier=self.new_user, display_name="name", share_history_time=share_history_time + ) participants = [new_participant] failed_participants = self.chat_thread_client.add_participants(participants) @@ -216,7 +186,6 @@ def test_add_participants(self): # no error occured while adding participants assert len(failed_participants) == 0 - @pytest.mark.live_test_only @recorded_by_proxy def test_remove_participant(self): @@ -226,9 +195,8 @@ def test_remove_participant(self): share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) new_participant = ChatParticipant( - identifier=self.new_user, - display_name='name', - share_history_time=share_history_time) + identifier=self.new_user, display_name="name", share_history_time=share_history_time + ) participants = [new_participant] self.chat_thread_client.add_participants(participants) @@ -258,7 +226,6 @@ def test_send_read_receipt(self): self.chat_thread_client.send_read_receipt(message_id) - def _wait_on_thread(self, chat_client, thread_id, message_id): # print("Read Receipts Sent: ", read_receipts_sent) chat_thread_client = chat_client.get_chat_thread_client(thread_id) @@ -276,7 +243,6 @@ def _wait_on_thread(self, chat_client, thread_id, message_id): time.sleep(2) raise Exception("Read receipts not updated in 20 seconds. Failing.") - @pytest.mark.live_test_only @recorded_by_proxy def test_list_read_receipts(self): @@ -295,14 +261,16 @@ def test_list_read_receipts(self): chat_thread_client_new_user = self.chat_client_new_user.get_chat_thread_client(self.thread_id) # second user sends 1 message message_result_new_user = chat_thread_client_new_user.send_message( - "content", - sender_display_name="sender_display_name") + "content", sender_display_name="sender_display_name" + ) message_id_new_user = message_result_new_user.id # send read receipt chat_thread_client_new_user.send_read_receipt(message_id_new_user) if self.is_live: - self._wait_on_thread(chat_client=self.chat_client_new_user, thread_id=self.thread_id, message_id=message_id_new_user) + self._wait_on_thread( + chat_client=self.chat_client_new_user, thread_id=self.thread_id, message_id=message_id_new_user + ) # list read receipts read_receipts = self.chat_thread_client.list_read_receipts(results_per_page=2, skip=0) diff --git a/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_e2e_async.py b/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_e2e_async.py index 2c81e9d654cd..f510003b9a3a 100644 --- a/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_e2e_async.py +++ b/sdk/communication/azure-communication-chat/tests/test_chat_thread_client_e2e_async.py @@ -10,14 +10,8 @@ from devtools_testutils.aio import recorded_by_proxy_async from azure.communication.identity import CommunicationIdentityClient -from azure.communication.chat.aio import ( - ChatClient, - CommunicationTokenCredential -) -from azure.communication.chat import ( - ChatParticipant, - ChatMessageType -) +from azure.communication.chat.aio import ChatClient, CommunicationTokenCredential +from azure.communication.chat import ChatParticipant, ChatMessageType from azure.communication.chat._shared.utils import parse_connection_str from chat_e2e_helper import get_connection_str @@ -48,14 +42,12 @@ def setup_method(self): # create ChatClient self.chat_client = ChatClient( - self.endpoint, - CommunicationTokenCredential(self.token), - http_logging_policy=get_http_logging_policy() + self.endpoint, CommunicationTokenCredential(self.token), http_logging_policy=get_http_logging_policy() ) self.chat_client_new_user = ChatClient( - self.endpoint, - CommunicationTokenCredential(self.token_new_user), - http_logging_policy=get_http_logging_policy() + self.endpoint, + CommunicationTokenCredential(self.token_new_user), + http_logging_policy=get_http_logging_policy(), ) def teardown_method(self): @@ -69,11 +61,9 @@ async def _create_thread(self): topic = "test topic" share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) - participants = [ChatParticipant( - identifier=self.user, - display_name='name', - share_history_time=share_history_time - )] + participants = [ + ChatParticipant(identifier=self.user, display_name="name", share_history_time=share_history_time) + ] create_chat_thread_result = await self.chat_client.create_chat_thread(topic, thread_participants=participants) self.chat_thread_client = self.chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id) self.thread_id = self.chat_thread_client.thread_id @@ -84,29 +74,20 @@ async def _create_thread_w_two_users(self): share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) participants = [ - ChatParticipant( - identifier=self.user, - display_name='name', - share_history_time=share_history_time - ), - ChatParticipant( - identifier=self.new_user, - display_name='name', - share_history_time=share_history_time - ) + ChatParticipant(identifier=self.user, display_name="name", share_history_time=share_history_time), + ChatParticipant(identifier=self.new_user, display_name="name", share_history_time=share_history_time), ] create_chat_thread_result = await self.chat_client.create_chat_thread(topic, thread_participants=participants) self.chat_thread_client = self.chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id) self.thread_id = self.chat_thread_client.thread_id - async def _send_message(self): # send a message - content = 'hello world' - sender_display_name = 'sender name' + content = "hello world" + sender_display_name = "sender name" create_message_result = await self.chat_thread_client.send_message( - content, - sender_display_name=sender_display_name) + content, sender_display_name=sender_display_name + ) message_id = create_message_result.id return message_id @@ -133,12 +114,12 @@ async def test_send_message(self): await self._create_thread() async with self.chat_thread_client: - content = 'hello world' - sender_display_name = 'sender name' + content = "hello world" + sender_display_name = "sender name" create_message_result = await self.chat_thread_client.send_message( - content, - sender_display_name=sender_display_name) + content, sender_display_name=sender_display_name + ) create_message_result_id = create_message_result.id assert create_message_result_id @@ -159,7 +140,7 @@ async def test_get_message(self): message = await self.chat_thread_client.get_message(message_id) assert message.id == message_id assert message.type == ChatMessageType.TEXT - assert message.content.message == 'hello world' + assert message.content.message == "hello world" # delete chat threads if not self.is_playback(): @@ -232,9 +213,8 @@ async def test_list_participants(self): share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) new_participant = ChatParticipant( - identifier=self.new_user, - display_name='name', - share_history_time=share_history_time) + identifier=self.new_user, display_name="name", share_history_time=share_history_time + ) await self.chat_thread_client.add_participants([new_participant]) @@ -261,9 +241,8 @@ async def test_add_participants(self): share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) new_participant = ChatParticipant( - identifier=self.new_user, - display_name='name', - share_history_time=share_history_time) + identifier=self.new_user, display_name="name", share_history_time=share_history_time + ) participants = [new_participant] failed_participants = await self.chat_thread_client.add_participants(participants) @@ -286,9 +265,8 @@ async def test_remove_participant(self): share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=timezone.utc) new_participant = ChatParticipant( - identifier=self.new_user, - display_name='name', - share_history_time=share_history_time) + identifier=self.new_user, display_name="name", share_history_time=share_history_time + ) participants = [new_participant] await self.chat_thread_client.add_participants(participants) @@ -372,23 +350,25 @@ async def test_list_read_receipts(self): await self.chat_thread_client.send_read_receipt(message_id) if self.is_live: - await self._wait_on_thread(chat_client=self.chat_client, thread_id=self.thread_id, message_id=message_id) - - + await self._wait_on_thread( + chat_client=self.chat_client, thread_id=self.thread_id, message_id=message_id + ) # get chat thread client for second user chat_thread_client_new_user = self.chat_client_new_user.get_chat_thread_client(self.thread_id) # second user sends 1 message message_result_new_user = await chat_thread_client_new_user.send_message( - "content", - sender_display_name="sender_display_name") + "content", sender_display_name="sender_display_name" + ) message_id_new_user = message_result_new_user.id # send read receipt await chat_thread_client_new_user.send_read_receipt(message_id_new_user) if self.is_live: - await self._wait_on_thread(chat_client=self.chat_client_new_user, thread_id=self.thread_id, message_id=message_id_new_user) + await self._wait_on_thread( + chat_client=self.chat_client_new_user, thread_id=self.thread_id, message_id=message_id_new_user + ) # list read receipts read_receipts = self.chat_thread_client.list_read_receipts(results_per_page=2, skip=0) diff --git a/sdk/communication/azure-communication-chat/tests/test_communication_identifier_serializer.py b/sdk/communication/azure-communication-chat/tests/test_communication_identifier_serializer.py index a78fadf7c78f..77175c1a4f2d 100644 --- a/sdk/communication/azure-communication-chat/tests/test_communication_identifier_serializer.py +++ b/sdk/communication/azure-communication-chat/tests/test_communication_identifier_serializer.py @@ -5,63 +5,52 @@ # ------------------------------------------------------------------------- import unittest from azure.communication.chat._communication_identifier_serializer import serialize_identifier, deserialize_identifier -from azure.communication.chat._generated.models import( +from azure.communication.chat._generated.models import ( CommunicationIdentifierModel, MicrosoftTeamsUserIdentifierModel, CommunicationUserIdentifierModel, - PhoneNumberIdentifierModel + PhoneNumberIdentifierModel, ) -from azure.communication.chat._shared.models import( +from azure.communication.chat._shared.models import ( CommunicationUserIdentifier, CommunicationCloudEnvironment, UnknownIdentifier, PhoneNumberIdentifier, - MicrosoftTeamsUserIdentifier + MicrosoftTeamsUserIdentifier, ) + class CommunicationUserIdentifierSerializerTest(unittest.TestCase): def setUp(self): - self.testPhoneNumber="+12223334444" + self.testPhoneNumber = "+12223334444" self.testUserModel = CommunicationUserIdentifierModel(id="User Id") self.testPhoneNumberModel = PhoneNumberIdentifierModel(value=self.testPhoneNumber) - self.testTeamsUserModel = MicrosoftTeamsUserIdentifierModel(user_id="Microsoft Teams User Id", - is_anonymous=True, - cloud=CommunicationCloudEnvironment.PUBLIC) - + self.testTeamsUserModel = MicrosoftTeamsUserIdentifierModel( + user_id="Microsoft Teams User Id", is_anonymous=True, cloud=CommunicationCloudEnvironment.PUBLIC + ) def test_serialize_communication_user(self): - communication_identifier_model = serialize_identifier( - CommunicationUserIdentifier("an id") - ) + communication_identifier_model = serialize_identifier(CommunicationUserIdentifier("an id")) - assert communication_identifier_model['communication_user']['id'] is "an id" + assert communication_identifier_model["communication_user"]["id"] is "an id" def test_deserialize_communication_user(self): communication_identifier_actual = deserialize_identifier( - CommunicationIdentifierModel( - raw_id="an id", - communication_user=self.testUserModel - ) + CommunicationIdentifierModel(raw_id="an id", communication_user=self.testUserModel) ) communication_identifier_expected = CommunicationUserIdentifier("an id") assert isinstance(communication_identifier_actual, CommunicationUserIdentifier) - assert communication_identifier_actual.properties['id'] == communication_identifier_expected.properties['id'] + assert communication_identifier_actual.properties["id"] == communication_identifier_expected.properties["id"] def test_serialize_unknown_identifier(self): - unknown_identifier_model = serialize_identifier( - UnknownIdentifier("an id") - ) + unknown_identifier_model = serialize_identifier(UnknownIdentifier("an id")) - assert unknown_identifier_model['raw_id'] is "an id" + assert unknown_identifier_model["raw_id"] is "an id" def test_deserialize_unknown_identifier(self): - unknown_identifier_actual = deserialize_identifier( - CommunicationIdentifierModel( - raw_id="an id" - ) - ) + unknown_identifier_actual = deserialize_identifier(CommunicationIdentifierModel(raw_id="an id")) unknown_identifier_expected = UnknownIdentifier("an id") @@ -69,66 +58,59 @@ def test_deserialize_unknown_identifier(self): assert unknown_identifier_actual.raw_id == unknown_identifier_expected.raw_id def test_serialize_phone_number(self): - phone_number_identifier_model = serialize_identifier( - PhoneNumberIdentifier("phonenumber") - ) + phone_number_identifier_model = serialize_identifier(PhoneNumberIdentifier("phonenumber")) - assert phone_number_identifier_model['phone_number']['value'] is "phonenumber" + assert phone_number_identifier_model["phone_number"]["value"] is "phonenumber" def test_deserialize_phone_number(self): phone_number_identifier_actual = deserialize_identifier( - CommunicationIdentifierModel( - raw_id="someid", - phone_number=self.testPhoneNumberModel - ) + CommunicationIdentifierModel(raw_id="someid", phone_number=self.testPhoneNumberModel) ) phone_number_identifier_expected = PhoneNumberIdentifier(self.testPhoneNumber, raw_id="someid") assert isinstance(phone_number_identifier_actual, PhoneNumberIdentifier) - assert phone_number_identifier_actual.properties['value'] == phone_number_identifier_expected.properties['value'] + assert ( + phone_number_identifier_actual.properties["value"] == phone_number_identifier_expected.properties["value"] + ) assert phone_number_identifier_actual.raw_id == phone_number_identifier_expected.raw_id def test_serialize_teams_user(self): teams_user_identifier_model = serialize_identifier( - MicrosoftTeamsUserIdentifier( - user_id="teamsid", - cloud=CommunicationCloudEnvironment.PUBLIC, - raw_id="someid" - ) + MicrosoftTeamsUserIdentifier(user_id="teamsid", cloud=CommunicationCloudEnvironment.PUBLIC, raw_id="someid") ) - assert teams_user_identifier_model['microsoft_teams_user']['user_id'] is "teamsid" - assert teams_user_identifier_model['microsoft_teams_user']['cloud'] is CommunicationCloudEnvironment.PUBLIC - assert teams_user_identifier_model['raw_id'] is "someid" + assert teams_user_identifier_model["microsoft_teams_user"]["user_id"] is "teamsid" + assert teams_user_identifier_model["microsoft_teams_user"]["cloud"] is CommunicationCloudEnvironment.PUBLIC + assert teams_user_identifier_model["raw_id"] is "someid" def test_deserialize_teams_user(self): teams_user_identifier_actual = deserialize_identifier( - CommunicationIdentifierModel( - raw_id="someid", - microsoft_teams_user=self.testTeamsUserModel - ) + CommunicationIdentifierModel(raw_id="someid", microsoft_teams_user=self.testTeamsUserModel) ) teams_user_identifier_expected = MicrosoftTeamsUserIdentifier( raw_id="someid", user_id="Microsoft Teams User Id", cloud=CommunicationCloudEnvironment.PUBLIC, - is_anonymous=True + is_anonymous=True, ) assert isinstance(teams_user_identifier_actual, MicrosoftTeamsUserIdentifier) assert teams_user_identifier_actual.raw_id == teams_user_identifier_expected.raw_id - assert teams_user_identifier_actual.properties['user_id'] == teams_user_identifier_expected.properties['user_id'] - assert teams_user_identifier_actual.properties['is_anonymous'] == teams_user_identifier_expected.properties['is_anonymous'] - assert teams_user_identifier_actual.properties['cloud'] == teams_user_identifier_expected.properties['cloud'] + assert ( + teams_user_identifier_actual.properties["user_id"] == teams_user_identifier_expected.properties["user_id"] + ) + assert ( + teams_user_identifier_actual.properties["is_anonymous"] + == teams_user_identifier_expected.properties["is_anonymous"] + ) + assert teams_user_identifier_actual.properties["cloud"] == teams_user_identifier_expected.properties["cloud"] def test_serialize_foreign_throws(self): foreign_obj = "Foreign object" - self.assertRaises( - TypeError, - lambda : serialize_identifier(foreign_obj) - ) + self.assertRaises(TypeError, lambda: serialize_identifier(foreign_obj)) + if __name__ == "__main__": - unittest.main() \ No newline at end of file + unittest.main() diff --git a/sdk/communication/azure-communication-chat/tests/unittest_helpers.py b/sdk/communication/azure-communication-chat/tests/unittest_helpers.py index 45142b807611..3bc29f4ede4b 100644 --- a/sdk/communication/azure-communication-chat/tests/unittest_helpers.py +++ b/sdk/communication/azure-communication-chat/tests/unittest_helpers.py @@ -18,4 +18,4 @@ def mock_response(status_code=200, headers=None, json_payload=None): response.text = lambda encoding=None: "" response.headers["content-type"] = "text/plain" response.content_type = "text/plain" - return response \ No newline at end of file + return response diff --git a/sdk/communication/azure-communication-email/azure/communication/email/__init__.py b/sdk/communication/azure-communication-email/azure/communication/email/__init__.py index b6ecdc17c2cb..6916c6bfc57c 100644 --- a/sdk/communication/azure-communication-email/azure/communication/email/__init__.py +++ b/sdk/communication/azure-communication-email/azure/communication/email/__init__.py @@ -6,4 +6,4 @@ from ._email_client import EmailClient -__all__ = ['EmailClient'] +__all__ = ["EmailClient"] diff --git a/sdk/communication/azure-communication-email/azure/communication/email/_email_client.py b/sdk/communication/azure-communication-email/azure/communication/email/_email_client.py index 65e5a10d1f3e..c54ed6c368c2 100644 --- a/sdk/communication/azure-communication-email/azure/communication/email/_email_client.py +++ b/sdk/communication/azure-communication-email/azure/communication/email/_email_client.py @@ -37,17 +37,13 @@ class EmailClient(object): Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - endpoint: str, - credential: Union[TokenCredential, AzureKeyCredential], - **kwargs - ) -> None: + + def __init__(self, endpoint: str, credential: Union[TokenCredential, AzureKeyCredential], **kwargs) -> None: try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError: - raise ValueError("Account URL must be a string.") # pylint: disable=raise-missing-from + raise ValueError("Account URL must be a string.") # pylint: disable=raise-missing-from if endpoint.endswith("/"): endpoint = endpoint[:-1] @@ -57,18 +53,11 @@ def __init__( authentication_policy = get_authentication_policy(endpoint, credential) self._generated_client = AzureCommunicationEmailService( - endpoint, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - **kwargs + endpoint, authentication_policy=authentication_policy, sdk_moniker=SDK_MONIKER, **kwargs ) @classmethod - def from_connection_string( - cls, - conn_str: str, - **kwargs - ) -> 'EmailClient': + def from_connection_string(cls, conn_str: str, **kwargs) -> "EmailClient": """Create EmailClient from a Connection String. :param str conn_str: @@ -81,11 +70,7 @@ def from_connection_string( return cls(endpoint, AzureKeyCredential(access_key), **kwargs) @distributed_trace - def begin_send( - self, - message: Union[JSON, IO], - **kwargs: Any - ) -> LROPoller[JSON]: + def begin_send(self, message: Union[JSON, IO], **kwargs: Any) -> LROPoller[JSON]: # cSpell:disable """Queues an email message to be sent to one or more recipients. diff --git a/sdk/communication/azure-communication-email/azure/communication/email/_shared/auth_policy_utils.py b/sdk/communication/azure-communication-email/azure/communication/email/_shared/auth_policy_utils.py index d3bc1bfda04f..a771dd2fd42f 100644 --- a/sdk/communication/azure-communication-email/azure/communication/email/_shared/auth_policy_utils.py +++ b/sdk/communication/azure-communication-email/azure/communication/email/_shared/auth_policy_utils.py @@ -43,9 +43,7 @@ def get_authentication_policy( return AsyncBearerTokenCredentialPolicy( credential, "https://communication.azure.com//.default" # type: ignore ) - return BearerTokenCredentialPolicy( - credential, "https://communication.azure.com//.default" # type: ignore - ) + return BearerTokenCredentialPolicy(credential, "https://communication.azure.com//.default") # type: ignore if isinstance(credential, (AzureKeyCredential, str)): return HMACCredentialsPolicy(endpoint, credential, decode_url=decode_url) diff --git a/sdk/communication/azure-communication-email/azure/communication/email/_shared/models.py b/sdk/communication/azure-communication-email/azure/communication/email/_shared/models.py index 7b646472045c..43875e1197e5 100644 --- a/sdk/communication/azure-communication-email/azure/communication/email/_shared/models.py +++ b/sdk/communication/azure-communication-email/azure/communication/email/_shared/models.py @@ -14,8 +14,11 @@ class DeprecatedEnumMeta(CaseInsensitiveEnumMeta): def __getattribute__(cls, item): if item.upper() == "MICROSOFT_BOT": - warnings.warn("MICROSOFT_BOT is deprecated and has been replaced by \ - MICROSOFT_TEAMS_APP identifier.", DeprecationWarning) + warnings.warn( + "MICROSOFT_BOT is deprecated and has been replaced by \ + MICROSOFT_TEAMS_APP identifier.", + DeprecationWarning, + ) item = "MICROSOFT_TEAMS_APP" return super().__getattribute__(item) @@ -47,14 +50,17 @@ class CommunicationCloudEnvironment(str, Enum, metaclass=CaseInsensitiveEnumMeta @runtime_checkable class CommunicationIdentifier(Protocol): """Communication Identifier.""" + @property def raw_id(self) -> str: """The raw ID of the identifier.""" ... + @property def kind(self) -> CommunicationIdentifierKind: """The type of identifier.""" ... + @property def properties(self) -> Mapping[str, Any]: """The properties of the identifier.""" @@ -83,12 +89,14 @@ def properties(self) -> Mapping[str, Any]: class CommunicationUserProperties(TypedDict): """Dictionary of properties for a CommunicationUserIdentifier.""" + id: str """ID of the Communication user as returned from Azure Communication Identity.""" class CommunicationUserIdentifier: """Represents a user in Azure Communication Service.""" + kind: Literal[CommunicationIdentifierKind.COMMUNICATION_USER] = CommunicationIdentifierKind.COMMUNICATION_USER """The type of identifier.""" properties: CommunicationUserProperties @@ -116,12 +124,14 @@ def __eq__(self, other): class PhoneNumberProperties(TypedDict): """Dictionary of properties for a PhoneNumberIdentifier.""" + value: str """The phone number in E.164 format.""" class PhoneNumberIdentifier: """Represents a phone number.""" + kind: Literal[CommunicationIdentifierKind.PHONE_NUMBER] = CommunicationIdentifierKind.PHONE_NUMBER """The type of identifier.""" properties: PhoneNumberProperties @@ -165,6 +175,7 @@ class UnknownIdentifier: It is not advisable to rely on the `kind` property with a value `unknown`, as it could become a new or existing distinct type in the future. """ + kind: Literal[CommunicationIdentifierKind.UNKNOWN] = CommunicationIdentifierKind.UNKNOWN """The type of identifier.""" properties: Mapping[str, Any] @@ -188,6 +199,7 @@ def __eq__(self, other): class MicrosoftTeamsUserProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsUserIdentifier.""" + user_id: str """The id of the Microsoft Teams user. If the user isn't anonymous, the id is the AAD object id of the user.""" is_anonymous: bool @@ -198,6 +210,7 @@ class MicrosoftTeamsUserProperties(TypedDict): class MicrosoftTeamsUserIdentifier: """Represents an identifier for a Microsoft Teams user.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_USER] = CommunicationIdentifierKind.MICROSOFT_TEAMS_USER """The type of identifier.""" properties: MicrosoftTeamsUserProperties @@ -246,6 +259,7 @@ def _format_raw_id(self, properties: MicrosoftTeamsUserProperties) -> str: class MicrosoftTeamsAppProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsAppIdentifier.""" + app_id: str """The id of the Microsoft Teams application.""" cloud: Union[CommunicationCloudEnvironment, str] @@ -254,6 +268,7 @@ class MicrosoftTeamsAppProperties(TypedDict): class _botbackcompatdict(dict): """Backwards compatible properties.""" + def __getitem__(self, __key: Any) -> Any: try: return super().__getitem__(__key) @@ -267,6 +282,7 @@ def __getitem__(self, __key: Any) -> Any: class MicrosoftTeamsAppIdentifier: """Represents an identifier for a Microsoft Teams application.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_APP] = CommunicationIdentifierKind.MICROSOFT_TEAMS_APP """The type of identifier.""" properties: MicrosoftTeamsAppProperties @@ -282,10 +298,13 @@ def __init__(self, app_id: str, **kwargs: Any) -> None: :keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed from the other properties. """ - self.properties = cast(MicrosoftTeamsAppProperties, _botbackcompatdict( - app_id=app_id, - cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, - )) + self.properties = cast( + MicrosoftTeamsAppProperties, + _botbackcompatdict( + app_id=app_id, + cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, + ), + ) raw_id: Optional[str] = kwargs.get("raw_id") self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties) @@ -323,7 +342,7 @@ def __init__(self, bot_id, **kwargs): """ warnings.warn( "The MicrosoftBotIdentifier is deprecated and has been replaced by MicrosoftTeamsAppIdentifier.", - DeprecationWarning + DeprecationWarning, ) super().__init__(bot_id, **kwargs) @@ -339,9 +358,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d :rtype: CommunicationIdentifier """ if raw_id.startswith(PHONE_NUMBER_PREFIX): - return PhoneNumberIdentifier( - value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id - ) + return PhoneNumberIdentifier(value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id) segments = raw_id.split(":", maxsplit=2) if len(segments) < 3: @@ -350,9 +367,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d prefix = f"{segments[0]}:{segments[1]}:" suffix = segments[2] if prefix == TEAMS_USER_ANONYMOUS_PREFIX: - return MicrosoftTeamsUserIdentifier( - user_id=suffix, is_anonymous=True, raw_id=raw_id - ) + return MicrosoftTeamsUserIdentifier(user_id=suffix, is_anonymous=True, raw_id=raw_id) if prefix == TEAMS_USER_PUBLIC_CLOUD_PREFIX: return MicrosoftTeamsUserIdentifier( user_id=suffix, diff --git a/sdk/communication/azure-communication-email/azure/communication/email/_shared/policy.py b/sdk/communication/azure-communication-email/azure/communication/email/_shared/policy.py index 2fd2e7426c73..79aa48136fd3 100644 --- a/sdk/communication/azure-communication-email/azure/communication/email/_shared/policy.py +++ b/sdk/communication/azure-communication-email/azure/communication/email/_shared/policy.py @@ -50,9 +50,7 @@ def _compute_hmac( else: decoded_secret = base64.b64decode(self._access_key) - digest = hmac.new( - decoded_secret, value.encode("utf-8"), hashlib.sha256 - ).digest() + digest = hmac.new(decoded_secret, value.encode("utf-8"), hashlib.sha256).digest() return base64.b64encode(digest).decode("utf-8") @@ -101,22 +99,10 @@ def _sign_request(self, request): utc_now = get_current_utc_time() if request.http_request.body is None: request.http_request.body = "" - content_digest = hashlib.sha256( - (request.http_request.body.encode("utf-8")) - ).digest() + content_digest = hashlib.sha256((request.http_request.body.encode("utf-8"))).digest() content_hash = base64.b64encode(content_digest).decode("utf-8") - string_to_sign = ( - verb - + "\n" - + query_url - + "\n" - + utc_now - + ";" - + self._host - + ";" - + content_hash - ) + string_to_sign = verb + "\n" + query_url + "\n" + utc_now + ";" + self._host + ";" + content_hash signature = self._compute_hmac(string_to_sign) @@ -124,10 +110,7 @@ def _sign_request(self, request): "x-ms-date": utc_now, "x-ms-content-sha256": content_hash, "x-ms-return-client-request-id": "true", - "Authorization": "HMAC-SHA256 SignedHeaders=" - + signed_headers - + "&Signature=" - + signature, + "Authorization": "HMAC-SHA256 SignedHeaders=" + signed_headers + "&Signature=" + signature, } request.http_request.headers.update(signature_header) diff --git a/sdk/communication/azure-communication-email/azure/communication/email/_shared/user_credential.py b/sdk/communication/azure-communication-email/azure/communication/email/_shared/user_credential.py index c7c150052918..54603e7b32ce 100644 --- a/sdk/communication/azure-communication-email/azure/communication/email/_shared/user_credential.py +++ b/sdk/communication/azure-communication-email/azure/communication/email/_shared/user_credential.py @@ -38,9 +38,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._lock = Condition(Lock()) self._some_thread_refreshing = False @@ -54,9 +52,7 @@ def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -80,9 +76,7 @@ def _update_token_and_reschedule(self): try: new_token = self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -109,12 +103,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() if timespan <= TIMEOUT_MAX: self._timer = Timer(timespan, self._update_token_and_reschedule) self._timer.daemon = True diff --git a/sdk/communication/azure-communication-email/azure/communication/email/_shared/user_credential_async.py b/sdk/communication/azure-communication-email/azure/communication/email/_shared/user_credential_async.py index dcd934aba464..15ad17da1a8c 100644 --- a/sdk/communication/azure-communication-email/azure/communication/email/_shared/user_credential_async.py +++ b/sdk/communication/azure-communication-email/azure/communication/email/_shared/user_credential_async.py @@ -40,9 +40,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._async_mutex = Lock() if sys.version_info[:3] == (3, 10, 0): @@ -60,9 +58,7 @@ async def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -86,9 +82,7 @@ async def _update_token_and_reschedule(self): try: new_token = await self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") async with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -115,12 +109,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() self._timer = AsyncTimer(timespan, self._update_token_and_reschedule) self._timer.start() diff --git a/sdk/communication/azure-communication-email/azure/communication/email/_shared/utils.py b/sdk/communication/azure-communication-email/azure/communication/email/_shared/utils.py index 47da8a283e5f..8576c31ddc56 100644 --- a/sdk/communication/azure-communication-email/azure/communication/email/_shared/utils.py +++ b/sdk/communication/azure-communication-email/azure/communication/email/_shared/utils.py @@ -87,9 +87,7 @@ def create_access_token(token): payload = json.loads(padded_base64_payload) return AccessToken( token, - _convert_datetime_to_utc_int( - datetime.fromtimestamp(payload["exp"], TZ_UTC) - ), + _convert_datetime_to_utc_int(datetime.fromtimestamp(payload["exp"], TZ_UTC)), ) except ValueError as val_error: raise ValueError(token_parse_err_msg) from val_error diff --git a/sdk/communication/azure-communication-email/azure/communication/email/aio/__init__.py b/sdk/communication/azure-communication-email/azure/communication/email/aio/__init__.py index aa02483033ff..a74f3c131fb1 100644 --- a/sdk/communication/azure-communication-email/azure/communication/email/aio/__init__.py +++ b/sdk/communication/azure-communication-email/azure/communication/email/aio/__init__.py @@ -1,5 +1,5 @@ from ._email_client_async import EmailClient __all__ = [ - 'EmailClient', + "EmailClient", ] diff --git a/sdk/communication/azure-communication-email/azure/communication/email/aio/_email_client_async.py b/sdk/communication/azure-communication-email/azure/communication/email/aio/_email_client_async.py index 90fcddb4fb4a..5e287c1840b4 100644 --- a/sdk/communication/azure-communication-email/azure/communication/email/aio/_email_client_async.py +++ b/sdk/communication/azure-communication-email/azure/communication/email/aio/_email_client_async.py @@ -22,7 +22,8 @@ from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class EmailClient(object): # pylint: disable=client-accepts-api-version-keyword + +class EmailClient(object): # pylint: disable=client-accepts-api-version-keyword """A client to interact with the AzureCommunicationService Email gateway asynchronously. This client provides operations to send an email and monitor its status. @@ -36,17 +37,13 @@ class EmailClient(object): # pylint: disable=client-accepts-api-version-keyword Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - endpoint: str, - credential: Union[AsyncTokenCredential, AzureKeyCredential], - **kwargs - ) -> None: + + def __init__(self, endpoint: str, credential: Union[AsyncTokenCredential, AzureKeyCredential], **kwargs) -> None: try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError: - raise ValueError("Account URL must be a string.") # pylint: disable=raise-missing-from + raise ValueError("Account URL must be a string.") # pylint: disable=raise-missing-from if endpoint.endswith("/"): endpoint = endpoint[:-1] @@ -56,18 +53,11 @@ def __init__( authentication_policy = get_authentication_policy(endpoint, credential, decode_url=True, is_async=True) self._generated_client = AzureCommunicationEmailService( - endpoint, - authentication_policy=authentication_policy, - sdk_moniker=SDK_MONIKER, - **kwargs + endpoint, authentication_policy=authentication_policy, sdk_moniker=SDK_MONIKER, **kwargs ) @classmethod - def from_connection_string( - cls, - conn_str: str, - **kwargs - ) -> 'EmailClient': + def from_connection_string(cls, conn_str: str, **kwargs) -> "EmailClient": """Create EmailClient from a Connection String. :param str conn_str: @@ -80,11 +70,7 @@ def from_connection_string( return cls(endpoint, AzureKeyCredential(access_key), **kwargs) @distributed_trace_async - async def begin_send( - self, - message: Union[JSON, IO], - **kwargs: Any - ) -> AsyncLROPoller[JSON]: + async def begin_send(self, message: Union[JSON, IO], **kwargs: Any) -> AsyncLROPoller[JSON]: # cSpell:disable """Queues an email message to be sent to one or more recipients. diff --git a/sdk/communication/azure-communication-email/samples/send_email_to_multiple_recipients_sample.py b/sdk/communication/azure-communication-email/samples/send_email_to_multiple_recipients_sample.py index 4009aaf0f805..283063d82ecc 100644 --- a/sdk/communication/azure-communication-email/samples/send_email_to_multiple_recipients_sample.py +++ b/sdk/communication/azure-communication-email/samples/send_email_to_multiple_recipients_sample.py @@ -27,6 +27,7 @@ sys.path.append("..") + class EmailMultipleRecipientSample(object): connection_string = os.getenv("COMMUNICATION_CONNECTION_STRING_EMAIL") @@ -43,34 +44,35 @@ def send_email_to_multiple_recipients(self): "content": { "subject": "This is the subject", "plainText": "This is the body", - "html": "html>

This is the body

" + "html": "html>

This is the body

", }, "recipients": { "to": [ {"address": self.recipient_address, "displayName": "Customer Name"}, - {"address": self.second_recipient_address, "displayName": "Customer Name 2"} + {"address": self.second_recipient_address, "displayName": "Customer Name 2"}, ], "cc": [ {"address": self.recipient_address, "displayName": "Customer Name"}, - {"address": self.second_recipient_address, "displayName": "Customer Name 2"} + {"address": self.second_recipient_address, "displayName": "Customer Name 2"}, ], "bcc": [ {"address": self.recipient_address, "displayName": "Customer Name"}, - {"address": self.second_recipient_address, "displayName": "Customer Name 2"} - ] + {"address": self.second_recipient_address, "displayName": "Customer Name 2"}, + ], }, - "senderAddress": self.sender_address + "senderAddress": self.sender_address, } try: # sending the email message poller = email_client.begin_send(message) response = poller.result() - print("Operation ID: " + response['id']) + print("Operation ID: " + response["id"]) except HttpResponseError as ex: print(ex) pass -if __name__ == '__main__': + +if __name__ == "__main__": sample = EmailMultipleRecipientSample() sample.send_email_to_multiple_recipients() diff --git a/sdk/communication/azure-communication-email/samples/send_email_to_multiple_recipients_sample_async.py b/sdk/communication/azure-communication-email/samples/send_email_to_multiple_recipients_sample_async.py index c8f4a5e4d8d2..432b8d40aa40 100644 --- a/sdk/communication/azure-communication-email/samples/send_email_to_multiple_recipients_sample_async.py +++ b/sdk/communication/azure-communication-email/samples/send_email_to_multiple_recipients_sample_async.py @@ -28,6 +28,7 @@ sys.path.append("..") + class EmailMultipleRecipientSampleAsync(object): connection_string = os.getenv("COMMUNICATION_CONNECTION_STRING_EMAIL") @@ -44,23 +45,23 @@ async def send_email_to_multiple_recipients_async(self): "content": { "subject": "This is the subject", "plainText": "This is the body", - "html": "html>

This is the body

" + "html": "html>

This is the body

", }, "recipients": { "to": [ {"address": self.recipient_address, "displayName": "Customer Name"}, - {"address": self.second_recipient_address, "displayName": "Customer Name 2"} + {"address": self.second_recipient_address, "displayName": "Customer Name 2"}, ], "cc": [ {"address": self.recipient_address, "displayName": "Customer Name"}, - {"address": self.second_recipient_address, "displayName": "Customer Name 2"} + {"address": self.second_recipient_address, "displayName": "Customer Name 2"}, ], "bcc": [ {"address": self.recipient_address, "displayName": "Customer Name"}, - {"address": self.second_recipient_address, "displayName": "Customer Name 2"} - ] + {"address": self.second_recipient_address, "displayName": "Customer Name 2"}, + ], }, - "senderAddress": self.sender_address + "senderAddress": self.sender_address, } async with email_client: @@ -68,11 +69,12 @@ async def send_email_to_multiple_recipients_async(self): # sending the email message poller = await email_client.begin_send(message) response = await poller.result() - print("Operation ID: " + response['id']) + print("Operation ID: " + response["id"]) except HttpResponseError as ex: print(ex) pass -if __name__ == '__main__': + +if __name__ == "__main__": sample = EmailMultipleRecipientSampleAsync() asyncio.run(sample.send_email_to_multiple_recipients_async()) diff --git a/sdk/communication/azure-communication-email/samples/send_email_to_single_recipient_sample.py b/sdk/communication/azure-communication-email/samples/send_email_to_single_recipient_sample.py index 6b3b6936a64f..a668e3db6941 100644 --- a/sdk/communication/azure-communication-email/samples/send_email_to_single_recipient_sample.py +++ b/sdk/communication/azure-communication-email/samples/send_email_to_single_recipient_sample.py @@ -26,12 +26,13 @@ sys.path.append("..") + class EmailSingleRecipientSample(object): connection_string = os.getenv("COMMUNICATION_CONNECTION_STRING_EMAIL") sender_address = os.getenv("SENDER_ADDRESS") recipient_address = os.getenv("RECIPIENT_ADDRESS") - + def send_email_to_single_recipient(self): # creating the email client email_client = EmailClient.from_connection_string(self.connection_string) @@ -41,28 +42,22 @@ def send_email_to_single_recipient(self): "content": { "subject": "This is the subject", "plainText": "This is the body", - "html": "

This is the body

" + "html": "

This is the body

", }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] - }, - "senderAddress": self.sender_address + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, + "senderAddress": self.sender_address, } try: # sending the email message poller = email_client.begin_send(message) response = poller.result() - print("Operation ID: " + response['id']) + print("Operation ID: " + response["id"]) except HttpResponseError as ex: print(ex) pass -if __name__ == '__main__': + +if __name__ == "__main__": sample = EmailSingleRecipientSample() sample.send_email_to_single_recipient() diff --git a/sdk/communication/azure-communication-email/samples/send_email_to_single_recipient_sample_async.py b/sdk/communication/azure-communication-email/samples/send_email_to_single_recipient_sample_async.py index 4eb11129389d..ea894d73bf04 100644 --- a/sdk/communication/azure-communication-email/samples/send_email_to_single_recipient_sample_async.py +++ b/sdk/communication/azure-communication-email/samples/send_email_to_single_recipient_sample_async.py @@ -27,12 +27,13 @@ sys.path.append("..") + class EmailSingleRecipientSampleAsync(object): connection_string = os.getenv("COMMUNICATION_CONNECTION_STRING_EMAIL") sender_address = os.getenv("SENDER_ADDRESS") recipient_address = os.getenv("RECIPIENT_ADDRESS") - + async def send_email_to_single_recipient_async(self): # creating the email client email_client = EmailClient.from_connection_string(self.connection_string) @@ -42,17 +43,10 @@ async def send_email_to_single_recipient_async(self): "content": { "subject": "This is the subject", "plainText": "This is the body", - "html": "html>

This is the body

" + "html": "html>

This is the body

", }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] - }, - "senderAddress": self.sender_address + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, + "senderAddress": self.sender_address, } async with email_client: @@ -60,11 +54,12 @@ async def send_email_to_single_recipient_async(self): # sending the email message poller = await email_client.begin_send(message) response = await poller.result() - print("Operation ID: " + response['id']) + print("Operation ID: " + response["id"]) except HttpResponseError as ex: print(ex) pass -if __name__ == '__main__': + +if __name__ == "__main__": sample = EmailSingleRecipientSampleAsync() asyncio.run(sample.send_email_to_single_recipient_async()) diff --git a/sdk/communication/azure-communication-email/samples/send_email_with_attachments_sample.py b/sdk/communication/azure-communication-email/samples/send_email_with_attachments_sample.py index 3a7a6c5a1fbe..be4ad09386ab 100644 --- a/sdk/communication/azure-communication-email/samples/send_email_with_attachments_sample.py +++ b/sdk/communication/azure-communication-email/samples/send_email_with_attachments_sample.py @@ -27,20 +27,19 @@ sys.path.append("..") + class EmailWithAttachmentSample(object): connection_string = os.getenv("COMMUNICATION_CONNECTION_STRING_EMAIL") sender_address = os.getenv("SENDER_ADDRESS") recipient_address = os.getenv("RECIPIENT_ADDRESS") - + def send_email_with_attachment(self): # creating the email client email_client = EmailClient.from_connection_string(self.connection_string) # creating the email message - attachment_path = os.path.join( - os.path.dirname(os.path.realpath(__file__)), - "attachment.txt") + attachment_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "attachment.txt") with open(attachment_path, "rb") as file: file_bytes = file.read() @@ -51,35 +50,25 @@ def send_email_with_attachment(self): "content": { "subject": "This is the subject", "plainText": "This is the body", - "html": "html>

This is the body

" - }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] + "html": "html>

This is the body

", }, + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, "senderAddress": self.sender_address, "attachments": [ - { - "name": "attachment.txt", - "contentType": "text/plain", - "contentInBase64": file_bytes_b64.decode() - } - ] + {"name": "attachment.txt", "contentType": "text/plain", "contentInBase64": file_bytes_b64.decode()} + ], } try: # sending the email message poller = email_client.begin_send(message) response = poller.result() - print("Operation ID: " + response['id']) + print("Operation ID: " + response["id"]) except HttpResponseError as ex: print(ex) pass -if __name__ == '__main__': + +if __name__ == "__main__": sample = EmailWithAttachmentSample() sample.send_email_with_attachment() diff --git a/sdk/communication/azure-communication-email/samples/send_email_with_attachments_sample_async.py b/sdk/communication/azure-communication-email/samples/send_email_with_attachments_sample_async.py index 5402f28dd08d..a3835037d095 100644 --- a/sdk/communication/azure-communication-email/samples/send_email_with_attachments_sample_async.py +++ b/sdk/communication/azure-communication-email/samples/send_email_with_attachments_sample_async.py @@ -28,20 +28,19 @@ sys.path.append("..") + class EmailWithAttachmentSampleAsync(object): connection_string = os.getenv("COMMUNICATION_CONNECTION_STRING_EMAIL") sender_address = os.getenv("SENDER_ADDRESS") recipient_address = os.getenv("RECIPIENT_ADDRESS") - + async def send_email_with_attachment_async(self): # creating the email client email_client = EmailClient.from_connection_string(self.connection_string) # creating the email message - attachment_path = os.path.join( - os.path.dirname(os.path.realpath(__file__)), - "attachment.txt") + attachment_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "attachment.txt") with open(attachment_path, "rb") as file: file_bytes = file.read() @@ -52,24 +51,13 @@ async def send_email_with_attachment_async(self): "content": { "subject": "This is the subject", "plainText": "This is the body", - "html": "html>

This is the body

" - }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] + "html": "html>

This is the body

", }, + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, "senderAddress": self.sender_address, "attachments": [ - { - "name": "attachment.txt", - "contentType": "text/plain", - "contentInBase64": file_bytes_b64.decode() - } - ] + {"name": "attachment.txt", "contentType": "text/plain", "contentInBase64": file_bytes_b64.decode()} + ], } async with email_client: @@ -77,11 +65,12 @@ async def send_email_with_attachment_async(self): # sending the email message poller = await email_client.begin_send(message) response = await poller.result() - print("Operation ID: " + response['id']) + print("Operation ID: " + response["id"]) except HttpResponseError as ex: print(ex) pass -if __name__ == '__main__': + +if __name__ == "__main__": sample = EmailWithAttachmentSampleAsync() asyncio.run(sample.send_email_with_attachment_async()) diff --git a/sdk/communication/azure-communication-email/samples/send_email_with_inline_attachments_sample.py b/sdk/communication/azure-communication-email/samples/send_email_with_inline_attachments_sample.py index 6cf4869776b3..4789a63be2e6 100644 --- a/sdk/communication/azure-communication-email/samples/send_email_with_inline_attachments_sample.py +++ b/sdk/communication/azure-communication-email/samples/send_email_with_inline_attachments_sample.py @@ -27,6 +27,7 @@ sys.path.append("..") + class EmailWithAttachmentSample(object): connection_string = os.getenv("COMMUNICATION_CONNECTION_STRING_EMAIL") @@ -38,9 +39,7 @@ def send_email_with_attachment(self): email_client = EmailClient.from_connection_string(self.connection_string) # creating the email message - attachment_path = os.path.join( - os.path.dirname(os.path.realpath(__file__)), - "inline_image.gif") + attachment_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "inline_image.gif") with open(attachment_path, "rb") as file: file_bytes = file.read() @@ -51,36 +50,30 @@ def send_email_with_attachment(self): "content": { "subject": "This is the subject", "plainText": "This is the body", - "html": "This is the body
" - }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] + "html": 'This is the body
', }, + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, "senderAddress": self.sender_address, "attachments": [ { "name": "inline_image.gif", "contentType": "image/gif", "contentInBase64": file_bytes_b64.decode(), - "contentId": "my-inline-image" + "contentId": "my-inline-image", } - ] + ], } try: # sending the email message poller = email_client.begin_send(message) response = poller.result() - print("Operation ID: " + response['id']) + print("Operation ID: " + response["id"]) except HttpResponseError as ex: print(ex) pass -if __name__ == '__main__': + +if __name__ == "__main__": sample = EmailWithAttachmentSample() sample.send_email_with_attachment() diff --git a/sdk/communication/azure-communication-email/samples/send_email_with_inline_attachments_sample_async.py b/sdk/communication/azure-communication-email/samples/send_email_with_inline_attachments_sample_async.py index ae883081cc75..bc8190e0e2ba 100644 --- a/sdk/communication/azure-communication-email/samples/send_email_with_inline_attachments_sample_async.py +++ b/sdk/communication/azure-communication-email/samples/send_email_with_inline_attachments_sample_async.py @@ -28,6 +28,7 @@ sys.path.append("..") + class EmailWithAttachmentSampleAsync(object): connection_string = os.getenv("COMMUNICATION_CONNECTION_STRING_EMAIL") @@ -39,9 +40,7 @@ async def send_email_with_attachment_async(self): email_client = EmailClient.from_connection_string(self.connection_string) # creating the email message - attachment_path = os.path.join( - os.path.dirname(os.path.realpath(__file__)), - "inline_image.gif") + attachment_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "inline_image.gif") with open(attachment_path, "rb") as file: file_bytes = file.read() @@ -52,25 +51,18 @@ async def send_email_with_attachment_async(self): "content": { "subject": "This is the subject", "plainText": "This is the body", - "html": "This is the body
" - }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] + "html": 'This is the body
', }, + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, "senderAddress": self.sender_address, "attachments": [ { "name": "inline_image.gif", "contentType": "image/gif", "contentInBase64": file_bytes_b64.decode(), - "contentId": "my-inline-image" + "contentId": "my-inline-image", } - ] + ], } async with email_client: @@ -78,11 +70,12 @@ async def send_email_with_attachment_async(self): # sending the email message poller = await email_client.begin_send(message) response = await poller.result() - print("Operation ID: " + response['id']) + print("Operation ID: " + response["id"]) except HttpResponseError as ex: print(ex) pass -if __name__ == '__main__': + +if __name__ == "__main__": sample = EmailWithAttachmentSampleAsync() asyncio.run(sample.send_email_with_attachment_async()) diff --git a/sdk/communication/azure-communication-email/setup.py b/sdk/communication/azure-communication-email/setup.py index b5db5e23cf4b..d90a0a86e595 100644 --- a/sdk/communication/azure-communication-email/setup.py +++ b/sdk/communication/azure-communication-email/setup.py @@ -1,10 +1,10 @@ #!/usr/bin/env python -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- import re import os.path @@ -16,63 +16,69 @@ PACKAGE_PPRINT_NAME = "MyService Management" # a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace('-', '/') +package_folder_path = PACKAGE_NAME.replace("-", "/") # a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace('-', '.') +namespace_name = PACKAGE_NAME.replace("-", ".") # Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, 'version.py') - if os.path.exists(os.path.join(package_folder_path, 'version.py')) - else os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) +with open( + ( + os.path.join(package_folder_path, "version.py") + if os.path.exists(os.path.join(package_folder_path, "version.py")) + else os.path.join(package_folder_path, "_version.py") + ), + "r", +) as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: - raise RuntimeError('Cannot find version information') + raise RuntimeError("Cannot find version information") -with open('README.md', encoding='utf-8') as f: +with open("README.md", encoding="utf-8") as f: readme = f.read() -with open('CHANGELOG.md', encoding='utf-8') as f: +with open("CHANGELOG.md", encoding="utf-8") as f: changelog = f.read() setup( name=PACKAGE_NAME, version=version, - description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), - long_description=readme + '\n\n' + changelog, - long_description_content_type='text/markdown', - license='MIT License', - author='Microsoft Corporation', - author_email='azpysdkhelp@microsoft.com', - url='https://github.com/Azure/azure-sdk-for-python', + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description=readme + "\n\n" + changelog, + long_description_content_type="text/markdown", + license="MIT License", + author="Microsoft Corporation", + author_email="azpysdkhelp@microsoft.com", + url="https://github.com/Azure/azure-sdk-for-python", keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product classifiers=[ "Development Status :: 5 - Production/Stable", - 'Programming Language :: Python', - 'Programming Language :: Python :: 3 :: Only', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - 'License :: OSI Approved :: MIT License', + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: MIT License", ], zip_safe=False, - packages=find_packages(exclude=[ - 'tests', - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.communication', - ]), + packages=find_packages( + exclude=[ + "tests", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + "azure.communication", + ] + ), include_package_data=True, package_data={ - 'pytyped': ['py.typed'], + "pytyped": ["py.typed"], }, install_requires=[ - 'msrest>=0.7.1', - 'azure-common>=1.1', - 'azure-mgmt-core>=1.3.2', + "msrest>=0.7.1", + "azure-common>=1.1", + "azure-mgmt-core>=1.3.2", ], - python_requires=">=3.8" + python_requires=">=3.8", ) diff --git a/sdk/communication/azure-communication-email/tests/async_preparers.py b/sdk/communication/azure-communication-email/tests/async_preparers.py index 962acc531742..e52e74786c85 100644 --- a/sdk/communication/azure-communication-email/tests/async_preparers.py +++ b/sdk/communication/azure-communication-email/tests/async_preparers.py @@ -6,6 +6,7 @@ import os from devtools_testutils import is_live + def email_decorator_async(func, **kwargs): async def wrapper(self, *args, **kwargs): if is_live(): @@ -16,7 +17,7 @@ async def wrapper(self, *args, **kwargs): self.communication_connection_string = "endpoint=https://someEndpoint/;accesskey=someAccessKeyw==" self.sender_address = "someSender@contoso.com" self.recipient_address = "someRecipient@domain.com" - + EXPONENTIAL_BACKOFF = 1.5 RETRY_COUNT = 0 @@ -37,5 +38,5 @@ async def wrapper(self, *args, **kwargs): RETRY_COUNT += 1 if exc.status_code != 429 or RETRY_COUNT >= 6: raise - + return wrapper diff --git a/sdk/communication/azure-communication-email/tests/conftest.py b/sdk/communication/azure-communication-email/tests/conftest.py index 20f477fbf432..ef0ca6c23cc4 100644 --- a/sdk/communication/azure-communication-email/tests/conftest.py +++ b/sdk/communication/azure-communication-email/tests/conftest.py @@ -25,19 +25,30 @@ # -------------------------------------------------------------------------- import pytest import os -from devtools_testutils import add_general_regex_sanitizer, add_header_regex_sanitizer, add_body_key_sanitizer, set_default_session_settings, add_uri_regex_sanitizer +from devtools_testutils import ( + add_general_regex_sanitizer, + add_header_regex_sanitizer, + add_body_key_sanitizer, + set_default_session_settings, + add_uri_regex_sanitizer, +) from azure.communication.email._shared.utils import parse_connection_str from azure.communication.email._api_versions import DEFAULT_VERSION + @pytest.fixture(scope="session", autouse=True) def add_sanitizers(test_proxy): set_default_session_settings() - communication_connection_string = os.getenv("COMMUNICATION_CONNECTION_STRING_EMAIL", "endpoint=https://someEndpoint/;accesskey=someAccessKeyw==") + communication_connection_string = os.getenv( + "COMMUNICATION_CONNECTION_STRING_EMAIL", "endpoint=https://someEndpoint/;accesskey=someAccessKeyw==" + ) sender_address = os.getenv("SENDER_ADDRESS", "someSender@contoso.com") recipient_address = os.getenv("RECIPIENT_ADDRESS", "someRecipient@domain.com") - add_general_regex_sanitizer(regex=communication_connection_string, value="endpoint=https://someEndpoint/;accesskey=someAccessKeyw==") + add_general_regex_sanitizer( + regex=communication_connection_string, value="endpoint=https://someEndpoint/;accesskey=someAccessKeyw==" + ) add_general_regex_sanitizer(regex=sender_address, value="someSender@contoso.com") add_general_regex_sanitizer(regex=recipient_address, value="someRecipient@domain.com") @@ -47,7 +58,11 @@ def add_sanitizers(test_proxy): add_general_regex_sanitizer(regex=endpoint, value="someEndpoint") add_header_regex_sanitizer(key="x-ms-content-sha256", value="sanitized") - add_header_regex_sanitizer(key="Operation-Location", value="https://someEndpoint/emails/operations/someId?api-version=" + DEFAULT_VERSION) + add_header_regex_sanitizer( + key="Operation-Location", value="https://someEndpoint/emails/operations/someId?api-version=" + DEFAULT_VERSION + ) - add_uri_regex_sanitizer(regex="https://[^/]+/emails/operations/.*?api", value="https://someEndpoint/emails/operations/someId?api") + add_uri_regex_sanitizer( + regex="https://[^/]+/emails/operations/.*?api", value="https://someEndpoint/emails/operations/someId?api" + ) add_uri_regex_sanitizer(regex="https://[^/]+/emails:send\\?api", value="https://someEndpoint/emails:send?api") diff --git a/sdk/communication/azure-communication-email/tests/preparers.py b/sdk/communication/azure-communication-email/tests/preparers.py index 849d18caadef..5c02ff1353ed 100644 --- a/sdk/communication/azure-communication-email/tests/preparers.py +++ b/sdk/communication/azure-communication-email/tests/preparers.py @@ -6,6 +6,7 @@ import os from devtools_testutils import is_live + def email_decorator(func, **kwargs): def wrapper(self, *args, **kwargs): if is_live(): @@ -16,7 +17,7 @@ def wrapper(self, *args, **kwargs): self.communication_connection_string = "endpoint=https://someEndpoint/;accesskey=someAccessKeyw==" self.sender_address = "someSender@contoso.com" self.recipient_address = "someRecipient@domain.com" - + func(self, *args, **kwargs) return wrapper diff --git a/sdk/communication/azure-communication-email/tests/test_email_client_e2e.py b/sdk/communication/azure-communication-email/tests/test_email_client_e2e.py index 78a627cb41c6..84a63f01a7f5 100644 --- a/sdk/communication/azure-communication-email/tests/test_email_client_e2e.py +++ b/sdk/communication/azure-communication-email/tests/test_email_client_e2e.py @@ -7,6 +7,7 @@ from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy from preparers import email_decorator + class TestEmailClient(AzureRecordedTestCase): @email_decorator @recorded_by_proxy @@ -18,20 +19,13 @@ def test_send_email_single_recipient(self): "subject": "This is the subject", "plainText": "This is the body", }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] - }, - "senderAddress": self.sender_address + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, + "senderAddress": self.sender_address, } poller = email_client.begin_send(message) response = poller.result() - assert response['status'] == "Succeeded" + assert response["status"] == "Succeeded" @email_decorator @recorded_by_proxy @@ -45,22 +39,16 @@ def test_send_email_multiple_recipients(self): }, "recipients": { "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - }, - { - "address": self.recipient_address, - "displayName": "Customer Name 2" - } + {"address": self.recipient_address, "displayName": "Customer Name"}, + {"address": self.recipient_address, "displayName": "Customer Name 2"}, ] }, - "senderAddress": self.sender_address + "senderAddress": self.sender_address, } poller = email_client.begin_send(message) response = poller.result() - assert response['status'] == "Succeeded" + assert response["status"] == "Succeeded" @email_decorator @recorded_by_proxy @@ -72,27 +60,20 @@ def test_send_email_attachment(self): "subject": "This is the subject", "plainText": "This is the body", }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] - }, + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, "senderAddress": self.sender_address, "attachments": [ { "name": "readme.txt", "contentType": "text/plain", - "contentInBase64": "ZW1haWwgdGVzdCBhdHRhY2htZW50" #cspell:disable-line + "contentInBase64": "ZW1haWwgdGVzdCBhdHRhY2htZW50", # cspell:disable-line } - ] + ], } poller = email_client.begin_send(message) response = poller.result() - assert response['status'] == "Succeeded" + assert response["status"] == "Succeeded" @email_decorator @recorded_by_proxy @@ -103,28 +84,20 @@ def test_send_email_inline_attachment(self): "content": { "subject": "This is the subject", "plainText": "This is the body", - "html": "This is the body
" - }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] + "html": 'This is the body
', }, + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, "senderAddress": self.sender_address, "attachments": [ { "name": "inline_image.bmp", "contentType": "image/bmp", - "contentInBase64": "Qk06AAAAAAAAADYAAAAoAAAAAQAAAAEAAAABABgAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAzFUzAA==", #cspell:disable-line - "contentId": "my-inline-image" + "contentInBase64": "Qk06AAAAAAAAADYAAAAoAAAAAQAAAAEAAAABABgAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAzFUzAA==", # cspell:disable-line + "contentId": "my-inline-image", } - ] + ], } poller = email_client.begin_send(message) response = poller.result() - assert response['status'] == "Succeeded" - + assert response["status"] == "Succeeded" diff --git a/sdk/communication/azure-communication-email/tests/test_email_client_e2e_async.py b/sdk/communication/azure-communication-email/tests/test_email_client_e2e_async.py index 31d3c1c57c94..49b9a50f1cce 100644 --- a/sdk/communication/azure-communication-email/tests/test_email_client_e2e_async.py +++ b/sdk/communication/azure-communication-email/tests/test_email_client_e2e_async.py @@ -10,6 +10,7 @@ from devtools_testutils.aio import recorded_by_proxy_async from async_preparers import email_decorator_async + class TestEmailClient(AzureRecordedTestCase): @email_decorator_async @recorded_by_proxy_async @@ -21,21 +22,14 @@ async def test_send_email_single_recipient(self): "subject": "This is the subject", "plainText": "This is the body", }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] - }, - "senderAddress": self.sender_address + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, + "senderAddress": self.sender_address, } async with email_client: poller = await email_client.begin_send(message) response = await poller.result() - assert response['status'] == "Succeeded" + assert response["status"] == "Succeeded" @email_decorator_async @recorded_by_proxy_async @@ -49,23 +43,17 @@ async def test_send_email_multiple_recipients(self): }, "recipients": { "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - }, - { - "address": self.recipient_address, - "displayName": "Customer Name 2" - } + {"address": self.recipient_address, "displayName": "Customer Name"}, + {"address": self.recipient_address, "displayName": "Customer Name 2"}, ] }, - "senderAddress": self.sender_address + "senderAddress": self.sender_address, } async with email_client: poller = await email_client.begin_send(message) response = await poller.result() - assert response['status'] == "Succeeded" + assert response["status"] == "Succeeded" @email_decorator_async @recorded_by_proxy_async @@ -77,28 +65,21 @@ async def test_send_email_attachment(self): "subject": "This is the subject", "plainText": "This is the body", }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] - }, + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, "senderAddress": self.sender_address, "attachments": [ { "name": "readme.txt", "contentType": "text/plain", - "contentInBase64": "ZW1haWwgdGVzdCBhdHRhY2htZW50" #cspell:disable-line + "contentInBase64": "ZW1haWwgdGVzdCBhdHRhY2htZW50", # cspell:disable-line } - ] + ], } async with email_client: poller = await email_client.begin_send(message) response = await poller.result() - assert response['status'] == "Succeeded" + assert response["status"] == "Succeeded" @email_decorator_async @recorded_by_proxy_async @@ -109,29 +90,21 @@ async def test_send_email_inline_attachment(self): "content": { "subject": "This is the subject", "plainText": "This is the body", - "html": "This is the body
" - }, - "recipients": { - "to": [ - { - "address": self.recipient_address, - "displayName": "Customer Name" - } - ] + "html": 'This is the body
', }, + "recipients": {"to": [{"address": self.recipient_address, "displayName": "Customer Name"}]}, "senderAddress": self.sender_address, "attachments": [ { "name": "inline_image.bmp", "contentType": "image/bmp", - "contentInBase64": "Qk06AAAAAAAAADYAAAAoAAAAAQAAAAEAAAABABgAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAzFUzAA==", #cspell:disable-line - "contentId": "my-inline-image" + "contentInBase64": "Qk06AAAAAAAAADYAAAAoAAAAAQAAAAEAAAABABgAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAzFUzAA==", # cspell:disable-line + "contentId": "my-inline-image", } - ] + ], } async with email_client: poller = await email_client.begin_send(message) response = await poller.result() - assert response['status'] == "Succeeded" - + assert response["status"] == "Succeeded" diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_communication_identity_client.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_communication_identity_client.py index 76d6997bd389..49a8f97b0516 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_communication_identity_client.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_communication_identity_client.py @@ -89,13 +89,9 @@ def create_user(self, **kwargs): :return: CommunicationUserIdentifier :rtype: ~azure.communication.identity.CommunicationUserIdentifier """ - identity_access_token = ( - self._identity_service_client.communication_identity.create(**kwargs) - ) + identity_access_token = self._identity_service_client.communication_identity.create(**kwargs) - return CommunicationUserIdentifier( - identity_access_token.identity.id, raw_id=identity_access_token.identity.id - ) + return CommunicationUserIdentifier(identity_access_token.identity.id, raw_id=identity_access_token.identity.id) @distributed_trace def create_user_and_token( @@ -148,9 +144,7 @@ def delete_user( :return: None :rtype: None """ - self._identity_service_client.communication_identity.delete( - user.properties["id"], **kwargs - ) + self._identity_service_client.communication_identity.delete(user.properties["id"], **kwargs) @distributed_trace def get_token( diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_client.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_client.py index 2b37eedb95cf..45e7da9919ec 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_client.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_client.py @@ -36,16 +36,10 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self, endpoint: str, **kwargs: Any ) -> None: _endpoint = "{endpoint}" - self._config = CommunicationIdentityClientConfiguration( - endpoint=endpoint, **kwargs - ) - self._client: PipelineClient = PipelineClient( - base_url=_endpoint, config=self._config, **kwargs - ) + self._config = CommunicationIdentityClientConfiguration(endpoint=endpoint, **kwargs) + self._client: PipelineClient = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) - client_models = { - k: v for k, v in _models.__dict__.items() if isinstance(v, type) - } + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False @@ -73,14 +67,10 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: request_copy = deepcopy(request) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request_copy.url = self._client.format_url( - request_copy.url, **path_format_arguments - ) + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) return self._client.send_request(request_copy, **kwargs) def close(self) -> None: diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_configuration.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_configuration.py index 45be507cba3c..3ba79d8d9d97 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_configuration.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_configuration.py @@ -39,30 +39,16 @@ def __init__(self, endpoint: str, **kwargs: Any) -> None: self.endpoint = endpoint self.api_version = api_version - kwargs.setdefault( - "sdk_moniker", "communicationidentityclient/{}".format(VERSION) - ) + kwargs.setdefault("sdk_moniker", "communicationidentityclient/{}".format(VERSION)) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get( - "user_agent_policy" - ) or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy( - **kwargs - ) + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get( - "logging_policy" - ) or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get( - "http_logging_policy" - ) or policies.HttpLoggingPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get( - "custom_hook_policy" - ) or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy( - **kwargs - ) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_serialization.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_serialization.py index 0e93b271f2b6..c13084631923 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_serialization.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/_serialization.py @@ -84,9 +84,7 @@ class RawDeserializer: CONTEXT_NAME = "deserialized_data" @classmethod - def deserialize_from_text( - cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None - ) -> Any: + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: """Decode data according to content-type. Accept a stream of data as well, but will be load at once in memory for now. @@ -148,14 +146,10 @@ def _json_attemp(data): # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError( - "Cannot deserialize content-type: {}".format(content_type) - ) + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod - def deserialize_from_http_generics( - cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping - ) -> Any: + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: """Deserialize from HTTP response. Use bytes and headers to NOT use any requests/aiohttp or whatever @@ -376,9 +370,7 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: def as_dict( self, keep_readonly: bool = True, - key_transformer: Callable[ - [str, Dict[str, Any], Any], Any - ] = attribute_transformer, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, **kwargs: Any ) -> JSON: """Return a dict that can be serialized using json.dump. @@ -412,18 +404,14 @@ def my_key_transformer(key, attr_desc, value): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize( - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) + return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) @classmethod def _infer_class_models(cls): try: str_models = cls.__module__.rsplit(".", 1)[0] models = sys.modules[str_models] - client_models = { - k: v for k, v in models.__dict__.items() if isinstance(v, type) - } + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") except Exception: @@ -432,9 +420,7 @@ def _infer_class_models(cls): return client_models @classmethod - def deserialize( - cls: Type[ModelType], data: Any, content_type: Optional[str] = None - ) -> ModelType: + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. @@ -495,13 +481,9 @@ def _classify(cls, response, objects): if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop( - rest_api_response_key, None - ) or response.pop(subtype_key, None) + subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) else: - subtype_value = xml_key_extractor( - subtype_key, cls._attribute_map[subtype_key], response - ) + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: # Try to match base class. Can be class name only # (bug to fix in Autorest to support x-ms-discriminator-name) @@ -629,9 +611,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): try: is_xml_model_serialization = kwargs["is_xml"] except KeyError: - is_xml_model_serialization = kwargs.setdefault( - "is_xml", target_obj.is_xml_model() - ) + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) serialized = {} if is_xml_model_serialization: @@ -640,9 +620,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): attributes = target_obj._attribute_map for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get( - "readonly", False - ): + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): continue if attr_name == "additional_properties" and attr_desc["key"] == "": @@ -654,15 +632,11 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if is_xml_model_serialization: pass # Don't provide "transformer" for XML for now. Keep "orig_attr" else: # JSON - keys, orig_attr = key_transformer( - attr, attr_desc.copy(), orig_attr - ) + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) keys = keys if isinstance(keys, list) else [keys] kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data( - orig_attr, attr_desc["type"], **kwargs - ) + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) if is_xml_model_serialization: xml_desc = attr_desc.get("xml", {}) @@ -710,9 +684,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): raise except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format( - attr_name, class_name, str(target_obj) - ) + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) raise_with_traceback(SerializationError, msg, err) else: return serialized @@ -734,9 +706,7 @@ def body(self, data, data_type, **kwargs): is_xml_model_serialization = kwargs["is_xml"] except KeyError: if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault( - "is_xml", internal_data_type.is_xml_model() - ) + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) else: is_xml_model_serialization = False if internal_data_type and not isinstance(internal_data_type, Enum): @@ -757,9 +727,7 @@ def body(self, data, data_type, **kwargs): ] data = deserializer._deserialize(data_type, data) except DeserializationError as err: - raise_with_traceback( - SerializationError, "Unable to build a model: " + str(err), err - ) + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) return self._serialize(data, data_type, **kwargs) @@ -804,11 +772,7 @@ def query(self, name, data, data_type, **kwargs): if data_type.startswith("["): internal_data_type = data_type[1:-1] do_quote = not kwargs.get("skip_quote", False) - return str( - self.serialize_iter( - data, internal_data_type, do_quote=do_quote, **kwargs - ) - ) + return str(self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs)) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -967,9 +931,7 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialized.append(None) if kwargs.get("do_quote", False): - serialized = [ - "" if s is None else quote(str(s), safe="") for s in serialized - ] + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] if div: serialized = ["" if s is None else str(s) for s in serialized] @@ -986,9 +948,7 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): is_wrapped = xml_desc.get("wrapped", False) node_name = xml_desc.get("itemsName", xml_name) if is_wrapped: - final_result = _create_xml_node( - xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None) - ) + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) else: final_result = [] # All list elements to "local_node" @@ -1020,9 +980,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): serialized = {} for key, value in attr.items(): try: - serialized[self.serialize_unicode(key)] = self.serialize_data( - value, dict_type, **kwargs - ) + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) except ValueError as err: if isinstance(err, SerializationError): raise @@ -1033,9 +991,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): xml_desc = serialization_ctxt["xml"] xml_name = xml_desc["name"] - final_result = _create_xml_node( - xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None) - ) + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) for key, value in serialized.items(): ET.SubElement(final_result, key).text = value return final_result @@ -1081,9 +1037,7 @@ def serialize_object(self, attr, **kwargs): serialized = {} for key, value in attr.items(): try: - serialized[self.serialize_unicode(key)] = self.serialize_object( - value, **kwargs - ) + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) except ValueError: serialized[self.serialize_unicode(key)] = None return serialized @@ -1300,9 +1254,7 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): key = _decode_attribute_map_key(dict_keys[0]) break working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor( - working_key, None, working_data - ) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well @@ -1395,10 +1347,7 @@ def xml_key_extractor(attr, attr_desc, data): # - Wrapped node # - Internal type is an enum (considered basic types) # - Internal type has no XML/Name node - if is_wrapped or ( - internal_type - and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map) - ): + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): children = data.findall(xml_name) # If internal type has a local name and it's not a list, I use that name elif not is_iter_type and internal_type and "name" in internal_type_xml_map: @@ -1406,9 +1355,7 @@ def xml_key_extractor(attr, attr_desc, data): children = data.findall(xml_name) # That's an array else: - if ( - internal_type - ): # Complex type, ignore itemsName and use the complex type name + if internal_type: # Complex type, ignore itemsName and use the complex type name items_name = _extract_name_from_internal_type(internal_type) else: items_name = xml_desc.get("itemsName", xml_name) @@ -1437,9 +1384,7 @@ def xml_key_extractor(attr, attr_desc, data): # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: - raise DeserializationError( - "Find several XML '{}' where it was not expected".format(xml_name) - ) + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) return children[0] @@ -1452,9 +1397,7 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - valid_date = re.compile( - r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?" - ) + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): self.deserialize_type = { @@ -1510,11 +1453,7 @@ def _deserialize(self, target_obj, data): """ # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): - constants = [ - name - for name, config in getattr(data, "_validation", {}).items() - if config.get("constant") - ] + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: for attr, mapconfig in data._attribute_map.items(): if attr in constants: @@ -1524,9 +1463,7 @@ def _deserialize(self, target_obj, data): continue local_type = mapconfig["type"] internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance( - internal_data_type, Enum - ): + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): continue setattr(data, attr, self._deserialize(local_type, value)) return data @@ -1580,10 +1517,7 @@ def _deserialize(self, target_obj, data): def _build_additional_properties(self, attribute_map, data): if not self.additional_properties_detection: return None - if ( - "additional_properties" in attribute_map - and attribute_map.get("additional_properties", {}).get("key") != "" - ): + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": # Check empty string. If it's not empty, someone has a real "additionalProperties" return None if isinstance(data, ET.Element): @@ -1663,21 +1597,15 @@ def _unpack_content(raw_data, content_type=None): if context: if RawDeserializer.CONTEXT_NAME in context: return context[RawDeserializer.CONTEXT_NAME] - raise ValueError( - "This pipeline didn't have the RawDeserializer policy; can't deserialize" - ) + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") # Assume this is enough to recognize universal_http.ClientResponse without importing it if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics( - raw_data.text(), raw_data.headers - ) + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) # Assume this enough to recognize requests.Response without importing it. if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics( - raw_data.text, raw_data.headers - ) + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore @@ -1692,17 +1620,9 @@ def _instantiate_model(self, response, attrs, additional_properties=None): if callable(response): subtype = getattr(response, "_subtype_map", {}) try: - readonly = [ - k for k, v in response._validation.items() if v.get("readonly") - ] - const = [ - k for k, v in response._validation.items() if v.get("constant") - ] - kwargs = { - k: v - for k, v in attrs.items() - if k not in subtype and k not in readonly + const - } + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} response_obj = response(**kwargs) for attr in readonly: setattr(response_obj, attr, attrs.get(attr)) @@ -1739,17 +1659,11 @@ def deserialize_data(self, data, data_type): if data_type in self.basic_types.values(): return self.deserialize_basic(data, data_type) if data_type in self.deserialize_type: - if isinstance( - data, self.deserialize_expected_types.get(data_type, tuple()) - ): + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): return data is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if ( - isinstance(data, ET.Element) - and is_a_text_parsing_type(data_type) - and not data.text - ): + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: return None data_val = self.deserialize_type[data_type](data) return data_val @@ -1780,16 +1694,10 @@ def deserialize_iter(self, attr, iter_type): """ if attr is None: return None - if isinstance( - attr, ET.Element - ): # If I receive an element here, get the children + if isinstance(attr, ET.Element): # If I receive an element here, get the children attr = list(attr) if not isinstance(attr, (list, set)): - raise DeserializationError( - "Cannot deserialize as [{}] an object of type {}".format( - iter_type, type(attr) - ) - ) + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) return [self.deserialize_data(a, iter_type) for a in attr] def deserialize_dict(self, attr, dict_type): @@ -1801,9 +1709,7 @@ def deserialize_dict(self, attr, dict_type): :rtype: dict """ if isinstance(attr, list): - return { - x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr - } + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} if isinstance(attr, ET.Element): # Transform value into {"Key": "value"} @@ -2035,9 +1941,7 @@ def deserialize_date(attr): if isinstance(attr, ET.Element): attr = attr.text if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError( - "Date must have only digits and -. Received: %s" % attr - ) + 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=0, defaultday=0) @@ -2052,9 +1956,7 @@ def deserialize_time(attr): if isinstance(attr, ET.Element): attr = attr.text if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError( - "Date must have only digits and -. Received: %s" % attr - ) + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) return isodate.parse_time(attr) @staticmethod @@ -2070,10 +1972,7 @@ def deserialize_rfc(attr): try: parsed_date = email.utils.parsedate_tz(attr) # type: ignore date_obj = datetime.datetime( - *parsed_date[:6], - tzinfo=_FixedOffset( - datetime.timedelta(minutes=(parsed_date[9] or 0) / 60) - ) + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) ) if not date_obj.tzinfo: date_obj = date_obj.astimezone(tz=TZ_UTC) diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/_client.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/_client.py index be66deb8e491..0c09e59bf350 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/_client.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/_client.py @@ -36,16 +36,10 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self, endpoint: str, **kwargs: Any ) -> None: _endpoint = "{endpoint}" - self._config = CommunicationIdentityClientConfiguration( - endpoint=endpoint, **kwargs - ) - self._client: AsyncPipelineClient = AsyncPipelineClient( - base_url=_endpoint, config=self._config, **kwargs - ) + self._config = CommunicationIdentityClientConfiguration(endpoint=endpoint, **kwargs) + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) - client_models = { - k: v for k, v in _models.__dict__.items() if isinstance(v, type) - } + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False @@ -53,9 +47,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._client, self._config, self._serialize, self._deserialize ) - def send_request( - self, request: HttpRequest, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -75,14 +67,10 @@ def send_request( request_copy = deepcopy(request) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request_copy.url = self._client.format_url( - request_copy.url, **path_format_arguments - ) + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/_configuration.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/_configuration.py index 0b009b26b7f3..fe759886cbce 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/_configuration.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/_configuration.py @@ -39,32 +39,16 @@ def __init__(self, endpoint: str, **kwargs: Any) -> None: self.endpoint = endpoint self.api_version = api_version - kwargs.setdefault( - "sdk_moniker", "communicationidentityclient/{}".format(VERSION) - ) + kwargs.setdefault("sdk_moniker", "communicationidentityclient/{}".format(VERSION)) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get( - "user_agent_policy" - ) or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy( - **kwargs - ) + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get( - "logging_policy" - ) or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get( - "http_logging_policy" - ) or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy( - **kwargs - ) - self.custom_hook_policy = kwargs.get( - "custom_hook_policy" - ) or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get( - "redirect_policy" - ) or policies.AsyncRedirectPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/operations/_operations.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/operations/_operations.py index b222fbb649fc..d3449860771f 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/operations/_operations.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/operations/_operations.py @@ -32,9 +32,7 @@ ) T = TypeVar("T") -ClsType = Optional[ - Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any] -] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class CommunicationIdentityOperations: @@ -54,9 +52,7 @@ def __init__(self, *args, **kwargs) -> None: self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = ( - input_args.pop(0) if input_args else kwargs.pop("deserializer") - ) + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload async def create( @@ -83,11 +79,7 @@ async def create( @overload async def create( - self, - body: Optional[IO] = None, - *, - content_type: str = "application/json", - **kwargs: Any + self, body: Optional[IO] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CommunicationIdentityAccessTokenResult: """Create a new identity, and optionally, an access token. @@ -106,9 +98,7 @@ async def create( @distributed_trace_async async def create( - self, - body: Optional[Union[_models.CommunicationIdentityCreateRequest, IO]] = None, - **kwargs: Any + self, body: Optional[Union[_models.CommunicationIdentityCreateRequest, IO]] = None, **kwargs: Any ) -> _models.CommunicationIdentityAccessTokenResult: """Create a new identity, and optionally, an access token. @@ -136,12 +126,8 @@ async def create( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", None) - ) - cls: ClsType[_models.CommunicationIdentityAccessTokenResult] = kwargs.pop( - "cls", None - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CommunicationIdentityAccessTokenResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -163,17 +149,13 @@ async def create( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = ( - await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -181,17 +163,11 @@ async def create( if response.status_code not in [201]: if _stream: await response.read() # Load the body in memory and close the socket - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) - error = self._deserialize.failsafe_deserialize( - _models.CommunicationErrorResponse, pipeline_response - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize( - "CommunicationIdentityAccessTokenResult", pipeline_response - ) + deserialized = self._deserialize("CommunicationIdentityAccessTokenResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) @@ -199,9 +175,7 @@ async def create( return deserialized @distributed_trace_async - async def delete( - self, id: str, **kwargs: Any - ) -> None: # pylint: disable=inconsistent-return-statements + async def delete(self, id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """Delete the identity, revoke all tokens for the identity and delete all associated data. Delete the identity, revoke all tokens for the identity and delete all associated data. @@ -232,17 +206,13 @@ async def delete( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = ( - await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -250,12 +220,8 @@ async def delete( if response.status_code not in [204]: if _stream: await response.read() # Load the body in memory and close the socket - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) - error = self._deserialize.failsafe_deserialize( - _models.CommunicationErrorResponse, pipeline_response - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) if cls: @@ -295,17 +261,13 @@ async def revoke_access_tokens( # pylint: disable=inconsistent-return-statement params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = ( - await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -313,12 +275,8 @@ async def revoke_access_tokens( # pylint: disable=inconsistent-return-statement if response.status_code not in [204]: if _stream: await response.read() # Load the body in memory and close the socket - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) - error = self._deserialize.failsafe_deserialize( - _models.CommunicationErrorResponse, pipeline_response - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) if cls: @@ -326,11 +284,7 @@ async def revoke_access_tokens( # pylint: disable=inconsistent-return-statement @overload async def exchange_teams_user_access_token( - self, - body: _models.TeamsUserExchangeTokenRequest, - *, - content_type: str = "application/json", - **kwargs: Any + self, body: _models.TeamsUserExchangeTokenRequest, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CommunicationIdentityAccessToken: """Exchange an Azure Active Directory (Azure AD) access token of a Teams user for a new Communication Identity access token with a matching expiration time. @@ -399,9 +353,7 @@ async def exchange_teams_user_access_token( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", None) - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.CommunicationIdentityAccessToken] = kwargs.pop("cls", None) content_type = content_type or "application/json" @@ -421,17 +373,13 @@ async def exchange_teams_user_access_token( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = ( - await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -439,17 +387,11 @@ async def exchange_teams_user_access_token( if response.status_code not in [200]: if _stream: await response.read() # Load the body in memory and close the socket - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) - error = self._deserialize.failsafe_deserialize( - _models.CommunicationErrorResponse, pipeline_response - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize( - "CommunicationIdentityAccessToken", pipeline_response - ) + deserialized = self._deserialize("CommunicationIdentityAccessToken", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) @@ -483,12 +425,7 @@ async def issue_access_token( @overload async def issue_access_token( - self, - id: str, - body: IO, - *, - content_type: str = "application/json", - **kwargs: Any + self, id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.CommunicationIdentityAccessToken: """Issue a new token for an identity. @@ -508,10 +445,7 @@ async def issue_access_token( @distributed_trace_async async def issue_access_token( - self, - id: str, - body: Union[_models.CommunicationIdentityAccessTokenRequest, IO], - **kwargs: Any + self, id: str, body: Union[_models.CommunicationIdentityAccessTokenRequest, IO], **kwargs: Any ) -> _models.CommunicationIdentityAccessToken: """Issue a new token for an identity. @@ -540,9 +474,7 @@ async def issue_access_token( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", None) - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.CommunicationIdentityAccessToken] = kwargs.pop("cls", None) content_type = content_type or "application/json" @@ -551,9 +483,7 @@ async def issue_access_token( if isinstance(body, (IOBase, bytes)): _content = body else: - _json = self._serialize.body( - body, "CommunicationIdentityAccessTokenRequest" - ) + _json = self._serialize.body(body, "CommunicationIdentityAccessTokenRequest") request = build_communication_identity_issue_access_token_request( id=id, @@ -565,17 +495,13 @@ async def issue_access_token( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = ( - await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -583,17 +509,11 @@ async def issue_access_token( if response.status_code not in [200]: if _stream: await response.read() # Load the body in memory and close the socket - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) - error = self._deserialize.failsafe_deserialize( - _models.CommunicationErrorResponse, pipeline_response - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize( - "CommunicationIdentityAccessToken", pipeline_response - ) + deserialized = self._deserialize("CommunicationIdentityAccessToken", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/operations/_patch.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/operations/_patch.py index d400d2d124e2..f7dd32510333 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/operations/_patch.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/aio/operations/_patch.py @@ -8,9 +8,7 @@ """ from typing import List -__all__: List[ - str -] = [] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/models/_models.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/models/_models.py index 94d0df20019d..a9f24485d60b 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/models/_models.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/models/_models.py @@ -109,9 +109,7 @@ class CommunicationIdentity(_serialization.Model): "id": {"key": "id", "type": "str"}, } - def __init__( - self, *, id: str, **kwargs: Any - ) -> None: # pylint: disable=redefined-builtin + def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin """ :keyword id: Identifier of the identity. Required. :paramtype id: str @@ -258,9 +256,7 @@ class CommunicationIdentityCreateRequest(_serialization.Model): def __init__( self, *, - create_token_with_scopes: Optional[ - List[Union[str, "_models.CommunicationTokenScope"]] - ] = None, + create_token_with_scopes: Optional[List[Union[str, "_models.CommunicationTokenScope"]]] = None, expires_in_minutes: int = 1440, **kwargs: Any ) -> None: diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/models/_patch.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/models/_patch.py index d400d2d124e2..f7dd32510333 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/models/_patch.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/models/_patch.py @@ -8,9 +8,7 @@ """ from typing import List -__all__: List[ - str -] = [] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/operations/_operations.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/operations/_operations.py index 78ac9e7b6fcd..a60d0262ba38 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/operations/_operations.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/operations/_operations.py @@ -26,9 +26,7 @@ from .._serialization import Serializer T = TypeVar("T") -ClsType = Optional[ - Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any] -] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -40,12 +38,8 @@ def build_communication_identity_create_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", None) - ) - api_version: str = kwargs.pop( - "api_version", _params.pop("api-version", "2023-10-01") - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -56,25 +50,17 @@ def build_communication_identity_create_request( # Construct headers if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header( - "content_type", content_type, "str" - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", url=_url, params=_params, headers=_headers, **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_communication_identity_delete_request( - id: str, **kwargs: Any -) -> HttpRequest: # pylint: disable=name-too-long +def build_communication_identity_delete_request(id: str, **kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop( - "api_version", _params.pop("api-version", "2023-10-01") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -91,9 +77,7 @@ def build_communication_identity_delete_request( # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", url=_url, params=_params, headers=_headers, **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_communication_identity_revoke_access_tokens_request( # pylint: disable=name-too-long @@ -102,9 +86,7 @@ def build_communication_identity_revoke_access_tokens_request( # pylint: disabl _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop( - "api_version", _params.pop("api-version", "2023-10-01") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -121,9 +103,7 @@ def build_communication_identity_revoke_access_tokens_request( # pylint: disabl # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", url=_url, params=_params, headers=_headers, **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_communication_identity_exchange_teams_user_access_token_request( # pylint: disable=name-too-long @@ -132,12 +112,8 @@ def build_communication_identity_exchange_teams_user_access_token_request( # py _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", None) - ) - api_version: str = kwargs.pop( - "api_version", _params.pop("api-version", "2023-10-01") - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -148,14 +124,10 @@ def build_communication_identity_exchange_teams_user_access_token_request( # py # Construct headers if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header( - "content_type", content_type, "str" - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", url=_url, params=_params, headers=_headers, **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_communication_identity_issue_access_token_request( # pylint: disable=name-too-long @@ -164,12 +136,8 @@ def build_communication_identity_issue_access_token_request( # pylint: disable= _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", None) - ) - api_version: str = kwargs.pop( - "api_version", _params.pop("api-version", "2023-10-01") - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -185,14 +153,10 @@ def build_communication_identity_issue_access_token_request( # pylint: disable= # Construct headers if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header( - "content_type", content_type, "str" - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", url=_url, params=_params, headers=_headers, **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class CommunicationIdentityOperations: @@ -212,9 +176,7 @@ def __init__(self, *args, **kwargs): self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = ( - input_args.pop(0) if input_args else kwargs.pop("deserializer") - ) + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload def create( @@ -294,12 +256,8 @@ def create( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", None) - ) - cls: ClsType[_models.CommunicationIdentityAccessTokenResult] = kwargs.pop( - "cls", None - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CommunicationIdentityAccessTokenResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -321,17 +279,13 @@ def create( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = ( - self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -339,17 +293,11 @@ def create( if response.status_code not in [201]: if _stream: response.read() # Load the body in memory and close the socket - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) - error = self._deserialize.failsafe_deserialize( - _models.CommunicationErrorResponse, pipeline_response - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize( - "CommunicationIdentityAccessTokenResult", pipeline_response - ) + deserialized = self._deserialize("CommunicationIdentityAccessTokenResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) @@ -357,9 +305,7 @@ def create( return deserialized @distributed_trace - def delete( - self, id: str, **kwargs: Any - ) -> None: # pylint: disable=inconsistent-return-statements + def delete(self, id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """Delete the identity, revoke all tokens for the identity and delete all associated data. Delete the identity, revoke all tokens for the identity and delete all associated data. @@ -390,17 +336,13 @@ def delete( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = ( - self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -408,21 +350,15 @@ def delete( if response.status_code not in [204]: if _stream: response.read() # Load the body in memory and close the socket - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) - error = self._deserialize.failsafe_deserialize( - _models.CommunicationErrorResponse, pipeline_response - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) if cls: return cls(pipeline_response, None, {}) @distributed_trace - def revoke_access_tokens( - self, id: str, **kwargs: Any - ) -> None: # pylint: disable=inconsistent-return-statements + def revoke_access_tokens(self, id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """Revoke all access tokens for the specific identity. Revoke all access tokens for the specific identity. @@ -453,17 +389,13 @@ def revoke_access_tokens( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = ( - self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -471,12 +403,8 @@ def revoke_access_tokens( if response.status_code not in [204]: if _stream: response.read() # Load the body in memory and close the socket - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) - error = self._deserialize.failsafe_deserialize( - _models.CommunicationErrorResponse, pipeline_response - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) if cls: @@ -557,9 +485,7 @@ def exchange_teams_user_access_token( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", None) - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.CommunicationIdentityAccessToken] = kwargs.pop("cls", None) content_type = content_type or "application/json" @@ -579,17 +505,13 @@ def exchange_teams_user_access_token( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = ( - self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -597,17 +519,11 @@ def exchange_teams_user_access_token( if response.status_code not in [200]: if _stream: response.read() # Load the body in memory and close the socket - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) - error = self._deserialize.failsafe_deserialize( - _models.CommunicationErrorResponse, pipeline_response - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize( - "CommunicationIdentityAccessToken", pipeline_response - ) + deserialized = self._deserialize("CommunicationIdentityAccessToken", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) @@ -698,9 +614,7 @@ def issue_access_token( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", None) - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.CommunicationIdentityAccessToken] = kwargs.pop("cls", None) content_type = content_type or "application/json" @@ -709,9 +623,7 @@ def issue_access_token( if isinstance(body, (IOBase, bytes)): _content = body else: - _json = self._serialize.body( - body, "CommunicationIdentityAccessTokenRequest" - ) + _json = self._serialize.body(body, "CommunicationIdentityAccessTokenRequest") request = build_communication_identity_issue_access_token_request( id=id, @@ -723,17 +635,13 @@ def issue_access_token( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) _stream = False - pipeline_response: PipelineResponse = ( - self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -741,17 +649,11 @@ def issue_access_token( if response.status_code not in [200]: if _stream: response.read() # Load the body in memory and close the socket - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) - error = self._deserialize.failsafe_deserialize( - _models.CommunicationErrorResponse, pipeline_response - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize( - "CommunicationIdentityAccessToken", pipeline_response - ) + deserialized = self._deserialize("CommunicationIdentityAccessToken", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/operations/_patch.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/operations/_patch.py index d400d2d124e2..f7dd32510333 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/operations/_patch.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_generated/operations/_patch.py @@ -8,9 +8,7 @@ """ from typing import List -__all__: List[ - str -] = [] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/auth_policy_utils.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/auth_policy_utils.py index 08adcbbee6f4..3789d8a8b98f 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/auth_policy_utils.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/auth_policy_utils.py @@ -43,9 +43,7 @@ def get_authentication_policy( return AsyncBearerTokenCredentialPolicy( credential, "https://communication.azure.com//.default" # type: ignore ) - return BearerTokenCredentialPolicy( - credential, "https://communication.azure.com//.default" # type: ignore - ) + return BearerTokenCredentialPolicy(credential, "https://communication.azure.com//.default") # type: ignore if isinstance(credential, (AzureKeyCredential, str)): return HMACCredentialsPolicy(endpoint, credential, decode_url=decode_url) diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/models.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/models.py index 7b646472045c..43875e1197e5 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/models.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/models.py @@ -14,8 +14,11 @@ class DeprecatedEnumMeta(CaseInsensitiveEnumMeta): def __getattribute__(cls, item): if item.upper() == "MICROSOFT_BOT": - warnings.warn("MICROSOFT_BOT is deprecated and has been replaced by \ - MICROSOFT_TEAMS_APP identifier.", DeprecationWarning) + warnings.warn( + "MICROSOFT_BOT is deprecated and has been replaced by \ + MICROSOFT_TEAMS_APP identifier.", + DeprecationWarning, + ) item = "MICROSOFT_TEAMS_APP" return super().__getattribute__(item) @@ -47,14 +50,17 @@ class CommunicationCloudEnvironment(str, Enum, metaclass=CaseInsensitiveEnumMeta @runtime_checkable class CommunicationIdentifier(Protocol): """Communication Identifier.""" + @property def raw_id(self) -> str: """The raw ID of the identifier.""" ... + @property def kind(self) -> CommunicationIdentifierKind: """The type of identifier.""" ... + @property def properties(self) -> Mapping[str, Any]: """The properties of the identifier.""" @@ -83,12 +89,14 @@ def properties(self) -> Mapping[str, Any]: class CommunicationUserProperties(TypedDict): """Dictionary of properties for a CommunicationUserIdentifier.""" + id: str """ID of the Communication user as returned from Azure Communication Identity.""" class CommunicationUserIdentifier: """Represents a user in Azure Communication Service.""" + kind: Literal[CommunicationIdentifierKind.COMMUNICATION_USER] = CommunicationIdentifierKind.COMMUNICATION_USER """The type of identifier.""" properties: CommunicationUserProperties @@ -116,12 +124,14 @@ def __eq__(self, other): class PhoneNumberProperties(TypedDict): """Dictionary of properties for a PhoneNumberIdentifier.""" + value: str """The phone number in E.164 format.""" class PhoneNumberIdentifier: """Represents a phone number.""" + kind: Literal[CommunicationIdentifierKind.PHONE_NUMBER] = CommunicationIdentifierKind.PHONE_NUMBER """The type of identifier.""" properties: PhoneNumberProperties @@ -165,6 +175,7 @@ class UnknownIdentifier: It is not advisable to rely on the `kind` property with a value `unknown`, as it could become a new or existing distinct type in the future. """ + kind: Literal[CommunicationIdentifierKind.UNKNOWN] = CommunicationIdentifierKind.UNKNOWN """The type of identifier.""" properties: Mapping[str, Any] @@ -188,6 +199,7 @@ def __eq__(self, other): class MicrosoftTeamsUserProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsUserIdentifier.""" + user_id: str """The id of the Microsoft Teams user. If the user isn't anonymous, the id is the AAD object id of the user.""" is_anonymous: bool @@ -198,6 +210,7 @@ class MicrosoftTeamsUserProperties(TypedDict): class MicrosoftTeamsUserIdentifier: """Represents an identifier for a Microsoft Teams user.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_USER] = CommunicationIdentifierKind.MICROSOFT_TEAMS_USER """The type of identifier.""" properties: MicrosoftTeamsUserProperties @@ -246,6 +259,7 @@ def _format_raw_id(self, properties: MicrosoftTeamsUserProperties) -> str: class MicrosoftTeamsAppProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsAppIdentifier.""" + app_id: str """The id of the Microsoft Teams application.""" cloud: Union[CommunicationCloudEnvironment, str] @@ -254,6 +268,7 @@ class MicrosoftTeamsAppProperties(TypedDict): class _botbackcompatdict(dict): """Backwards compatible properties.""" + def __getitem__(self, __key: Any) -> Any: try: return super().__getitem__(__key) @@ -267,6 +282,7 @@ def __getitem__(self, __key: Any) -> Any: class MicrosoftTeamsAppIdentifier: """Represents an identifier for a Microsoft Teams application.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_APP] = CommunicationIdentifierKind.MICROSOFT_TEAMS_APP """The type of identifier.""" properties: MicrosoftTeamsAppProperties @@ -282,10 +298,13 @@ def __init__(self, app_id: str, **kwargs: Any) -> None: :keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed from the other properties. """ - self.properties = cast(MicrosoftTeamsAppProperties, _botbackcompatdict( - app_id=app_id, - cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, - )) + self.properties = cast( + MicrosoftTeamsAppProperties, + _botbackcompatdict( + app_id=app_id, + cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, + ), + ) raw_id: Optional[str] = kwargs.get("raw_id") self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties) @@ -323,7 +342,7 @@ def __init__(self, bot_id, **kwargs): """ warnings.warn( "The MicrosoftBotIdentifier is deprecated and has been replaced by MicrosoftTeamsAppIdentifier.", - DeprecationWarning + DeprecationWarning, ) super().__init__(bot_id, **kwargs) @@ -339,9 +358,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d :rtype: CommunicationIdentifier """ if raw_id.startswith(PHONE_NUMBER_PREFIX): - return PhoneNumberIdentifier( - value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id - ) + return PhoneNumberIdentifier(value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id) segments = raw_id.split(":", maxsplit=2) if len(segments) < 3: @@ -350,9 +367,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d prefix = f"{segments[0]}:{segments[1]}:" suffix = segments[2] if prefix == TEAMS_USER_ANONYMOUS_PREFIX: - return MicrosoftTeamsUserIdentifier( - user_id=suffix, is_anonymous=True, raw_id=raw_id - ) + return MicrosoftTeamsUserIdentifier(user_id=suffix, is_anonymous=True, raw_id=raw_id) if prefix == TEAMS_USER_PUBLIC_CLOUD_PREFIX: return MicrosoftTeamsUserIdentifier( user_id=suffix, diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/policy.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/policy.py index 2fd2e7426c73..79aa48136fd3 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/policy.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/policy.py @@ -50,9 +50,7 @@ def _compute_hmac( else: decoded_secret = base64.b64decode(self._access_key) - digest = hmac.new( - decoded_secret, value.encode("utf-8"), hashlib.sha256 - ).digest() + digest = hmac.new(decoded_secret, value.encode("utf-8"), hashlib.sha256).digest() return base64.b64encode(digest).decode("utf-8") @@ -101,22 +99,10 @@ def _sign_request(self, request): utc_now = get_current_utc_time() if request.http_request.body is None: request.http_request.body = "" - content_digest = hashlib.sha256( - (request.http_request.body.encode("utf-8")) - ).digest() + content_digest = hashlib.sha256((request.http_request.body.encode("utf-8"))).digest() content_hash = base64.b64encode(content_digest).decode("utf-8") - string_to_sign = ( - verb - + "\n" - + query_url - + "\n" - + utc_now - + ";" - + self._host - + ";" - + content_hash - ) + string_to_sign = verb + "\n" + query_url + "\n" + utc_now + ";" + self._host + ";" + content_hash signature = self._compute_hmac(string_to_sign) @@ -124,10 +110,7 @@ def _sign_request(self, request): "x-ms-date": utc_now, "x-ms-content-sha256": content_hash, "x-ms-return-client-request-id": "true", - "Authorization": "HMAC-SHA256 SignedHeaders=" - + signed_headers - + "&Signature=" - + signature, + "Authorization": "HMAC-SHA256 SignedHeaders=" + signed_headers + "&Signature=" + signature, } request.http_request.headers.update(signature_header) diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/user_credential.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/user_credential.py index c7c150052918..54603e7b32ce 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/user_credential.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/user_credential.py @@ -38,9 +38,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._lock = Condition(Lock()) self._some_thread_refreshing = False @@ -54,9 +52,7 @@ def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -80,9 +76,7 @@ def _update_token_and_reschedule(self): try: new_token = self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -109,12 +103,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() if timespan <= TIMEOUT_MAX: self._timer = Timer(timespan, self._update_token_and_reschedule) self._timer.daemon = True diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/user_credential_async.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/user_credential_async.py index dcd934aba464..15ad17da1a8c 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/user_credential_async.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/user_credential_async.py @@ -40,9 +40,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._async_mutex = Lock() if sys.version_info[:3] == (3, 10, 0): @@ -60,9 +58,7 @@ async def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -86,9 +82,7 @@ async def _update_token_and_reschedule(self): try: new_token = await self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") async with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -115,12 +109,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() self._timer = AsyncTimer(timespan, self._update_token_and_reschedule) self._timer.start() diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/utils.py b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/utils.py index 47da8a283e5f..8576c31ddc56 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/utils.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/_shared/utils.py @@ -87,9 +87,7 @@ def create_access_token(token): payload = json.loads(padded_base64_payload) return AccessToken( token, - _convert_datetime_to_utc_int( - datetime.fromtimestamp(payload["exp"], TZ_UTC) - ), + _convert_datetime_to_utc_int(datetime.fromtimestamp(payload["exp"], TZ_UTC)), ) except ValueError as val_error: raise ValueError(token_parse_err_msg) from val_error diff --git a/sdk/communication/azure-communication-identity/azure/communication/identity/aio/_communication_identity_client_async.py b/sdk/communication/azure-communication-identity/azure/communication/identity/aio/_communication_identity_client_async.py index 35a826db1d72..2e4e7ba182cd 100644 --- a/sdk/communication/azure-communication-identity/azure/communication/identity/aio/_communication_identity_client_async.py +++ b/sdk/communication/azure-communication-identity/azure/communication/identity/aio/_communication_identity_client_async.py @@ -40,12 +40,7 @@ class CommunicationIdentityClient: :language: python """ - def __init__( - self, - endpoint: str, - credential: Union[AsyncTokenCredential, AzureKeyCredential], - **kwargs - ) -> None: + def __init__(self, endpoint: str, credential: Union[AsyncTokenCredential, AzureKeyCredential], **kwargs) -> None: try: if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint @@ -60,17 +55,13 @@ def __init__( self._identity_service_client = CommunicationIdentityClientGen( self._endpoint, api_version=self._api_version, - authentication_policy=get_authentication_policy( - endpoint, credential, decode_url=True, is_async=True - ), + authentication_policy=get_authentication_policy(endpoint, credential, decode_url=True, is_async=True), sdk_moniker=SDK_MONIKER, **kwargs ) @classmethod - def from_connection_string( - cls, conn_str: str, **kwargs - ) -> "CommunicationIdentityClient": + def from_connection_string(cls, conn_str: str, **kwargs) -> "CommunicationIdentityClient": """Create CommunicationIdentityClient from a Connection String. :param str conn_str: @@ -91,13 +82,9 @@ async def create_user(self, **kwargs) -> "CommunicationUserIdentifier": :return: CommunicationUserIdentifier :rtype: ~azure.communication.identity.CommunicationUserIdentifier """ - identity_access_token = ( - await self._identity_service_client.communication_identity.create(**kwargs) - ) + identity_access_token = await self._identity_service_client.communication_identity.create(**kwargs) - return CommunicationUserIdentifier( - identity_access_token.identity.id, raw_id=identity_access_token.identity.id - ) + return CommunicationUserIdentifier(identity_access_token.identity.id, raw_id=identity_access_token.identity.id) @distributed_trace_async async def create_user_and_token( @@ -145,16 +132,11 @@ async def delete_user(self, user: CommunicationUserIdentifier, **kwargs) -> None :return: None :rtype: None """ - await self._identity_service_client.communication_identity.delete( - user.properties["id"], **kwargs - ) + await self._identity_service_client.communication_identity.delete(user.properties["id"], **kwargs) @distributed_trace_async async def get_token( - self, - user: CommunicationUserIdentifier, - scopes: List[Union[str, "CommunicationTokenScope"]], - **kwargs + self, user: CommunicationUserIdentifier, scopes: List[Union[str, "CommunicationTokenScope"]], **kwargs ) -> AccessToken: """Generates a new token for an identity. diff --git a/sdk/communication/azure-communication-identity/samples/identity_samples.py b/sdk/communication/azure-communication-identity/samples/identity_samples.py index 85422a0f0a51..781afd26041c 100644 --- a/sdk/communication/azure-communication-identity/samples/identity_samples.py +++ b/sdk/communication/azure-communication-identity/samples/identity_samples.py @@ -49,25 +49,15 @@ def get_token(self): CommunicationTokenScope, ) - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): - + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: + endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, get_credential() - ) + identity_client = CommunicationIdentityClient(endpoint, get_credential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) user = identity_client.create_user() print(f"Getting token for: {user.properties.get('id')}") - tokenresponse = identity_client.get_token( - user, scopes=[CommunicationTokenScope.CHAT] - ) + tokenresponse = identity_client.get_token(user, scopes=[CommunicationTokenScope.CHAT]) print(f"Token issued with value: {tokenresponse.token}") def get_token_with_custom_expiration(self): @@ -76,20 +66,12 @@ def get_token_with_custom_expiration(self): CommunicationTokenScope, ) - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): - + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: + endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, get_credential() - ) + identity_client = CommunicationIdentityClient(endpoint, get_credential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) user = identity_client.create_user() print(f"Getting token for: {user.properties.get('id')}") token_expires_in = timedelta(hours=1) @@ -106,24 +88,14 @@ def revoke_tokens(self): CommunicationTokenScope, ) - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): - + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: + endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, get_credential() - ) + identity_client = CommunicationIdentityClient(endpoint, get_credential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) user = identity_client.create_user() - tokenresponse = identity_client.get_token( - user, scopes=[CommunicationTokenScope.CHAT] - ) + tokenresponse = identity_client.get_token(user, scopes=[CommunicationTokenScope.CHAT]) print(f"Revoking token: {tokenresponse.token}") identity_client.revoke_tokens(user) print(f"{tokenresponse.token} revoked successfully") @@ -131,20 +103,12 @@ def revoke_tokens(self): def create_user(self): from azure.communication.identity import CommunicationIdentityClient - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): - + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: + endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, get_credential() - ) + identity_client = CommunicationIdentityClient(endpoint, get_credential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) print("Creating new user") user = identity_client.create_user() print(f"User created with id: {user.properties.get('id')}") @@ -155,24 +119,14 @@ def create_user_and_token(self): CommunicationTokenScope, ) - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): - + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: + endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, get_credential() - ) + identity_client = CommunicationIdentityClient(endpoint, get_credential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) print("Creating new user with token") - user, tokenresponse = identity_client.create_user_and_token( - scopes=[CommunicationTokenScope.CHAT] - ) + user, tokenresponse = identity_client.create_user_and_token(scopes=[CommunicationTokenScope.CHAT]) print(f"User created with id: {user.properties.get('id')}") print(f"Token issued with value: {tokenresponse.token}") @@ -182,20 +136,12 @@ def create_user_and_token_with_custom_expiration(self): CommunicationTokenScope, ) - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): - + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: + endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, get_credential() - ) + identity_client = CommunicationIdentityClient(endpoint, get_credential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) print("Creating new user with token") token_expires_in = timedelta(hours=1) user, tokenresponse = identity_client.create_user_and_token( @@ -207,20 +153,12 @@ def create_user_and_token_with_custom_expiration(self): def delete_user(self): from azure.communication.identity import CommunicationIdentityClient - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): - + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: + endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, get_credential() - ) + identity_client = CommunicationIdentityClient(endpoint, get_credential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) user = identity_client.create_user() print(f"Deleting user: {user.properties.get('id')}") identity_client.delete_user(user) @@ -232,20 +170,12 @@ def get_token_for_teams_user(self): return from azure.communication.identity import CommunicationIdentityClient - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): - + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: + endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, get_credential() - ) + identity_client = CommunicationIdentityClient(endpoint, get_credential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) msal_app = PublicClientApplication( client_id=self.m365_client_id, @@ -262,9 +192,7 @@ def get_token_for_teams_user(self): teams_user_oid = result["id_token_claims"]["oid"] print(f"AAD access token of a Teams User: {aad_token}") - tokenresponse = identity_client.get_token_for_teams_user( - aad_token, self.m365_client_id, teams_user_oid - ) + tokenresponse = identity_client.get_token_for_teams_user(aad_token, self.m365_client_id, teams_user_oid) print(f"Token issued with value: {tokenresponse.token}") diff --git a/sdk/communication/azure-communication-identity/samples/identity_samples_async.py b/sdk/communication/azure-communication-identity/samples/identity_samples_async.py index 268573ab1aef..b7f74a8f2c7b 100644 --- a/sdk/communication/azure-communication-identity/samples/identity_samples_async.py +++ b/sdk/communication/azure-communication-identity/samples/identity_samples_async.py @@ -49,49 +49,31 @@ async def get_token(self): from azure.communication.identity.aio import CommunicationIdentityClient from azure.communication.identity import CommunicationTokenScope - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: from azure.identity.aio import DefaultAzureCredential endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, DefaultAzureCredential() - ) + identity_client = CommunicationIdentityClient(endpoint, DefaultAzureCredential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) async with identity_client: user = await identity_client.create_user() print(f"Issuing token for: {user.properties.get('id')}") - tokenresponse = await identity_client.get_token( - user, scopes=[CommunicationTokenScope.CHAT] - ) + tokenresponse = await identity_client.get_token(user, scopes=[CommunicationTokenScope.CHAT]) print(f"Token issued with value: {tokenresponse.token}") async def get_token_with_custom_expiration(self): from azure.communication.identity.aio import CommunicationIdentityClient from azure.communication.identity import CommunicationTokenScope - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: from azure.identity.aio import DefaultAzureCredential endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, DefaultAzureCredential() - ) + identity_client = CommunicationIdentityClient(endpoint, DefaultAzureCredential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) async with identity_client: user = await identity_client.create_user() @@ -108,27 +90,17 @@ async def revoke_tokens(self): from azure.communication.identity.aio import CommunicationIdentityClient from azure.communication.identity import CommunicationTokenScope - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: from azure.identity.aio import DefaultAzureCredential endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, DefaultAzureCredential() - ) + identity_client = CommunicationIdentityClient(endpoint, DefaultAzureCredential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) async with identity_client: user = await identity_client.create_user() - tokenresponse = await identity_client.get_token( - user, scopes=[CommunicationTokenScope.CHAT] - ) + tokenresponse = await identity_client.get_token(user, scopes=[CommunicationTokenScope.CHAT]) print(f"Revoking token: {tokenresponse.token}") await identity_client.revoke_tokens(user) print(f"{tokenresponse.token} revoked successfully") @@ -136,21 +108,13 @@ async def revoke_tokens(self): async def create_user(self): from azure.communication.identity.aio import CommunicationIdentityClient - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: from azure.identity.aio import DefaultAzureCredential endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, DefaultAzureCredential() - ) + identity_client = CommunicationIdentityClient(endpoint, DefaultAzureCredential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) async with identity_client: print("Creating new user") @@ -161,27 +125,17 @@ async def create_user_and_token(self): from azure.communication.identity.aio import CommunicationIdentityClient from azure.communication.identity import CommunicationTokenScope - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: from azure.identity.aio import DefaultAzureCredential endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, DefaultAzureCredential() - ) + identity_client = CommunicationIdentityClient(endpoint, DefaultAzureCredential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) async with identity_client: print("Creating new user with token") - user, tokenresponse = await identity_client.create_user_and_token( - scopes=[CommunicationTokenScope.CHAT] - ) + user, tokenresponse = await identity_client.create_user_and_token(scopes=[CommunicationTokenScope.CHAT]) print(f"User created with id: {user.properties.get('id')}") print(f"Token issued with value: {tokenresponse.token}") @@ -189,21 +143,13 @@ async def create_user_and_token_with_custom_expiration(self): from azure.communication.identity.aio import CommunicationIdentityClient from azure.communication.identity import CommunicationTokenScope - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: from azure.identity.aio import DefaultAzureCredential endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, DefaultAzureCredential() - ) + identity_client = CommunicationIdentityClient(endpoint, DefaultAzureCredential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) async with identity_client: print("Creating new user with token") @@ -217,21 +163,13 @@ async def create_user_and_token_with_custom_expiration(self): async def delete_user(self): from azure.communication.identity.aio import CommunicationIdentityClient - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: from azure.identity.aio import DefaultAzureCredential endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, DefaultAzureCredential() - ) + identity_client = CommunicationIdentityClient(endpoint, DefaultAzureCredential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) async with identity_client: user = await identity_client.create_user() @@ -245,21 +183,13 @@ async def get_token_for_teams_user(self): return from azure.communication.identity.aio import CommunicationIdentityClient - if ( - self.client_id is not None - and self.client_secret is not None - and self.tenant_id is not None - ): + if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None: from azure.identity.aio import DefaultAzureCredential endpoint, _ = parse_connection_str(self.connection_string) - identity_client = CommunicationIdentityClient( - endpoint, DefaultAzureCredential() - ) + identity_client = CommunicationIdentityClient(endpoint, DefaultAzureCredential()) else: - identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string - ) + identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) async with identity_client: msal_app = PublicClientApplication( diff --git a/sdk/communication/azure-communication-identity/setup.py b/sdk/communication/azure-communication-identity/setup.py index 8ea708be45e4..20933d51cdd3 100644 --- a/sdk/communication/azure-communication-identity/setup.py +++ b/sdk/communication/azure-communication-identity/setup.py @@ -20,9 +20,7 @@ # Version extraction inspired from 'requests' with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: - version = re.search( - r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE - ).group(1) + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError("Cannot find version information") @@ -32,9 +30,7 @@ setup( name=PACKAGE_NAME, version=version, - description="Microsoft Azure {} Client Library for Python".format( - PACKAGE_PPRINT_NAME - ), + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), long_description_content_type="text/markdown", # ensure that these are updated to reflect the package owners' information long_description=long_description, diff --git a/sdk/communication/azure-communication-identity/tests/_shared/utils.py b/sdk/communication/azure-communication-identity/tests/_shared/utils.py index 955346bee1a6..69a0d2586209 100644 --- a/sdk/communication/azure-communication-identity/tests/_shared/utils.py +++ b/sdk/communication/azure-communication-identity/tests/_shared/utils.py @@ -20,7 +20,7 @@ def create_token_credential(): from .fake_token_credential import FakeTokenCredential return FakeTokenCredential() - + return get_credential() @@ -32,7 +32,7 @@ def async_create_token_credential(): from .async_fake_token_credential import AsyncFakeTokenCredential return AsyncFakeTokenCredential() - + return get_credential(is_async=True) diff --git a/sdk/communication/azure-communication-identity/tests/acs_identity_test_case.py b/sdk/communication/azure-communication-identity/tests/acs_identity_test_case.py index aff36719c651..e4b4d7879413 100644 --- a/sdk/communication/azure-communication-identity/tests/acs_identity_test_case.py +++ b/sdk/communication/azure-communication-identity/tests/acs_identity_test_case.py @@ -13,9 +13,7 @@ class ACSIdentityTestCase(AzureRecordedTestCase): def setUp(self): if is_live(): - self.connection_str = os.getenv( - "COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING" - ) + self.connection_str = os.getenv("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING") self.m365_client_id = os.getenv("COMMUNICATION_M365_APP_ID") self.m365_aad_authority = os.getenv("COMMUNICATION_M365_AAD_AUTHORITY") self.m365_aad_tenant = os.getenv("COMMUNICATION_M365_AAD_TENANT") @@ -24,13 +22,9 @@ def setUp(self): self.expired_teams_token = os.getenv("COMMUNICATION_EXPIRED_TEAMS_TOKEN") self.endpoint, _ = parse_connection_str(self.connection_str) self._resource_name = self.endpoint.split(".")[0] - self.skip_get_token_for_teams_user_tests = os.getenv( - "SKIP_INT_IDENTITY_EXCHANGE_TOKEN_TEST" - ) + self.skip_get_token_for_teams_user_tests = os.getenv("SKIP_INT_IDENTITY_EXCHANGE_TOKEN_TEST") else: - self.connection_str = ( - "endpoint=https://sanitized.communication.azure.com/;accesskey=fake===" - ) + self.connection_str = "endpoint=https://sanitized.communication.azure.com/;accesskey=fake===" self.endpoint, _ = parse_connection_str(self.connection_str) self.m365_client_id = "sanitized" self.m365_aad_authority = "sanitized" diff --git a/sdk/communication/azure-communication-identity/tests/conftest.py b/sdk/communication/azure-communication-identity/tests/conftest.py index 02e31a2b9424..7ca768fcac7a 100644 --- a/sdk/communication/azure-communication-identity/tests/conftest.py +++ b/sdk/communication/azure-communication-identity/tests/conftest.py @@ -47,9 +47,7 @@ def add_sanitizers(test_proxy): connection_str = os.environ.get("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING") if connection_str is not None: endpoint, _ = parse_connection_str(connection_str) - add_general_string_sanitizer( - target=endpoint, value="sanitized.communication.azure.com" - ) + add_general_string_sanitizer(target=endpoint, value="sanitized.communication.azure.com") msal_username = os.environ.get("COMMUNICATION_MSAL_USERNAME", "sanitized") add_general_regex_sanitizer(regex=msal_username, value="sanitized") @@ -57,9 +55,7 @@ def add_sanitizers(test_proxy): msal_password = os.environ.get("COMMUNICATION_MSAL_PASSWORD", "sanitized") add_general_regex_sanitizer(regex=msal_password, value="sanitized") - expired_teams_token = os.environ.get( - "COMMUNICATION_EXPIRED_TEAMS_TOKEN", "sanitized" - ) + expired_teams_token = os.environ.get("COMMUNICATION_EXPIRED_TEAMS_TOKEN", "sanitized") add_general_regex_sanitizer(regex=expired_teams_token, value="sanitized") add_body_key_sanitizer(json_path="*.id", value="sanitized") @@ -70,12 +66,8 @@ def add_sanitizers(test_proxy): add_body_key_sanitizer(json_path="*.domain_name", value="sanitized") add_body_key_sanitizer(json_path="appId", value="sanitized") - add_general_regex_sanitizer( - regex="/identities/([^/?]+)", value="/identities/sanitized" - ) - add_general_regex_sanitizer( - regex="common/userrealm/([^/.]+)", value="common/userrealm/sanitized@test" - ) + add_general_regex_sanitizer(regex="/identities/([^/?]+)", value="/identities/sanitized") + add_general_regex_sanitizer(regex="common/userrealm/([^/.]+)", value="common/userrealm/sanitized@test") add_header_regex_sanitizer(key="P3P", value="sanitized") add_header_regex_sanitizer(key="Set-Cookie", value="sanitized") @@ -89,6 +81,4 @@ def add_sanitizers(test_proxy): add_header_regex_sanitizer(key="x-ms-date", value="sanitized") add_header_regex_sanitizer(key="x-ms-ests-server", value="sanitized") add_header_regex_sanitizer(key="x-ms-request-id", value="sanitized") - add_header_regex_sanitizer( - key="Content-Security-Policy-Report-Only", value="sanitized" - ) + add_header_regex_sanitizer(key="Content-Security-Policy-Report-Only", value="sanitized") diff --git a/sdk/communication/azure-communication-identity/tests/test_communication_identity_client.py b/sdk/communication/azure-communication-identity/tests/test_communication_identity_client.py index 35f298611983..ef9411b614da 100644 --- a/sdk/communication/azure-communication-identity/tests/test_communication_identity_client.py +++ b/sdk/communication/azure-communication-identity/tests/test_communication_identity_client.py @@ -37,9 +37,7 @@ def create_client_from_token_credential(self): credential = FakeTokenCredential() else: credential = get_credential() - return CommunicationIdentityClient( - self.endpoint, credential, http_logging_policy=get_http_logging_policy() - ) + return CommunicationIdentityClient(self.endpoint, credential, http_logging_policy=get_http_logging_policy()) @recorded_by_proxy def test_create_user_from_token_credential(self): @@ -67,14 +65,10 @@ def test_create_user_and_token(self, _, scopes): assert user.properties.get("id") is not None assert token_response.token is not None - @pytest.mark.parametrize( - "_, value", [("min_valid_hours", 1), ("max_valid_hours", 24)] - ) + @pytest.mark.parametrize("_, value", [("min_valid_hours", 1), ("max_valid_hours", 24)]) @ArgumentPasser() @recorded_by_proxy - def test_create_user_and_token_with_valid_custom_expirations_new( - self, _, valid_hours - ): + def test_create_user_and_token_with_valid_custom_expirations_new(self, _, valid_hours): identity_client = self.create_client_from_connection_string() token_expires_in = timedelta(hours=valid_hours) user, token_response = identity_client.create_user_and_token( @@ -84,18 +78,12 @@ def test_create_user_and_token_with_valid_custom_expirations_new( assert token_response.token is not None if is_live(): - assert is_token_expiration_within_allowed_deviation( - token_expires_in, token_response.expires_on - ) + assert is_token_expiration_within_allowed_deviation(token_expires_in, token_response.expires_on) - @pytest.mark.parametrize( - "_, value", [("min_invalid_mins", 59), ("max_invalid_mins", 1441)] - ) + @pytest.mark.parametrize("_, value", [("min_invalid_mins", 59), ("max_invalid_mins", 1441)]) @ArgumentPasser() @recorded_by_proxy - def test_create_user_and_token_with_invalid_custom_expirations( - self, _, invalid_mins - ): + def test_create_user_and_token_with_invalid_custom_expirations(self, _, invalid_mins): identity_client = self.create_client_from_connection_string() token_expires_in = timedelta(minutes=invalid_mins) @@ -127,16 +115,12 @@ def test_get_token(self): identity_client = self.create_client_from_connection_string() user = identity_client.create_user() - token_response = identity_client.get_token( - user, scopes=[CommunicationTokenScope.CHAT] - ) + token_response = identity_client.get_token(user, scopes=[CommunicationTokenScope.CHAT]) assert user.properties.get("id") is not None assert token_response.token is not None - @pytest.mark.parametrize( - "_, value", [("min_valid_hours", 1), ("max_valid_hours", 24)] - ) + @pytest.mark.parametrize("_, value", [("min_valid_hours", 1), ("max_valid_hours", 24)]) @ArgumentPasser() @recorded_by_proxy def test_get_token_with_valid_custom_expirations(self, _, valid_hours): @@ -153,13 +137,9 @@ def test_get_token_with_valid_custom_expirations(self, _, valid_hours): assert user.properties.get("id") is not None assert token_response.token is not None if is_live(): - assert is_token_expiration_within_allowed_deviation( - token_expires_in, token_response.expires_on - ) + assert is_token_expiration_within_allowed_deviation(token_expires_in, token_response.expires_on) - @pytest.mark.parametrize( - "_, value", [("min_invalid_mins", 59), ("max_invalid_mins", 1441)] - ) + @pytest.mark.parametrize("_, value", [("min_invalid_mins", 59), ("max_invalid_mins", 1441)]) @ArgumentPasser() @recorded_by_proxy def test_get_token_with_invalid_custom_expirations(self, _, invalid_mins): @@ -183,9 +163,7 @@ def test_revoke_tokens_from_token_credential(self): identity_client = self.create_client_from_token_credential() user = identity_client.create_user() - token_response = identity_client.get_token( - user, scopes=[CommunicationTokenScope.CHAT] - ) + token_response = identity_client.get_token(user, scopes=[CommunicationTokenScope.CHAT]) identity_client.revoke_tokens(user) assert user.properties.get("id") is not None @@ -196,9 +174,7 @@ def test_revoke_tokens(self): identity_client = self.create_client_from_connection_string() user = identity_client.create_user() - token_response = identity_client.get_token( - user, scopes=[CommunicationTokenScope.CHAT] - ) + token_response = identity_client.get_token(user, scopes=[CommunicationTokenScope.CHAT]) identity_client.revoke_tokens(user) assert user.properties.get("id") is not None @@ -270,9 +246,7 @@ def test_get_token_for_teams_user_from_token_credential(self): return identity_client = self.create_client_from_token_credential() aad_token, user_object_id = self.generate_teams_user_aad_token() - token_response = identity_client.get_token_for_teams_user( - aad_token, self.m365_client_id, user_object_id - ) + token_response = identity_client.get_token_for_teams_user(aad_token, self.m365_client_id, user_object_id) assert token_response.token is not None @recorded_by_proxy @@ -281,14 +255,10 @@ def test_get_token_for_teams_user_with_valid_params(self): return identity_client = self.create_client_from_connection_string() aad_token, user_object_id = self.generate_teams_user_aad_token() - token_response = identity_client.get_token_for_teams_user( - aad_token, self.m365_client_id, user_object_id - ) + token_response = identity_client.get_token_for_teams_user(aad_token, self.m365_client_id, user_object_id) assert token_response.token is not None - @pytest.mark.parametrize( - "_, value", [("empty_token", ""), ("invalid_token", "invalid")] - ) + @pytest.mark.parametrize("_, value", [("empty_token", ""), ("invalid_token", "invalid")]) @ArgumentPasser() @recorded_by_proxy def test_get_token_for_teams_user_with_invalid_token(self, _, invalid_token): @@ -296,9 +266,7 @@ def test_get_token_for_teams_user_with_invalid_token(self, _, invalid_token): return identity_client = self.create_client_from_connection_string() with pytest.raises(Exception) as ex: - identity_client.get_token_for_teams_user( - invalid_token, self.m365_client_id, "" - ) + identity_client.get_token_for_teams_user(invalid_token, self.m365_client_id, "") assert str(ex.value.status_code) == "401" assert ex.value.message is not None @@ -309,15 +277,11 @@ def test_get_token_for_teams_user_with_expired_token(self): identity_client = self.create_client_from_connection_string() _, user_object_id = self.generate_teams_user_aad_token() with pytest.raises(Exception) as ex: - identity_client.get_token_for_teams_user( - self.expired_teams_token, self.m365_client_id, user_object_id - ) + identity_client.get_token_for_teams_user(self.expired_teams_token, self.m365_client_id, user_object_id) assert str(ex.value.status_code) == "401" assert ex.value.message is not None - @pytest.mark.parametrize( - "_, value", [("empty_client_id", ""), ("invalid_client_id", "invalid")] - ) + @pytest.mark.parametrize("_, value", [("empty_client_id", ""), ("invalid_client_id", "invalid")]) @ArgumentPasser() @recorded_by_proxy def test_get_token_for_teams_user_with_invalid_client_id(self, _, invalid_client): @@ -326,9 +290,7 @@ def test_get_token_for_teams_user_with_invalid_client_id(self, _, invalid_client identity_client = self.create_client_from_connection_string() aad_token, user_object_id = self.generate_teams_user_aad_token() with pytest.raises(Exception) as ex: - identity_client.get_token_for_teams_user( - aad_token, invalid_client, user_object_id - ) + identity_client.get_token_for_teams_user(aad_token, invalid_client, user_object_id) assert str(ex.value.status_code) == "400" assert ex.value.message is not None @@ -339,9 +301,7 @@ def test_get_token_for_teams_user_with_wrong_client_id(self): identity_client = self.create_client_from_connection_string() aad_token, user_object_id = self.generate_teams_user_aad_token() with pytest.raises(Exception) as ex: - identity_client.get_token_for_teams_user( - aad_token, user_object_id, user_object_id - ) + identity_client.get_token_for_teams_user(aad_token, user_object_id, user_object_id) assert str(ex.value.status_code) == "400" assert ex.value.message is not None @@ -351,17 +311,13 @@ def test_get_token_for_teams_user_with_wrong_client_id(self): ) @ArgumentPasser() @recorded_by_proxy - def test_get_token_for_teams_user_with_invalid_user_object_id( - self, _, invalid_user_object - ): + def test_get_token_for_teams_user_with_invalid_user_object_id(self, _, invalid_user_object): if self.skip_get_token_for_teams_user_test(): return identity_client = self.create_client_from_connection_string() aad_token, _ = self.generate_teams_user_aad_token() with pytest.raises(Exception) as ex: - identity_client.get_token_for_teams_user( - aad_token, self.m365_client_id, invalid_user_object - ) + identity_client.get_token_for_teams_user(aad_token, self.m365_client_id, invalid_user_object) assert str(ex.value.status_code) == "400" assert ex.value.message is not None @@ -372,8 +328,6 @@ def test_get_token_for_teams_user_with_wrong_user_object_id(self): identity_client = self.create_client_from_connection_string() aad_token, _ = self.generate_teams_user_aad_token() with pytest.raises(Exception) as ex: - identity_client.get_token_for_teams_user( - aad_token, self.m365_client_id, self.m365_client_id - ) + identity_client.get_token_for_teams_user(aad_token, self.m365_client_id, self.m365_client_id) assert str(ex.value.status_code) == "400" assert ex.value.message is not None diff --git a/sdk/communication/azure-communication-identity/tests/test_communication_identity_client_async.py b/sdk/communication/azure-communication-identity/tests/test_communication_identity_client_async.py index 9b05026adfb4..dc4b04dcd811 100644 --- a/sdk/communication/azure-communication-identity/tests/test_communication_identity_client_async.py +++ b/sdk/communication/azure-communication-identity/tests/test_communication_identity_client_async.py @@ -32,9 +32,7 @@ def create_client_from_token_credential(self): credential = AsyncFakeCredential() else: credential = get_credential(is_async=True) - return CommunicationIdentityClient( - self.endpoint, credential, http_logging_policy=get_http_logging_policy() - ) + return CommunicationIdentityClient(self.endpoint, credential, http_logging_policy=get_http_logging_policy()) @recorded_by_proxy_async async def test_create_user_from_token_credential(self): @@ -61,9 +59,7 @@ async def test_create_user(self): async def test_create_user_and_token(self, _, scopes): identity_client = self.create_client_from_connection_string() async with identity_client: - user, token_response = await identity_client.create_user_and_token( - scopes=scopes - ) + user, token_response = await identity_client.create_user_and_token(scopes=scopes) assert user.properties.get("id") is not None assert token_response.token is not None @@ -82,9 +78,7 @@ async def test_create_user_and_token_with_custom_minimum_validity(self): assert token_response.token is not None if is_live(): - assert is_token_expiration_within_allowed_deviation( - token_expires_in, token_response.expires_on - ) + assert is_token_expiration_within_allowed_deviation(token_expires_in, token_response.expires_on) @recorded_by_proxy_async async def test_create_user_and_token_with_custom_maximum_validity(self): @@ -100,9 +94,7 @@ async def test_create_user_and_token_with_custom_maximum_validity(self): assert token_response.token is not None if is_live(): - assert is_token_expiration_within_allowed_deviation( - token_expires_in, token_response.expires_on - ) + assert is_token_expiration_within_allowed_deviation(token_expires_in, token_response.expires_on) @recorded_by_proxy_async async def test_create_user_and_token_with_custom_validity_under_minimum_allowed( @@ -158,9 +150,7 @@ async def test_get_token(self): identity_client = self.create_client_from_connection_string() async with identity_client: user = await identity_client.create_user() - token_response = await identity_client.get_token( - user, scopes=[CommunicationTokenScope.CHAT] - ) + token_response = await identity_client.get_token(user, scopes=[CommunicationTokenScope.CHAT]) assert user.properties.get("id") is not None assert token_response.token is not None @@ -182,9 +172,7 @@ async def test_get_token_with_custom_minimum_validity(self): assert token_response.token is not None if is_live(): - assert is_token_expiration_within_allowed_deviation( - token_expires_in, token_response.expires_on - ) + assert is_token_expiration_within_allowed_deviation(token_expires_in, token_response.expires_on) @recorded_by_proxy_async async def test_get_token_with_custom_maximum_validity(self): @@ -203,9 +191,7 @@ async def test_get_token_with_custom_maximum_validity(self): assert token_response.token is not None if is_live(): - assert is_token_expiration_within_allowed_deviation( - token_expires_in, token_response.expires_on - ) + assert is_token_expiration_within_allowed_deviation(token_expires_in, token_response.expires_on) @recorded_by_proxy_async async def test_get_token_with_custom_validity_under_minimum_allowed(self): @@ -246,9 +232,7 @@ async def test_revoke_tokens_from_token_credential(self): identity_client = self.create_client_from_token_credential() async with identity_client: user = await identity_client.create_user() - token_response = await identity_client.get_token( - user, scopes=[CommunicationTokenScope.CHAT] - ) + token_response = await identity_client.get_token(user, scopes=[CommunicationTokenScope.CHAT]) await identity_client.revoke_tokens(user) assert user.properties.get("id") is not None @@ -259,9 +243,7 @@ async def test_revoke_tokens(self): identity_client = self.create_client_from_connection_string() async with identity_client: user = await identity_client.create_user() - token_response = await identity_client.get_token( - user, scopes=[CommunicationTokenScope.CHAT] - ) + token_response = await identity_client.get_token(user, scopes=[CommunicationTokenScope.CHAT]) await identity_client.revoke_tokens(user) assert user.properties.get("id") is not None @@ -317,9 +299,7 @@ async def test_get_token_with_no_user(self): identity_client = self.create_client_from_connection_string() async with identity_client: with pytest.raises(Exception) as ex: - await identity_client.get_token( - user=None, scopes=[CommunicationTokenScope.CHAT] - ) + await identity_client.get_token(user=None, scopes=[CommunicationTokenScope.CHAT]) assert ex is not None and ex.value is not None @@ -366,9 +346,7 @@ async def test_get_token_for_teams_user_with_invalid_token(self): identity_client = self.create_client_from_connection_string() async with identity_client: with pytest.raises(Exception) as ex: - await identity_client.get_token_for_teams_user( - "invalid", self.m365_client_id, "" - ) + await identity_client.get_token_for_teams_user("invalid", self.m365_client_id, "") assert str(ex.value.status_code) == "401" assert ex.value.message is not None @@ -380,9 +358,7 @@ async def test_get_token_for_teams_user_with_empty_token(self): identity_client = self.create_client_from_connection_string() async with identity_client: with pytest.raises(Exception) as ex: - await identity_client.get_token_for_teams_user( - "", self.m365_client_id, "" - ) + await identity_client.get_token_for_teams_user("", self.m365_client_id, "") assert str(ex.value.status_code) == "401" assert ex.value.message is not None @@ -410,9 +386,7 @@ async def test_get_token_for_teams_user_with_empty_client_id(self): aad_token, user_object_id = self.generate_teams_user_aad_token() async with identity_client: with pytest.raises(Exception) as ex: - await identity_client.get_token_for_teams_user( - aad_token, "", user_object_id - ) + await identity_client.get_token_for_teams_user(aad_token, "", user_object_id) assert str(ex.value.status_code) == "400" assert ex.value.message is not None @@ -425,9 +399,7 @@ async def test_get_token_for_teams_user_with_invalid_client_id(self): aad_token, user_object_id = self.generate_teams_user_aad_token() async with identity_client: with pytest.raises(Exception) as ex: - await identity_client.get_token_for_teams_user( - aad_token, "invalid", user_object_id - ) + await identity_client.get_token_for_teams_user(aad_token, "invalid", user_object_id) assert str(ex.value.status_code) == "400" assert ex.value.message is not None @@ -440,9 +412,7 @@ async def test_get_token_for_teams_user_with_wrong_client_id(self): aad_token, user_object_id = self.generate_teams_user_aad_token() async with identity_client: with pytest.raises(Exception) as ex: - await identity_client.get_token_for_teams_user( - aad_token, user_object_id, user_object_id - ) + await identity_client.get_token_for_teams_user(aad_token, user_object_id, user_object_id) assert str(ex.value.status_code) == "400" assert ex.value.message is not None @@ -455,9 +425,7 @@ async def test_get_token_for_teams_user_with_invalid_user_object_id(self): aad_token, _ = self.generate_teams_user_aad_token() async with identity_client: with pytest.raises(Exception) as ex: - await identity_client.get_token_for_teams_user( - aad_token, self.m365_client_id, "invalid" - ) + await identity_client.get_token_for_teams_user(aad_token, self.m365_client_id, "invalid") assert str(ex.value.status_code) == "400" assert ex.value.message is not None @@ -470,9 +438,7 @@ async def test_get_token_for_teams_user_with_empty_user_object_id(self): aad_token, _ = self.generate_teams_user_aad_token() async with identity_client: with pytest.raises(Exception) as ex: - await identity_client.get_token_for_teams_user( - aad_token, self.m365_client_id, "" - ) + await identity_client.get_token_for_teams_user(aad_token, self.m365_client_id, "") assert str(ex.value.status_code) == "400" assert ex.value.message is not None @@ -485,9 +451,7 @@ async def test_get_token_for_teams_user_with_wrong_user_object_id(self): aad_token, _ = self.generate_teams_user_aad_token() async with identity_client: with pytest.raises(Exception) as ex: - await identity_client.get_token_for_teams_user( - aad_token, self.m365_client_id, self.m365_client_id - ) + await identity_client.get_token_for_teams_user(aad_token, self.m365_client_id, self.m365_client_id) assert str(ex.value.status_code) == "400" assert ex.value.message is not None diff --git a/sdk/communication/azure-communication-identity/tests/test_deprecations.py b/sdk/communication/azure-communication-identity/tests/test_deprecations.py index 11ba67ca6a97..f1d36ba5d352 100644 --- a/sdk/communication/azure-communication-identity/tests/test_deprecations.py +++ b/sdk/communication/azure-communication-identity/tests/test_deprecations.py @@ -6,7 +6,8 @@ # -------------------------------------------------------------------------- import pytest -import azure.communication.identity as models +import azure.communication.identity as models + class TestDeprecations: @@ -18,9 +19,10 @@ def test_deprecated_bot_kind(self): with pytest.deprecated_call(): props = models.CommunicationIdentifierKind.MICROSOFT_BOT assert props == models.CommunicationIdentifierKind.MICROSOFT_TEAMS_APP - + def test_deprecated_bot_identifier(self): from azure.communication.identity._shared.models import _MicrosoftBotIdentifier + with pytest.deprecated_call(): bot = _MicrosoftBotIdentifier("bot_id", is_resource_account_configured=False, cloud="PUBLIC") assert bot.kind == models.CommunicationIdentifierKind.microsoft_bot diff --git a/sdk/communication/azure-communication-identity/tests/test_identifier_raw_id.py b/sdk/communication/azure-communication-identity/tests/test_identifier_raw_id.py index a89cace1cf57..98c20a32f054 100644 --- a/sdk/communication/azure-communication-identity/tests/test_identifier_raw_id.py +++ b/sdk/communication/azure-communication-identity/tests/test_identifier_raw_id.py @@ -24,43 +24,29 @@ def test_raw_id(self): ), "8:gcch-acs:bbbcbc1e-9f06-482a-b5d8-20e3f26ef0cd_45ab2481-1c1c-4005-be24-0ffb879b1130", ) + _assert_raw_id(CommunicationUserIdentifier(id="someFutureFormat"), "someFutureFormat") _assert_raw_id( - CommunicationUserIdentifier(id="someFutureFormat"), "someFutureFormat" - ) - _assert_raw_id( - MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ), + MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130"), "8:orgid:45ab2481-1c1c-4005-be24-0ffb879b1130", ) _assert_raw_id( - MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC" - ), + MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC"), "8:orgid:45ab2481-1c1c-4005-be24-0ffb879b1130", ) _assert_raw_id( - MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD" - ), + MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD"), "8:dod:45ab2481-1c1c-4005-be24-0ffb879b1130", ) _assert_raw_id( - MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH" - ), + MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH"), "8:gcch:45ab2481-1c1c-4005-be24-0ffb879b1130", ) _assert_raw_id( - MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", is_anonymous=False - ), + MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", is_anonymous=False), "8:orgid:45ab2481-1c1c-4005-be24-0ffb879b1130", ) _assert_raw_id( - MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", is_anonymous=True - ), + MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", is_anonymous=True), "8:teamsvisitor:45ab2481-1c1c-4005-be24-0ffb879b1130", ) _assert_raw_id( @@ -71,27 +57,19 @@ def test_raw_id(self): "8:orgid:legacyFormat", ) _assert_raw_id( - MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ), + MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130"), "28:orgid:45ab2481-1c1c-4005-be24-0ffb879b1130", ) _assert_raw_id( - MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC" - ), + MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC"), "28:orgid:45ab2481-1c1c-4005-be24-0ffb879b1130", ) _assert_raw_id( - MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD" - ), + MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD"), "28:dod:45ab2481-1c1c-4005-be24-0ffb879b1130", ) _assert_raw_id( - MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH" - ), + MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH"), "28:gcch:45ab2481-1c1c-4005-be24-0ffb879b1130", ) _assert_raw_id(PhoneNumberIdentifier(value="+112345556789"), "4:+112345556789") @@ -101,9 +79,7 @@ def test_raw_id(self): "4:otherFormat", ) _assert_raw_id( - PhoneNumberIdentifier( - value="otherFormat", raw_id="4:207ffef6-9444-41fb-92ab-20eacaae2768" - ), + PhoneNumberIdentifier(value="otherFormat", raw_id="4:207ffef6-9444-41fb-92ab-20eacaae2768"), "4:207ffef6-9444-41fb-92ab-20eacaae2768", ) # cspell:disable @@ -147,14 +123,10 @@ def test_identifier_from_raw_id(self): id="8:gcch-acs:bbbcbc1e-9f06-482a-b5d8-20e3f26ef0cd_45ab2481-1c1c-4005-be24-0ffb879b1130" ), ) - _assert_communication_identifier( - "8:acs:something", CommunicationUserIdentifier(id="8:acs:something") - ) + _assert_communication_identifier("8:acs:something", CommunicationUserIdentifier(id="8:acs:something")) _assert_communication_identifier( "8:orgid:45ab2481-1c1c-4005-be24-0ffb879b1130", - MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ), + MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130"), ) _assert_communication_identifier( "8:orgid:45ab2481-1c1c-4005-be24-0ffb879b1130", @@ -182,52 +154,31 @@ def test_identifier_from_raw_id(self): ) _assert_communication_identifier( "8:teamsvisitor:45ab2481-1c1c-4005-be24-0ffb879b1130", - MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", is_anonymous=True - ), + MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", is_anonymous=True), ) _assert_communication_identifier( "8:orgid:legacyFormat", - MicrosoftTeamsUserIdentifier( - user_id="legacyFormat", cloud="PUBLIC", is_anonymous=False - ), + MicrosoftTeamsUserIdentifier(user_id="legacyFormat", cloud="PUBLIC", is_anonymous=False), ) _assert_communication_identifier( "28:orgid:45ab2481-1c1c-4005-be24-0ffb879b1130", - MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ), + MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130"), ) _assert_communication_identifier( "28:orgid:45ab2481-1c1c-4005-be24-0ffb879b1130", - MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", - cloud="PUBLIC" - ), + MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC"), ) _assert_communication_identifier( "28:dod:45ab2481-1c1c-4005-be24-0ffb879b1130", - MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", - cloud="DOD" - ), + MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD"), ) _assert_communication_identifier( "28:gcch:45ab2481-1c1c-4005-be24-0ffb879b1130", - MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", - cloud="GCCH" - ), - ) - _assert_communication_identifier( - "4:+112345556789", PhoneNumberIdentifier(value="+112345556789") - ) - _assert_communication_identifier( - "4:112345556789", PhoneNumberIdentifier(value="112345556789") - ) - _assert_communication_identifier( - "4:otherFormat", PhoneNumberIdentifier(value="otherFormat") + MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH"), ) + _assert_communication_identifier("4:+112345556789", PhoneNumberIdentifier(value="+112345556789")) + _assert_communication_identifier("4:112345556789", PhoneNumberIdentifier(value="112345556789")) + _assert_communication_identifier("4:otherFormat", PhoneNumberIdentifier(value="otherFormat")) _assert_communication_identifier( "4:207ffef6-9444-41fb-92ab-20eacaae2768", PhoneNumberIdentifier(value="207ffef6-9444-41fb-92ab-20eacaae2768"), @@ -235,40 +186,26 @@ def test_identifier_from_raw_id(self): # cspell:disable _assert_communication_identifier( "4:207ffef6-9444-41fb-92ab-20eacaae2768_207ffef6-9444-41fb-92ab-20eacaae2768", - PhoneNumberIdentifier( - value="207ffef6-9444-41fb-92ab-20eacaae2768_207ffef6-9444-41fb-92ab-20eacaae2768" - ), + PhoneNumberIdentifier(value="207ffef6-9444-41fb-92ab-20eacaae2768_207ffef6-9444-41fb-92ab-20eacaae2768"), ) _assert_communication_identifier( "4:+112345556789_207ffef6-9444-41fb-92ab-20eacaae2768", - PhoneNumberIdentifier( - value="+112345556789_207ffef6-9444-41fb-92ab-20eacaae2768" - ), + PhoneNumberIdentifier(value="+112345556789_207ffef6-9444-41fb-92ab-20eacaae2768"), ) # cspell:enable _assert_communication_identifier( "28:ag08-global:01234567-89ab-cdef-0123-456789abcdef", - UnknownIdentifier( - identifier="28:ag08-global:01234567-89ab-cdef-0123-456789abcdef" - ), + UnknownIdentifier(identifier="28:ag08-global:01234567-89ab-cdef-0123-456789abcdef"), ) _assert_communication_identifier("", UnknownIdentifier(identifier="")) with pytest.raises(Exception): identifier_from_raw_id(None) def test_roundtrip(self): - _assert_roundtrip( - "8:acs:bbbcbc1e-9f06-482a-b5d8-20e3f26ef0cd_45ab2481-1c1c-4005-be24-0ffb879b1130" - ) - _assert_roundtrip( - "8:spool:bbbcbc1e-9f06-482a-b5d8-20e3f26ef0cd_45ab2481-1c1c-4005-be24-0ffb879b1130" - ) - _assert_roundtrip( - "8:dod-acs:bbbcbc1e-9f06-482a-b5d8-20e3f26ef0cd_45ab2481-1c1c-4005-be24-0ffb879b1130" - ) - _assert_roundtrip( - "8:gcch-acs:bbbcbc1e-9f06-482a-b5d8-20e3f26ef0cd_45ab2481-1c1c-4005-be24-0ffb879b1130" - ) + _assert_roundtrip("8:acs:bbbcbc1e-9f06-482a-b5d8-20e3f26ef0cd_45ab2481-1c1c-4005-be24-0ffb879b1130") + _assert_roundtrip("8:spool:bbbcbc1e-9f06-482a-b5d8-20e3f26ef0cd_45ab2481-1c1c-4005-be24-0ffb879b1130") + _assert_roundtrip("8:dod-acs:bbbcbc1e-9f06-482a-b5d8-20e3f26ef0cd_45ab2481-1c1c-4005-be24-0ffb879b1130") + _assert_roundtrip("8:gcch-acs:bbbcbc1e-9f06-482a-b5d8-20e3f26ef0cd_45ab2481-1c1c-4005-be24-0ffb879b1130") _assert_roundtrip("8:acs:something") _assert_roundtrip("8:orgid:45ab2481-1c1c-4005-be24-0ffb879b1130") _assert_roundtrip("8:dod:45ab2481-1c1c-4005-be24-0ffb879b1130") @@ -280,9 +217,7 @@ def test_roundtrip(self): _assert_roundtrip("4:otherFormat") _assert_roundtrip("4:207ffef6-9444-41fb-92ab-20eacaae2768") # cspell:disable - _assert_roundtrip( - "4:207ffef6-9444-41fb-92ab-20eacaae2768_207ffef6-9444-41fb-92ab-20eacaae2768" - ) + _assert_roundtrip("4:207ffef6-9444-41fb-92ab-20eacaae2768_207ffef6-9444-41fb-92ab-20eacaae2768") _assert_roundtrip("4:+112345556789_207ffef6-9444-41fb-92ab-20eacaae2768") # cspell:enable _assert_roundtrip("28:45ab2481-1c1c-4005-be24-0ffb879b1130") @@ -312,24 +247,16 @@ def test_equality_based_on_raw_id(self): # MicrosoftTeamsUserIdentifiers are equal. assert MicrosoftTeamsUserIdentifier( user_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ) == MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ) + ) == MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130") assert MicrosoftTeamsUserIdentifier( user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC" - ) == MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC" - ) + ) == MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC") assert MicrosoftTeamsUserIdentifier( user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD" - ) == MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD" - ) + ) == MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD") assert MicrosoftTeamsUserIdentifier( user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH" - ) == MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH" - ) + ) == MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH") assert MicrosoftTeamsUserIdentifier( user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH", @@ -352,14 +279,10 @@ def test_equality_based_on_raw_id(self): # MicrosoftTeamsUserIdentifiers are not equal. assert MicrosoftTeamsUserIdentifier( user_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ) != MicrosoftTeamsUserIdentifier( - user_id="55ab2481-1c1c-4005-be24-0ffb879b1130" - ) + ) != MicrosoftTeamsUserIdentifier(user_id="55ab2481-1c1c-4005-be24-0ffb879b1130") assert MicrosoftTeamsUserIdentifier( user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH" - ) != MicrosoftTeamsUserIdentifier( - user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD" - ) + ) != MicrosoftTeamsUserIdentifier(user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD") assert MicrosoftTeamsUserIdentifier( user_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH", @@ -373,71 +296,48 @@ def test_equality_based_on_raw_id(self): # MicrosoftTeamsAppIdentifiers are equal. assert MicrosoftTeamsAppIdentifier( app_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ) == MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ) + ) == MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130") assert MicrosoftTeamsAppIdentifier( app_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ) == MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC" - ) + ) == MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC") assert MicrosoftTeamsAppIdentifier( app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC" - ) == MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ) + ) == MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130") assert MicrosoftTeamsAppIdentifier( app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC" - ) == MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC" - ) + ) == MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC") assert MicrosoftTeamsAppIdentifier( app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD" - ) == MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD" - ) + ) == MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD") assert MicrosoftTeamsAppIdentifier( app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH" - ) == MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH" - ) + ) == MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="GCCH") # MicrosoftTeamsAppIdentifiers are not equal. assert MicrosoftTeamsAppIdentifier( app_id="54ab2481-1c1c-4005-be24-0ffb879b1130" - ) != MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130" - ) + ) != MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130") assert MicrosoftTeamsAppIdentifier( app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="PUBLIC" - ) != MicrosoftTeamsAppIdentifier( - app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD" - ) + ) != MicrosoftTeamsAppIdentifier(app_id="45ab2481-1c1c-4005-be24-0ffb879b1130", cloud="DOD") # PhoneNumberIdentifiers are equal. - assert PhoneNumberIdentifier(value="+112345556789") == PhoneNumberIdentifier( - value="+112345556789" - ) + assert PhoneNumberIdentifier(value="+112345556789") == PhoneNumberIdentifier(value="+112345556789") # PhoneNumberIdentifiers are not equal. - assert PhoneNumberIdentifier(value="+112345556789") != PhoneNumberIdentifier( - value="+512345556789" - ) + assert PhoneNumberIdentifier(value="+112345556789") != PhoneNumberIdentifier(value="+512345556789") # UnknownIdentifiers are equal. - assert UnknownIdentifier( - identifier="28:ag08-global:01234567-89ab-cdef-0123-456789abcdef" - ) == UnknownIdentifier( + assert UnknownIdentifier(identifier="28:ag08-global:01234567-89ab-cdef-0123-456789abcdef") == UnknownIdentifier( identifier="28:ag08-global:01234567-89ab-cdef-0123-456789abcdef" ) # UnknownIdentifiers are not equal. - assert UnknownIdentifier( - identifier="48:8888-global:01234567-89ab-cdef-0123-456789abcdef" - ) != UnknownIdentifier( + assert UnknownIdentifier(identifier="48:8888-global:01234567-89ab-cdef-0123-456789abcdef") != UnknownIdentifier( identifier="48:ag08-global:01234567-89ab-cdef-0123-456789abcdef" ) + def _assert_raw_id(identifier, want): # type: (CommunicationIdentifier, str) -> None assert identifier.raw_id == want diff --git a/sdk/communication/azure-communication-identity/tests/test_user_credential.py b/sdk/communication/azure-communication-identity/tests/test_user_credential.py index 5af3bb6b8ae9..599c5912904e 100644 --- a/sdk/communication/azure-communication-identity/tests/test_user_credential.py +++ b/sdk/communication/azure-communication-identity/tests/test_user_credential.py @@ -28,9 +28,7 @@ class TestCommunicationTokenCredential(TestCase): @classmethod def setUpClass(cls): - cls.sample_token = generate_token_with_custom_expiry_epoch( - 32503680000 - ) # 1/1/2030 + cls.sample_token = generate_token_with_custom_expiry_epoch(32503680000) # 1/1/2030 cls.expired_token = generate_token_with_custom_expiry_epoch(100) # 1/1/1970 def test_communicationtokencredential_decodes_token(self): @@ -39,9 +37,7 @@ def test_communicationtokencredential_decodes_token(self): self.assertEqual(access_token.token, self.sample_token) def test_communicationtokencredential_throws_if_invalid_token(self): - self.assertRaises( - ValueError, lambda: CommunicationTokenCredential("foo.bar.tar") - ) + self.assertRaises(ValueError, lambda: CommunicationTokenCredential("foo.bar.tar")) def test_communicationtokencredential_throws_if_nonstring_token(self): self.assertRaises(TypeError, lambda: CommunicationTokenCredential(454)) @@ -51,18 +47,10 @@ def test_communicationtokencredential_throws_if_proactive_refresh_enabled_withou ): with pytest.raises(ValueError) as err: CommunicationTokenCredential(self.sample_token, proactive_refresh=True) - assert ( - str(err.value) - == "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + assert str(err.value) == "When 'proactive_refresh' is True, 'token_refresher' must not be None." with pytest.raises(ValueError) as err: - CommunicationTokenCredential( - self.sample_token, proactive_refresh=True, token_refresher=None - ) - assert ( - str(err.value) - == "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + CommunicationTokenCredential(self.sample_token, proactive_refresh=True, token_refresher=None) + assert str(err.value) == "When 'proactive_refresh' is True, 'token_refresher' must not be None." def test_communicationtokencredential_static_token_returns_expired_token(self): credential = CommunicationTokenCredential(self.expired_token) @@ -70,9 +58,7 @@ def test_communicationtokencredential_static_token_returns_expired_token(self): def test_communicationtokencredential_token_expired_refresh_called(self): refresher = MagicMock(return_value=create_access_token(self.sample_token)) - credential = CommunicationTokenCredential( - self.expired_token, token_refresher=refresher - ) + credential = CommunicationTokenCredential(self.expired_token, token_refresher=refresher) access_token = credential.get_token() refresher.assert_called_once() self.assertEqual(access_token.token, self.sample_token) @@ -81,18 +67,14 @@ def test_communicationtokencredential_raises_if_refresher_returns_expired_token( self, ): refresher = MagicMock(return_value=create_access_token(self.expired_token)) - credential = CommunicationTokenCredential( - self.expired_token, token_refresher=refresher - ) + credential = CommunicationTokenCredential(self.expired_token, token_refresher=refresher) with self.assertRaises(ValueError): credential.get_token() self.assertEqual(refresher.call_count, 1) def test_uses_initial_token_as_expected(self): refresher = MagicMock(return_value=create_access_token(self.expired_token)) - credential = CommunicationTokenCredential( - self.sample_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(self.sample_token, token_refresher=refresher, proactive_refresh=True) access_token = credential.get_token() self.assertEqual(refresher.call_count, 0) @@ -105,18 +87,14 @@ def test_proactive_refresher_should_not_be_called_before_specified_time(self): skip_to_timestamp = start_timestamp + (refresh_minutes - 5) * 60 initial_token = generate_token_with_custom_expiry(token_validity_minutes * 60) - refreshed_token = generate_token_with_custom_expiry( - 2 * token_validity_minutes * 60 - ) + refreshed_token = generate_token_with_custom_expiry(2 * token_validity_minutes * 60) refresher = MagicMock(return_value=create_access_token(refreshed_token)) with patch( user_credential.__name__ + "." + get_current_utc_as_int.__name__, return_value=skip_to_timestamp, ): - credential = CommunicationTokenCredential( - initial_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(initial_token, token_refresher=refresher, proactive_refresh=True) access_token = credential.get_token() assert refresher.call_count == 0 @@ -128,23 +106,17 @@ def test_proactive_refresher_should_be_called_after_specified_time(self): refresh_minutes = 10 token_validity_minutes = 60 start_timestamp = get_current_utc_as_int() - skip_to_timestamp = ( - start_timestamp + (token_validity_minutes - refresh_minutes + 5) * 60 - ) + skip_to_timestamp = start_timestamp + (token_validity_minutes - refresh_minutes + 5) * 60 initial_token = generate_token_with_custom_expiry(token_validity_minutes * 60) - refreshed_token = generate_token_with_custom_expiry( - 2 * token_validity_minutes * 60 - ) + refreshed_token = generate_token_with_custom_expiry(2 * token_validity_minutes * 60) refresher = MagicMock(return_value=create_access_token(refreshed_token)) with patch( user_credential.__name__ + "." + get_current_utc_as_int.__name__, return_value=skip_to_timestamp, ): - credential = CommunicationTokenCredential( - initial_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(initial_token, token_refresher=refresher, proactive_refresh=True) access_token = credential.get_token() assert refresher.call_count == 1 @@ -156,22 +128,12 @@ def test_proactive_refresher_keeps_scheduling_again(self): refresh_minutes = 10 token_validity_minutes = 60 expired_token = generate_token_with_custom_expiry(-5 * 60) - skip_to_timestamp = ( - get_current_utc_as_int() - + (token_validity_minutes - refresh_minutes) * 60 - + 1 - ) - first_refreshed_token = create_access_token( - generate_token_with_custom_expiry(token_validity_minutes * 60) - ) - last_refreshed_token = create_access_token( - generate_token_with_custom_expiry(2 * token_validity_minutes * 60) - ) + skip_to_timestamp = get_current_utc_as_int() + (token_validity_minutes - refresh_minutes) * 60 + 1 + first_refreshed_token = create_access_token(generate_token_with_custom_expiry(token_validity_minutes * 60)) + last_refreshed_token = create_access_token(generate_token_with_custom_expiry(2 * token_validity_minutes * 60)) refresher = MagicMock(side_effect=[first_refreshed_token, last_refreshed_token]) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher, proactive_refresh=True) access_token = credential.get_token() with patch( user_credential.__name__ + "." + get_current_utc_as_int.__name__, @@ -195,9 +157,7 @@ def test_fractional_backoff_applied_when_token_expiring(self): ] ) - credential = CommunicationTokenCredential( - expiring_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expiring_token, token_refresher=refresher, proactive_refresh=True) next_milestone = token_validity_seconds / 2 @@ -215,9 +175,7 @@ def test_refresher_should_not_be_called_when_token_still_valid(self): new_token = generate_token_with_custom_expiry(10 * 60) refresher = MagicMock(return_value=create_access_token(new_token)) - credential = CommunicationTokenCredential( - generated_token, token_refresher=refresher, proactive_refresh=False - ) + credential = CommunicationTokenCredential(generated_token, token_refresher=refresher, proactive_refresh=False) for _ in range(10): access_token = credential.get_token() @@ -225,32 +183,21 @@ def test_refresher_should_not_be_called_when_token_still_valid(self): assert generated_token == access_token.token def test_exit_cancels_timer(self): - refreshed_token = create_access_token( - generate_token_with_custom_expiry(30 * 60) - ) + refreshed_token = create_access_token(generate_token_with_custom_expiry(30 * 60)) refresher = MagicMock(return_value=refreshed_token) - credential = CommunicationTokenCredential( - self.expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(self.expired_token, token_refresher=refresher, proactive_refresh=True) credential.get_token() credential.close() assert credential._timer is None def test_exit_enter_scenario_throws_exception(self): - refreshed_token = create_access_token( - generate_token_with_custom_expiry(30 * 60) - ) + refreshed_token = create_access_token(generate_token_with_custom_expiry(30 * 60)) refresher = MagicMock(return_value=refreshed_token) - credential = CommunicationTokenCredential( - self.expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(self.expired_token, token_refresher=refresher, proactive_refresh=True) credential.get_token() credential.close() assert credential._timer is None with pytest.raises(RuntimeError) as err: credential.get_token() - assert ( - str(err.value) - == "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + assert str(err.value) == "An instance of CommunicationTokenCredential cannot be reused once it has been closed." diff --git a/sdk/communication/azure-communication-identity/tests/test_user_credential_async.py b/sdk/communication/azure-communication-identity/tests/test_user_credential_async.py index e4e7296ad5e8..145d3cb94013 100644 --- a/sdk/communication/azure-communication-identity/tests/test_user_credential_async.py +++ b/sdk/communication/azure-communication-identity/tests/test_user_credential_async.py @@ -53,30 +53,18 @@ async def test_communicationtokencredential_throws_if_proactive_refresh_enabled_ ): with pytest.raises(ValueError) as err: CommunicationTokenCredential(self.sample_token, proactive_refresh=True) - assert ( - str(err.value) - == "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + assert str(err.value) == "When 'proactive_refresh' is True, 'token_refresher' must not be None." with pytest.raises(ValueError) as err: - CommunicationTokenCredential( - self.sample_token, proactive_refresh=True, token_refresher=None - ) - assert ( - str(err.value) - == "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + CommunicationTokenCredential(self.sample_token, proactive_refresh=True, token_refresher=None) + assert str(err.value) == "When 'proactive_refresh' is True, 'token_refresher' must not be None." @pytest.mark.asyncio async def test_refresher_should_be_called_immediately_with_expired_token(self): refreshed_token = generate_token_with_custom_expiry(10 * 60) - refresher = MagicMock( - return_value=self.get_completed_future(create_access_token(refreshed_token)) - ) + refresher = MagicMock(return_value=self.get_completed_future(create_access_token(refreshed_token))) expired_token = generate_token_with_custom_expiry(-(5 * 60)) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher) access_token = await credential.get_token() refresher.assert_called_once() @@ -88,9 +76,7 @@ async def test_refresher_should_not_be_called_before_expiring_time(self): refreshed_token = generate_token_with_custom_expiry(10 * 60) refresher = MagicMock(return_value=create_access_token(refreshed_token)) - credential = CommunicationTokenCredential( - initial_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(initial_token, token_refresher=refresher, proactive_refresh=True) access_token = await credential.get_token() refresher.assert_not_called() @@ -102,9 +88,7 @@ async def test_refresher_should_not_be_called_when_token_still_valid(self): new_token = generate_token_with_custom_expiry(10 * 60) refresher = MagicMock(return_value=create_access_token(new_token)) - credential = CommunicationTokenCredential( - generated_token, token_refresher=refresher, proactive_refresh=False - ) + credential = CommunicationTokenCredential(generated_token, token_refresher=refresher, proactive_refresh=False) for _ in range(10): access_token = await credential.get_token() @@ -114,13 +98,9 @@ async def test_refresher_should_not_be_called_when_token_still_valid(self): @pytest.mark.asyncio async def test_raises_if_refresher_returns_expired_token(self): expired_token = generate_token_with_custom_expiry(-(10 * 60)) - refresher = MagicMock( - return_value=self.get_completed_future(create_access_token(expired_token)) - ) + refresher = MagicMock(return_value=self.get_completed_future(create_access_token(expired_token))) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher) with self.assertRaises(ValueError): await credential.get_token() @@ -134,18 +114,14 @@ async def test_proactive_refresher_should_not_be_called_before_specified_time(se skip_to_timestamp = start_timestamp + (refresh_minutes - 5) * 60 initial_token = generate_token_with_custom_expiry(token_validity_minutes * 60) - refreshed_token = generate_token_with_custom_expiry( - 2 * token_validity_minutes * 60 - ) + refreshed_token = generate_token_with_custom_expiry(2 * token_validity_minutes * 60) refresher = MagicMock(return_value=create_access_token(refreshed_token)) with patch( user_credential_async.__name__ + "." + get_current_utc_as_int.__name__, return_value=skip_to_timestamp, ): - credential = CommunicationTokenCredential( - initial_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(initial_token, token_refresher=refresher, proactive_refresh=True) access_token = await credential.get_token() assert refresher.call_count == 0 @@ -158,25 +134,17 @@ async def test_proactive_refresher_should_be_called_after_specified_time(self): refresh_minutes = 10 token_validity_minutes = 60 start_timestamp = get_current_utc_as_int() - skip_to_timestamp = ( - start_timestamp + (token_validity_minutes - refresh_minutes + 5) * 60 - ) + skip_to_timestamp = start_timestamp + (token_validity_minutes - refresh_minutes + 5) * 60 initial_token = generate_token_with_custom_expiry(token_validity_minutes * 60) - refreshed_token = generate_token_with_custom_expiry( - 2 * token_validity_minutes * 60 - ) - refresher = MagicMock( - return_value=self.get_completed_future(create_access_token(refreshed_token)) - ) + refreshed_token = generate_token_with_custom_expiry(2 * token_validity_minutes * 60) + refresher = MagicMock(return_value=self.get_completed_future(create_access_token(refreshed_token))) with patch( user_credential_async.__name__ + "." + get_current_utc_as_int.__name__, return_value=skip_to_timestamp, ): - credential = CommunicationTokenCredential( - initial_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(initial_token, token_refresher=refresher, proactive_refresh=True) access_token = await credential.get_token() assert refresher.call_count == 1 @@ -189,17 +157,9 @@ async def test_proactive_refresher_keeps_scheduling_again(self): refresh_minutes = 10 token_validity_minutes = 60 expired_token = generate_token_with_custom_expiry(-5 * 60) - skip_to_timestamp = ( - get_current_utc_as_int() - + (token_validity_minutes - refresh_minutes) * 60 - + 1 - ) - first_refreshed_token = create_access_token( - generate_token_with_custom_expiry(token_validity_minutes * 60) - ) - last_refreshed_token = create_access_token( - generate_token_with_custom_expiry(2 * token_validity_minutes * 60) - ) + skip_to_timestamp = get_current_utc_as_int() + (token_validity_minutes - refresh_minutes) * 60 + 1 + first_refreshed_token = create_access_token(generate_token_with_custom_expiry(token_validity_minutes * 60)) + last_refreshed_token = create_access_token(generate_token_with_custom_expiry(2 * token_validity_minutes * 60)) refresher = MagicMock( side_effect=[ self.get_completed_future(first_refreshed_token), @@ -207,9 +167,7 @@ async def test_proactive_refresher_keeps_scheduling_again(self): ] ) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher, proactive_refresh=True) access_token = await credential.get_token() with patch( user_credential_async.__name__ + "." + get_current_utc_as_int.__name__, @@ -234,9 +192,7 @@ async def test_fractional_backoff_applied_when_token_expiring(self): ] ) - credential = CommunicationTokenCredential( - expiring_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expiring_token, token_refresher=refresher, proactive_refresh=True) next_milestone = token_validity_seconds / 2 assert credential._timer.interval == next_milestone @@ -253,14 +209,10 @@ async def test_fractional_backoff_applied_when_token_expiring(self): @pytest.mark.asyncio async def test_exit_cancels_timer(self): - refreshed_token = create_access_token( - generate_token_with_custom_expiry(30 * 60) - ) + refreshed_token = create_access_token(generate_token_with_custom_expiry(30 * 60)) refresher = MagicMock(return_value=refreshed_token) expired_token = generate_token_with_custom_expiry(-10 * 60) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher, proactive_refresh=True) credential.get_token() credential.close() assert credential._timer is not None @@ -269,21 +221,14 @@ async def test_exit_cancels_timer(self): @pytest.mark.asyncio async def test_exit_enter_scenario_throws_exception(self): - refreshed_token = create_access_token( - generate_token_with_custom_expiry(30 * 60) - ) + refreshed_token = create_access_token(generate_token_with_custom_expiry(30 * 60)) refresher = MagicMock(return_value=refreshed_token) expired_token = generate_token_with_custom_expiry(-10 * 60) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher, proactive_refresh=True) credential.get_token() credential.close() assert credential._timer is not None with pytest.raises(RuntimeError) as err: credential.get_token() - assert ( - str(err.value) - == "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + assert str(err.value) == "An instance of CommunicationTokenCredential cannot be reused once it has been closed." diff --git a/sdk/communication/azure-communication-identity/tests/test_user_credential_async_with_context_manager.py b/sdk/communication/azure-communication-identity/tests/test_user_credential_async_with_context_manager.py index 1e997c7e7e2d..5bf3d46b81a2 100644 --- a/sdk/communication/azure-communication-identity/tests/test_user_credential_async_with_context_manager.py +++ b/sdk/communication/azure-communication-identity/tests/test_user_credential_async_with_context_manager.py @@ -53,30 +53,18 @@ async def test_communicationtokencredential_throws_if_proactive_refresh_enabled_ ): with pytest.raises(ValueError) as err: CommunicationTokenCredential(self.sample_token, proactive_refresh=True) - assert ( - str(err.value) - == "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + assert str(err.value) == "When 'proactive_refresh' is True, 'token_refresher' must not be None." with pytest.raises(ValueError) as err: - CommunicationTokenCredential( - self.sample_token, proactive_refresh=True, token_refresher=None - ) - assert ( - str(err.value) - == "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + CommunicationTokenCredential(self.sample_token, proactive_refresh=True, token_refresher=None) + assert str(err.value) == "When 'proactive_refresh' is True, 'token_refresher' must not be None." @pytest.mark.asyncio async def test_refresher_should_be_called_immediately_with_expired_token(self): refreshed_token = generate_token_with_custom_expiry(10 * 60) - refresher = MagicMock( - return_value=self.get_completed_future(create_access_token(refreshed_token)) - ) + refresher = MagicMock(return_value=self.get_completed_future(create_access_token(refreshed_token))) expired_token = generate_token_with_custom_expiry(-(5 * 60)) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher) async with credential: access_token = await credential.get_token() @@ -88,14 +76,10 @@ async def test_refresher_should_be_called_immediately_with_expired_token_and_pro self, ): refreshed_token = generate_token_with_custom_expiry(10 * 60) - refresher = MagicMock( - return_value=self.get_completed_future(create_access_token(refreshed_token)) - ) + refresher = MagicMock(return_value=self.get_completed_future(create_access_token(refreshed_token))) expired_token = generate_token_with_custom_expiry(-(5 * 60)) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher, proactive_refresh=True) async with credential: access_token = await credential.get_token() @@ -108,9 +92,7 @@ async def test_refresher_should_not_be_called_before_expiring_time(self): refreshed_token = generate_token_with_custom_expiry(10 * 60) refresher = MagicMock(return_value=create_access_token(refreshed_token)) - credential = CommunicationTokenCredential( - initial_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(initial_token, token_refresher=refresher, proactive_refresh=True) async with credential: access_token = await credential.get_token() @@ -123,9 +105,7 @@ async def test_refresher_should_not_be_called_when_token_still_valid(self): new_token = generate_token_with_custom_expiry(10 * 60) refresher = MagicMock(return_value=create_access_token(new_token)) - credential = CommunicationTokenCredential( - generated_token, token_refresher=refresher, proactive_refresh=False - ) + credential = CommunicationTokenCredential(generated_token, token_refresher=refresher, proactive_refresh=False) async with credential: for _ in range(10): access_token = await credential.get_token() @@ -136,13 +116,9 @@ async def test_refresher_should_not_be_called_when_token_still_valid(self): @pytest.mark.asyncio async def test_raises_if_refresher_returns_expired_token(self): expired_token = generate_token_with_custom_expiry(-(10 * 60)) - refresher = MagicMock( - return_value=self.get_completed_future(create_access_token(expired_token)) - ) + refresher = MagicMock(return_value=self.get_completed_future(create_access_token(expired_token))) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher) async with credential: with self.assertRaises(ValueError): await credential.get_token() @@ -157,18 +133,14 @@ async def test_proactive_refresher_should_not_be_called_before_specified_time(se skip_to_timestamp = start_timestamp + (refresh_minutes - 5) * 60 initial_token = generate_token_with_custom_expiry(token_validity_minutes * 60) - refreshed_token = generate_token_with_custom_expiry( - 2 * token_validity_minutes * 60 - ) + refreshed_token = generate_token_with_custom_expiry(2 * token_validity_minutes * 60) refresher = MagicMock(return_value=create_access_token(refreshed_token)) with patch( user_credential_async.__name__ + "." + get_current_utc_as_int.__name__, return_value=skip_to_timestamp, ): - credential = CommunicationTokenCredential( - initial_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(initial_token, token_refresher=refresher, proactive_refresh=True) async with credential: access_token = await credential.get_token() @@ -182,25 +154,17 @@ async def test_proactive_refresher_should_be_called_after_specified_time(self): refresh_minutes = 10 token_validity_minutes = 60 start_timestamp = get_current_utc_as_int() - skip_to_timestamp = ( - start_timestamp + (token_validity_minutes - refresh_minutes + 5) * 60 - ) + skip_to_timestamp = start_timestamp + (token_validity_minutes - refresh_minutes + 5) * 60 initial_token = generate_token_with_custom_expiry(token_validity_minutes * 60) - refreshed_token = generate_token_with_custom_expiry( - 2 * token_validity_minutes * 60 - ) - refresher = MagicMock( - return_value=self.get_completed_future(create_access_token(refreshed_token)) - ) + refreshed_token = generate_token_with_custom_expiry(2 * token_validity_minutes * 60) + refresher = MagicMock(return_value=self.get_completed_future(create_access_token(refreshed_token))) with patch( user_credential_async.__name__ + "." + get_current_utc_as_int.__name__, return_value=skip_to_timestamp, ): - credential = CommunicationTokenCredential( - initial_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(initial_token, token_refresher=refresher, proactive_refresh=True) async with credential: access_token = await credential.get_token() @@ -214,17 +178,9 @@ async def test_proactive_refresher_keeps_scheduling_again(self): refresh_minutes = 10 token_validity_minutes = 60 expired_token = generate_token_with_custom_expiry(-5 * 60) - skip_to_timestamp = ( - get_current_utc_as_int() - + (token_validity_minutes - refresh_minutes) * 60 - + 1 - ) - first_refreshed_token = create_access_token( - generate_token_with_custom_expiry(token_validity_minutes * 60) - ) - last_refreshed_token = create_access_token( - generate_token_with_custom_expiry(2 * token_validity_minutes * 60) - ) + skip_to_timestamp = get_current_utc_as_int() + (token_validity_minutes - refresh_minutes) * 60 + 1 + first_refreshed_token = create_access_token(generate_token_with_custom_expiry(token_validity_minutes * 60)) + last_refreshed_token = create_access_token(generate_token_with_custom_expiry(2 * token_validity_minutes * 60)) refresher = MagicMock( side_effect=[ self.get_completed_future(first_refreshed_token), @@ -232,9 +188,7 @@ async def test_proactive_refresher_keeps_scheduling_again(self): ] ) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher, proactive_refresh=True) async with credential: access_token = await credential.get_token() with patch( @@ -260,9 +214,7 @@ async def test_fractional_backoff_applied_when_token_expiring(self): ] ) - credential = CommunicationTokenCredential( - expiring_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expiring_token, token_refresher=refresher, proactive_refresh=True) next_milestone = token_validity_seconds / 2 assert credential._timer.interval == next_milestone @@ -280,14 +232,10 @@ async def test_fractional_backoff_applied_when_token_expiring(self): @pytest.mark.asyncio async def test_exit_cancels_timer(self): - refreshed_token = create_access_token( - generate_token_with_custom_expiry(30 * 60) - ) + refreshed_token = create_access_token(generate_token_with_custom_expiry(30 * 60)) refresher = MagicMock(return_value=refreshed_token) expired_token = generate_token_with_custom_expiry(-10 * 60) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher, proactive_refresh=True) async with credential: assert credential._timer is not None assert refresher.call_count == 0 @@ -295,14 +243,10 @@ async def test_exit_cancels_timer(self): @pytest.mark.asyncio async def test_exit_enter_scenario_throws_exception(self): - refreshed_token = create_access_token( - generate_token_with_custom_expiry(30 * 60) - ) + refreshed_token = create_access_token(generate_token_with_custom_expiry(30 * 60)) refresher = MagicMock(return_value=refreshed_token) expired_token = generate_token_with_custom_expiry(-10 * 60) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher, proactive_refresh=True) async with credential: assert credential._timer is not None assert credential._timer is not None @@ -310,7 +254,4 @@ async def test_exit_enter_scenario_throws_exception(self): with pytest.raises(RuntimeError) as err: with credential: assert credential._timer is not None - assert ( - str(err.value) - == "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + assert str(err.value) == "An instance of CommunicationTokenCredential cannot be reused once it has been closed." diff --git a/sdk/communication/azure-communication-identity/tests/test_user_credential_with_context_manager.py b/sdk/communication/azure-communication-identity/tests/test_user_credential_with_context_manager.py index 6476cfadfad7..1768d28af36c 100644 --- a/sdk/communication/azure-communication-identity/tests/test_user_credential_with_context_manager.py +++ b/sdk/communication/azure-communication-identity/tests/test_user_credential_with_context_manager.py @@ -25,9 +25,7 @@ class TestCommunicationTokenCredential(TestCase): @classmethod def setUpClass(cls): - cls.sample_token = generate_token_with_custom_expiry_epoch( - 32503680000 - ) # 1/1/2030 + cls.sample_token = generate_token_with_custom_expiry_epoch(32503680000) # 1/1/2030 cls.expired_token = generate_token_with_custom_expiry_epoch(100) # 1/1/1970 def test_communicationtokencredential_decodes_token(self): @@ -36,9 +34,7 @@ def test_communicationtokencredential_decodes_token(self): self.assertEqual(access_token.token, self.sample_token) def test_communicationtokencredential_throws_if_invalid_token(self): - self.assertRaises( - ValueError, lambda: CommunicationTokenCredential("foo.bar.tar") - ) + self.assertRaises(ValueError, lambda: CommunicationTokenCredential("foo.bar.tar")) def test_communicationtokencredential_throws_if_nonstring_token(self): self.assertRaises(TypeError, lambda: CommunicationTokenCredential(454)) @@ -48,18 +44,10 @@ def test_communicationtokencredential_throws_if_proactive_refresh_enabled_withou ): with pytest.raises(ValueError) as err: CommunicationTokenCredential(self.sample_token, proactive_refresh=True) - assert ( - str(err.value) - == "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + assert str(err.value) == "When 'proactive_refresh' is True, 'token_refresher' must not be None." with pytest.raises(ValueError) as err: - CommunicationTokenCredential( - self.sample_token, proactive_refresh=True, token_refresher=None - ) - assert ( - str(err.value) - == "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + CommunicationTokenCredential(self.sample_token, proactive_refresh=True, token_refresher=None) + assert str(err.value) == "When 'proactive_refresh' is True, 'token_refresher' must not be None." def test_communicationtokencredential_static_token_returns_expired_token(self): with CommunicationTokenCredential(self.expired_token) as credential: @@ -67,9 +55,7 @@ def test_communicationtokencredential_static_token_returns_expired_token(self): def test_communicationtokencredential_token_expired_refresh_called(self): refresher = MagicMock(return_value=create_access_token(self.sample_token)) - with CommunicationTokenCredential( - self.expired_token, token_refresher=refresher - ) as credential: + with CommunicationTokenCredential(self.expired_token, token_refresher=refresher) as credential: access_token = credential.get_token() refresher.assert_called_once() self.assertEqual(access_token.token, self.sample_token) @@ -89,18 +75,14 @@ def test_communicationtokencredential_raises_if_refresher_returns_expired_token( self, ): refresher = MagicMock(return_value=create_access_token(self.expired_token)) - with CommunicationTokenCredential( - self.expired_token, token_refresher=refresher - ) as credential: + with CommunicationTokenCredential(self.expired_token, token_refresher=refresher) as credential: with self.assertRaises(ValueError): credential.get_token() self.assertEqual(refresher.call_count, 1) def test_uses_initial_token_as_expected(self): refresher = MagicMock(return_value=create_access_token(self.expired_token)) - credential = CommunicationTokenCredential( - self.sample_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(self.sample_token, token_refresher=refresher, proactive_refresh=True) with credential: access_token = credential.get_token() @@ -114,18 +96,14 @@ def test_proactive_refresher_should_not_be_called_before_specified_time(self): skip_to_timestamp = start_timestamp + (refresh_minutes - 5) * 60 initial_token = generate_token_with_custom_expiry(token_validity_minutes * 60) - refreshed_token = generate_token_with_custom_expiry( - 2 * token_validity_minutes * 60 - ) + refreshed_token = generate_token_with_custom_expiry(2 * token_validity_minutes * 60) refresher = MagicMock(return_value=create_access_token(refreshed_token)) with patch( user_credential.__name__ + "." + get_current_utc_as_int.__name__, return_value=skip_to_timestamp, ): - credential = CommunicationTokenCredential( - initial_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(initial_token, token_refresher=refresher, proactive_refresh=True) with credential: access_token = credential.get_token() @@ -138,23 +116,17 @@ def test_proactive_refresher_should_be_called_after_specified_time(self): refresh_minutes = 10 token_validity_minutes = 60 start_timestamp = get_current_utc_as_int() - skip_to_timestamp = ( - start_timestamp + (token_validity_minutes - refresh_minutes + 5) * 60 - ) + skip_to_timestamp = start_timestamp + (token_validity_minutes - refresh_minutes + 5) * 60 initial_token = generate_token_with_custom_expiry(token_validity_minutes * 60) - refreshed_token = generate_token_with_custom_expiry( - 2 * token_validity_minutes * 60 - ) + refreshed_token = generate_token_with_custom_expiry(2 * token_validity_minutes * 60) refresher = MagicMock(return_value=create_access_token(refreshed_token)) with patch( user_credential.__name__ + "." + get_current_utc_as_int.__name__, return_value=skip_to_timestamp, ): - credential = CommunicationTokenCredential( - initial_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(initial_token, token_refresher=refresher, proactive_refresh=True) with credential: access_token = credential.get_token() @@ -167,22 +139,12 @@ def test_proactive_refresher_keeps_scheduling_again(self): refresh_minutes = 10 token_validity_minutes = 60 expired_token = generate_token_with_custom_expiry(-5 * 60) - skip_to_timestamp = ( - get_current_utc_as_int() - + (token_validity_minutes - refresh_minutes) * 60 - + 1 - ) - first_refreshed_token = create_access_token( - generate_token_with_custom_expiry(token_validity_minutes * 60) - ) - last_refreshed_token = create_access_token( - generate_token_with_custom_expiry(2 * token_validity_minutes * 60) - ) + skip_to_timestamp = get_current_utc_as_int() + (token_validity_minutes - refresh_minutes) * 60 + 1 + first_refreshed_token = create_access_token(generate_token_with_custom_expiry(token_validity_minutes * 60)) + last_refreshed_token = create_access_token(generate_token_with_custom_expiry(2 * token_validity_minutes * 60)) refresher = MagicMock(side_effect=[first_refreshed_token, last_refreshed_token]) - credential = CommunicationTokenCredential( - expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expired_token, token_refresher=refresher, proactive_refresh=True) with credential: access_token = credential.get_token() with patch( @@ -207,9 +169,7 @@ def test_fractional_backoff_applied_when_token_expiring(self): ] ) - credential = CommunicationTokenCredential( - expiring_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(expiring_token, token_refresher=refresher, proactive_refresh=True) next_milestone = token_validity_seconds / 2 @@ -229,9 +189,7 @@ def test_refresher_should_not_be_called_when_token_still_valid(self): new_token = generate_token_with_custom_expiry(10 * 60) refresher = MagicMock(return_value=create_access_token(new_token)) - credential = CommunicationTokenCredential( - generated_token, token_refresher=refresher, proactive_refresh=False - ) + credential = CommunicationTokenCredential(generated_token, token_refresher=refresher, proactive_refresh=False) with credential: for _ in range(10): access_token = credential.get_token() @@ -240,25 +198,17 @@ def test_refresher_should_not_be_called_when_token_still_valid(self): assert generated_token == access_token.token def test_exit_cancels_timer(self): - refreshed_token = create_access_token( - generate_token_with_custom_expiry(30 * 60) - ) + refreshed_token = create_access_token(generate_token_with_custom_expiry(30 * 60)) refresher = MagicMock(return_value=refreshed_token) - credential = CommunicationTokenCredential( - self.expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(self.expired_token, token_refresher=refresher, proactive_refresh=True) with credential: assert credential._timer is not None assert credential._timer is None def test_exit_enter_scenario_throws_exception(self): - refreshed_token = create_access_token( - generate_token_with_custom_expiry(30 * 60) - ) + refreshed_token = create_access_token(generate_token_with_custom_expiry(30 * 60)) refresher = MagicMock(return_value=refreshed_token) - credential = CommunicationTokenCredential( - self.expired_token, token_refresher=refresher, proactive_refresh=True - ) + credential = CommunicationTokenCredential(self.expired_token, token_refresher=refresher, proactive_refresh=True) with credential: assert credential._timer is not None assert credential._timer is None @@ -266,7 +216,4 @@ def test_exit_enter_scenario_throws_exception(self): with pytest.raises(RuntimeError) as err: with credential: assert credential._timer is not None - assert ( - str(err.value) - == "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + assert str(err.value) == "An instance of CommunicationTokenCredential cannot be reused once it has been closed." diff --git a/sdk/communication/azure-communication-identity/tests/test_utils.py b/sdk/communication/azure-communication-identity/tests/test_utils.py index 0a3dc805310c..ae3fc2935624 100644 --- a/sdk/communication/azure-communication-identity/tests/test_utils.py +++ b/sdk/communication/azure-communication-identity/tests/test_utils.py @@ -12,39 +12,27 @@ class UtilsTest(unittest.TestCase): @staticmethod def get_token_with_custom_expiry(expires_on): expiry_json = '{"exp": ' + str(expires_on) + "}" - base64expiry = ( - base64.b64encode(expiry_json.encode("utf-8")).decode("utf-8").rstrip("=") - ) + base64expiry = base64.b64encode(expiry_json.encode("utf-8")).decode("utf-8").rstrip("=") token_template = ( - "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." - + base64expiry - + ".adM-ddBZZlQ1WlN3pdPBOF5G4Wh9iZpxNP_fSvpF4cWs" + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." + base64expiry + ".adM-ddBZZlQ1WlN3pdPBOF5G4Wh9iZpxNP_fSvpF4cWs" ) return token_template def test_convert_datetime_to_utc_int(self): # UTC - utc_time_in_sec = _convert_datetime_to_utc_int( - datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=dateutil.tz.tzutc()) - ) + utc_time_in_sec = _convert_datetime_to_utc_int(datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=dateutil.tz.tzutc())) assert utc_time_in_sec == 0 # UTC naive (without a timezone specified) - utc_naive_time_in_sec = _convert_datetime_to_utc_int( - datetime(1970, 1, 1, 0, 0, 0, 0) - ) + utc_naive_time_in_sec = _convert_datetime_to_utc_int(datetime(1970, 1, 1, 0, 0, 0, 0)) assert utc_naive_time_in_sec == 0 # PST is UTC-8 pst_time_in_sec = _convert_datetime_to_utc_int( - datetime( - 1970, 1, 1, 0, 0, 0, 0, tzinfo=dateutil.tz.gettz("America/Vancouver") - ) + datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=dateutil.tz.gettz("America/Vancouver")) ) assert pst_time_in_sec == 8 * 3600 # EST is UTC-5 est_time_in_sec = _convert_datetime_to_utc_int( - datetime( - 1970, 1, 1, 0, 0, 0, 0, tzinfo=dateutil.tz.gettz("America/New_York") - ) + datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=dateutil.tz.gettz("America/New_York")) ) assert est_time_in_sec == 5 * 3600 # CST is UTC+8 diff --git a/sdk/communication/azure-communication-identity/tests/utils.py b/sdk/communication/azure-communication-identity/tests/utils.py index 107cfb0448ae..a0c53b3529b0 100644 --- a/sdk/communication/azure-communication-identity/tests/utils.py +++ b/sdk/communication/azure-communication-identity/tests/utils.py @@ -8,9 +8,7 @@ from azure.communication.identity import CommunicationTokenScope -def is_token_expiration_within_allowed_deviation( - expected_token_expiration, token_expires_in, allowed_deviation=0.05 -): +def is_token_expiration_within_allowed_deviation(expected_token_expiration, token_expires_in, allowed_deviation=0.05): # type: (timedelta, datetime, float) -> bool utc_now = datetime.now(timezone.utc) token_expiration = parser.parse(str(token_expires_in)) diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_model_base.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_model_base.py index 1ddc071517d6..d951cecef5ac 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_model_base.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_model_base.py @@ -378,16 +378,13 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: return default @typing.overload - def pop(self, key: str) -> typing.Any: - ... + def pop(self, key: str) -> typing.Any: ... @typing.overload - def pop(self, key: str, default: _T) -> _T: - ... + def pop(self, key: str, default: _T) -> _T: ... @typing.overload - def pop(self, key: str, default: typing.Any) -> typing.Any: - ... + def pop(self, key: str, default: typing.Any) -> typing.Any: ... def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: if default is _UNSET: @@ -404,12 +401,10 @@ def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: self._data.update(*args, **kwargs) @typing.overload - def setdefault(self, key: str, default: None = None) -> None: - ... + def setdefault(self, key: str, default: None = None) -> None: ... @typing.overload - def setdefault(self, key: str, default: typing.Any) -> typing.Any: - ... + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: if default is _UNSET: diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py index b6747c961542..cebc890fbfda 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py @@ -5951,20 +5951,17 @@ def _reclassify_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: - ... + ) -> _models._models.ReclassifyJobResult: ... @overload def _reclassify_job( # pylint: disable=protected-access self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: - ... + ) -> _models._models.ReclassifyJobResult: ... @overload def _reclassify_job( # pylint: disable=protected-access self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: - ... + ) -> _models._models.ReclassifyJobResult: ... @distributed_trace def _reclassify_job( # pylint: disable=protected-access @@ -6062,20 +6059,17 @@ def _cancel_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: - ... + ) -> _models._models.CancelJobResult: ... @overload def _cancel_job( # pylint: disable=protected-access self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: - ... + ) -> _models._models.CancelJobResult: ... @overload def _cancel_job( # pylint: disable=protected-access self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: - ... + ) -> _models._models.CancelJobResult: ... @distributed_trace def _cancel_job( # pylint: disable=protected-access @@ -6178,8 +6172,7 @@ def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: - ... + ) -> _models._models.CompleteJobResult: ... @overload def _complete_job( # pylint: disable=protected-access @@ -6190,8 +6183,7 @@ def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: - ... + ) -> _models._models.CompleteJobResult: ... @overload def _complete_job( # pylint: disable=protected-access @@ -6202,8 +6194,7 @@ def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: - ... + ) -> _models._models.CompleteJobResult: ... @distributed_trace def _complete_job( # pylint: disable=protected-access @@ -6309,8 +6300,7 @@ def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: - ... + ) -> _models._models.CloseJobResult: ... @overload def _close_job( # pylint: disable=protected-access @@ -6321,8 +6311,7 @@ def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: - ... + ) -> _models._models.CloseJobResult: ... @overload def _close_job( # pylint: disable=protected-access @@ -6333,8 +6322,7 @@ def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: - ... + ) -> _models._models.CloseJobResult: ... @distributed_trace def _close_job( # pylint: disable=protected-access @@ -7062,8 +7050,7 @@ def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: - ... + ) -> _models._models.DeclineJobOfferResult: ... @overload def _decline_job_offer( # pylint: disable=protected-access @@ -7074,8 +7061,7 @@ def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: - ... + ) -> _models._models.DeclineJobOfferResult: ... @overload def _decline_job_offer( # pylint: disable=protected-access @@ -7086,8 +7072,7 @@ def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: - ... + ) -> _models._models.DeclineJobOfferResult: ... @distributed_trace def _decline_job_offer( # pylint: disable=protected-access diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py index a42a1a9ecbaf..ba355e5a489f 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py @@ -1753,10 +1753,7 @@ def upsert_job( """ def upsert_job( # pylint: disable=docstring-missing-param - self, - job_id: str, - *args: Union[_models.RouterJob, JSON, IO[bytes]], - **kwargs: Any + self, job_id: str, *args: Union[_models.RouterJob, JSON, IO[bytes]], **kwargs: Any ) -> _models.RouterJob: """Update a job. diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py index f56155fa52fb..ce08bff0ad1d 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py @@ -5049,20 +5049,17 @@ async def _reclassify_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: - ... + ) -> _models._models.ReclassifyJobResult: ... @overload async def _reclassify_job( # pylint: disable=protected-access self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: - ... + ) -> _models._models.ReclassifyJobResult: ... @overload async def _reclassify_job( # pylint: disable=protected-access self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: - ... + ) -> _models._models.ReclassifyJobResult: ... @distributed_trace_async async def _reclassify_job( # pylint: disable=protected-access @@ -5160,20 +5157,17 @@ async def _cancel_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: - ... + ) -> _models._models.CancelJobResult: ... @overload async def _cancel_job( # pylint: disable=protected-access self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: - ... + ) -> _models._models.CancelJobResult: ... @overload async def _cancel_job( # pylint: disable=protected-access self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: - ... + ) -> _models._models.CancelJobResult: ... @distributed_trace_async async def _cancel_job( # pylint: disable=protected-access @@ -5276,8 +5270,7 @@ async def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: - ... + ) -> _models._models.CompleteJobResult: ... @overload async def _complete_job( # pylint: disable=protected-access @@ -5288,8 +5281,7 @@ async def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: - ... + ) -> _models._models.CompleteJobResult: ... @overload async def _complete_job( # pylint: disable=protected-access @@ -5300,8 +5292,7 @@ async def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: - ... + ) -> _models._models.CompleteJobResult: ... @distributed_trace_async async def _complete_job( # pylint: disable=protected-access @@ -5407,8 +5398,7 @@ async def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: - ... + ) -> _models._models.CloseJobResult: ... @overload async def _close_job( # pylint: disable=protected-access @@ -5419,8 +5409,7 @@ async def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: - ... + ) -> _models._models.CloseJobResult: ... @overload async def _close_job( # pylint: disable=protected-access @@ -5431,8 +5420,7 @@ async def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: - ... + ) -> _models._models.CloseJobResult: ... @distributed_trace_async async def _close_job( # pylint: disable=protected-access @@ -6161,8 +6149,7 @@ async def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: - ... + ) -> _models._models.DeclineJobOfferResult: ... @overload async def _decline_job_offer( # pylint: disable=protected-access @@ -6173,8 +6160,7 @@ async def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: - ... + ) -> _models._models.DeclineJobOfferResult: ... @overload async def _decline_job_offer( # pylint: disable=protected-access @@ -6185,8 +6171,7 @@ async def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: - ... + ) -> _models._models.DeclineJobOfferResult: ... @distributed_trace_async async def _decline_job_offer( # pylint: disable=protected-access diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py index 746ee8a85300..56b16aa93487 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py @@ -55,8 +55,7 @@ def __init__( assignment_id: str, job_id: str, worker_id: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -115,8 +114,7 @@ def __init__( min_concurrent_offers: Optional[int] = None, max_concurrent_offers: Optional[int] = None, bypass_selectors: Optional[bool] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -178,8 +176,7 @@ def __init__( bypass_selectors: Optional[bool] = None, scoring_rule: Optional["_models.RouterRule"] = None, scoring_rule_options: Optional["_models.ScoringRuleOptions"] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -220,8 +217,7 @@ def __init__( *, kind: str, id: Optional[str] = None, # pylint: disable=redefined-builtin - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -267,8 +263,7 @@ def __init__( id: Optional[str] = None, # pylint: disable=redefined-builtin note: Optional[str] = None, disposition_code: Optional[str] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -304,8 +299,7 @@ def __init__( *, note: Optional[str] = None, disposition_code: Optional[str] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -377,8 +371,7 @@ def __init__( queue_selector_attachments: Optional[List["_models.QueueSelectorAttachment"]] = None, prioritization_rule: Optional["_models.RouterRule"] = None, worker_selector_attachments: Optional[List["_models.WorkerSelectorAttachment"]] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -422,8 +415,7 @@ def __init__( disposition_code: Optional[str] = None, close_at: Optional[datetime.datetime] = None, note: Optional[str] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -456,8 +448,7 @@ def __init__( self, *, note: Optional[str] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -500,8 +491,7 @@ def __init__( self, *, kind: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -544,8 +534,7 @@ def __init__( *, condition: "_models.RouterRule", queue_selectors: List["_models.RouterQueueSelector"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -585,8 +574,7 @@ def __init__( self, *, kind: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -629,8 +617,7 @@ def __init__( *, condition: "_models.RouterRule", worker_selectors: List["_models.RouterWorkerSelector"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -665,8 +652,7 @@ def __init__( self, *, retry_offer_at: Optional[datetime.datetime] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -714,8 +700,7 @@ def __init__( self, *, kind: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -781,8 +766,7 @@ def __init__( name: Optional[str] = None, offer_expires_after_seconds: Optional[float] = None, mode: Optional["_models.DistributionMode"] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -827,8 +811,7 @@ def __init__( *, name: Optional[str] = None, exception_rules: Optional[List["_models.ExceptionRule"]] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -868,8 +851,7 @@ def __init__( id: str, # pylint: disable=redefined-builtin trigger: "_models.ExceptionTrigger", actions: List["_models.ExceptionAction"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -905,8 +887,7 @@ def __init__( self, *, kind: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -948,8 +929,7 @@ def __init__( *, expression: str, language: Optional[Union[str, "_models.ExpressionRouterRuleLanguage"]] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -990,8 +970,7 @@ def __init__( *, function_uri: str, credential: Optional["_models.FunctionRouterRuleCredential"] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1033,8 +1012,7 @@ def __init__( function_key: Optional[str] = None, app_key: Optional[str] = None, client_id: Optional[str] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1075,8 +1053,7 @@ def __init__( self, *, kind: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1121,8 +1098,7 @@ def __init__( min_concurrent_offers: Optional[int] = None, max_concurrent_offers: Optional[int] = None, bypass_selectors: Optional[bool] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1172,8 +1148,7 @@ def __init__( queue_id: Optional[str] = None, priority: Optional[int] = None, worker_selectors: Optional[List["_models.RouterWorkerSelector"]] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1207,8 +1182,7 @@ def __init__( *, client_id: Optional[str] = None, client_secret: Optional[str] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1254,8 +1228,7 @@ def __init__( *, key: str, label_operator: Union[str, "_models.LabelOperator"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1307,8 +1280,7 @@ def __init__( key: str, label_operator: Union[str, "_models.LabelOperator"], expires_after_seconds: Optional[float] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1361,8 +1333,7 @@ def __init__( self, *, threshold: int, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1399,8 +1370,7 @@ def __init__( *, weight: float, queue_selectors: List["_models.RouterQueueSelector"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1447,8 +1417,7 @@ def __init__( id: Optional[str] = None, # pylint: disable=redefined-builtin classification_policy_id: Optional[str] = None, labels_to_upsert: Optional[Dict[str, Any]] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1502,8 +1471,7 @@ def __init__( min_concurrent_offers: Optional[int] = None, max_concurrent_offers: Optional[int] = None, bypass_selectors: Optional[bool] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1546,8 +1514,7 @@ def __init__( channel_id: str, capacity_cost_per_job: int, max_number_of_jobs: Optional[int] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1677,8 +1644,7 @@ def __init__( tags: Optional[Dict[str, Any]] = None, notes: Optional[List["_models.RouterJobNote"]] = None, matching_mode: Optional["_models.JobMatchingMode"] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1729,8 +1695,7 @@ def __init__( worker_id: Optional[str] = None, completed_at: Optional[datetime.datetime] = None, closed_at: Optional[datetime.datetime] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1766,8 +1731,7 @@ def __init__( *, message: str, added_at: Optional[datetime.datetime] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1818,8 +1782,7 @@ def __init__( capacity_cost: int, offered_at: Optional[datetime.datetime] = None, expires_at: Optional[datetime.datetime] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1870,8 +1833,7 @@ def __init__( queue_id: str, queue_length: int, estimated_wait_time_minutes: float, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1930,8 +1892,7 @@ def __init__( distribution_policy_id: Optional[str] = None, labels: Optional[Dict[str, Any]] = None, exception_policy_id: Optional[str] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1977,8 +1938,7 @@ def __init__( key: str, label_operator: Union[str, "_models.LabelOperator"], value: Optional[Any] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2026,8 +1986,7 @@ def __init__( length: int, estimated_wait_time_minutes: Optional[Dict[str, float]] = None, longest_job_wait_time_minutes: Optional[float] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2123,8 +2082,7 @@ def __init__( channels: Optional[List["_models.RouterChannel"]] = None, available_for_offers: Optional[bool] = None, max_concurrent_offers: Optional[int] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2170,8 +2128,7 @@ def __init__( job_id: str, capacity_cost: int, assigned_at: datetime.datetime, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2237,8 +2194,7 @@ def __init__( value: Optional[Any] = None, expires_after_seconds: Optional[float] = None, expedite: Optional[bool] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2274,8 +2230,7 @@ def __init__( self, *, rule: "_models.RouterRule", - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2311,8 +2266,7 @@ def __init__( self, *, rule: "_models.RouterRule", - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2349,8 +2303,7 @@ def __init__( self, *, schedule_at: datetime.datetime, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2408,8 +2361,7 @@ def __init__( scoring_parameters: Optional[List[Union[str, "_models.ScoringRuleParameterSelector"]]] = None, is_batch_scoring_enabled: Optional[bool] = None, descending_order: Optional[bool] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2445,8 +2397,7 @@ def __init__( self, *, queue_selector: "_models.RouterQueueSelector", - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2484,8 +2435,7 @@ def __init__( self, *, value: Optional[Any] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2521,8 +2471,7 @@ def __init__( self, *, worker_selector: "_models.RouterWorkerSelector", - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2565,8 +2514,7 @@ def __init__( self, *, suspend_matching: Optional[bool] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2601,8 +2549,7 @@ def __init__( *, job_id: str, unassignment_count: int, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2638,8 +2585,7 @@ def __init__( self, *, threshold_seconds: float, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2687,8 +2633,7 @@ def __init__( authorization_server_uri: Optional[str] = None, client_credential: Optional["_models.OAuth2WebhookClientCredential"] = None, webhook_uri: Optional[str] = None, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2727,8 +2672,7 @@ def __init__( self, *, allocations: List["_models.QueueWeightedAllocation"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2767,8 +2711,7 @@ def __init__( self, *, allocations: List["_models.WorkerWeightedAllocation"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -2805,8 +2748,7 @@ def __init__( *, weight: float, worker_selectors: List["_models.RouterWorkerSelector"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): diff --git a/sdk/communication/azure-communication-jobrouter/samples/router_worker_crud_ops_async.py b/sdk/communication/azure-communication-jobrouter/samples/router_worker_crud_ops_async.py index ee461febddf8..67e2071427d8 100644 --- a/sdk/communication/azure-communication-jobrouter/samples/router_worker_crud_ops_async.py +++ b/sdk/communication/azure-communication-jobrouter/samples/router_worker_crud_ops_async.py @@ -139,7 +139,7 @@ async def create_worker_w_limit_concurrent_offers(self): ], labels={"Location": "NA", "English": 7, "O365": True, "Xbox_Support": False}, tags={"Name": "John Doe", "Department": "IT_HelpDesk"}, - max_concurrent_offers = 1, + max_concurrent_offers=1, ), ) diff --git a/sdk/communication/azure-communication-jobrouter/tests/_shared/utils.py b/sdk/communication/azure-communication-jobrouter/tests/_shared/utils.py index 955346bee1a6..69a0d2586209 100644 --- a/sdk/communication/azure-communication-jobrouter/tests/_shared/utils.py +++ b/sdk/communication/azure-communication-jobrouter/tests/_shared/utils.py @@ -20,7 +20,7 @@ def create_token_credential(): from .fake_token_credential import FakeTokenCredential return FakeTokenCredential() - + return get_credential() @@ -32,7 +32,7 @@ def async_create_token_credential(): from .async_fake_token_credential import AsyncFakeTokenCredential return AsyncFakeTokenCredential() - + return get_credential(is_async=True) diff --git a/sdk/communication/azure-communication-jobrouter/tests/conftest.py b/sdk/communication/azure-communication-jobrouter/tests/conftest.py index 15c11590efd7..3eebc195c198 100644 --- a/sdk/communication/azure-communication-jobrouter/tests/conftest.py +++ b/sdk/communication/azure-communication-jobrouter/tests/conftest.py @@ -43,6 +43,7 @@ # fixture needs to be visible from conftest + # autouse=True will trigger this fixture on each pytest run, even if it's not explicitly used by a test method @pytest.fixture(scope="session", autouse=True) def start_proxy(test_proxy): diff --git a/sdk/communication/azure-communication-phonenumbers/azure/__init__.py b/sdk/communication/azure-communication-phonenumbers/azure/__init__.py index 69e3be50dac4..8db66d3d0f0f 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/__init__.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/__init__.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/__init__.py index 69e3be50dac4..8db66d3d0f0f 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/__init__.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/__init__.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/__init__.py index ab180ebada62..0ec6ebc9852f 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/__init__.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/__init__.py @@ -24,19 +24,19 @@ ) __all__ = [ - 'PurchasedPhoneNumber', - 'PhoneNumberCapabilities', - 'PhoneNumberCost', - 'PhoneNumberSearchResult', - 'BillingFrequency', - 'PhoneNumberAssignmentType', - 'PhoneNumberCapabilityType', - 'PhoneNumberType', - 'PhoneNumberAreaCode', - 'PhoneNumberAdministrativeDivision', - 'PhoneNumberCountry', - 'PhoneNumberLocality', - 'PhoneNumberOffering', - 'OperatorInformationResult', - 'PhoneNumbersClient' + "PurchasedPhoneNumber", + "PhoneNumberCapabilities", + "PhoneNumberCost", + "PhoneNumberSearchResult", + "BillingFrequency", + "PhoneNumberAssignmentType", + "PhoneNumberCapabilityType", + "PhoneNumberType", + "PhoneNumberAreaCode", + "PhoneNumberAdministrativeDivision", + "PhoneNumberCountry", + "PhoneNumberLocality", + "PhoneNumberOffering", + "OperatorInformationResult", + "PhoneNumbersClient", ] diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_phone_numbers_client.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_phone_numbers_client.py index 2dd7d34b6ea3..faa85c3dff75 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_phone_numbers_client.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_phone_numbers_client.py @@ -54,21 +54,15 @@ class PhoneNumbersClient: :paramtype api_version: str """ - def __init__( - self, - endpoint: str, - credential: Union[TokenCredential, AzureKeyCredential], - **kwargs: Any - ) -> None: + def __init__(self, endpoint: str, credential: Union[TokenCredential, AzureKeyCredential], **kwargs: Any) -> None: try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError as e: raise ValueError("Account URL must be a string.") from e if not credential: - raise ValueError( - "You need to provide account shared key to authenticate.") + raise ValueError("You need to provide account shared key to authenticate.") self._endpoint = endpoint self._accepted_language = kwargs.pop("accepted_language", None) @@ -76,16 +70,13 @@ def __init__( self._phone_number_client = PhoneNumbersClientGen( self._endpoint, api_version=self._api_version, - authentication_policy=get_authentication_policy( - endpoint, credential), + authentication_policy=get_authentication_policy(endpoint, credential), sdk_moniker=SDK_MONIKER, - **kwargs) + **kwargs + ) @classmethod - def from_connection_string( - cls, conn_str: str, - **kwargs: Any - ) -> "PhoneNumbersClient": + def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "PhoneNumbersClient": """Create PhoneNumbersClient from a Connection String. :param str conn_str: @@ -98,11 +89,7 @@ def from_connection_string( return cls(endpoint, access_key, **kwargs) @distributed_trace - def begin_purchase_phone_numbers( - self, - search_id: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_purchase_phone_numbers(self, search_id: str, **kwargs: Any) -> LROPoller[None]: """Purchases phone numbers. :param search_id: The search id. @@ -118,20 +105,13 @@ def begin_purchase_phone_numbers( """ purchase_request = PhoneNumberPurchaseRequest(search_id=search_id) - polling_interval = kwargs.pop( - 'polling_interval', _DEFAULT_POLLING_INTERVAL_IN_SECONDS) + polling_interval = kwargs.pop("polling_interval", _DEFAULT_POLLING_INTERVAL_IN_SECONDS) return self._phone_number_client.phone_numbers.begin_purchase_phone_numbers( - body=purchase_request, - polling_interval=polling_interval, - **kwargs + body=purchase_request, polling_interval=polling_interval, **kwargs ) @distributed_trace - def begin_release_phone_number( - self, - phone_number: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_release_phone_number(self, phone_number: str, **kwargs: Any) -> LROPoller[None]: """Releases an purchased phone number. :param phone_number: Phone number to be released, e.g. +55534567890. @@ -145,22 +125,19 @@ def begin_release_phone_number( :returns: A poller to wait on the status of the release operation. :rtype: ~azure.core.polling.LROPoller[None] """ - polling_interval = kwargs.pop( - "polling_interval", _DEFAULT_POLLING_INTERVAL_IN_SECONDS) + polling_interval = kwargs.pop("polling_interval", _DEFAULT_POLLING_INTERVAL_IN_SECONDS) return self._phone_number_client.phone_numbers.begin_release_phone_number( - phone_number, - polling_interval=polling_interval, - **kwargs + phone_number, polling_interval=polling_interval, **kwargs ) @distributed_trace def begin_search_available_phone_numbers( - self, - country_code: str, - phone_number_type: Union[PhoneNumberType, str], - assignment_type: Union[PhoneNumberAssignmentType, str], - capabilities: PhoneNumberCapabilities, - **kwargs: Any + self, + country_code: str, + phone_number_type: Union[PhoneNumberType, str], + assignment_type: Union[PhoneNumberAssignmentType, str], + capabilities: PhoneNumberCapabilities, + **kwargs: Any ) -> LROPoller[PhoneNumberSearchResult]: """Search for available phone numbers to purchase. @@ -192,16 +169,12 @@ def begin_search_available_phone_numbers( phone_number_type=phone_number_type, assignment_type=assignment_type, capabilities=capabilities, - quantity=kwargs.pop('quantity', None), - area_code=kwargs.pop('area_code', None) + quantity=kwargs.pop("quantity", None), + area_code=kwargs.pop("area_code", None), ) - polling_interval = kwargs.pop( - 'polling_interval', _DEFAULT_POLLING_INTERVAL_IN_SECONDS) + polling_interval = kwargs.pop("polling_interval", _DEFAULT_POLLING_INTERVAL_IN_SECONDS) return self._phone_number_client.phone_numbers.begin_search_available_phone_numbers( - country_code, - search_request, - polling_interval=polling_interval, - **kwargs + country_code, search_request, polling_interval=polling_interval, **kwargs ) @distributed_trace @@ -231,35 +204,25 @@ def begin_update_phone_number_capabilities( :rtype: ~azure.core.polling.LROPoller[~azure.communication.phonenumbers.PurchasedPhoneNumber] """ - capabilities_request = PhoneNumberCapabilitiesRequest( - calling=calling, sms=sms) + capabilities_request = PhoneNumberCapabilitiesRequest(calling=calling, sms=sms) - polling_interval = kwargs.pop( - 'polling_interval', _DEFAULT_POLLING_INTERVAL_IN_SECONDS) + polling_interval = kwargs.pop("polling_interval", _DEFAULT_POLLING_INTERVAL_IN_SECONDS) if not phone_number: raise ValueError("phone_number can't be empty") poller = self._phone_number_client.phone_numbers.begin_update_capabilities( - phone_number, - body=capabilities_request, - polling_interval=polling_interval, - **kwargs + phone_number, body=capabilities_request, polling_interval=polling_interval, **kwargs ) result_properties = poller.result().additional_properties - if 'status' in result_properties and result_properties['status'].lower() == 'failed': - raise HttpResponseError( - message=result_properties['error']['message']) + if "status" in result_properties and result_properties["status"].lower() == "failed": + raise HttpResponseError(message=result_properties["error"]["message"]) return poller @distributed_trace - def get_purchased_phone_number( - self, - phone_number: str, - **kwargs: Any - ) -> PurchasedPhoneNumber: + def get_purchased_phone_number(self, phone_number: str, **kwargs: Any) -> PurchasedPhoneNumber: """Gets the details of the given purchased phone number. :param phone_number: The purchased phone number whose details are to be fetched in E.164 format, @@ -268,16 +231,10 @@ def get_purchased_phone_number( :return: The details of the given purchased phone number. :rtype: ~azure.communication.phonenumbers.PurchasedPhoneNumber """ - return self._phone_number_client.phone_numbers.get_by_number( - phone_number, - **kwargs - ) + return self._phone_number_client.phone_numbers.get_by_number(phone_number, **kwargs) @distributed_trace - def list_purchased_phone_numbers( - self, - **kwargs: Any - ) -> ItemPaged[PurchasedPhoneNumber]: + def list_purchased_phone_numbers(self, **kwargs: Any) -> ItemPaged[PurchasedPhoneNumber]: """Gets the list of all purchased phone numbers. :keyword skip: An optional parameter for how many entries to skip, for pagination purposes. The @@ -289,15 +246,10 @@ def list_purchased_phone_numbers( :returns: An iterator of purchased phone numbers. :rtype: ~azure.core.paging.ItemPaged[~azure.communication.phonenumbers.PurchasedPhoneNumber] """ - return self._phone_number_client.phone_numbers.list_phone_numbers( - **kwargs - ) + return self._phone_number_client.phone_numbers.list_phone_numbers(**kwargs) @distributed_trace - def list_available_countries( - self, - **kwargs: Any - ) -> ItemPaged[PhoneNumberCountry]: + def list_available_countries(self, **kwargs: Any) -> ItemPaged[PhoneNumberCountry]: """Gets the list of supported countries. Gets the list of supported countries. @@ -311,16 +263,11 @@ def list_available_countries( :raises ~azure.core.exceptions.HttpResponseError: """ return self._phone_number_client.phone_numbers.list_available_countries( - accept_language=self._accepted_language, - **kwargs + accept_language=self._accepted_language, **kwargs ) @distributed_trace - def list_available_localities( - self, - country_code: str, - **kwargs: Any - ) -> ItemPaged[PhoneNumberLocality]: + def list_available_localities(self, country_code: str, **kwargs: Any) -> ItemPaged[PhoneNumberLocality]: """Gets the list of cities or towns with available phone numbers. Gets the list of cities or towns with available phone numbers. @@ -340,18 +287,13 @@ def list_available_localities( """ return self._phone_number_client.phone_numbers.list_available_localities( country_code, - administrative_division=kwargs.pop( - "administrative_division", None), + administrative_division=kwargs.pop("administrative_division", None), accept_language=self._accepted_language, **kwargs ) @distributed_trace - def list_available_offerings( - self, - country_code: str, - **kwargs: Any - ) -> ItemPaged[PhoneNumberOffering]: + def list_available_offerings(self, country_code: str, **kwargs: Any) -> ItemPaged[PhoneNumberOffering]: """List available offerings of capabilities with rates for the given country/region. List available offerings of capabilities with rates for the given country/region. @@ -381,10 +323,7 @@ def list_available_offerings( @distributed_trace def list_available_area_codes( - self, - country_code: str, - phone_number_type: PhoneNumberType, - **kwargs: Any + self, country_code: str, phone_number_type: PhoneNumberType, **kwargs: Any ) -> ItemPaged[PhoneNumberAreaCode]: """Gets the list of available area codes. @@ -412,21 +351,15 @@ def list_available_area_codes( return self._phone_number_client.phone_numbers.list_area_codes( country_code, phone_number_type=phone_number_type, - assignment_type=kwargs.pop( - "assignment_type", None), - locality=kwargs.pop( - "locality", None), - administrative_division=kwargs.pop( - "administrative_division", None), + assignment_type=kwargs.pop("assignment_type", None), + locality=kwargs.pop("locality", None), + administrative_division=kwargs.pop("administrative_division", None), **kwargs ) @distributed_trace def search_operator_information( - self, - phone_numbers: Union[str, List[str]], - options: Optional[OperatorInformationOptions] = None, - **kwargs: Any + self, phone_numbers: Union[str, List[str]], options: Optional[OperatorInformationOptions] = None, **kwargs: Any ) -> OperatorInformationResult: """Searches for operator information for a given list of phone numbers. @@ -438,11 +371,8 @@ def search_operator_information( :rtype: ~azure.communication.phonenumbers.OperatorInformationResult """ if not isinstance(phone_numbers, list): - phone_numbers = [ phone_numbers ] + phone_numbers = [phone_numbers] if options is None: options = OperatorInformationOptions(include_additional_operator_details=False) - request = OperatorInformationRequest(phone_numbers = phone_numbers, options=options) - return self._phone_number_client.phone_numbers.operator_information_search( - request, - **kwargs - ) + request = OperatorInformationRequest(phone_numbers=phone_numbers, options=options) + return self._phone_number_client.phone_numbers.operator_information_search(request, **kwargs) diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/auth_policy_utils.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/auth_policy_utils.py index 4ea2048feb08..f021c34e892d 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/auth_policy_utils.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/auth_policy_utils.py @@ -43,9 +43,7 @@ def get_authentication_policy( return AsyncBearerTokenCredentialPolicy( credential, "https://communication.azure.com//.default" # type: ignore ) - return BearerTokenCredentialPolicy( - credential, "https://communication.azure.com//.default" # type: ignore - ) + return BearerTokenCredentialPolicy(credential, "https://communication.azure.com//.default") # type: ignore if isinstance(credential, (AzureKeyCredential, str)): return HMACCredentialsPolicy(endpoint, credential, decode_url=decode_url) diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/models.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/models.py index 7b646472045c..43875e1197e5 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/models.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/models.py @@ -14,8 +14,11 @@ class DeprecatedEnumMeta(CaseInsensitiveEnumMeta): def __getattribute__(cls, item): if item.upper() == "MICROSOFT_BOT": - warnings.warn("MICROSOFT_BOT is deprecated and has been replaced by \ - MICROSOFT_TEAMS_APP identifier.", DeprecationWarning) + warnings.warn( + "MICROSOFT_BOT is deprecated and has been replaced by \ + MICROSOFT_TEAMS_APP identifier.", + DeprecationWarning, + ) item = "MICROSOFT_TEAMS_APP" return super().__getattribute__(item) @@ -47,14 +50,17 @@ class CommunicationCloudEnvironment(str, Enum, metaclass=CaseInsensitiveEnumMeta @runtime_checkable class CommunicationIdentifier(Protocol): """Communication Identifier.""" + @property def raw_id(self) -> str: """The raw ID of the identifier.""" ... + @property def kind(self) -> CommunicationIdentifierKind: """The type of identifier.""" ... + @property def properties(self) -> Mapping[str, Any]: """The properties of the identifier.""" @@ -83,12 +89,14 @@ def properties(self) -> Mapping[str, Any]: class CommunicationUserProperties(TypedDict): """Dictionary of properties for a CommunicationUserIdentifier.""" + id: str """ID of the Communication user as returned from Azure Communication Identity.""" class CommunicationUserIdentifier: """Represents a user in Azure Communication Service.""" + kind: Literal[CommunicationIdentifierKind.COMMUNICATION_USER] = CommunicationIdentifierKind.COMMUNICATION_USER """The type of identifier.""" properties: CommunicationUserProperties @@ -116,12 +124,14 @@ def __eq__(self, other): class PhoneNumberProperties(TypedDict): """Dictionary of properties for a PhoneNumberIdentifier.""" + value: str """The phone number in E.164 format.""" class PhoneNumberIdentifier: """Represents a phone number.""" + kind: Literal[CommunicationIdentifierKind.PHONE_NUMBER] = CommunicationIdentifierKind.PHONE_NUMBER """The type of identifier.""" properties: PhoneNumberProperties @@ -165,6 +175,7 @@ class UnknownIdentifier: It is not advisable to rely on the `kind` property with a value `unknown`, as it could become a new or existing distinct type in the future. """ + kind: Literal[CommunicationIdentifierKind.UNKNOWN] = CommunicationIdentifierKind.UNKNOWN """The type of identifier.""" properties: Mapping[str, Any] @@ -188,6 +199,7 @@ def __eq__(self, other): class MicrosoftTeamsUserProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsUserIdentifier.""" + user_id: str """The id of the Microsoft Teams user. If the user isn't anonymous, the id is the AAD object id of the user.""" is_anonymous: bool @@ -198,6 +210,7 @@ class MicrosoftTeamsUserProperties(TypedDict): class MicrosoftTeamsUserIdentifier: """Represents an identifier for a Microsoft Teams user.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_USER] = CommunicationIdentifierKind.MICROSOFT_TEAMS_USER """The type of identifier.""" properties: MicrosoftTeamsUserProperties @@ -246,6 +259,7 @@ def _format_raw_id(self, properties: MicrosoftTeamsUserProperties) -> str: class MicrosoftTeamsAppProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsAppIdentifier.""" + app_id: str """The id of the Microsoft Teams application.""" cloud: Union[CommunicationCloudEnvironment, str] @@ -254,6 +268,7 @@ class MicrosoftTeamsAppProperties(TypedDict): class _botbackcompatdict(dict): """Backwards compatible properties.""" + def __getitem__(self, __key: Any) -> Any: try: return super().__getitem__(__key) @@ -267,6 +282,7 @@ def __getitem__(self, __key: Any) -> Any: class MicrosoftTeamsAppIdentifier: """Represents an identifier for a Microsoft Teams application.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_APP] = CommunicationIdentifierKind.MICROSOFT_TEAMS_APP """The type of identifier.""" properties: MicrosoftTeamsAppProperties @@ -282,10 +298,13 @@ def __init__(self, app_id: str, **kwargs: Any) -> None: :keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed from the other properties. """ - self.properties = cast(MicrosoftTeamsAppProperties, _botbackcompatdict( - app_id=app_id, - cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, - )) + self.properties = cast( + MicrosoftTeamsAppProperties, + _botbackcompatdict( + app_id=app_id, + cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, + ), + ) raw_id: Optional[str] = kwargs.get("raw_id") self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties) @@ -323,7 +342,7 @@ def __init__(self, bot_id, **kwargs): """ warnings.warn( "The MicrosoftBotIdentifier is deprecated and has been replaced by MicrosoftTeamsAppIdentifier.", - DeprecationWarning + DeprecationWarning, ) super().__init__(bot_id, **kwargs) @@ -339,9 +358,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d :rtype: CommunicationIdentifier """ if raw_id.startswith(PHONE_NUMBER_PREFIX): - return PhoneNumberIdentifier( - value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id - ) + return PhoneNumberIdentifier(value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id) segments = raw_id.split(":", maxsplit=2) if len(segments) < 3: @@ -350,9 +367,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d prefix = f"{segments[0]}:{segments[1]}:" suffix = segments[2] if prefix == TEAMS_USER_ANONYMOUS_PREFIX: - return MicrosoftTeamsUserIdentifier( - user_id=suffix, is_anonymous=True, raw_id=raw_id - ) + return MicrosoftTeamsUserIdentifier(user_id=suffix, is_anonymous=True, raw_id=raw_id) if prefix == TEAMS_USER_PUBLIC_CLOUD_PREFIX: return MicrosoftTeamsUserIdentifier( user_id=suffix, diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/policy.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/policy.py index 2fd2e7426c73..79aa48136fd3 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/policy.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/policy.py @@ -50,9 +50,7 @@ def _compute_hmac( else: decoded_secret = base64.b64decode(self._access_key) - digest = hmac.new( - decoded_secret, value.encode("utf-8"), hashlib.sha256 - ).digest() + digest = hmac.new(decoded_secret, value.encode("utf-8"), hashlib.sha256).digest() return base64.b64encode(digest).decode("utf-8") @@ -101,22 +99,10 @@ def _sign_request(self, request): utc_now = get_current_utc_time() if request.http_request.body is None: request.http_request.body = "" - content_digest = hashlib.sha256( - (request.http_request.body.encode("utf-8")) - ).digest() + content_digest = hashlib.sha256((request.http_request.body.encode("utf-8"))).digest() content_hash = base64.b64encode(content_digest).decode("utf-8") - string_to_sign = ( - verb - + "\n" - + query_url - + "\n" - + utc_now - + ";" - + self._host - + ";" - + content_hash - ) + string_to_sign = verb + "\n" + query_url + "\n" + utc_now + ";" + self._host + ";" + content_hash signature = self._compute_hmac(string_to_sign) @@ -124,10 +110,7 @@ def _sign_request(self, request): "x-ms-date": utc_now, "x-ms-content-sha256": content_hash, "x-ms-return-client-request-id": "true", - "Authorization": "HMAC-SHA256 SignedHeaders=" - + signed_headers - + "&Signature=" - + signature, + "Authorization": "HMAC-SHA256 SignedHeaders=" + signed_headers + "&Signature=" + signature, } request.http_request.headers.update(signature_header) diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/user_credential.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/user_credential.py index c7c150052918..54603e7b32ce 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/user_credential.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/user_credential.py @@ -38,9 +38,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._lock = Condition(Lock()) self._some_thread_refreshing = False @@ -54,9 +52,7 @@ def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -80,9 +76,7 @@ def _update_token_and_reschedule(self): try: new_token = self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -109,12 +103,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() if timespan <= TIMEOUT_MAX: self._timer = Timer(timespan, self._update_token_and_reschedule) self._timer.daemon = True diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/user_credential_async.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/user_credential_async.py index dcd934aba464..15ad17da1a8c 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/user_credential_async.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/user_credential_async.py @@ -40,9 +40,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._async_mutex = Lock() if sys.version_info[:3] == (3, 10, 0): @@ -60,9 +58,7 @@ async def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -86,9 +82,7 @@ async def _update_token_and_reschedule(self): try: new_token = await self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") async with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -115,12 +109,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() self._timer = AsyncTimer(timespan, self._update_token_and_reschedule) self._timer.start() diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/utils.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/utils.py index 47da8a283e5f..8576c31ddc56 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/utils.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_shared/utils.py @@ -87,9 +87,7 @@ def create_access_token(token): payload = json.loads(padded_base64_payload) return AccessToken( token, - _convert_datetime_to_utc_int( - datetime.fromtimestamp(payload["exp"], TZ_UTC) - ), + _convert_datetime_to_utc_int(datetime.fromtimestamp(payload["exp"], TZ_UTC)), ) except ValueError as val_error: raise ValueError(token_parse_err_msg) from val_error diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/__init__.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/__init__.py index 6c133642985f..bc19e9c60fb5 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/__init__.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/__init__.py @@ -1,5 +1,5 @@ from ._phone_numbers_client_async import PhoneNumbersClient __all__ = [ - 'PhoneNumbersClient', + "PhoneNumbersClient", ] diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/_phone_numbers_client_async.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/_phone_numbers_client_async.py index d4d2a965d4e2..baa6295d3453 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/_phone_numbers_client_async.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/_phone_numbers_client_async.py @@ -55,20 +55,16 @@ class PhoneNumbersClient: """ def __init__( - self, - endpoint: str, - credential: Union[AsyncTokenCredential, AzureKeyCredential], - **kwargs: Any + self, endpoint: str, credential: Union[AsyncTokenCredential, AzureKeyCredential], **kwargs: Any ) -> None: try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError as e: raise ValueError("Account URL must be a string.") from e if not credential: - raise ValueError( - "You need to provide account shared key to authenticate.") + raise ValueError("You need to provide account shared key to authenticate.") self._endpoint = endpoint self._accepted_language = kwargs.pop("accepted_language", None) @@ -76,16 +72,13 @@ def __init__( self._phone_number_client = PhoneNumbersClientGen( self._endpoint, api_version=self._api_version, - authentication_policy=get_authentication_policy( - endpoint, credential, is_async=True), + authentication_policy=get_authentication_policy(endpoint, credential, is_async=True), sdk_moniker=SDK_MONIKER, - **kwargs) + **kwargs + ) @classmethod - def from_connection_string( - cls, conn_str: str, - **kwargs: Any - ) -> "PhoneNumbersClient": + def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "PhoneNumbersClient": """Create PhoneNumbersClient from a Connection String. :param str conn_str: @@ -98,11 +91,7 @@ def from_connection_string( return cls(endpoint, access_key, **kwargs) @distributed_trace_async - async def begin_purchase_phone_numbers( - self, - search_id: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_purchase_phone_numbers(self, search_id: str, **kwargs: Any) -> AsyncLROPoller[None]: """Purchases phone numbers. :param search_id: The search id. @@ -118,20 +107,13 @@ async def begin_purchase_phone_numbers( """ purchase_request = PhoneNumberPurchaseRequest(search_id=search_id) - polling_interval = kwargs.pop( - 'polling_interval', _DEFAULT_POLLING_INTERVAL_IN_SECONDS) + polling_interval = kwargs.pop("polling_interval", _DEFAULT_POLLING_INTERVAL_IN_SECONDS) return await self._phone_number_client.phone_numbers.begin_purchase_phone_numbers( - body=purchase_request, - polling_interval=polling_interval, - **kwargs + body=purchase_request, polling_interval=polling_interval, **kwargs ) @distributed_trace_async - async def begin_release_phone_number( - self, - phone_number: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_release_phone_number(self, phone_number: str, **kwargs: Any) -> AsyncLROPoller[None]: """Releases an purchased phone number. :param phone_number: Phone number to be released, e.g. +11234567890. @@ -145,12 +127,9 @@ async def begin_release_phone_number( :returns: A poller to wait on the release operation. :rtype: ~azure.core.polling.AsyncLROPoller[None] """ - polling_interval = kwargs.pop( - 'polling_interval', _DEFAULT_POLLING_INTERVAL_IN_SECONDS) + polling_interval = kwargs.pop("polling_interval", _DEFAULT_POLLING_INTERVAL_IN_SECONDS) return await self._phone_number_client.phone_numbers.begin_release_phone_number( - phone_number, - polling_interval=polling_interval, - **kwargs + phone_number, polling_interval=polling_interval, **kwargs ) @distributed_trace_async @@ -192,16 +171,12 @@ async def begin_search_available_phone_numbers( phone_number_type=phone_number_type, assignment_type=assignment_type, capabilities=capabilities, - quantity=kwargs.pop('quantity', None), - area_code=kwargs.pop('area_code', None) + quantity=kwargs.pop("quantity", None), + area_code=kwargs.pop("area_code", None), ) - polling_interval = kwargs.pop( - 'polling_interval', _DEFAULT_POLLING_INTERVAL_IN_SECONDS) + polling_interval = kwargs.pop("polling_interval", _DEFAULT_POLLING_INTERVAL_IN_SECONDS) return await self._phone_number_client.phone_numbers.begin_search_available_phone_numbers( - country_code, - search_request, - polling_interval=polling_interval, - **kwargs + country_code, search_request, polling_interval=polling_interval, **kwargs ) @distributed_trace_async @@ -230,28 +205,17 @@ async def begin_update_phone_number_capabilities( :returns: A poller to wait on the update operation. :rtype: ~azure.core.polling.AsyncLROPoller[~azure.communication.phonenumbers.PurchasedPhoneNumber] """ - capabilities_request = PhoneNumberCapabilitiesRequest( - calling=calling, - sms=sms - ) + capabilities_request = PhoneNumberCapabilitiesRequest(calling=calling, sms=sms) - polling_interval = kwargs.pop( - 'polling_interval', _DEFAULT_POLLING_INTERVAL_IN_SECONDS) + polling_interval = kwargs.pop("polling_interval", _DEFAULT_POLLING_INTERVAL_IN_SECONDS) if not phone_number: raise ValueError("phone_number can't be empty") return await self._phone_number_client.phone_numbers.begin_update_capabilities( - phone_number, - body=capabilities_request, - polling_interval=polling_interval, - **kwargs + phone_number, body=capabilities_request, polling_interval=polling_interval, **kwargs ) @distributed_trace_async - async def get_purchased_phone_number( - self, - phone_number: str, - **kwargs: Any - ) -> PurchasedPhoneNumber: + async def get_purchased_phone_number(self, phone_number: str, **kwargs: Any) -> PurchasedPhoneNumber: """Gets the details of the given purchased phone number. :param phone_number: The purchased phone number whose details are to be fetched in E.164 format, @@ -260,16 +224,10 @@ async def get_purchased_phone_number( :return: The details of the given purchased phone number. :rtype: ~azure.communication.phonenumbers.PurchasedPhoneNumber """ - return await self._phone_number_client.phone_numbers.get_by_number( - phone_number, - **kwargs - ) + return await self._phone_number_client.phone_numbers.get_by_number(phone_number, **kwargs) @distributed_trace - def list_purchased_phone_numbers( - self, - **kwargs: Any - ) -> AsyncItemPaged[PurchasedPhoneNumber]: + def list_purchased_phone_numbers(self, **kwargs: Any) -> AsyncItemPaged[PurchasedPhoneNumber]: """Gets the list of all purchased phone numbers. Gets the list of all purchased phone numbers. @@ -285,15 +243,10 @@ def list_purchased_phone_numbers( ~azure.core.async_paging.AsyncItemPaged[~azure.communication.phonenumbers.PurchasedPhoneNumber] :raises ~azure.core.exceptions.HttpResponseError: """ - return self._phone_number_client.phone_numbers.list_phone_numbers( - **kwargs - ) + return self._phone_number_client.phone_numbers.list_phone_numbers(**kwargs) @distributed_trace - def list_available_countries( - self, - **kwargs: Any - ) -> AsyncItemPaged[PhoneNumberCountry]: + def list_available_countries(self, **kwargs: Any) -> AsyncItemPaged[PhoneNumberCountry]: """Gets the list of supported countries. Gets the list of supported countries. @@ -307,16 +260,11 @@ def list_available_countries( :raises ~azure.core.exceptions.HttpResponseError: """ return self._phone_number_client.phone_numbers.list_available_countries( - accept_language=self._accepted_language, - **kwargs + accept_language=self._accepted_language, **kwargs ) @distributed_trace - def list_available_localities( - self, - country_code: str, - **kwargs: Any - ) -> AsyncItemPaged[PhoneNumberLocality]: + def list_available_localities(self, country_code: str, **kwargs: Any) -> AsyncItemPaged[PhoneNumberLocality]: """Gets the list of cities or towns with available phone numbers. Gets the list of cities or towns with available phone numbers. @@ -336,18 +284,13 @@ def list_available_localities( """ return self._phone_number_client.phone_numbers.list_available_localities( country_code, - administrative_division=kwargs.pop( - "administrative_division", None), + administrative_division=kwargs.pop("administrative_division", None), accept_language=self._accepted_language, **kwargs ) @distributed_trace - def list_available_offerings( - self, - country_code: str, - **kwargs: Any - ) -> AsyncItemPaged[PhoneNumberOffering]: + def list_available_offerings(self, country_code: str, **kwargs: Any) -> AsyncItemPaged[PhoneNumberOffering]: """List available offerings of capabilities with rates for the given country/region. List available offerings of capabilities with rates for the given country/region. @@ -377,10 +320,7 @@ def list_available_offerings( @distributed_trace def list_available_area_codes( - self, - country_code: str, - phone_number_type: PhoneNumberType, - **kwargs: Any + self, country_code: str, phone_number_type: PhoneNumberType, **kwargs: Any ) -> AsyncItemPaged[PhoneNumberAreaCode]: """Gets the list of available area codes. @@ -408,21 +348,15 @@ def list_available_area_codes( return self._phone_number_client.phone_numbers.list_area_codes( country_code, phone_number_type=phone_number_type, - assignment_type=kwargs.pop( - "assignment_type", None), - locality=kwargs.pop( - "locality", None), - administrative_division=kwargs.pop( - "administrative_division", None), + assignment_type=kwargs.pop("assignment_type", None), + locality=kwargs.pop("locality", None), + administrative_division=kwargs.pop("administrative_division", None), **kwargs ) @distributed_trace def search_operator_information( - self, - phone_numbers: Union[str, List[str]], - options: Optional[OperatorInformationOptions] = None, - **kwargs: Any + self, phone_numbers: Union[str, List[str]], options: Optional[OperatorInformationOptions] = None, **kwargs: Any ) -> OperatorInformationResult: """Searches for operator information for a given list of phone numbers. @@ -434,14 +368,11 @@ def search_operator_information( :rtype: ~azure.communication.phonenumbers.OperatorInformationResult """ if not isinstance(phone_numbers, list): - phone_numbers = [ phone_numbers ] + phone_numbers = [phone_numbers] if options is None: options = OperatorInformationOptions(include_additional_operator_details=False) - request = OperatorInformationRequest(phone_numbers = phone_numbers, options = options) - return self._phone_number_client.phone_numbers.operator_information_search( - request, - **kwargs - ) + request = OperatorInformationRequest(phone_numbers=phone_numbers, options=options) + return self._phone_number_client.phone_numbers.operator_information_search(request, **kwargs) async def __aenter__(self) -> "PhoneNumbersClient": await self._phone_number_client.__aenter__() diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/__init__.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/__init__.py index 8a794b0629c3..a36930f5e8fa 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/__init__.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/__init__.py @@ -8,8 +8,4 @@ from ._sip_routing_client import SipRoutingClient from ._models import SipTrunk, SipTrunkRoute -__all__ = [ - 'SipRoutingClient', - 'SipTrunk', - 'SipTrunkRoute' -] +__all__ = ["SipRoutingClient", "SipTrunk", "SipTrunkRoute"] diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_generated/_patch.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_generated/_patch.py index f99e77fef986..17dbc073e01b 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_generated/_patch.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_generated/_patch.py @@ -25,6 +25,7 @@ # # -------------------------------------------------------------------------- + # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_generated/aio/_patch.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_generated/aio/_patch.py index f99e77fef986..17dbc073e01b 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_generated/aio/_patch.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_generated/aio/_patch.py @@ -25,6 +25,7 @@ # # -------------------------------------------------------------------------- + # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_models.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_models.py index 27d7f74153cc..2dd596947474 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_models.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_models.py @@ -4,6 +4,7 @@ # license information. # -------------------------------------------------------------------------- + class SipTrunk(object): """Represents a SIP trunk for routing calls. See RFC 4904. @@ -14,22 +15,20 @@ class SipTrunk(object): """ _attribute_map = { - 'fqdn': {'key': 'fqdn', 'type': 'str'}, - 'sip_signaling_port': {'key': 'sipSignalingPort', 'type': 'int'}, + "fqdn": {"key": "fqdn", "type": "str"}, + "sip_signaling_port": {"key": "sipSignalingPort", "type": "int"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword fqdn: FQDN of the trunk. :paramtype fqdn: str :keyword sip_signaling_port: Gets or sets SIP signaling port of the trunk. :paramtype sip_signaling_port: int """ - self.fqdn = kwargs.get('fqdn', None) - self.sip_signaling_port = kwargs.get('sip_signaling_port', None) + self.fqdn = kwargs.get("fqdn", None) + self.sip_signaling_port = kwargs.get("sip_signaling_port", None) + class SipTrunkRoute(object): """Represents a trunk route for routing calls. @@ -49,16 +48,13 @@ class SipTrunkRoute(object): """ _attribute_map = { - 'description': {'key': 'description', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'number_pattern': {'key': 'numberPattern', 'type': 'str'}, - 'trunks': {'key': 'trunks', 'type': '[str]'}, + "description": {"key": "description", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "number_pattern": {"key": "numberPattern", "type": "str"}, + "trunks": {"key": "trunks", "type": "[str]"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword description: Gets or sets description of the route. :paramtype description: Optional[str] @@ -73,7 +69,7 @@ def __init__( FQDN. :paramtype trunks: Optional[List[str]] """ - self.description = kwargs.get('description', None) - self.name = kwargs.get('name', None) - self.number_pattern = kwargs.get('number_pattern', None) - self.trunks = kwargs.get('trunks',None) + self.description = kwargs.get("description", None) + self.name = kwargs.get("name", None) + self.number_pattern = kwargs.get("number_pattern", None) + self.trunks = kwargs.get("trunks", None) diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_sip_routing_client.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_sip_routing_client.py index dd58bd1f7530..82c91a030f88 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_sip_routing_client.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/_sip_routing_client.py @@ -10,12 +10,8 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.paging import ItemPaged -from._models import SipTrunk, SipTrunkRoute -from ._generated.models import ( - SipConfiguration, - SipTrunkInternal, - SipTrunkRouteInternal -) +from ._models import SipTrunk, SipTrunkRoute +from ._generated.models import SipConfiguration, SipTrunkInternal, SipTrunkRouteInternal from ._generated._client import SIPRoutingService from .._shared.auth_policy_utils import get_authentication_policy from .._shared.utils import parse_connection_str @@ -51,7 +47,7 @@ def __init__( if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError: - raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from + raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from parsed_url = urlparse(endpoint.rstrip("/")) if not parsed_url.netloc: @@ -61,10 +57,7 @@ def __init__( self._authentication_policy = get_authentication_policy(endpoint, credential) self._rest_service = SIPRoutingService( - self._endpoint, - authentication_policy=self._authentication_policy, - sdk_moniker=SDK_MONIKER, - **kwargs + self._endpoint, authentication_policy=self._authentication_policy, sdk_moniker=SDK_MONIKER, **kwargs ) @classmethod @@ -100,11 +93,10 @@ def get_trunk( if trunk_fqdn is None: raise ValueError("Parameter 'trunk_fqdn' must not be None.") - config = self._rest_service.sip_routing.get( - **kwargs) + config = self._rest_service.sip_routing.get(**kwargs) trunk = config.trunks[trunk_fqdn] - return SipTrunk(fqdn=trunk_fqdn,sip_signaling_port=trunk.sip_signaling_port) + return SipTrunk(fqdn=trunk_fqdn, sip_signaling_port=trunk.sip_signaling_port) @distributed_trace def set_trunk( @@ -123,7 +115,7 @@ def set_trunk( if trunk is None: raise ValueError("Parameter 'trunk' must not be None.") - self._update_trunks_([trunk],**kwargs) + self._update_trunks_([trunk], **kwargs) @distributed_trace def delete_trunk( @@ -142,14 +134,11 @@ def delete_trunk( if trunk_fqdn is None: raise ValueError("Parameter 'trunk_fqdn' must not be None.") - self._rest_service.sip_routing.update( - body=SipConfiguration(trunks={trunk_fqdn:None}), - **kwargs) + self._rest_service.sip_routing.update(body=SipConfiguration(trunks={trunk_fqdn: None}), **kwargs) @distributed_trace def list_trunks( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> ItemPaged[SipTrunk] """Retrieves the currently configured SIP trunks. @@ -157,24 +146,20 @@ def list_trunks( :rtype: ItemPaged[~azure.communication.siprouting.models.SipTrunk] :raises: ~azure.core.exceptions.HttpResponseError """ + def extract_data(config): - list_of_elem = [SipTrunk( - fqdn=k, - sip_signaling_port=v.sip_signaling_port) for k,v in config.trunks.items()] + list_of_elem = [SipTrunk(fqdn=k, sip_signaling_port=v.sip_signaling_port) for k, v in config.trunks.items()] return None, list_of_elem # pylint: disable=unused-argument def get_next(nextLink=None): - return self._rest_service.sip_routing.get( - **kwargs - ) + return self._rest_service.sip_routing.get(**kwargs) return ItemPaged(get_next, extract_data) @distributed_trace def list_routes( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> ItemPaged[SipTrunkRoute] """Retrieves the currently configured SIP routes. @@ -184,18 +169,15 @@ def list_routes( """ def extract_data(config): - list_of_elem = [SipTrunkRoute( - description=x.description, - name=x.name, - number_pattern=x.number_pattern, - trunks=x.trunks) for x in config.routes] + list_of_elem = [ + SipTrunkRoute(description=x.description, name=x.name, number_pattern=x.number_pattern, trunks=x.trunks) + for x in config.routes + ] return None, list_of_elem # pylint: disable=unused-argument def get_next(nextLink=None): - return self._rest_service.sip_routing.get( - **kwargs - ) + return self._rest_service.sip_routing.get(**kwargs) return ItemPaged(get_next, extract_data) @@ -226,9 +208,7 @@ def set_trunks( config.trunks[x.fqdn] = None if len(config.trunks) > 0: - self._rest_service.sip_routing.update( - body=config, **kwargs - ) + self._rest_service.sip_routing.update(body=config, **kwargs) @distributed_trace def set_routes( @@ -247,32 +227,28 @@ def set_routes( if routes is None: raise ValueError("Parameter 'routes' must not be None.") - routes_internal = [SipTrunkRouteInternal( - description=x.description, - name=x.name, - number_pattern=x.number_pattern, - trunks=x.trunks - ) for x in routes] - self._rest_service.sip_routing.update( - body=SipConfiguration(routes=routes_internal), **kwargs - ) + routes_internal = [ + SipTrunkRouteInternal( + description=x.description, name=x.name, number_pattern=x.number_pattern, trunks=x.trunks + ) + for x in routes + ] + self._rest_service.sip_routing.update(body=SipConfiguration(routes=routes_internal), **kwargs) def _list_trunks_(self, **kwargs): - config = self._rest_service.sip_routing.get( - **kwargs) - return [SipTrunk(fqdn=k,sip_signaling_port=v.sip_signaling_port) for k,v in config.trunks.items()] + config = self._rest_service.sip_routing.get(**kwargs) + return [SipTrunk(fqdn=k, sip_signaling_port=v.sip_signaling_port) for k, v in config.trunks.items()] - def _update_trunks_(self, + def _update_trunks_( + self, trunks, # type: List[SipTrunk] **kwargs # type: Any - ): # type: (...) -> SipTrunk + ): # type: (...) -> SipTrunk trunks_internal = {x.fqdn: SipTrunkInternal(sip_signaling_port=x.sip_signaling_port) for x in trunks} modified_config = SipConfiguration(trunks=trunks_internal) - new_config = self._rest_service.sip_routing.update( - body=modified_config, **kwargs - ) - return [SipTrunk(fqdn=k,sip_signaling_port=v.sip_signaling_port) for k,v in new_config.trunks.items()] + new_config = self._rest_service.sip_routing.update(body=modified_config, **kwargs) + return [SipTrunk(fqdn=k, sip_signaling_port=v.sip_signaling_port) for k, v in new_config.trunks.items()] def close(self) -> None: self._rest_service.close() diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/aio/__init__.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/aio/__init__.py index 75a7c5a76ac0..4c97b0bd296d 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/aio/__init__.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/aio/__init__.py @@ -6,6 +6,4 @@ from ._sip_routing_client_async import SipRoutingClient -__all__ = [ - 'SipRoutingClient' -] +__all__ = ["SipRoutingClient"] diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/aio/_sip_routing_client_async.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/aio/_sip_routing_client_async.py index 5f48dd5fb86f..1a8e16518155 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/aio/_sip_routing_client_async.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/siprouting/aio/_sip_routing_client_async.py @@ -13,11 +13,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from .._models import SipTrunk, SipTrunkRoute -from .._generated.models import ( - SipConfiguration, - SipTrunkInternal, - SipTrunkRouteInternal -) +from .._generated.models import SipConfiguration, SipTrunkInternal, SipTrunkRouteInternal from .._generated.aio._client import SIPRoutingService from ..._shared.auth_policy_utils import get_authentication_policy from ..._shared.utils import parse_connection_str @@ -60,16 +56,10 @@ def __init__( raise ValueError("Invalid URL: {}".format(endpoint)) self._endpoint = endpoint - self._authentication_policy = get_authentication_policy( - endpoint, credential, - is_async=True - ) + self._authentication_policy = get_authentication_policy(endpoint, credential, is_async=True) self._rest_service = SIPRoutingService( - self._endpoint, - authentication_policy=self._authentication_policy, - sdk_moniker=SDK_MONIKER, - **kwargs + self._endpoint, authentication_policy=self._authentication_policy, sdk_moniker=SDK_MONIKER, **kwargs ) @classmethod @@ -106,11 +96,10 @@ async def get_trunk( if trunk_fqdn is None: raise ValueError("Parameter 'trunk_fqdn' must not be None.") - config = await self._rest_service.sip_routing.get( - **kwargs) + config = await self._rest_service.sip_routing.get(**kwargs) trunk = config.trunks[trunk_fqdn] - return SipTrunk(fqdn=trunk_fqdn,sip_signaling_port=trunk.sip_signaling_port) + return SipTrunk(fqdn=trunk_fqdn, sip_signaling_port=trunk.sip_signaling_port) @distributed_trace_async async def set_trunk( @@ -129,7 +118,7 @@ async def set_trunk( if trunk is None: raise ValueError("Parameter 'trunk' must not be None.") - await self._update_trunks_([trunk],**kwargs) + await self._update_trunks_([trunk], **kwargs) @distributed_trace_async async def delete_trunk( @@ -148,14 +137,11 @@ async def delete_trunk( if trunk_fqdn is None: raise ValueError("Parameter 'trunk_fqdn' must not be None.") - await self._rest_service.sip_routing.update( - body=SipConfiguration(trunks={trunk_fqdn:None}), - **kwargs) + await self._rest_service.sip_routing.update(body=SipConfiguration(trunks={trunk_fqdn: None}), **kwargs) @distributed_trace def list_trunks( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> AsyncItemPaged[SipTrunk] """Retrieves list of currently configured SIP trunks. @@ -165,23 +151,18 @@ def list_trunks( """ async def extract_data(config): - list_of_elem = [SipTrunk( - fqdn=k, - sip_signaling_port=v.sip_signaling_port) for k,v in config.trunks.items()] + list_of_elem = [SipTrunk(fqdn=k, sip_signaling_port=v.sip_signaling_port) for k, v in config.trunks.items()] return None, AsyncList(list_of_elem) # pylint: disable=unused-argument async def get_next(nextLink=None): - return await self._rest_service.sip_routing.get( - **kwargs - ) + return await self._rest_service.sip_routing.get(**kwargs) return AsyncItemPaged(get_next, extract_data) @distributed_trace def list_routes( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> AsyncItemPaged[SipTrunkRoute] """Retrieves list of currently configured SIP routes. @@ -191,18 +172,15 @@ def list_routes( """ async def extract_data(config): - list_of_elem = [SipTrunkRoute( - description=x.description, - name=x.name, - number_pattern=x.number_pattern, - trunks=x.trunks) for x in config.routes] + list_of_elem = [ + SipTrunkRoute(description=x.description, name=x.name, number_pattern=x.number_pattern, trunks=x.trunks) + for x in config.routes + ] return None, AsyncList(list_of_elem) # pylint: disable=unused-argument async def get_next(nextLink=None): - return await self._rest_service.sip_routing.get( - **kwargs - ) + return await self._rest_service.sip_routing.get(**kwargs) return AsyncItemPaged(get_next, extract_data) @@ -233,9 +211,7 @@ async def set_trunks( config.trunks[x.fqdn] = None if len(config.trunks) > 0: - await self._rest_service.sip_routing.update( - body=config, **kwargs - ) + await self._rest_service.sip_routing.update(body=config, **kwargs) @distributed_trace_async async def set_routes( @@ -254,34 +230,28 @@ async def set_routes( if routes is None: raise ValueError("Parameter 'routes' must not be None.") - routes_internal = [SipTrunkRouteInternal( - description=x.description, - name=x.name, - number_pattern=x.number_pattern, - trunks=x.trunks - ) for x in routes] - await self._rest_service.sip_routing.update( - body=SipConfiguration(routes=routes_internal), - **kwargs + routes_internal = [ + SipTrunkRouteInternal( + description=x.description, name=x.name, number_pattern=x.number_pattern, trunks=x.trunks ) + for x in routes + ] + await self._rest_service.sip_routing.update(body=SipConfiguration(routes=routes_internal), **kwargs) async def _list_trunks_(self, **kwargs): - config = await self._rest_service.sip_routing.get( - **kwargs - ) - return [SipTrunk(fqdn=k,sip_signaling_port=v.sip_signaling_port) for k,v in config.trunks.items()] + config = await self._rest_service.sip_routing.get(**kwargs) + return [SipTrunk(fqdn=k, sip_signaling_port=v.sip_signaling_port) for k, v in config.trunks.items()] - async def _update_trunks_(self, + async def _update_trunks_( + self, trunks, # type: List[SipTrunk] **kwargs # type: Any - ): # type: (...) -> SipTrunk + ): # type: (...) -> SipTrunk trunks_internal = {x.fqdn: SipTrunkInternal(sip_signaling_port=x.sip_signaling_port) for x in trunks} modified_config = SipConfiguration(trunks=trunks_internal) - new_config = await self._rest_service.sip_routing.update( - body=modified_config, **kwargs - ) - return [SipTrunk(fqdn=k,sip_signaling_port=v.sip_signaling_port) for k,v in new_config.trunks.items()] + new_config = await self._rest_service.sip_routing.update(body=modified_config, **kwargs) + return [SipTrunk(fqdn=k, sip_signaling_port=v.sip_signaling_port) for k, v in new_config.trunks.items()] async def close(self) -> None: await self._rest_service.close() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/get_purchased_phone_number_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/get_purchased_phone_number_sample.py index 562eff620cef..ee5accf442d5 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/get_purchased_phone_number_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/get_purchased_phone_number_sample.py @@ -19,18 +19,18 @@ """ import os -from azure.communication.phonenumbers import ( - PhoneNumbersClient -) +from azure.communication.phonenumbers import PhoneNumbersClient -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') -phone_number = os.getenv("AZURE_PHONE_NUMBER") # e.g. "+18001234567" +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") +phone_number = os.getenv("AZURE_PHONE_NUMBER") # e.g. "+18001234567" phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + def get_purchased_phone_number_information(): purchased_phone_number_information = phone_numbers_client.get_purchased_phone_number(phone_number) - print('Phone number: ' + purchased_phone_number_information.phone_number) - print('Country code: ' + purchased_phone_number_information.country_code) + print("Phone number: " + purchased_phone_number_information.phone_number) + print("Country code: " + purchased_phone_number_information.country_code) + -if __name__ == '__main__': +if __name__ == "__main__": get_purchased_phone_number_information() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/get_purchased_phone_number_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/get_purchased_phone_number_sample_async.py index 5c8bdd7bcbf7..1d5cf6cbe1fe 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/get_purchased_phone_number_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/get_purchased_phone_number_sample_async.py @@ -20,19 +20,19 @@ import asyncio import os -from azure.communication.phonenumbers.aio import ( - PhoneNumbersClient -) +from azure.communication.phonenumbers.aio import PhoneNumbersClient -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') -phone_number = os.getenv("AZURE_PHONE_NUMBER") # e.g. "+18001234567" +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") +phone_number = os.getenv("AZURE_PHONE_NUMBER") # e.g. "+18001234567" phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + async def get_purchased_phone_number_information(): async with phone_numbers_client: purchased_phone_number_information = await phone_numbers_client.get_purchased_phone_number(phone_number) - print('Phone number: ' + purchased_phone_number_information.phone_number) - print('Country code: ' + purchased_phone_number_information.country_code) + print("Phone number: " + purchased_phone_number_information.phone_number) + print("Country code: " + purchased_phone_number_information.country_code) + -if __name__ == '__main__': +if __name__ == "__main__": asyncio.run(get_purchased_phone_number_information()) diff --git a/sdk/communication/azure-communication-phonenumbers/samples/list_purchased_phone_numbers_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/list_purchased_phone_numbers_sample.py index a4b1bacce68c..d9e25d9f2b9f 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/list_purchased_phone_numbers_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/list_purchased_phone_numbers_sample.py @@ -18,19 +18,18 @@ """ import os -from azure.communication.phonenumbers import ( - PhoneNumbersClient -) +from azure.communication.phonenumbers import PhoneNumbersClient -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + def list_purchased_phone_numbers(): purchased_phone_numbers = phone_numbers_client.list_purchased_phone_numbers() - print('Purchased phone numbers:') + print("Purchased phone numbers:") for acquired_phone_number in purchased_phone_numbers: print(acquired_phone_number.phone_number) -if __name__ == '__main__': +if __name__ == "__main__": list_purchased_phone_numbers() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/list_purchased_phone_numbers_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/list_purchased_phone_numbers_sample_async.py index 7929efe58b0a..606f8241bdd9 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/list_purchased_phone_numbers_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/list_purchased_phone_numbers_sample_async.py @@ -19,13 +19,12 @@ import asyncio import os -from azure.communication.phonenumbers.aio import ( - PhoneNumbersClient -) +from azure.communication.phonenumbers.aio import PhoneNumbersClient -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + async def list_purchased_phone_numbers(): async with phone_numbers_client: purchased_phone_numbers = phone_numbers_client.list_purchased_phone_numbers() @@ -34,5 +33,5 @@ async def list_purchased_phone_numbers(): print(item.phone_number) -if __name__ == '__main__': +if __name__ == "__main__": asyncio.run(list_purchased_phone_numbers()) diff --git a/sdk/communication/azure-communication-phonenumbers/samples/managed_identity_authentication_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/managed_identity_authentication_sample.py index e61ef7469769..506083340554 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/managed_identity_authentication_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/managed_identity_authentication_sample.py @@ -24,16 +24,17 @@ from azure.communication.phonenumbers._shared.utils import parse_connection_str from azure.identity import DefaultAzureCredential -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") endpoint, _ = parse_connection_str(connection_str) phone_numbers_client = PhoneNumbersClient(endpoint, DefaultAzureCredential()) + def list_purchased_phone_numbers_using_managed_identity(): purchased_phone_numbers = phone_numbers_client.list_purchased_phone_numbers() - print('Purchased phone numbers:') + print("Purchased phone numbers:") for acquired_phone_number in purchased_phone_numbers: print(acquired_phone_number.phone_number) -if __name__ == '__main__': +if __name__ == "__main__": list_purchased_phone_numbers_using_managed_identity() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/purchase_phone_number_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/purchase_phone_number_sample.py index ba28a82a4f04..320383080756 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/purchase_phone_number_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/purchase_phone_number_sample.py @@ -20,22 +20,18 @@ """ import os -from azure.communication.phonenumbers import ( - PhoneNumbersClient -) +from azure.communication.phonenumbers import PhoneNumbersClient -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") search_id = os.getenv("AZURE_COMMUNICATION_SERVICE_SEARCH_ID_TO_PURCHASE") phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + def purchase_phone_number(): - poller = phone_numbers_client.begin_purchase_phone_numbers( - search_id, - polling = True - ) + poller = phone_numbers_client.begin_purchase_phone_numbers(search_id, polling=True) poller.result() print("Result from the purchase operation: " + poller.status()) -if __name__ == '__main__': +if __name__ == "__main__": purchase_phone_number() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/purchase_phone_number_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/purchase_phone_number_sample_async.py index 05b4d4664d4c..22a61e2eecb9 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/purchase_phone_number_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/purchase_phone_number_sample_async.py @@ -21,23 +21,19 @@ import asyncio import os -from azure.communication.phonenumbers.aio import ( - PhoneNumbersClient -) +from azure.communication.phonenumbers.aio import PhoneNumbersClient -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") search_id = os.getenv("AZURE_COMMUNICATION_SERVICE_SEARCH_ID_TO_PURCHASE") phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + async def purchase_phone_number(): async with phone_numbers_client: - poller = await phone_numbers_client.begin_purchase_phone_numbers( - search_id, - polling = True - ) + poller = await phone_numbers_client.begin_purchase_phone_numbers(search_id, polling=True) await poller.result() print("Result from the purchase operation: " + poller.status()) -if __name__ == '__main__': +if __name__ == "__main__": asyncio.run(purchase_phone_number()) diff --git a/sdk/communication/azure-communication-phonenumbers/samples/release_phone_number_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/release_phone_number_sample.py index 6cd888bc3f67..2cdd28b8aec2 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/release_phone_number_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/release_phone_number_sample.py @@ -19,20 +19,18 @@ """ import os -from azure.communication.phonenumbers import ( - PhoneNumbersClient -) - -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') -phone_number_to_release = os.getenv( - "AZURE_PHONE_NUMBER_TO_RELEASE" # e.g. "+18001234567" -) +from azure.communication.phonenumbers import PhoneNumbersClient + +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") +phone_number_to_release = os.getenv("AZURE_PHONE_NUMBER_TO_RELEASE") # e.g. "+18001234567" phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + def release_phone_number(): poller = phone_numbers_client.begin_release_phone_number(phone_number_to_release) poller.result() - print('Status of the operation: ' + poller.status()) + print("Status of the operation: " + poller.status()) + -if __name__ == '__main__': +if __name__ == "__main__": release_phone_number() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/release_phone_number_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/release_phone_number_sample_async.py index a7dd20709e88..f031dc8ee1d7 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/release_phone_number_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/release_phone_number_sample_async.py @@ -20,21 +20,19 @@ import asyncio import os -from azure.communication.phonenumbers.aio import ( - PhoneNumbersClient -) - -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') -phone_number_to_release = os.getenv( - "AZURE_PHONE_NUMBER_TO_RELEASE" # e.g. "+18001234567" -) +from azure.communication.phonenumbers.aio import PhoneNumbersClient + +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") +phone_number_to_release = os.getenv("AZURE_PHONE_NUMBER_TO_RELEASE") # e.g. "+18001234567" phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + async def release_phone_number(): async with phone_numbers_client: poller = await phone_numbers_client.begin_release_phone_number(phone_number_to_release) await poller.result() - print('Status of the operation: ' + poller.status()) + print("Status of the operation: " + poller.status()) + -if __name__ == '__main__': +if __name__ == "__main__": asyncio.run(release_phone_number()) diff --git a/sdk/communication/azure-communication-phonenumbers/samples/search_available_phone_numbers_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/search_available_phone_numbers_sample.py index 0488fb58d8f4..d8b02dac69be 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/search_available_phone_numbers_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/search_available_phone_numbers_sample.py @@ -23,31 +23,27 @@ PhoneNumberType, PhoneNumberAssignmentType, PhoneNumberCapabilities, - PhoneNumberCapabilityType + PhoneNumberCapabilityType, ) -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + def search_available_phone_numbers(): capabilities = PhoneNumberCapabilities( - calling = PhoneNumberCapabilityType.INBOUND, - sms = PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) poller = phone_numbers_client.begin_search_available_phone_numbers( - "US", - PhoneNumberType.TOLL_FREE, - PhoneNumberAssignmentType.APPLICATION, - capabilities, - polling = True + "US", PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, polling=True ) search_result = poller.result() - print ('Search id: ' + search_result.search_id) + print("Search id: " + search_result.search_id) phone_number_list = search_result.phone_numbers - print('Reserved phone numbers:') + print("Reserved phone numbers:") for phone_number in phone_number_list: print(phone_number) -if __name__ == '__main__': +if __name__ == "__main__": search_available_phone_numbers() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/search_available_phone_numbers_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/search_available_phone_numbers_sample_async.py index f3ef3b67193b..829c5d7efabc 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/search_available_phone_numbers_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/search_available_phone_numbers_sample_async.py @@ -24,32 +24,28 @@ PhoneNumberType, PhoneNumberAssignmentType, PhoneNumberCapabilities, - PhoneNumberCapabilityType + PhoneNumberCapabilityType, ) -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + async def search_available_phone_numbers(): async with phone_numbers_client: capabilities = PhoneNumberCapabilities( - calling = PhoneNumberCapabilityType.INBOUND, - sms = PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) poller = await phone_numbers_client.begin_search_available_phone_numbers( - "US", - PhoneNumberType.TOLL_FREE, - PhoneNumberAssignmentType.APPLICATION, - capabilities, - polling = True + "US", PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, polling=True ) search_result = await poller.result() - print ('Search id: ' + search_result.search_id) + print("Search id: " + search_result.search_id) phone_number_list = search_result.phone_numbers - print('Reserved phone numbers:') + print("Reserved phone numbers:") for phone_number in phone_number_list: print(phone_number) -if __name__ == '__main__': +if __name__ == "__main__": asyncio.run(search_available_phone_numbers()) diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/delete_sip_trunk_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/delete_sip_trunk_sample.py index 4ff0afda7a84..65faec66e44c 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/delete_sip_trunk_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/delete_sip_trunk_sample.py @@ -23,9 +23,11 @@ connection_string = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") client = SipRoutingClient.from_connection_string(connection_string) + def delete_sip_trunk_sample(): trunk_fqdn = os.getenv("COMMUNICATION_SAMPLES_TRUNK_FQDN") client.delete_trunk(trunk_fqdn) + if __name__ == "__main__": delete_sip_trunk_sample() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/delete_sip_trunk_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/delete_sip_trunk_sample_async.py index 8516bfa17002..ac1ac9efcbc1 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/delete_sip_trunk_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/delete_sip_trunk_sample_async.py @@ -24,10 +24,12 @@ connection_string = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") client = SipRoutingClient.from_connection_string(connection_string) + async def delete_sip_trunk_sample(): trunk_fqdn = os.getenv("COMMUNICATION_SAMPLES_TRUNK_FQDN") async with client: await client.delete_trunk(trunk_fqdn) + if __name__ == "__main__": - asyncio.run(delete_sip_trunk_sample()) \ No newline at end of file + asyncio.run(delete_sip_trunk_sample()) diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_routes_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_routes_sample.py index 9de1b28fb2a8..b38e671fd2fe 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_routes_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_routes_sample.py @@ -22,6 +22,7 @@ connection_string = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") client = SipRoutingClient.from_connection_string(connection_string) + def get_sip_routes_sample(): sip_routes = client.list_routes() @@ -29,9 +30,10 @@ def get_sip_routes_sample(): print(route.name) print(route.description) print(route.number_pattern) - + for trunk_fqdn in route.trunks: print(trunk_fqdn) + if __name__ == "__main__": get_sip_routes_sample() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_routes_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_routes_sample_async.py index db482fb89b74..53229e227be5 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_routes_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_routes_sample_async.py @@ -23,6 +23,7 @@ connection_string = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") client = SipRoutingClient.from_connection_string(connection_string) + async def get_sip_routes_sample(): async with client: sip_routes = client.list_routes() @@ -31,9 +32,10 @@ async def get_sip_routes_sample(): print(route.name) print(route.description) print(route.number_pattern) - + for trunk_fqdn in route.trunks: print(trunk_fqdn) + if __name__ == "__main__": - asyncio.run(get_sip_routes_sample()) \ No newline at end of file + asyncio.run(get_sip_routes_sample()) diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunk_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunk_sample.py index 543803b9458c..7d6be24d1b92 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunk_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunk_sample.py @@ -23,6 +23,7 @@ connection_string = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") client = SipRoutingClient.from_connection_string(connection_string) + def get_sip_trunk_sample(): trunk_fqdn = os.getenv("COMMUNICATION_SAMPLES_TRUNK_FQDN") try: @@ -32,5 +33,6 @@ def get_sip_trunk_sample(): except KeyError: print("Trunk not found") + if __name__ == "__main__": get_sip_trunk_sample() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunk_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunk_sample_async.py index 780017a299c0..91de0e05fa80 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunk_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunk_sample_async.py @@ -24,6 +24,7 @@ connection_string = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") client = SipRoutingClient.from_connection_string(connection_string) + async def get_sip_trunk_sample(): trunk_fqdn = os.getenv("COMMUNICATION_SAMPLES_TRUNK_FQDN") try: @@ -34,5 +35,6 @@ async def get_sip_trunk_sample(): except KeyError: print("Trunk not found") + if __name__ == "__main__": asyncio.run(get_sip_trunk_sample()) diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunks_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunks_sample.py index cf0b27f62ccd..ce7030b9e9fd 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunks_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunks_sample.py @@ -22,6 +22,7 @@ connection_string = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") client = SipRoutingClient.from_connection_string(connection_string) + def get_sip_trunks_sample(): sip_trunks = client.list_trunks() @@ -29,5 +30,6 @@ def get_sip_trunks_sample(): print(trunk.fqdn) print(trunk.sip_signaling_port) + if __name__ == "__main__": get_sip_trunks_sample() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunks_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunks_sample_async.py index 2ab7c9a2e48a..54c5fbdad0fa 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunks_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/get_sip_trunks_sample_async.py @@ -23,6 +23,7 @@ connection_string = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") client = SipRoutingClient.from_connection_string(connection_string) + async def get_sip_trunks_sample(): async with client: sip_trunks = client.list_trunks() @@ -31,6 +32,6 @@ async def get_sip_trunks_sample(): print(trunk.fqdn) print(trunk.sip_signaling_port) + if __name__ == "__main__": asyncio.run(get_sip_trunks_sample()) - diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_routes_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_routes_sample.py index c3d03ca20c94..c72c2cfacae1 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_routes_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_routes_sample.py @@ -19,12 +19,18 @@ import os from azure.communication.phonenumbers.siprouting import SipRoutingClient, SipTrunkRoute -ROUTES = [SipTrunkRoute(name="First rule", description="Handle numbers starting with '+123'", number_pattern="\+123[0-9]+", trunks=[])] +ROUTES = [ + SipTrunkRoute( + name="First rule", description="Handle numbers starting with '+123'", number_pattern="\+123[0-9]+", trunks=[] + ) +] connection_string = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") client = SipRoutingClient.from_connection_string(connection_string) + def set_sip_routes_sample(): client.set_routes(ROUTES) + if __name__ == "__main__": set_sip_routes_sample() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_routes_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_routes_sample_async.py index 35c7a0c6203f..1f6938aec437 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_routes_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_routes_sample_async.py @@ -21,14 +21,19 @@ from azure.communication.phonenumbers.siprouting.aio import SipRoutingClient from azure.communication.phonenumbers.siprouting import SipTrunkRoute -ROUTES = [SipTrunkRoute(name="First rule", description="Handle numbers starting with '+123'", number_pattern="\+123[0-9]+", trunks=[])] +ROUTES = [ + SipTrunkRoute( + name="First rule", description="Handle numbers starting with '+123'", number_pattern="\+123[0-9]+", trunks=[] + ) +] connection_string = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") client = SipRoutingClient.from_connection_string(connection_string) + async def set_sip_routes_sample(): async with client: await client.set_routes(ROUTES) + if __name__ == "__main__": asyncio.run(set_sip_routes_sample()) - diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunk_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunk_sample.py index 9c340a9cc3c1..cd6fe6f837ac 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunk_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunk_sample.py @@ -26,9 +26,11 @@ signaling_port = os.getenv("COMMUNICATION_SAMPLES_SIGNALING_PORT") client = SipRoutingClient.from_connection_string(connection_string) new_trunk = SipTrunk(fqdn=fqdn, sip_signaling_port=signaling_port) - + + def set_sip_trunk_sample(): client.set_trunk(new_trunk) - + + if __name__ == "__main__": set_sip_trunk_sample() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunk_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunk_sample_async.py index a0e61f4a07ff..3b9f28ad62a1 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunk_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunk_sample_async.py @@ -29,10 +29,11 @@ client = SipRoutingClient.from_connection_string(connection_string) new_trunk = SipTrunk(fqdn=fqdn, sip_signaling_port=signaling_port) + async def set_sip_trunk_sample(): async with client: await client.set_trunk(new_trunk) + if __name__ == "__main__": asyncio.run(set_sip_trunk_sample()) - diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunks_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunks_sample.py index 31eb36f21cee..6d1beae587dc 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunks_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunks_sample.py @@ -27,8 +27,10 @@ signaling_port = os.getenv("COMMUNICATION_SAMPLES_SIGNALING_PORT") TRUNKS = [SipTrunk(fqdn=fqdn, sip_signaling_port=signaling_port)] + def set_sip_trunks_sample(): client.set_trunks(TRUNKS) + if __name__ == "__main__": set_sip_trunks_sample() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunks_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunks_sample_async.py index 742ff889db1d..8d8714f0a28c 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunks_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/siprouting/set_sip_trunks_sample_async.py @@ -29,10 +29,11 @@ signaling_port = os.getenv("COMMUNICATION_SAMPLES_SIGNALING_PORT") TRUNKS = [SipTrunk(fqdn=fqdn, sip_signaling_port=signaling_port)] + async def set_sip_trunks_sample(): async with client: await client.set_trunks(TRUNKS) + if __name__ == "__main__": asyncio.run(set_sip_trunks_sample()) - diff --git a/sdk/communication/azure-communication-phonenumbers/samples/update_phone_number_capabilities_sample.py b/sdk/communication/azure-communication-phonenumbers/samples/update_phone_number_capabilities_sample.py index d6e0a29e2a45..e5bd584f3104 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/update_phone_number_capabilities_sample.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/update_phone_number_capabilities_sample.py @@ -19,26 +19,23 @@ """ import os -from azure.communication.phonenumbers import ( - PhoneNumbersClient, - PhoneNumberCapabilityType -) - -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') -phone_number_to_update = os.getenv( - "AZURE_PHONE_NUMBER" # e.g. "+15551234567" -) +from azure.communication.phonenumbers import PhoneNumbersClient, PhoneNumberCapabilityType + +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") +phone_number_to_update = os.getenv("AZURE_PHONE_NUMBER") # e.g. "+15551234567" phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + def update_phone_number_capabilities(): poller = phone_numbers_client.begin_update_phone_number_capabilities( phone_number_to_update, PhoneNumberCapabilityType.INBOUND_OUTBOUND, PhoneNumberCapabilityType.INBOUND, - polling = True + polling=True, ) poller.result() - print('Status of the operation: ' + poller.status()) + print("Status of the operation: " + poller.status()) + -if __name__ == '__main__': +if __name__ == "__main__": update_phone_number_capabilities() diff --git a/sdk/communication/azure-communication-phonenumbers/samples/update_phone_number_capabilities_sample_async.py b/sdk/communication/azure-communication-phonenumbers/samples/update_phone_number_capabilities_sample_async.py index 0d8a6dd3e486..ebfef32512c7 100644 --- a/sdk/communication/azure-communication-phonenumbers/samples/update_phone_number_capabilities_sample_async.py +++ b/sdk/communication/azure-communication-phonenumbers/samples/update_phone_number_capabilities_sample_async.py @@ -23,22 +23,22 @@ from azure.communication.phonenumbers.aio import PhoneNumbersClient from azure.communication.phonenumbers import PhoneNumberCapabilityType -connection_str = os.getenv('COMMUNICATION_SAMPLES_CONNECTION_STRING') -phone_number_to_update = os.getenv( - "AZURE_PHONE_NUMBER" # e.g. "+15551234567" -) +connection_str = os.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING") +phone_number_to_update = os.getenv("AZURE_PHONE_NUMBER") # e.g. "+15551234567" phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) + async def update_phone_number_capabilities(): async with phone_numbers_client: poller = await phone_numbers_client.begin_update_phone_number_capabilities( phone_number_to_update, PhoneNumberCapabilityType.INBOUND_OUTBOUND, PhoneNumberCapabilityType.INBOUND, - polling = True + polling=True, ) await poller.result() - print('Status of the operation: ' + poller.status()) + print("Status of the operation: " + poller.status()) + -if __name__ == '__main__': +if __name__ == "__main__": asyncio.run(update_phone_number_capabilities()) diff --git a/sdk/communication/azure-communication-phonenumbers/setup.py b/sdk/communication/azure-communication-phonenumbers/setup.py index dd9d04d0f9ef..62c28d801132 100644 --- a/sdk/communication/azure-communication-phonenumbers/setup.py +++ b/sdk/communication/azure-communication-phonenumbers/setup.py @@ -3,79 +3,75 @@ from io import open import re -# example setup.py Feel free to copy the entire "azure-template" folder into a package folder named -# with "azure-". Ensure that the below arguments to setup() are updated to reflect +# example setup.py Feel free to copy the entire "azure-template" folder into a package folder named +# with "azure-". Ensure that the below arguments to setup() are updated to reflect # your package. -# this setup.py is set up in a specific way to keep the azure* and azure-mgmt-* namespaces WORKING all the way +# this setup.py is set up in a specific way to keep the azure* and azure-mgmt-* namespaces WORKING all the way # up from python 3.7. Reference here: https://github.com/Azure/azure-sdk-for-python/wiki/Azure-packaging PACKAGE_NAME = "azure-communication-phonenumbers" PACKAGE_PPRINT_NAME = "Communication Phone Numbers" # a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace('-', '/') +package_folder_path = PACKAGE_NAME.replace("-", "/") # a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace('-', '.') +namespace_name = PACKAGE_NAME.replace("-", ".") # Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) +with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: - raise RuntimeError('Cannot find version information') + raise RuntimeError("Cannot find version information") -with open('README.md', encoding='utf-8') as f: +with open("README.md", encoding="utf-8") as f: long_description = f.read() setup( name=PACKAGE_NAME, version=version, - description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), - long_description_content_type='text/markdown', - + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description_content_type="text/markdown", # ensure that these are updated to reflect the package owners' information long_description=long_description, - url='https://github.com/Azure/azure-sdk-for-python', + url="https://github.com/Azure/azure-sdk-for-python", keywords="azure, azure sdk", - author='Microsoft Corporation', - author_email='azuresdkengsysadmins@microsoft.com', - - license='MIT License', + author="Microsoft Corporation", + author_email="azuresdkengsysadmins@microsoft.com", + license="MIT License", # ensure that the development status reflects the status of your package classifiers=[ "Development Status :: 5 - Production/Stable", - - 'Programming Language :: Python', + "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - 'License :: OSI Approved :: MIT License', + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: MIT License", ], - packages=find_packages(exclude=[ - 'tests', - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.communication' - ]), + packages=find_packages( + exclude=[ + "tests", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + "azure.communication", + ] + ), include_package_data=True, package_data={ - 'pytyped': ['py.typed'], + "pytyped": ["py.typed"], }, python_requires=">=3.8", install_requires=[ "msrest>=0.7.1", - 'azure-core<2.0.0,>=1.28.0', + "azure-core<2.0.0,>=1.28.0", ], - extras_require={ - ":python_version<'3.8'": ["typing-extensions"] - }, + extras_require={":python_version<'3.8'": ["typing-extensions"]}, project_urls={ - 'Bug Reports': 'https://github.com/Azure/azure-sdk-for-python/issues', - 'Source': 'https://github.com/Azure/azure-sdk-for-python', - } + "Bug Reports": "https://github.com/Azure/azure-sdk-for-python/issues", + "Source": "https://github.com/Azure/azure-sdk-for-python", + }, ) diff --git a/sdk/communication/azure-communication-phonenumbers/test/conftest.py b/sdk/communication/azure-communication-phonenumbers/test/conftest.py index 593e58f7a034..e394aa11b7d5 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/conftest.py +++ b/sdk/communication/azure-communication-phonenumbers/test/conftest.py @@ -18,42 +18,32 @@ def add_sanitizers(test_proxy): client_id = os.getenv("AZURE_CLIENT_ID", "sanitized") client_secret = os.getenv("AZURE_CLIENT_SECRET", "sanitized") tenant_id = os.getenv("AZURE_TENANT_ID", "sanitized") - connection_str = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", - fake_connection_str) - dynamic_connection_str = os.getenv("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", - fake_connection_str) + connection_str = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", fake_connection_str) + dynamic_connection_str = os.getenv("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", fake_connection_str) endpoint, *_, access_key = parse_connection_str(connection_str) - dynamic_endpoint, * \ - _, dynamic_access_key = parse_connection_str(dynamic_connection_str) + dynamic_endpoint, *_, dynamic_access_key = parse_connection_str(dynamic_connection_str) add_general_string_sanitizer(target=client_id, value="sanitized") add_general_string_sanitizer(target=client_secret, value="sanitized") add_general_string_sanitizer(target=tenant_id, value="sanitized") - add_general_string_sanitizer( - target=connection_str, value=fake_connection_str) - add_general_string_sanitizer( - target=endpoint, value="sanitized.communication.azure.com") + add_general_string_sanitizer(target=connection_str, value=fake_connection_str) + add_general_string_sanitizer(target=endpoint, value="sanitized.communication.azure.com") add_general_string_sanitizer(target=access_key, value="fake==") - add_general_string_sanitizer( - target=dynamic_connection_str, value=fake_connection_str) - add_general_string_sanitizer( - target=dynamic_endpoint, value="sanitized.communication.azure.com") + add_general_string_sanitizer(target=dynamic_connection_str, value=fake_connection_str) + add_general_string_sanitizer(target=dynamic_endpoint, value="sanitized.communication.azure.com") add_general_string_sanitizer(target=dynamic_access_key, value="fake==") add_body_key_sanitizer(json_path="id", value="sanitized") add_body_key_sanitizer(json_path="phoneNumber", value="sanitized") add_body_key_sanitizer(json_path="phoneNumbers[*].id", value="sanitized") - add_body_key_sanitizer( - json_path="phoneNumbers[*].phoneNumber", value="sanitized") + add_body_key_sanitizer(json_path="phoneNumbers[*].phoneNumber", value="sanitized") - add_general_regex_sanitizer( - regex=r"-[0-9a-fA-F]{32}\.[0-9a-zA-Z\.]*(\.com|\.net|\.test)", value=".sanitized.com") + add_general_regex_sanitizer(regex=r"-[0-9a-fA-F]{32}\.[0-9a-zA-Z\.]*(\.com|\.net|\.test)", value=".sanitized.com") add_general_regex_sanitizer(regex=r"(?:(?:%2B)|\+)\d{10,15}", value="sanitized") - add_general_regex_sanitizer( - regex=r"phoneNumbers/[%2B\d]{10,15}", value="phoneNumbers/sanitized") + add_general_regex_sanitizer(regex=r"phoneNumbers/[%2B\d]{10,15}", value="phoneNumbers/sanitized") add_header_regex_sanitizer(key="P3P", value="sanitized") add_header_regex_sanitizer(key="Set-Cookie", value="sanitized") @@ -67,11 +57,9 @@ def add_sanitizers(test_proxy): add_header_regex_sanitizer(key="x-ms-date", value="sanitized") add_header_regex_sanitizer(key="x-ms-ests-server", value="sanitized") add_header_regex_sanitizer(key="x-ms-request-id", value="sanitized") - add_header_regex_sanitizer( - key="Content-Security-Policy-Report-Only", value="sanitized") + add_header_regex_sanitizer(key="Content-Security-Policy-Report-Only", value="sanitized") # Remove the following sanitizers since certain fields are needed in tests and are non-sensitive: # - AZSDK3493: $..name # - AZSDK2003: Location remove_batch_sanitizers(["AZSDK3493", "AZSDK2003"]) - diff --git a/sdk/communication/azure-communication-phonenumbers/test/phone_numbers_testcase.py b/sdk/communication/azure-communication-phonenumbers/test/phone_numbers_testcase.py index f26f1f5091fe..f8ff09152262 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/phone_numbers_testcase.py +++ b/sdk/communication/azure-communication-phonenumbers/test/phone_numbers_testcase.py @@ -11,13 +11,13 @@ class PhoneNumbersTestCase(AzureRecordedTestCase): - def setUp(self, use_dynamic_resource = False): + def setUp(self, use_dynamic_resource=False): if self.is_playback(): self.connection_str = "endpoint=https://sanitized.communication.azure.com/;accesskey=fake===" else: if use_dynamic_resource: - self.connection_str = os.environ['COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING'] + self.connection_str = os.environ["COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING"] else: - self.connection_str = os.environ['COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING'] + self.connection_str = os.environ["COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING"] endpoint, *_ = parse_connection_str(self.connection_str) - self._resource_name = endpoint.split(".")[0] \ No newline at end of file + self._resource_name = endpoint.split(".")[0] diff --git a/sdk/communication/azure-communication-phonenumbers/test/sip_routing_helper.py b/sdk/communication/azure-communication-phonenumbers/test/sip_routing_helper.py index 9c08d9eb95b7..d79784f959c2 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/sip_routing_helper.py +++ b/sdk/communication/azure-communication-phonenumbers/test/sip_routing_helper.py @@ -11,42 +11,43 @@ from devtools_testutils import is_live + def get_unique_fqdn(trunkId): - if(is_live()): + if is_live(): return trunkId + "-" + uuid.uuid4().hex + "." + _get_root_domain() return trunkId + ".sanitized.com" + def assert_trunks_are_equal(response_trunks, request_trunks): assert len(response_trunks) == len(request_trunks), "Length of trunk list doesn't match." for k in range(len(request_trunks)): assert response_trunks[k].fqdn == request_trunks[k].fqdn, "Trunk FQDNs don't match." assert ( - response_trunks[k].sip_signaling_port==request_trunks[k].sip_signaling_port + response_trunks[k].sip_signaling_port == request_trunks[k].sip_signaling_port ), "SIP signaling ports don't match." + def assert_routes_are_equal(response_routes, request_routes): assert len(response_routes) == len(request_routes) for k in range(len(request_routes)): assert request_routes[k].name == response_routes[k].name, "Names don't match." assert request_routes[k].description == response_routes[k].description, "Descriptions don't match." - assert ( - request_routes[k].number_pattern == response_routes[k].number_pattern - ), "Number patterns don't match." + assert request_routes[k].number_pattern == response_routes[k].number_pattern, "Number patterns don't match." assert len(request_routes[k].trunks) == len(response_routes[k].trunks), "Trunk lists length doesn't match." for m in range(len(request_routes[k].trunks)): - assert request_routes[k].trunks[m] == response_routes[k].trunks[m] , "Trunk lists don't match." + assert request_routes[k].trunks[m] == response_routes[k].trunks[m], "Trunk lists don't match." + -def setup_configuration(connection_str,trunks=[],routes=[]): +def setup_configuration(connection_str, trunks=[], routes=[]): if is_live(): client = SipRoutingClient.from_connection_string( - connection_str, - http_logging_policy=get_http_logging_policy(), - header_policy=get_header_policy()) + connection_str, http_logging_policy=get_http_logging_policy(), header_policy=get_header_policy() + ) client.set_routes(routes) client.set_trunks(trunks) + def _get_root_domain(): - return os.getenv("AZURE_TEST_DOMAIN","testdomain.com") - + return os.getenv("AZURE_TEST_DOMAIN", "testdomain.com") diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client.py b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client.py index fc13ad8d8159..01efd7f06207 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client.py @@ -1,11 +1,7 @@ import os import pytest from devtools_testutils import recorded_by_proxy -from _shared.utils import ( - create_token_credential, - get_header_policy, - get_http_logging_policy -) +from _shared.utils import create_token_credential, get_header_policy, get_http_logging_policy from azure.communication.phonenumbers import PhoneNumbersClient from azure.communication.phonenumbers import ( PhoneNumberAssignmentType, @@ -20,12 +16,12 @@ SKIP_PURCHASE_PHONE_NUMBER_TESTS = True PURCHASE_PHONE_NUMBER_TEST_SKIP_REASON = "Phone numbers shouldn't be purchased in live tests" -SKIP_INT_PHONE_NUMBER_TESTS = os.getenv( - "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST", "false") == "true" -INT_PHONE_NUMBER_TEST_SKIP_REASON = "Phone numbers setting SMS capability does not support in INT. Skip these tests in INT." +SKIP_INT_PHONE_NUMBER_TESTS = os.getenv("COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST", "false") == "true" +INT_PHONE_NUMBER_TEST_SKIP_REASON = ( + "Phone numbers setting SMS capability does not support in INT. Skip these tests in INT." +) -SKIP_UPDATE_CAPABILITIES_TESTS = os.getenv( - "COMMUNICATION_SKIP_CAPABILITIES_LIVE_TEST", "false") == "true" +SKIP_UPDATE_CAPABILITIES_TESTS = os.getenv("COMMUNICATION_SKIP_CAPABILITIES_LIVE_TEST", "false") == "true" SKIP_UPDATE_CAPABILITIES_TESTS_REASON = "Phone number capabilities are skipped." @@ -38,7 +34,7 @@ def _get_test_phone_number(): def is_client_error_status_code( - status_code # type: int + status_code, # type: int ): return status_code >= 400 and status_code < 500 @@ -51,23 +47,17 @@ def setup_method(self): self.country_code = "US" else: self.phone_number = _get_test_phone_number() - self.country_code = os.getenv( - "AZURE_COMMUNICATION_SERVICE_COUNTRY_CODE", "US") + self.country_code = os.getenv("AZURE_COMMUNICATION_SERVICE_COUNTRY_CODE", "US") self.phone_number_client = PhoneNumbersClient.from_connection_string( - self.connection_str, - http_logging_policy=get_http_logging_policy(), - headers_policy=get_header_policy() + self.connection_str, http_logging_policy=get_http_logging_policy(), headers_policy=get_header_policy() ) def _get_managed_identity_phone_number_client(self): endpoint, *_ = parse_connection_str(self.connection_str) credential = create_token_credential() return PhoneNumbersClient( - endpoint, - credential, - http_logging_policy=get_http_logging_policy(), - headers_policy=get_header_policy() + endpoint, credential, http_logging_policy=get_http_logging_policy(), headers_policy=get_header_policy() ) @recorded_by_proxy @@ -85,14 +75,12 @@ def test_list_purchased_phone_numbers(self, **kwargs): @recorded_by_proxy def test_get_purchased_phone_number_from_managed_identity(self, **kwargs): phone_number_client = self._get_managed_identity_phone_number_client() - phone_number = phone_number_client.get_purchased_phone_number( - self.phone_number) + phone_number = phone_number_client.get_purchased_phone_number(self.phone_number) assert phone_number.phone_number == self.phone_number @recorded_by_proxy def test_get_purchased_phone_number(self, **kwargs): - phone_number = self.phone_number_client.get_purchased_phone_number( - self.phone_number) + phone_number = self.phone_number_client.get_purchased_phone_number(self.phone_number) assert phone_number.phone_number == self.phone_number @pytest.mark.skipif(SKIP_INT_PHONE_NUMBER_TESTS, reason=INT_PHONE_NUMBER_TEST_SKIP_REASON) @@ -100,15 +88,14 @@ def test_get_purchased_phone_number(self, **kwargs): def test_search_available_phone_numbers_from_managed_identity(self, **kwargs): phone_number_client = self._get_managed_identity_phone_number_client() capabilities = PhoneNumberCapabilities( - calling=PhoneNumberCapabilityType.INBOUND, - sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) poller = phone_number_client.begin_search_available_phone_numbers( self.country_code, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, - polling=True + polling=True, ) assert poller.result() @@ -116,15 +103,14 @@ def test_search_available_phone_numbers_from_managed_identity(self, **kwargs): @recorded_by_proxy def test_search_available_phone_numbers(self, **kwargs): capabilities = PhoneNumberCapabilities( - calling=PhoneNumberCapabilityType.INBOUND, - sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) poller = self.phone_number_client.begin_search_available_phone_numbers( self.country_code, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, - polling=True + polling=True, ) assert poller.result() @@ -133,15 +119,19 @@ def test_search_available_phone_numbers(self, **kwargs): @recorded_by_proxy def test_update_phone_number_capabilities_from_managed_identity(self, **kwargs): phone_number_client = self._get_managed_identity_phone_number_client() - current_phone_number = phone_number_client.get_purchased_phone_number( - self.phone_number) - calling_capabilities = PhoneNumberCapabilityType.INBOUND if current_phone_number.capabilities.calling == PhoneNumberCapabilityType.OUTBOUND else PhoneNumberCapabilityType.OUTBOUND - sms_capabilities = PhoneNumberCapabilityType.INBOUND_OUTBOUND if current_phone_number.capabilities.sms == PhoneNumberCapabilityType.OUTBOUND else PhoneNumberCapabilityType.OUTBOUND + current_phone_number = phone_number_client.get_purchased_phone_number(self.phone_number) + calling_capabilities = ( + PhoneNumberCapabilityType.INBOUND + if current_phone_number.capabilities.calling == PhoneNumberCapabilityType.OUTBOUND + else PhoneNumberCapabilityType.OUTBOUND + ) + sms_capabilities = ( + PhoneNumberCapabilityType.INBOUND_OUTBOUND + if current_phone_number.capabilities.sms == PhoneNumberCapabilityType.OUTBOUND + else PhoneNumberCapabilityType.OUTBOUND + ) poller = phone_number_client.begin_update_phone_number_capabilities( - self.phone_number, - sms_capabilities, - calling_capabilities, - polling=True + self.phone_number, sms_capabilities, calling_capabilities, polling=True ) assert poller.result() assert poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value @@ -150,15 +140,19 @@ def test_update_phone_number_capabilities_from_managed_identity(self, **kwargs): @pytest.mark.skipif(SKIP_UPDATE_CAPABILITIES_TESTS, reason=SKIP_UPDATE_CAPABILITIES_TESTS_REASON) @recorded_by_proxy def test_update_phone_number_capabilities(self, **kwargs): - current_phone_number = self.phone_number_client.get_purchased_phone_number( - self.phone_number) - calling_capabilities = PhoneNumberCapabilityType.INBOUND if current_phone_number.capabilities.calling == PhoneNumberCapabilityType.OUTBOUND else PhoneNumberCapabilityType.OUTBOUND - sms_capabilities = PhoneNumberCapabilityType.INBOUND_OUTBOUND if current_phone_number.capabilities.sms == PhoneNumberCapabilityType.OUTBOUND else PhoneNumberCapabilityType.OUTBOUND + current_phone_number = self.phone_number_client.get_purchased_phone_number(self.phone_number) + calling_capabilities = ( + PhoneNumberCapabilityType.INBOUND + if current_phone_number.capabilities.calling == PhoneNumberCapabilityType.OUTBOUND + else PhoneNumberCapabilityType.OUTBOUND + ) + sms_capabilities = ( + PhoneNumberCapabilityType.INBOUND_OUTBOUND + if current_phone_number.capabilities.sms == PhoneNumberCapabilityType.OUTBOUND + else PhoneNumberCapabilityType.OUTBOUND + ) poller = self.phone_number_client.begin_update_phone_number_capabilities( - self.phone_number, - sms_capabilities, - calling_capabilities, - polling=True + self.phone_number, sms_capabilities, calling_capabilities, polling=True ) assert poller.result() assert poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value @@ -168,24 +162,21 @@ def test_update_phone_number_capabilities(self, **kwargs): def test_purchase_phone_number_from_managed_identity(self, **kwargs): phone_number_client = self._get_managed_identity_phone_number_client() capabilities = PhoneNumberCapabilities( - calling=PhoneNumberCapabilityType.INBOUND, - sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) search_poller = phone_number_client.begin_search_available_phone_numbers( self.country_code, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, - polling=True + polling=True, ) phone_number_to_buy = search_poller.result() - purchase_poller = phone_number_client.begin_purchase_phone_numbers( - phone_number_to_buy.search_id, polling=True) + purchase_poller = phone_number_client.begin_purchase_phone_numbers(phone_number_to_buy.search_id, polling=True) purchase_poller.result() assert purchase_poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value - release_poller = phone_number_client.begin_release_phone_number( - phone_number_to_buy.phone_numbers[0]) + release_poller = phone_number_client.begin_release_phone_number(phone_number_to_buy.phone_numbers[0]) release_poller.result() assert release_poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value @@ -193,24 +184,23 @@ def test_purchase_phone_number_from_managed_identity(self, **kwargs): @recorded_by_proxy def test_purchase_phone_numbers(self, **kwargs): capabilities = PhoneNumberCapabilities( - calling=PhoneNumberCapabilityType.INBOUND, - sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) search_poller = self.phone_number_client.begin_search_available_phone_numbers( self.country_code, PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, - polling=True + polling=True, ) phone_number_to_buy = search_poller.result() purchase_poller = self.phone_number_client.begin_purchase_phone_numbers( - phone_number_to_buy.search_id, polling=True) + phone_number_to_buy.search_id, polling=True + ) purchase_poller.result() assert purchase_poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value - release_poller = self.phone_number_client.begin_release_phone_number( - phone_number_to_buy.phone_numbers[0]) + release_poller = self.phone_number_client.begin_release_phone_number(phone_number_to_buy.phone_numbers[0]) release_poller.result() assert release_poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value @@ -224,24 +214,20 @@ def test_get_purchased_phone_number_with_invalid_phone_number(self, **kwargs): with pytest.raises(Exception) as ex: self.phone_number_client.get_purchased_phone_number(phone_number) - assert is_client_error_status_code( - ex.value.status_code) is True, 'Status code {ex.value.status_code} does not indicate a client error' # type: ignore + assert ( + is_client_error_status_code(ex.value.status_code) is True + ), "Status code {ex.value.status_code} does not indicate a client error" # type: ignore assert ex.value.message is not None # type: ignore @recorded_by_proxy def test_search_available_phone_numbers_with_invalid_country_code(self, **kwargs): capabilities = PhoneNumberCapabilities( - calling=PhoneNumberCapabilityType.INBOUND, - sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) with pytest.raises(Exception) as ex: self.phone_number_client.begin_search_available_phone_numbers( - "XX", - PhoneNumberType.TOLL_FREE, - PhoneNumberAssignmentType.APPLICATION, - capabilities, - polling=True + "XX", PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, polling=True ) @recorded_by_proxy @@ -256,10 +242,11 @@ def test_update_phone_number_capabilities_with_unauthorized_number(self, **kwarg phone_number, PhoneNumberCapabilityType.INBOUND_OUTBOUND, PhoneNumberCapabilityType.INBOUND, - polling=True + polling=True, ) - assert is_client_error_status_code( - ex.value.status_code) is True, 'Status code {ex.value.status_code} does not indicate a client error' # type: ignore + assert ( + is_client_error_status_code(ex.value.status_code) is True + ), "Status code {ex.value.status_code} does not indicate a client error" # type: ignore assert ex.value.message is not None # type: ignore @recorded_by_proxy @@ -274,10 +261,11 @@ def test_update_phone_number_capabilities_with_invalid_number(self, **kwargs): phone_number, PhoneNumberCapabilityType.INBOUND_OUTBOUND, PhoneNumberCapabilityType.INBOUND, - polling=True + polling=True, ) - assert is_client_error_status_code( - ex.value.status_code) is True, 'Status code {ex.value.status_code} does not indicate a client error' # type: ignore + assert ( + is_client_error_status_code(ex.value.status_code) is True + ), "Status code {ex.value.status_code} does not indicate a client error" # type: ignore assert ex.value.message is not None # type: ignore @recorded_by_proxy @@ -292,27 +280,29 @@ def test_update_phone_number_capabilities_with_empty_number(self, **kwargs): phone_number, PhoneNumberCapabilityType.INBOUND_OUTBOUND, PhoneNumberCapabilityType.INBOUND, - polling=True + polling=True, ) @recorded_by_proxy def test_list_toll_free_area_codes_from_managed_identity(self): phone_number_client = self._get_managed_identity_phone_number_client() area_codes = phone_number_client.list_available_area_codes( - "US", PhoneNumberType.TOLL_FREE, assignment_type=PhoneNumberAssignmentType.APPLICATION) - - expected_area_codes = { "888", "877", "866", "855", "844", "800", "833", "88" } + "US", PhoneNumberType.TOLL_FREE, assignment_type=PhoneNumberAssignmentType.APPLICATION + ) + + expected_area_codes = {"888", "877", "866", "855", "844", "800", "833", "88"} for area_code in area_codes: assert area_code.area_code in expected_area_codes - + assert area_codes is not None @recorded_by_proxy def test_list_toll_free_area_codes(self): area_codes = self.phone_number_client.list_available_area_codes( - "US", PhoneNumberType.TOLL_FREE, assignment_type=PhoneNumberAssignmentType.APPLICATION) - - expected_area_codes = { "888", "877", "866", "855", "844", "800", "833", "88" } + "US", PhoneNumberType.TOLL_FREE, assignment_type=PhoneNumberAssignmentType.APPLICATION + ) + + expected_area_codes = {"888", "877", "866", "855", "844", "800", "833", "88"} for area_code in area_codes: assert area_code.area_code in expected_area_codes @@ -321,18 +311,26 @@ def test_list_toll_free_area_codes(self): @recorded_by_proxy def test_list_geographic_area_codes_from_managed_identity(self): phone_number_client = self._get_managed_identity_phone_number_client() - first_locality = phone_number_client.list_available_localities( - "US").next() + first_locality = phone_number_client.list_available_localities("US").next() area_codes = self.phone_number_client.list_available_area_codes( - "US", PhoneNumberType.GEOGRAPHIC, assignment_type=PhoneNumberAssignmentType.PERSON, locality=first_locality.localized_name, administrative_division=first_locality.administrative_division.abbreviated_name) + "US", + PhoneNumberType.GEOGRAPHIC, + assignment_type=PhoneNumberAssignmentType.PERSON, + locality=first_locality.localized_name, + administrative_division=first_locality.administrative_division.abbreviated_name, + ) assert area_codes.next() @recorded_by_proxy def test_list_geographic_area_codes(self): - first_locality = self.phone_number_client.list_available_localities( - "US").next() + first_locality = self.phone_number_client.list_available_localities("US").next() area_codes = self.phone_number_client.list_available_area_codes( - "US", PhoneNumberType.GEOGRAPHIC, assignment_type=PhoneNumberAssignmentType.PERSON, locality=first_locality.localized_name, administrative_division=first_locality.administrative_division.abbreviated_name) + "US", + PhoneNumberType.GEOGRAPHIC, + assignment_type=PhoneNumberAssignmentType.PERSON, + locality=first_locality.localized_name, + administrative_division=first_locality.administrative_division.abbreviated_name, + ) assert area_codes.next() @recorded_by_proxy @@ -362,15 +360,16 @@ def test_list_localities_with_ad_from_managed_identity(self): phone_number_client = self._get_managed_identity_phone_number_client() first_locality = phone_number_client.list_available_localities("US") localities = phone_number_client.list_available_localities( - "US", administrative_division=first_locality.next().administrative_division.abbreviated_name) + "US", administrative_division=first_locality.next().administrative_division.abbreviated_name + ) assert localities.next() @recorded_by_proxy def test_list_localities_with_ad(self): - first_locality = self.phone_number_client.list_available_localities( - "US") + first_locality = self.phone_number_client.list_available_localities("US") localities = self.phone_number_client.list_available_localities( - "US", administrative_division=first_locality.next().administrative_division.abbreviated_name) + "US", administrative_division=first_locality.next().administrative_division.abbreviated_name + ) assert localities.next() @recorded_by_proxy @@ -387,15 +386,16 @@ def test_list_offerings(self): @recorded_by_proxy def test_search_operator_information_with_too_many_phone_numbers(self): if self.is_playback(): - phone_numbers = [ "sanitized", "sanitized" ] + phone_numbers = ["sanitized", "sanitized"] else: - phone_numbers = [ self.phone_number, self.phone_number ] + phone_numbers = [self.phone_number, self.phone_number] with pytest.raises(Exception) as ex: self.phone_number_client.search_operator_information(phone_numbers) - assert is_client_error_status_code( - ex.value.status_code) is True, 'Status code {ex.value.status_code} does not indicate a client error' # type: ignore + assert ( + is_client_error_status_code(ex.value.status_code) is True + ), "Status code {ex.value.status_code} does not indicate a client error" # type: ignore assert ex.value.message is not None # type: ignore @recorded_by_proxy @@ -405,7 +405,7 @@ def test_search_operator_information_with_list(self): else: phone_number = self.phone_number - results = self.phone_number_client.search_operator_information([ phone_number ]) + results = self.phone_number_client.search_operator_information([phone_number]) assert len(results.values) == 1 assert results.values[0].phone_number == self.phone_number diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client_async.py b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client_async.py index fefd3ec7517b..5bae93088fb4 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client_async.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client_async.py @@ -1,11 +1,7 @@ import os from devtools_testutils.aio import recorded_by_proxy_async import pytest -from _shared.utils import ( - async_create_token_credential, - get_header_policy, - get_http_logging_policy -) +from _shared.utils import async_create_token_credential, get_header_policy, get_http_logging_policy from azure.communication.phonenumbers.aio import PhoneNumbersClient from azure.communication.phonenumbers import ( PhoneNumberAssignmentType, @@ -20,12 +16,12 @@ SKIP_PURCHASE_PHONE_NUMBER_TESTS = True PURCHASE_PHONE_NUMBER_TEST_SKIP_REASON = "Phone numbers shouldn't be purchased in live tests" -SKIP_INT_PHONE_NUMBER_TESTS = os.getenv( - "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST", "false") == "true" -INT_PHONE_NUMBER_TEST_SKIP_REASON = "Phone numbers setting SMS capability does not support in INT. Skip these tests in INT." +SKIP_INT_PHONE_NUMBER_TESTS = os.getenv("COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST", "false") == "true" +INT_PHONE_NUMBER_TEST_SKIP_REASON = ( + "Phone numbers setting SMS capability does not support in INT. Skip these tests in INT." +) -SKIP_UPDATE_CAPABILITIES_TESTS = os.getenv( - "COMMUNICATION_SKIP_CAPABILITIES_LIVE_TEST", "false") == "true" +SKIP_UPDATE_CAPABILITIES_TESTS = os.getenv("COMMUNICATION_SKIP_CAPABILITIES_LIVE_TEST", "false") == "true" SKIP_UPDATE_CAPABILITIES_TESTS_REASON = "Phone number capabilities are skipped." @@ -38,7 +34,7 @@ def _get_test_phone_number(): def is_client_error_status_code( - status_code # type: int + status_code, # type: int ): return status_code >= 400 and status_code < 500 @@ -46,30 +42,23 @@ def is_client_error_status_code( @pytest.mark.asyncio class TestPhoneNumbersClientAsync(PhoneNumbersTestCase): def setup_method(self): - super(TestPhoneNumbersClientAsync, self).setUp( - use_dynamic_resource=False) + super(TestPhoneNumbersClientAsync, self).setUp(use_dynamic_resource=False) if self.is_playback(): self.phone_number = "sanitized" self.country_code = "US" else: self.phone_number = _get_test_phone_number() - self.country_code = os.getenv( - "AZURE_COMMUNICATION_SERVICE_COUNTRY_CODE", "US") + self.country_code = os.getenv("AZURE_COMMUNICATION_SERVICE_COUNTRY_CODE", "US") self.phone_number_client = PhoneNumbersClient.from_connection_string( - self.connection_str, - http_logging_policy=get_http_logging_policy(), - headers_policy=get_header_policy() + self.connection_str, http_logging_policy=get_http_logging_policy(), headers_policy=get_header_policy() ) def _get_managed_identity_phone_number_client(self): endpoint, *_ = parse_connection_str(self.connection_str) credential = async_create_token_credential() return PhoneNumbersClient( - endpoint, - credential, - http_logging_policy=get_http_logging_policy(), - headers_policy=get_header_policy() + endpoint, credential, http_logging_policy=get_http_logging_policy(), headers_policy=get_header_policy() ) @recorded_by_proxy_async @@ -109,8 +98,7 @@ async def test_get_purchased_phone_number(self): async def test_search_available_phone_numbers_from_managed_identity(self): phone_number_client = self._get_managed_identity_phone_number_client() capabilities = PhoneNumberCapabilities( - calling=PhoneNumberCapabilityType.INBOUND, - sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) async with phone_number_client: poller = await phone_number_client.begin_search_available_phone_numbers( @@ -118,7 +106,7 @@ async def test_search_available_phone_numbers_from_managed_identity(self): PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, - polling=True + polling=True, ) assert poller.result() @@ -126,8 +114,7 @@ async def test_search_available_phone_numbers_from_managed_identity(self): @recorded_by_proxy_async async def test_search_available_phone_numbers(self): capabilities = PhoneNumberCapabilities( - calling=PhoneNumberCapabilityType.INBOUND, - sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) async with self.phone_number_client: poller = await self.phone_number_client.begin_search_available_phone_numbers( @@ -135,7 +122,7 @@ async def test_search_available_phone_numbers(self): PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, - polling=True + polling=True, ) assert poller.result() @@ -145,13 +132,18 @@ async def test_search_available_phone_numbers(self): async def test_update_phone_number_capabilities(self): async with self.phone_number_client: current_phone_number = await self.phone_number_client.get_purchased_phone_number(self.phone_number) - calling_capabilities = PhoneNumberCapabilityType.INBOUND if current_phone_number.capabilities.calling == PhoneNumberCapabilityType.OUTBOUND else PhoneNumberCapabilityType.OUTBOUND - sms_capabilities = PhoneNumberCapabilityType.INBOUND_OUTBOUND if current_phone_number.capabilities.sms == PhoneNumberCapabilityType.OUTBOUND else PhoneNumberCapabilityType.OUTBOUND + calling_capabilities = ( + PhoneNumberCapabilityType.INBOUND + if current_phone_number.capabilities.calling == PhoneNumberCapabilityType.OUTBOUND + else PhoneNumberCapabilityType.OUTBOUND + ) + sms_capabilities = ( + PhoneNumberCapabilityType.INBOUND_OUTBOUND + if current_phone_number.capabilities.sms == PhoneNumberCapabilityType.OUTBOUND + else PhoneNumberCapabilityType.OUTBOUND + ) poller = await self.phone_number_client.begin_update_phone_number_capabilities( - self.phone_number, - sms_capabilities, - calling_capabilities, - polling=True + self.phone_number, sms_capabilities, calling_capabilities, polling=True ) assert await poller.result() assert poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value @@ -163,13 +155,18 @@ async def test_update_phone_number_capabilities_from_managed_identity(self): phone_number_client = self._get_managed_identity_phone_number_client() async with phone_number_client: current_phone_number = await phone_number_client.get_purchased_phone_number(self.phone_number) - calling_capabilities = PhoneNumberCapabilityType.INBOUND if current_phone_number.capabilities.calling == PhoneNumberCapabilityType.OUTBOUND else PhoneNumberCapabilityType.OUTBOUND - sms_capabilities = PhoneNumberCapabilityType.INBOUND_OUTBOUND if current_phone_number.capabilities.sms == PhoneNumberCapabilityType.OUTBOUND else PhoneNumberCapabilityType.OUTBOUND + calling_capabilities = ( + PhoneNumberCapabilityType.INBOUND + if current_phone_number.capabilities.calling == PhoneNumberCapabilityType.OUTBOUND + else PhoneNumberCapabilityType.OUTBOUND + ) + sms_capabilities = ( + PhoneNumberCapabilityType.INBOUND_OUTBOUND + if current_phone_number.capabilities.sms == PhoneNumberCapabilityType.OUTBOUND + else PhoneNumberCapabilityType.OUTBOUND + ) poller = await phone_number_client.begin_update_phone_number_capabilities( - self.phone_number, - sms_capabilities, - calling_capabilities, - polling=True + self.phone_number, sms_capabilities, calling_capabilities, polling=True ) assert await poller.result() assert poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value @@ -179,8 +176,7 @@ async def test_update_phone_number_capabilities_from_managed_identity(self): async def test_purchase_phone_numbers_from_managed_identity(self): phone_number_client = self._get_managed_identity_phone_number_client() capabilities = PhoneNumberCapabilities( - calling=PhoneNumberCapabilityType.INBOUND, - sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) async with phone_number_client: search_poller = await phone_number_client.begin_search_available_phone_numbers( @@ -188,17 +184,17 @@ async def test_purchase_phone_numbers_from_managed_identity(self): PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, - polling=True + polling=True, ) phone_number_to_buy = await search_poller.result() purchase_poller = await phone_number_client.begin_purchase_phone_numbers( - phone_number_to_buy.search_id, polling=True) + phone_number_to_buy.search_id, polling=True + ) await purchase_poller.result() assert purchase_poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value - release_poller = await phone_number_client.begin_release_phone_number( - phone_number_to_buy.phone_numbers[0]) + release_poller = await phone_number_client.begin_release_phone_number(phone_number_to_buy.phone_numbers[0]) await release_poller.result() assert release_poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value @@ -206,8 +202,7 @@ async def test_purchase_phone_numbers_from_managed_identity(self): @recorded_by_proxy_async async def test_purchase_phone_numbers(self): capabilities = PhoneNumberCapabilities( - calling=PhoneNumberCapabilityType.INBOUND, - sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) async with self.phone_number_client: search_poller = await self.phone_number_client.begin_search_available_phone_numbers( @@ -215,17 +210,19 @@ async def test_purchase_phone_numbers(self): PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, - polling=True + polling=True, ) phone_number_to_buy = await search_poller.result() purchase_poller = await self.phone_number_client.begin_purchase_phone_numbers( - phone_number_to_buy.search_id, polling=True) + phone_number_to_buy.search_id, polling=True + ) await purchase_poller.result() assert purchase_poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value release_poller = await self.phone_number_client.begin_release_phone_number( - phone_number_to_buy.phone_numbers[0]) + phone_number_to_buy.phone_numbers[0] + ) await release_poller.result() assert release_poller.status() == PhoneNumberOperationStatus.SUCCEEDED.value @@ -240,25 +237,21 @@ async def test_get_purchased_phone_number_with_invalid_phone_number(self): async with self.phone_number_client: await self.phone_number_client.get_purchased_phone_number(phone_number) - assert is_client_error_status_code( - ex.value.status_code) is True, 'Status code {ex.value.status_code} does not indicate a client error' # type: ignore + assert ( + is_client_error_status_code(ex.value.status_code) is True + ), "Status code {ex.value.status_code} does not indicate a client error" # type: ignore assert ex.value.message is not None # type: ignore @recorded_by_proxy_async async def test_search_available_phone_numbers_with_invalid_country_code(self): capabilities = PhoneNumberCapabilities( - calling=PhoneNumberCapabilityType.INBOUND, - sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND + calling=PhoneNumberCapabilityType.INBOUND, sms=PhoneNumberCapabilityType.INBOUND_OUTBOUND ) with pytest.raises(Exception) as ex: async with self.phone_number_client: await self.phone_number_client.begin_search_available_phone_numbers( - "XX", - PhoneNumberType.TOLL_FREE, - PhoneNumberAssignmentType.APPLICATION, - capabilities, - polling=True + "XX", PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, polling=True ) @recorded_by_proxy_async @@ -274,11 +267,12 @@ async def test_update_phone_number_capabilities_with_unauthorized_number(self): phone_number, PhoneNumberCapabilityType.INBOUND_OUTBOUND, PhoneNumberCapabilityType.INBOUND, - polling=True + polling=True, ) - assert is_client_error_status_code( - ex.value.status_code) is True, 'Status code {ex.value.status_code} does not indicate a client error' # type: ignore + assert ( + is_client_error_status_code(ex.value.status_code) is True + ), "Status code {ex.value.status_code} does not indicate a client error" # type: ignore assert ex.value.message is not None # type: ignore @recorded_by_proxy_async @@ -294,11 +288,12 @@ async def test_update_phone_number_capabilities_with_invalid_number(self): phone_number, PhoneNumberCapabilityType.INBOUND_OUTBOUND, PhoneNumberCapabilityType.INBOUND, - polling=True + polling=True, ) - assert is_client_error_status_code( - ex.value.status_code) is True, 'Status code {ex.value.status_code} does not indicate a client error' # type: ignore + assert ( + is_client_error_status_code(ex.value.status_code) is True + ), "Status code {ex.value.status_code} does not indicate a client error" # type: ignore assert ex.value.message is not None # type: ignore @recorded_by_proxy_async @@ -314,7 +309,7 @@ async def test_update_phone_number_capabilities_with_empty_number(self): phone_number, PhoneNumberCapabilityType.INBOUND_OUTBOUND, PhoneNumberCapabilityType.INBOUND, - polling=True + polling=True, ) @recorded_by_proxy_async @@ -322,12 +317,13 @@ async def test_list_toll_free_area_codes_with_managed_identity(self): phone_number_client = self._get_managed_identity_phone_number_client() async with phone_number_client: area_codes = phone_number_client.list_available_area_codes( - "US", PhoneNumberType.TOLL_FREE, assignment_type=PhoneNumberAssignmentType.APPLICATION) + "US", PhoneNumberType.TOLL_FREE, assignment_type=PhoneNumberAssignmentType.APPLICATION + ) items = [] async for item in area_codes: items.append(item.area_code) - - expected_area_codes = { "888", "877", "866", "855", "844", "800", "833", "88" } + + expected_area_codes = {"888", "877", "866", "855", "844", "800", "833", "88"} for area_code in items: assert area_code in expected_area_codes @@ -337,15 +333,16 @@ async def test_list_toll_free_area_codes_with_managed_identity(self): async def test_list_toll_free_area_codes(self): async with self.phone_number_client: area_codes = self.phone_number_client.list_available_area_codes( - "US", PhoneNumberType.TOLL_FREE, assignment_type=PhoneNumberAssignmentType.APPLICATION) + "US", PhoneNumberType.TOLL_FREE, assignment_type=PhoneNumberAssignmentType.APPLICATION + ) items = [] async for item in area_codes: items.append(item.area_code) - - expected_area_codes = { "888", "877", "866", "855", "844", "800", "833", "88" } + + expected_area_codes = {"888", "877", "866", "855", "844", "800", "833", "88"} for area_code in items: assert area_code in expected_area_codes - + assert area_codes is not None @recorded_by_proxy_async @@ -355,7 +352,12 @@ async def test_list_geographic_area_codes_with_managed_identity(self): localities = phone_number_client.list_available_localities("US") async for first_locality in localities: area_codes = self.phone_number_client.list_available_area_codes( - "US", PhoneNumberType.GEOGRAPHIC, assignment_type=PhoneNumberAssignmentType.PERSON, locality=first_locality.localized_name, administrative_division=first_locality.administrative_division.abbreviated_name) + "US", + PhoneNumberType.GEOGRAPHIC, + assignment_type=PhoneNumberAssignmentType.PERSON, + locality=first_locality.localized_name, + administrative_division=first_locality.administrative_division.abbreviated_name, + ) items = [] async for item in area_codes: items.append(item) @@ -365,11 +367,15 @@ async def test_list_geographic_area_codes_with_managed_identity(self): @recorded_by_proxy_async async def test_list_geographic_area_codes(self): async with self.phone_number_client: - localities = self.phone_number_client.list_available_localities( - "US") + localities = self.phone_number_client.list_available_localities("US") async for first_locality in localities: area_codes = self.phone_number_client.list_available_area_codes( - "US", PhoneNumberType.GEOGRAPHIC, assignment_type=PhoneNumberAssignmentType.PERSON, locality=first_locality.localized_name, administrative_division=first_locality.administrative_division.abbreviated_name) + "US", + PhoneNumberType.GEOGRAPHIC, + assignment_type=PhoneNumberAssignmentType.PERSON, + locality=first_locality.localized_name, + administrative_division=first_locality.administrative_division.abbreviated_name, + ) items = [] async for item in area_codes: items.append(item) @@ -408,8 +414,7 @@ async def test_list_localities_with_managed_identity(self): @recorded_by_proxy_async async def test_list_localities(self): async with self.phone_number_client: - localities = self.phone_number_client.list_available_localities( - "US") + localities = self.phone_number_client.list_available_localities("US") items = [] async for item in localities: items.append(item) @@ -422,7 +427,8 @@ async def test_list_localities_with_ad_and_managed_identity(self): localities = phone_number_client.list_available_localities("US") async for first_locality in localities: localities = phone_number_client.list_available_localities( - "US", administrative_division=first_locality.administrative_division.abbreviated_name) + "US", administrative_division=first_locality.administrative_division.abbreviated_name + ) items = [] async for item in localities: items.append(item) @@ -432,11 +438,11 @@ async def test_list_localities_with_ad_and_managed_identity(self): @recorded_by_proxy_async async def test_list_localities_with_ad(self): async with self.phone_number_client: - localities = self.phone_number_client.list_available_localities( - "US") + localities = self.phone_number_client.list_available_localities("US") async for first_locality in localities: localities = self.phone_number_client.list_available_localities( - "US", administrative_division=first_locality.administrative_division.abbreviated_name) + "US", administrative_division=first_locality.administrative_division.abbreviated_name + ) items = [] async for item in localities: items.append(item) @@ -465,16 +471,17 @@ async def test_list_offerings(self): @recorded_by_proxy_async async def test_search_operator_information_with_too_many_phone_numbers(self): if self.is_playback(): - phone_numbers = [ "sanitized", "sanitized" ] + phone_numbers = ["sanitized", "sanitized"] else: - phone_numbers = [ self.phone_number, self.phone_number ] + phone_numbers = [self.phone_number, self.phone_number] with pytest.raises(Exception) as ex: async with self.phone_number_client: await self.phone_number_client.search_operator_information(phone_numbers) - assert is_client_error_status_code( - ex.value.status_code) is True, 'Status code {ex.value.status_code} does not indicate a client error' # type: ignore + assert ( + is_client_error_status_code(ex.value.status_code) is True + ), "Status code {ex.value.status_code} does not indicate a client error" # type: ignore assert ex.value.message is not None # type: ignore @recorded_by_proxy_async @@ -485,7 +492,7 @@ async def test_search_operator_information_with_list(self): phone_number = self.phone_number async with self.phone_number_client: - results = await self.phone_number_client.search_operator_information([ phone_number ]) + results = await self.phone_number_client.search_operator_information([phone_number]) assert len(results.values) == 1 assert results.values[0].phone_number == self.phone_number diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_models.py b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_models.py index a4f291d9c3ed..a1b92ab2ed0d 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_models.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_models.py @@ -11,24 +11,28 @@ test_unknown_id = "test_unknown_id" test_phone_number = "+123456789101" + def test_communication_user_identifier(): comm_user = models.CommunicationUserIdentifier(test_user_id) assert comm_user.kind == models.CommunicationIdentifierKind.COMMUNICATION_USER assert comm_user.raw_id == test_user_id assert comm_user.properties["id"] == test_user_id + def test_phone_number_identifier(): phone_num = models.PhoneNumberIdentifier(test_phone_number) assert phone_num.kind == models.CommunicationIdentifierKind.PHONE_NUMBER assert phone_num.raw_id == f"{models.PHONE_NUMBER_PREFIX}{test_phone_number}" assert phone_num.properties["value"] == test_phone_number + def test_unknown_identifier(): unknown = models.UnknownIdentifier(test_unknown_id) assert unknown.kind == models.CommunicationIdentifierKind.UNKNOWN assert unknown.raw_id == test_unknown_id assert unknown.properties == {} + def test_microsoft_teams_user_identifier(): teams_user = models.MicrosoftTeamsUserIdentifier(test_user_id) assert teams_user.kind == models.CommunicationIdentifierKind.MICROSOFT_TEAMS_USER @@ -37,52 +41,70 @@ def test_microsoft_teams_user_identifier(): assert teams_user.properties["is_anonymous"] == False assert teams_user.properties["cloud"] == models.CommunicationCloudEnvironment.PUBLIC + def test_identifier_from_raw_id_phone_number(): raw_id = f"{models.PHONE_NUMBER_PREFIX}{test_phone_number}" identifier = models.identifier_from_raw_id(raw_id) assert isinstance(identifier, models.PhoneNumberIdentifier) + def test_identifier_from_raw_id_teams_user(): raw_id = f"{models.TEAMS_USER_PUBLIC_CLOUD_PREFIX}{test_user_id}" identifier = models.identifier_from_raw_id(raw_id) assert isinstance(identifier, models.MicrosoftTeamsUserIdentifier) + def test_identifier_from_raw_id_unknown(): identifier = models.identifier_from_raw_id(test_unknown_id) assert isinstance(identifier, models.UnknownIdentifier) + def test_microsoft_teams_user_identifier_anonymous(): teams_user = models.MicrosoftTeamsUserIdentifier(test_user_id, is_anonymous=True) assert teams_user.kind == models.CommunicationIdentifierKind.MICROSOFT_TEAMS_USER - assert teams_user.raw_id == f'{models.TEAMS_USER_ANONYMOUS_PREFIX}{test_user_id}' + assert teams_user.raw_id == f"{models.TEAMS_USER_ANONYMOUS_PREFIX}{test_user_id}" assert teams_user.properties["user_id"] == test_user_id assert teams_user.properties["is_anonymous"] == True assert teams_user.properties["cloud"] == models.CommunicationCloudEnvironment.PUBLIC + def test_microsoft_teams_user_identifier_cloud_types(): for cloud, prefix in zip( [models.CommunicationCloudEnvironment.DOD, models.CommunicationCloudEnvironment.GCCH], - [models.TEAMS_USER_DOD_CLOUD_PREFIX, models.TEAMS_USER_GCCH_CLOUD_PREFIX] + [models.TEAMS_USER_DOD_CLOUD_PREFIX, models.TEAMS_USER_GCCH_CLOUD_PREFIX], ): teams_user = models.MicrosoftTeamsUserIdentifier(test_user_id, cloud=cloud) assert teams_user.kind == models.CommunicationIdentifierKind.MICROSOFT_TEAMS_USER - assert teams_user.raw_id == f'{prefix}{test_user_id}' + assert teams_user.raw_id == f"{prefix}{test_user_id}" assert teams_user.properties["user_id"] == test_user_id assert teams_user.properties["is_anonymous"] == False assert teams_user.properties["cloud"] == cloud + def test_identifier_from_raw_id_microsoft_teams_user(): - for prefix in [models.TEAMS_USER_ANONYMOUS_PREFIX, models.TEAMS_USER_PUBLIC_CLOUD_PREFIX, models.TEAMS_USER_DOD_CLOUD_PREFIX, models.TEAMS_USER_GCCH_CLOUD_PREFIX]: + for prefix in [ + models.TEAMS_USER_ANONYMOUS_PREFIX, + models.TEAMS_USER_PUBLIC_CLOUD_PREFIX, + models.TEAMS_USER_DOD_CLOUD_PREFIX, + models.TEAMS_USER_GCCH_CLOUD_PREFIX, + ]: raw_id = f"{prefix}:{test_user_id}" identifier = models.identifier_from_raw_id(raw_id) assert isinstance(identifier, models.MicrosoftTeamsUserIdentifier) + def test_identifier_from_raw_id_communication_user(): - for prefix in [models.ACS_USER_PREFIX, models.ACS_USER_DOD_CLOUD_PREFIX, models.ACS_USER_GCCH_CLOUD_PREFIX, models.SPOOL_USER_PREFIX]: + for prefix in [ + models.ACS_USER_PREFIX, + models.ACS_USER_DOD_CLOUD_PREFIX, + models.ACS_USER_GCCH_CLOUD_PREFIX, + models.SPOOL_USER_PREFIX, + ]: raw_id = f"{prefix}:{test_user_id}" identifier = models.identifier_from_raw_id(raw_id) assert isinstance(identifier, models.CommunicationUserIdentifier) + def test_communication_user_identifier_equality(): user1 = models.CommunicationUserIdentifier(test_user_id) user2 = models.CommunicationUserIdentifier(test_user_id) @@ -90,6 +112,7 @@ def test_communication_user_identifier_equality(): assert user1 == user2 assert user1 != user3 + def test_phone_number_identifier_equality(): phone1 = models.PhoneNumberIdentifier(test_phone_number) phone2 = models.PhoneNumberIdentifier(test_phone_number) @@ -97,9 +120,10 @@ def test_phone_number_identifier_equality(): assert phone1 == phone2 assert phone1 != phone3 + def test_microsoft_teams_user_identifier_equality(): user1 = models.MicrosoftTeamsUserIdentifier(test_user_id) user2 = models.MicrosoftTeamsUserIdentifier(test_user_id) user3 = models.MicrosoftTeamsUserIdentifier(test_unknown_id) assert user1 == user2 - assert user1 != user3 \ No newline at end of file + assert user1 != user3 diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_operations.py b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_operations.py index cccc676616e8..fb26e0751973 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_operations.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_operations.py @@ -7,15 +7,16 @@ import pytest from azure.core.rest import HttpRequest from azure.communication.phonenumbers._generated.operations._operations import ( -build_phone_numbers_get_search_result_request, -build_phone_numbers_purchase_phone_numbers_request, -build_phone_numbers_get_operation_request, -build_phone_numbers_cancel_operation_request, -build_phone_numbers_operator_information_search_request, + build_phone_numbers_get_search_result_request, + build_phone_numbers_purchase_phone_numbers_request, + build_phone_numbers_get_operation_request, + build_phone_numbers_cancel_operation_request, + build_phone_numbers_operator_information_search_request, ) test_id = "test_id" + def test_build_phone_numbers_get_search_result_request(): request = build_phone_numbers_get_search_result_request(test_id) @@ -25,6 +26,7 @@ def test_build_phone_numbers_get_search_result_request(): assert "api-version=2024-03-01-preview" in request.url assert request.headers["Accept"] == "application/json" + def test_build_phone_numbers_purchase_phone_numbers_request(): request = build_phone_numbers_purchase_phone_numbers_request() @@ -33,6 +35,7 @@ def test_build_phone_numbers_purchase_phone_numbers_request(): assert "/availablePhoneNumbers/:purchase" in request.url assert request.headers["Accept"] == "application/json" + def test_build_phone_numbers_get_operation_request(): request = build_phone_numbers_get_operation_request(test_id) @@ -41,6 +44,7 @@ def test_build_phone_numbers_get_operation_request(): assert test_id in request.url assert request.headers["Accept"] == "application/json" + def test_build_phone_numbers_cancel_operation_request(): request = build_phone_numbers_cancel_operation_request(test_id) @@ -49,6 +53,7 @@ def test_build_phone_numbers_cancel_operation_request(): assert test_id in request.url assert request.headers["Accept"] == "application/json" + def test_build_phone_numbers_operator_information_search_request(): request = build_phone_numbers_operator_information_search_request() @@ -56,4 +61,4 @@ def test_build_phone_numbers_operator_information_search_request(): assert request.method == "POST" assert "api-version=2024-03-01-preview" in request.url assert "operatorInformation/:search" in request.url - assert request.headers["Accept"] == "application/json" \ No newline at end of file + assert request.headers["Accept"] == "application/json" diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_user_credentials.py b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_user_credentials.py index feedc3731f1e..d8f0d8af7dd9 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_user_credentials.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_user_credentials.py @@ -10,80 +10,100 @@ from azure.communication.phonenumbers._shared.user_credential import CommunicationTokenCredential from azure.communication.phonenumbers._shared.utils import create_access_token + def generate_test_token(expiry_time_seconds=1000): payload = { "sub": "1234567890", "name": "John Doe", "iat": 1516239022, - "exp": time.time() + expiry_time_seconds # Expiration time + "exp": time.time() + expiry_time_seconds, # Expiration time } - return jwt.encode(payload, 'secret', algorithm='HS256') + return jwt.encode(payload, "secret", algorithm="HS256") + def token_refresher(expiry_time_seconds=1000): new_token = generate_test_token(expiry_time_seconds) return create_access_token(new_token) + def test_communication_token_credential_initialization(): test_token = generate_test_token() CommunicationTokenCredential(token=test_token) + def test_communication_token_credential_with_token_refresher(): test_token = generate_test_token() CommunicationTokenCredential(token=test_token, token_refresher=token_refresher) + def test_communication_token_credential_with_proactive_refresh(): test_token = generate_test_token() CommunicationTokenCredential(token=test_token, token_refresher=token_refresher, proactive_refresh=True) + def test_communication_token_credential_get_token(): test_token = generate_test_token() token_credential = CommunicationTokenCredential(token=test_token) result = token_credential.get_token() assert result.token == test_token + def test_communication_token_credential_get_token_with_refresh(): test_token = generate_test_token() token_credential = CommunicationTokenCredential(token=test_token, token_refresher=token_refresher) result = token_credential.get_token() assert result.token == test_token + def test_communication_token_credential_get_token_with_proactive_refresh(): test_token = generate_test_token() - token_credential = CommunicationTokenCredential(token=test_token, token_refresher=token_refresher, proactive_refresh=True) + token_credential = CommunicationTokenCredential( + token=test_token, token_refresher=token_refresher, proactive_refresh=True + ) result = token_credential.get_token() assert result.token == test_token + def test_communication_token_credential_with_non_string_token(): with pytest.raises(TypeError): - CommunicationTokenCredential(token=12345) + CommunicationTokenCredential(token=12345) + def test_communication_token_credential_with_proactive_refresh_but_no_token_refresher(): test_token = generate_test_token() with pytest.raises(ValueError): CommunicationTokenCredential(token=test_token, proactive_refresh=True) + def test_communication_token_credential_get_token_no_refresh(): test_token = generate_test_token() token_credential = CommunicationTokenCredential(token=test_token) assert (token_credential.get_token()).token == test_token + def test_communication_token_credential_context_manager(): test_token = generate_test_token() - with CommunicationTokenCredential(token=test_token, token_refresher=token_refresher, proactive_refresh=True) as token_credential: + with CommunicationTokenCredential( + token=test_token, token_refresher=token_refresher, proactive_refresh=True + ) as token_credential: assert (token_credential.get_token()).token == test_token + def test_communication_token_credential_close(): test_token = generate_test_token() - token_credential = CommunicationTokenCredential(token=test_token, token_refresher=token_refresher, proactive_refresh=True) + token_credential = CommunicationTokenCredential( + token=test_token, token_refresher=token_refresher, proactive_refresh=True + ) token_credential.close() assert token_credential._is_closed.is_set() assert token_credential._timer is None + def test_communication_token_credential_get_token_with_refresh_and_expiring_soon(): test_token = generate_test_token(3) token_credential = CommunicationTokenCredential(token=test_token, token_refresher=lambda: token_refresher()) time.sleep(4) new_token = token_credential.get_token() - decoded_test_token = jwt.decode(test_token, 'secret', options={"verify_exp": False}, algorithms=['HS256']) - decoded_new_token = jwt.decode(new_token.token, 'secret', options={"verify_exp": False}, algorithms=['HS256']) - assert decoded_new_token["exp"] > decoded_test_token["exp"] \ No newline at end of file + decoded_test_token = jwt.decode(test_token, "secret", options={"verify_exp": False}, algorithms=["HS256"]) + decoded_new_token = jwt.decode(new_token.token, "secret", options={"verify_exp": False}, algorithms=["HS256"]) + assert decoded_new_token["exp"] > decoded_test_token["exp"] diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_user_credentials_async.py b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_user_credentials_async.py index 0214bfba2e63..75d35179d40a 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_user_credentials_async.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_user_credentials_async.py @@ -11,34 +11,40 @@ from azure.communication.phonenumbers._shared.user_credential_async import CommunicationTokenCredential from azure.communication.phonenumbers._shared.utils import create_access_token + async def generate_test_token(expiry_time_seconds=1000): payload = { "sub": "1234567890", "name": "John Doe", "iat": 1516239022, - "exp": time.time() + expiry_time_seconds # Expiration time + "exp": time.time() + expiry_time_seconds, # Expiration time } - return jwt.encode(payload, 'secret', algorithm='HS256') + return jwt.encode(payload, "secret", algorithm="HS256") + async def token_refresher(expiry_time_seconds=1000): new_token = await generate_test_token(expiry_time_seconds) return create_access_token(new_token) + @pytest.mark.asyncio async def test_communication_token_credential_initialization(): test_token = await generate_test_token() CommunicationTokenCredential(token=test_token) + @pytest.mark.asyncio async def test_communication_token_credential_with_token_refresher(): test_token = await generate_test_token() CommunicationTokenCredential(token=test_token, token_refresher=token_refresher) + @pytest.mark.asyncio async def test_communication_token_credential_with_proactive_refresh(): test_token = await generate_test_token() CommunicationTokenCredential(token=test_token, token_refresher=token_refresher, proactive_refresh=True) + @pytest.mark.asyncio async def test_communication_token_credential_get_token(): test_token = await generate_test_token() @@ -46,6 +52,7 @@ async def test_communication_token_credential_get_token(): result = await token_credential.get_token() assert result.token == test_token + @pytest.mark.asyncio async def test_communication_token_credential_get_token_with_refresh(): test_token = await generate_test_token() @@ -53,17 +60,22 @@ async def test_communication_token_credential_get_token_with_refresh(): result = await token_credential.get_token() assert result.token == test_token + @pytest.mark.asyncio async def test_communication_token_credential_get_token_with_proactive_refresh(): test_token = await generate_test_token() - token_credential = CommunicationTokenCredential(token=test_token, token_refresher=token_refresher, proactive_refresh=True) + token_credential = CommunicationTokenCredential( + token=test_token, token_refresher=token_refresher, proactive_refresh=True + ) result = await token_credential.get_token() assert result.token == test_token + @pytest.mark.asyncio async def test_communication_token_credential_with_non_string_token(): with pytest.raises(TypeError): - CommunicationTokenCredential(token=12345) + CommunicationTokenCredential(token=12345) + @pytest.mark.asyncio async def test_communication_token_credential_with_proactive_refresh_but_no_token_refresher(): @@ -71,32 +83,40 @@ async def test_communication_token_credential_with_proactive_refresh_but_no_toke with pytest.raises(ValueError): CommunicationTokenCredential(token=test_token, proactive_refresh=True) + @pytest.mark.asyncio async def test_communication_token_credential_get_token_no_refresh(): test_token = await generate_test_token() token_credential = CommunicationTokenCredential(token=test_token) assert (await token_credential.get_token()).token == test_token + @pytest.mark.asyncio async def test_communication_token_credential_context_manager(): test_token = await generate_test_token() - async with CommunicationTokenCredential(token=test_token, token_refresher=token_refresher, proactive_refresh=True) as token_credential: + async with CommunicationTokenCredential( + token=test_token, token_refresher=token_refresher, proactive_refresh=True + ) as token_credential: assert (await token_credential.get_token()).token == test_token + @pytest.mark.asyncio async def test_communication_token_credential_close(): test_token = await generate_test_token() - token_credential = CommunicationTokenCredential(token=test_token, token_refresher=token_refresher, proactive_refresh=True) + token_credential = CommunicationTokenCredential( + token=test_token, token_refresher=token_refresher, proactive_refresh=True + ) await token_credential.close() assert token_credential._is_closed.is_set() assert token_credential._timer is None + @pytest.mark.asyncio async def test_communication_token_credential_get_token_with_refresh_and_expiring_soon(): test_token = await generate_test_token(3) token_credential = CommunicationTokenCredential(token=test_token, token_refresher=lambda: token_refresher()) await asyncio.sleep(4) new_token = await token_credential.get_token() - decoded_test_token = jwt.decode(test_token, 'secret', options={"verify_exp": False}, algorithms=['HS256']) - decoded_new_token = jwt.decode(new_token.token, 'secret', options={"verify_exp": False}, algorithms=['HS256']) + decoded_test_token = jwt.decode(test_token, "secret", options={"verify_exp": False}, algorithms=["HS256"]) + decoded_new_token = jwt.decode(new_token.token, "secret", options={"verify_exp": False}, algorithms=["HS256"]) assert decoded_new_token["exp"] > decoded_test_token["exp"] diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_utils.py b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_utils.py index c452ac7b4000..8c4b57b00b5d 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_utils.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_utils.py @@ -9,7 +9,13 @@ from azure.core.pipeline.policies import BearerTokenCredentialPolicy from azure.communication.phonenumbers._shared.policy import HMACCredentialsPolicy from azure.communication.phonenumbers._shared.auth_policy_utils import get_authentication_policy -from azure.communication.phonenumbers._shared.utils import parse_connection_str, get_current_utc_time, get_current_utc_as_int, create_access_token, _convert_datetime_to_utc_int +from azure.communication.phonenumbers._shared.utils import ( + parse_connection_str, + get_current_utc_time, + get_current_utc_as_int, + create_access_token, + _convert_datetime_to_utc_int, +) from azure.core.credentials import AccessToken, AzureKeyCredential from datetime import datetime, timezone from azure.core.serialization import TZ_UTC @@ -17,72 +23,86 @@ test_endpoint = "https://resource.azure.com/" + def test_convert_datetime_to_utc_int(): dt = datetime(2023, 1, 1, tzinfo=TZ_UTC) timestamp = _convert_datetime_to_utc_int(dt) assert timestamp == 1672531200 + def test_parse_connection_str_valid(): - conn_str = f'endpoint={test_endpoint};accesskey=keyValue' + conn_str = f"endpoint={test_endpoint};accesskey=keyValue" endpoint, key = parse_connection_str(conn_str) - assert endpoint == 'resource.azure.com' - assert key == 'keyValue' + assert endpoint == "resource.azure.com" + assert key == "keyValue" + def test_parse_connection_str_invalid(): - conn_str = 'invalid_string' + conn_str = "invalid_string" with pytest.raises(ValueError): parse_connection_str(conn_str) + def test_parse_connection_str_none(): conn_str = None with pytest.raises(ValueError): parse_connection_str(conn_str) + def test_get_current_utc_time(): fake_time = datetime(2023, 1, 1, tzinfo=timezone.utc) formatted_fake_time = "Sun, 01 Jan 2023 00:00:00 GMT" - with mock.patch('azure.communication.phonenumbers._shared.utils.datetime') as mock_datetime: + with mock.patch("azure.communication.phonenumbers._shared.utils.datetime") as mock_datetime: mock_datetime.now.return_value = fake_time result = get_current_utc_time() assert result == formatted_fake_time + def test_get_current_utc_as_int(): fake_time = datetime(2023, 1, 1, tzinfo=timezone.utc) fake_timestamp = int(fake_time.timestamp()) - with mock.patch('azure.communication.phonenumbers._shared.utils.datetime') as mock_datetime: + with mock.patch("azure.communication.phonenumbers._shared.utils.datetime") as mock_datetime: mock_datetime.utcnow.return_value = fake_time result = get_current_utc_as_int() assert result == fake_timestamp -@mock.patch('azure.communication.phonenumbers._shared.utils.base64.b64decode', return_value=json.dumps({'exp': 1672531200}).encode('ascii')) + +@mock.patch( + "azure.communication.phonenumbers._shared.utils.base64.b64decode", + return_value=json.dumps({"exp": 1672531200}).encode("ascii"), +) def test_create_access_token(mock_b64decode): - token = 'header.payload.signature' + token = "header.payload.signature" access_token = create_access_token(token) assert isinstance(access_token, AccessToken) assert access_token.token == token assert access_token.expires_on == 1672531200 + def test_create_access_token_invalid_format(): - token = 'invalid_token' + token = "invalid_token" with pytest.raises(ValueError): create_access_token(token) + def test_get_authentication_policy_bearer(): mock_credential = mock.MagicMock() mock_credential.get_token = mock.MagicMock() auth_policy = get_authentication_policy(test_endpoint, mock_credential) assert isinstance(auth_policy, BearerTokenCredentialPolicy) + def test_get_authentication_policy_hmac(): - auth_policy = get_authentication_policy(test_endpoint, 'keyValue') + auth_policy = get_authentication_policy(test_endpoint, "keyValue") assert isinstance(auth_policy, HMACCredentialsPolicy) + def test_get_authentication_policy_no_credential(): with pytest.raises(ValueError): get_authentication_policy(test_endpoint, None) + def test_get_authentication_policy_unsupported_credential(): unsupported_credential = mock.MagicMock() with pytest.raises(TypeError): get_authentication_policy(unsupported_credential) - diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_utils_async.py b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_utils_async.py index c6d565d54eb8..6494cf8322c9 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_utils_async.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_utils_async.py @@ -6,40 +6,43 @@ import pytest import asyncio -from azure.communication.phonenumbers._shared.utils_async import AsyncTimer +from azure.communication.phonenumbers._shared.utils_async import AsyncTimer call_count = 0 + async def callback(): global call_count call_count += 1 + @pytest.mark.asyncio async def test_timer_callback(): global call_count - call_count = 0 + call_count = 0 timer = AsyncTimer(0, callback) timer.start() - await asyncio.sleep(0.1) - assert call_count == 1 + await asyncio.sleep(0.1) + assert call_count == 1 + @pytest.mark.asyncio async def test_timer_cancel(): global call_count - call_count = 0 + call_count = 0 timer = AsyncTimer(10, callback) timer.start() timer.cancel() - assert call_count == 0 + assert call_count == 0 + @pytest.mark.asyncio async def test_timer_restart(): global call_count - call_count = 0 + call_count = 0 timer = AsyncTimer(0.5, callback) timer.start() timer.cancel() timer.start() - await asyncio.sleep(1) + await asyncio.sleep(1) assert call_count == 1 - diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_sip_routing_client_e2e.py b/sdk/communication/azure-communication-phonenumbers/test/test_sip_routing_client_e2e.py index a9eb551b9503..1d9129ad3ef7 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_sip_routing_client_e2e.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_sip_routing_client_e2e.py @@ -18,36 +18,36 @@ class TestSipRoutingClientE2E(PhoneNumbersTestCase): first_trunk = SipTrunk(fqdn=get_unique_fqdn("sbs1"), sip_signaling_port=1122) second_trunk = SipTrunk(fqdn=get_unique_fqdn("sbs2"), sip_signaling_port=1123) additional_trunk = SipTrunk(fqdn=get_unique_fqdn("sbs3"), sip_signaling_port=2222) - first_route = SipTrunkRoute(name="First rule", description="Handle numbers starting with '+123'", number_pattern="\\+123[0-9]+", trunks=[]) + first_route = SipTrunkRoute( + name="First rule", description="Handle numbers starting with '+123'", number_pattern="\\+123[0-9]+", trunks=[] + ) def setup_method(self): - super(TestSipRoutingClientE2E, self).setUp(use_dynamic_resource = True) + super(TestSipRoutingClientE2E, self).setUp(use_dynamic_resource=True) self._sip_routing_client = SipRoutingClient.from_connection_string( - self.connection_str, - http_logging_policy=get_http_logging_policy(), - headers_policy=get_header_policy() - ) - setup_configuration(self.connection_str,trunks=[self.first_trunk, self.second_trunk]) + self.connection_str, http_logging_policy=get_http_logging_policy(), headers_policy=get_header_policy() + ) + setup_configuration(self.connection_str, trunks=[self.first_trunk, self.second_trunk]) @recorded_by_proxy def test_get_trunks(self, **kwargs): trunks = self._sip_routing_client.list_trunks() trunks_list = self._get_as_list(trunks) - assert_trunks_are_equal(trunks_list,[self.first_trunk,self.second_trunk]) + assert_trunks_are_equal(trunks_list, [self.first_trunk, self.second_trunk]) @recorded_by_proxy def test_get_trunks_from_managed_identity(self, **kwargs): client = self._get_sip_client_managed_identity() trunks = client.list_trunks() trunks_list = self._get_as_list(trunks) - assert_trunks_are_equal(trunks_list,[self.first_trunk,self.second_trunk]) + assert_trunks_are_equal(trunks_list, [self.first_trunk, self.second_trunk]) @recorded_by_proxy def test_get_routes(self, **kwargs): self._sip_routing_client.set_routes([self.first_route]) routes = self._sip_routing_client.list_routes() routes_list = self._get_as_list(routes) - assert_routes_are_equal(routes_list,[self.first_route]) + assert_routes_are_equal(routes_list, [self.first_route]) @recorded_by_proxy def test_get_routes_from_managed_identity(self, **kwargs): @@ -55,14 +55,14 @@ def test_get_routes_from_managed_identity(self, **kwargs): client.set_routes([self.first_route]) routes = client.list_routes() routes_list = self._get_as_list(routes) - assert_routes_are_equal(routes_list,[self.first_route]) + assert_routes_are_equal(routes_list, [self.first_route]) @recorded_by_proxy def test_set_trunks(self, **kwargs): self._sip_routing_client.set_trunks([self.additional_trunk]) result_trunks = self._sip_routing_client.list_trunks() trunks_list = self._get_as_list(result_trunks) - assert_trunks_are_equal(trunks_list,[self.additional_trunk]) + assert_trunks_are_equal(trunks_list, [self.additional_trunk]) @recorded_by_proxy def test_set_trunks_from_managed_identity(self, **kwargs): @@ -70,36 +70,55 @@ def test_set_trunks_from_managed_identity(self, **kwargs): client.set_trunks([self.additional_trunk]) result_trunks = client.list_trunks() trunks_list = self._get_as_list(result_trunks) - assert_trunks_are_equal(trunks_list,[self.additional_trunk]) + assert_trunks_are_equal(trunks_list, [self.additional_trunk]) @recorded_by_proxy def test_set_trunks_empty_list(self, **kwargs): """Verification of bug fix. SDK shouldn't send empty PATCH, otherwise it will receive exception. This situation occurs, when sending empty trunks list to already empty trunk configuration.""" - try: + try: self._sip_routing_client.set_trunks([]) self._sip_routing_client.set_trunks([]) except HttpResponseError as exception: - assert False, "Trying to set empty trunks list returned Http error: " + str(exception.status_code) + ", message: " + exception.message + assert False, ( + "Trying to set empty trunks list returned Http error: " + + str(exception.status_code) + + ", message: " + + exception.message + ) @recorded_by_proxy def test_set_routes(self, **kwargs): - new_routes = [SipTrunkRoute(name="Alternative rule", description="Handle numbers starting with '+999'", number_pattern="\\+999[0-9]+", trunks=[])] + new_routes = [ + SipTrunkRoute( + name="Alternative rule", + description="Handle numbers starting with '+999'", + number_pattern="\\+999[0-9]+", + trunks=[], + ) + ] self._sip_routing_client.set_routes([self.first_route]) self._sip_routing_client.set_routes(new_routes) result_routes = self._sip_routing_client.list_routes() routes_list = self._get_as_list(result_routes) - assert_routes_are_equal(routes_list,new_routes) + assert_routes_are_equal(routes_list, new_routes) @recorded_by_proxy def test_set_routes_from_managed_identity(self, **kwargs): - new_routes = [SipTrunkRoute(name="Alternative rule", description="Handle numbers starting with '+999'", number_pattern="\\+999[0-9]+", trunks=[])] + new_routes = [ + SipTrunkRoute( + name="Alternative rule", + description="Handle numbers starting with '+999'", + number_pattern="\\+999[0-9]+", + trunks=[], + ) + ] client = self._get_sip_client_managed_identity() client.set_routes([self.first_route]) client.set_routes(new_routes) result_routes = client.list_routes() routes_list = self._get_as_list(result_routes) - assert_routes_are_equal(routes_list,new_routes) + assert_routes_are_equal(routes_list, new_routes) @recorded_by_proxy def test_delete_trunk(self, **kwargs): @@ -107,7 +126,7 @@ def test_delete_trunk(self, **kwargs): self._sip_routing_client.delete_trunk(trunk_to_delete) new_trunks = self._sip_routing_client.list_trunks() trunks_list = self._get_as_list(new_trunks) - assert_trunks_are_equal(trunks_list,[self.first_trunk]) + assert_trunks_are_equal(trunks_list, [self.first_trunk]) @recorded_by_proxy def test_delete_trunk_from_managed_identity(self, **kwargs): @@ -116,14 +135,14 @@ def test_delete_trunk_from_managed_identity(self, **kwargs): client.delete_trunk(trunk_to_delete) new_trunks = client.list_trunks() trunks_list = self._get_as_list(new_trunks) - assert_trunks_are_equal(trunks_list,[self.first_trunk]) + assert_trunks_are_equal(trunks_list, [self.first_trunk]) @recorded_by_proxy def test_add_trunk(self, **kwargs): self._sip_routing_client.set_trunk(self.additional_trunk) new_trunks = self._sip_routing_client.list_trunks() trunks_list = self._get_as_list(new_trunks) - assert_trunks_are_equal(trunks_list,[self.first_trunk,self.second_trunk,self.additional_trunk]) + assert_trunks_are_equal(trunks_list, [self.first_trunk, self.second_trunk, self.additional_trunk]) @recorded_by_proxy def test_add_trunk_from_managed_identity(self, **kwargs): @@ -131,7 +150,7 @@ def test_add_trunk_from_managed_identity(self, **kwargs): client.set_trunk(self.additional_trunk) new_trunks = client.list_trunks() trunks_list = self._get_as_list(new_trunks) - assert_trunks_are_equal(trunks_list,[self.first_trunk,self.second_trunk,self.additional_trunk]) + assert_trunks_are_equal(trunks_list, [self.first_trunk, self.second_trunk, self.additional_trunk]) @recorded_by_proxy def test_get_trunk(self, **kwargs): @@ -153,31 +172,31 @@ def test_get_trunk_not_existing_throws(self, **kwargs): @recorded_by_proxy def test_set_trunk(self, **kwargs): - modified_trunk = SipTrunk(fqdn=self.second_trunk.fqdn,sip_signaling_port=7777) + modified_trunk = SipTrunk(fqdn=self.second_trunk.fqdn, sip_signaling_port=7777) self._sip_routing_client.set_trunk(modified_trunk) new_trunks = self._sip_routing_client.list_trunks() trunks_list = self._get_as_list(new_trunks) - assert_trunks_are_equal(trunks_list,[self.first_trunk,modified_trunk]) - + assert_trunks_are_equal(trunks_list, [self.first_trunk, modified_trunk]) + @recorded_by_proxy def test_set_trunk_from_managed_identity(self, **kwargs): - modified_trunk = SipTrunk(fqdn=self.second_trunk.fqdn,sip_signaling_port=7777) + modified_trunk = SipTrunk(fqdn=self.second_trunk.fqdn, sip_signaling_port=7777) client = self._get_sip_client_managed_identity() client.set_trunk(modified_trunk) new_trunks = client.list_trunks() trunks_list = self._get_as_list(new_trunks) - assert_trunks_are_equal(trunks_list,[self.first_trunk,modified_trunk]) + assert_trunks_are_equal(trunks_list, [self.first_trunk, modified_trunk]) def _get_sip_client_managed_identity(self): endpoint, *_ = parse_connection_str(self.connection_str) credential = create_token_credential() - return SipRoutingClient(endpoint, credential, - http_logging_policy=get_http_logging_policy(), - headers_policy=get_header_policy()) - - def _get_as_list(self,iter): + return SipRoutingClient( + endpoint, credential, http_logging_policy=get_http_logging_policy(), headers_policy=get_header_policy() + ) + + def _get_as_list(self, iter): assert iter is not None, "No iterable was returned." items = [] for item in iter: items.append(item) - return items \ No newline at end of file + return items diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_sip_routing_client_e2e_async.py b/sdk/communication/azure-communication-phonenumbers/test/test_sip_routing_client_e2e_async.py index ad2e30b47349..c8636ce8ccc1 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_sip_routing_client_e2e_async.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_sip_routing_client_e2e_async.py @@ -16,38 +16,38 @@ @pytest.mark.asyncio -class TestSipRoutingClientE2EAsync(PhoneNumbersTestCase): - +class TestSipRoutingClientE2EAsync(PhoneNumbersTestCase): + first_trunk = SipTrunk(fqdn=get_unique_fqdn("sbs1"), sip_signaling_port=1122) second_trunk = SipTrunk(fqdn=get_unique_fqdn("sbs2"), sip_signaling_port=1123) additional_trunk = SipTrunk(fqdn=get_unique_fqdn("sbs3"), sip_signaling_port=2222) - first_route = SipTrunkRoute(name="First rule", description="Handle numbers starting with '+123'", number_pattern="\\+123[0-9]+", trunks=[]) - + first_route = SipTrunkRoute( + name="First rule", description="Handle numbers starting with '+123'", number_pattern="\\+123[0-9]+", trunks=[] + ) + def setup_method(self): - super(TestSipRoutingClientE2EAsync, self).setUp(use_dynamic_resource = True) + super(TestSipRoutingClientE2EAsync, self).setUp(use_dynamic_resource=True) self._sip_routing_client = SipRoutingClient.from_connection_string( - self.connection_str, - http_logging_policy=get_http_logging_policy(), - headers_policy=get_header_policy() + self.connection_str, http_logging_policy=get_http_logging_policy(), headers_policy=get_header_policy() ) - setup_configuration(self.connection_str,trunks=[self.first_trunk, self.second_trunk]) + setup_configuration(self.connection_str, trunks=[self.first_trunk, self.second_trunk]) @recorded_by_proxy_async async def test_get_trunks(self): async with self._sip_routing_client: trunks = self._sip_routing_client.list_trunks() trunks_list = await self._get_as_list(trunks) - - assert_trunks_are_equal(trunks_list,[self.first_trunk, self.second_trunk]), "Trunks are not equal." - + + assert_trunks_are_equal(trunks_list, [self.first_trunk, self.second_trunk]), "Trunks are not equal." + @recorded_by_proxy_async async def test_get_trunks_from_managed_identity(self): self._sip_routing_client = self._get_sip_client_managed_identity() async with self._sip_routing_client: trunks = self._sip_routing_client.list_trunks() trunks_list = await self._get_as_list(trunks) - - assert_trunks_are_equal(trunks_list,[self.first_trunk, self.second_trunk]), "Trunks are not equal." + + assert_trunks_are_equal(trunks_list, [self.first_trunk, self.second_trunk]), "Trunks are not equal." @recorded_by_proxy_async async def test_get_routes(self): @@ -56,7 +56,7 @@ async def test_get_routes(self): routes = self._sip_routing_client.list_routes() routes_list = await self._get_as_list(routes) - assert_routes_are_equal(routes_list,[self.first_route]), "Routes are not equal." + assert_routes_are_equal(routes_list, [self.first_route]), "Routes are not equal." @recorded_by_proxy_async async def test_get_routes_from_managed_identity(self): @@ -66,7 +66,7 @@ async def test_get_routes_from_managed_identity(self): routes = self._sip_routing_client.list_routes() routes_list = await self._get_as_list(routes) - assert_routes_are_equal(routes_list,[self.first_route]), "Routes are not equal." + assert_routes_are_equal(routes_list, [self.first_route]), "Routes are not equal." @recorded_by_proxy_async async def test_set_trunks(self): @@ -75,7 +75,7 @@ async def test_set_trunks(self): result_trunks = self._sip_routing_client.list_trunks() result_trunks_list = await self._get_as_list(result_trunks) - assert_trunks_are_equal(result_trunks_list,[self.additional_trunk]), "Trunks are not equal." + assert_trunks_are_equal(result_trunks_list, [self.additional_trunk]), "Trunks are not equal." @recorded_by_proxy_async async def test_set_trunks_from_managed_identity(self): @@ -85,33 +85,52 @@ async def test_set_trunks_from_managed_identity(self): result_trunks = self._sip_routing_client.list_trunks() result_trunks_list = await self._get_as_list(result_trunks) - assert_trunks_are_equal(result_trunks_list,[self.additional_trunk]), "Trunks are not equal." + assert_trunks_are_equal(result_trunks_list, [self.additional_trunk]), "Trunks are not equal." @recorded_by_proxy_async async def test_set_trunks_empty_list(self): """Verification of bug fix. SDK shouldn't send empty PATCH, otherwise it will receive exception. This situation occurs, when sending empty trunks list to already empty trunk configuration.""" async with self._sip_routing_client: - try: + try: await self._sip_routing_client.set_trunks([]) await self._sip_routing_client.set_trunks([]) except HttpResponseError as exception: - assert False, "Trying to set empty trunks list returned Http error: " + str(exception.status_code) + ", message: " + exception.message - + assert False, ( + "Trying to set empty trunks list returned Http error: " + + str(exception.status_code) + + ", message: " + + exception.message + ) + @recorded_by_proxy_async async def test_set_routes(self): - new_routes = [SipTrunkRoute(name="Alternative rule", description="Handle numbers starting with '+999'", number_pattern="\\+999[0-9]+", trunks=[])] + new_routes = [ + SipTrunkRoute( + name="Alternative rule", + description="Handle numbers starting with '+999'", + number_pattern="\\+999[0-9]+", + trunks=[], + ) + ] async with self._sip_routing_client: await self._sip_routing_client.set_routes([self.first_route]) await self._sip_routing_client.set_routes(new_routes) result_routes = self._sip_routing_client.list_routes() result_routes_list = await self._get_as_list(result_routes) - assert_routes_are_equal(result_routes_list,new_routes), "Routes are not equal." + assert_routes_are_equal(result_routes_list, new_routes), "Routes are not equal." @recorded_by_proxy_async async def test_set_routes_from_managed_identity(self): - new_routes = [SipTrunkRoute(name="Alternative rule", description="Handle numbers starting with '+999'", number_pattern="\\+999[0-9]+", trunks=[])] + new_routes = [ + SipTrunkRoute( + name="Alternative rule", + description="Handle numbers starting with '+999'", + number_pattern="\\+999[0-9]+", + trunks=[], + ) + ] self._sip_routing_client = self._get_sip_client_managed_identity() async with self._sip_routing_client: await self._sip_routing_client.set_routes([self.first_route]) @@ -119,7 +138,7 @@ async def test_set_routes_from_managed_identity(self): result_routes = self._sip_routing_client.list_routes() result_routes_list = await self._get_as_list(result_routes) - assert_routes_are_equal(result_routes_list,new_routes), "Routes are not equal." + assert_routes_are_equal(result_routes_list, new_routes), "Routes are not equal." @recorded_by_proxy_async async def test_delete_trunk(self): @@ -128,7 +147,7 @@ async def test_delete_trunk(self): await self._sip_routing_client.delete_trunk(trunk_to_delete) new_trunks = self._sip_routing_client.list_trunks() new_trunks_list = await self._get_as_list(new_trunks) - assert_trunks_are_equal(new_trunks_list,[self.first_trunk]), "Trunk was not deleted." + assert_trunks_are_equal(new_trunks_list, [self.first_trunk]), "Trunk was not deleted." @recorded_by_proxy_async async def test_delete_trunk_from_managed_identity(self): @@ -138,7 +157,7 @@ async def test_delete_trunk_from_managed_identity(self): await self._sip_routing_client.delete_trunk(trunk_to_delete) new_trunks = self._sip_routing_client.list_trunks() new_trunks_list = await self._get_as_list(new_trunks) - assert_trunks_are_equal(new_trunks_list,[self.first_trunk]), "Trunk was not deleted." + assert_trunks_are_equal(new_trunks_list, [self.first_trunk]), "Trunk was not deleted." @recorded_by_proxy_async async def test_add_trunk(self): @@ -146,8 +165,8 @@ async def test_add_trunk(self): await self._sip_routing_client.set_trunk(self.additional_trunk) new_trunks = self._sip_routing_client.list_trunks() new_trunks_list = await self._get_as_list(new_trunks) - assert_trunks_are_equal(new_trunks_list,[self.first_trunk,self.second_trunk,self.additional_trunk]) - + assert_trunks_are_equal(new_trunks_list, [self.first_trunk, self.second_trunk, self.additional_trunk]) + @recorded_by_proxy_async async def test_add_trunk_from_managed_identity(self): self._sip_routing_client = self._get_sip_client_managed_identity() @@ -155,14 +174,14 @@ async def test_add_trunk_from_managed_identity(self): await self._sip_routing_client.set_trunk(self.additional_trunk) new_trunks = self._sip_routing_client.list_trunks() new_trunks_list = await self._get_as_list(new_trunks) - assert_trunks_are_equal(new_trunks_list,[self.first_trunk,self.second_trunk,self.additional_trunk]) + assert_trunks_are_equal(new_trunks_list, [self.first_trunk, self.second_trunk, self.additional_trunk]) @recorded_by_proxy_async async def test_get_trunk(self): async with self._sip_routing_client: trunk = await self._sip_routing_client.get_trunk(self.first_trunk.fqdn) assert trunk is not None, "No trunk was returned." - assert_trunks_are_equal([trunk],[self.first_trunk]), "Returned trunk does not match the required trunk." + assert_trunks_are_equal([trunk], [self.first_trunk]), "Returned trunk does not match the required trunk." @recorded_by_proxy_async async def test_get_trunk_from_managed_identity(self): @@ -170,42 +189,40 @@ async def test_get_trunk_from_managed_identity(self): async with self._sip_routing_client: trunk = await self._sip_routing_client.get_trunk(self.first_trunk.fqdn) assert trunk is not None, "No trunk was returned." - assert_trunks_are_equal([trunk],[self.first_trunk]), "Returned trunk does not match the required trunk." + assert_trunks_are_equal([trunk], [self.first_trunk]), "Returned trunk does not match the required trunk." @recorded_by_proxy_async async def test_get_trunk_not_existing_throws(self, **kwargs): with pytest.raises(KeyError): await self._sip_routing_client.get_trunk("non-existing.fqdn.test") - + @recorded_by_proxy_async async def test_set_trunk(self): - modified_trunk = SipTrunk(fqdn=self.second_trunk.fqdn,sip_signaling_port=7777) + modified_trunk = SipTrunk(fqdn=self.second_trunk.fqdn, sip_signaling_port=7777) async with self._sip_routing_client: await self._sip_routing_client.set_trunk(modified_trunk) new_trunks = self._sip_routing_client.list_trunks() new_trunks_list = await self._get_as_list(new_trunks) - assert_trunks_are_equal(new_trunks_list,[self.first_trunk,modified_trunk]) - + assert_trunks_are_equal(new_trunks_list, [self.first_trunk, modified_trunk]) + @recorded_by_proxy_async async def test_set_trunk_from_managed_identity(self): - modified_trunk = SipTrunk(fqdn=self.second_trunk.fqdn,sip_signaling_port=7777) + modified_trunk = SipTrunk(fqdn=self.second_trunk.fqdn, sip_signaling_port=7777) self._sip_routing_client = self._get_sip_client_managed_identity() async with self._sip_routing_client: await self._sip_routing_client.set_trunk(modified_trunk) new_trunks = self._sip_routing_client.list_trunks() new_trunks_list = await self._get_as_list(new_trunks) - assert_trunks_are_equal(new_trunks_list,[self.first_trunk,modified_trunk]) + assert_trunks_are_equal(new_trunks_list, [self.first_trunk, modified_trunk]) def _get_sip_client_managed_identity(self): endpoint, *_ = parse_connection_str(self.connection_str) credential = async_create_token_credential() return SipRoutingClient( - endpoint, - credential, - http_logging_policy=get_http_logging_policy(), - headers_policy=get_header_policy()) - - async def _get_as_list(self,iter): + endpoint, credential, http_logging_policy=get_http_logging_policy(), headers_policy=get_header_policy() + ) + + async def _get_as_list(self, iter): assert iter is not None, "No iterable was returned." items = [] async for item in iter: diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/__init__.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/__init__.py index a5ab26c51f27..06aa3e45ebf5 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/__init__.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/__init__.py @@ -5,11 +5,7 @@ # -------------------------------------------------------------------------- import warnings from ._rooms_client import RoomsClient -from ._models import ( - CommunicationRoom, - RoomParticipant, - ParticipantRole -) +from ._models import CommunicationRoom, RoomParticipant, ParticipantRole from ._shared.models import ( CommunicationIdentifier, CommunicationIdentifierKind, @@ -22,39 +18,45 @@ MicrosoftTeamsAppIdentifier, MicrosoftTeamsAppProperties, MicrosoftTeamsUserIdentifier, - MicrosoftTeamsUserProperties + MicrosoftTeamsUserProperties, ) from ._version import VERSION __all__ = [ - 'CommunicationRoom', - 'ParticipantRole', - 'RoomsClient', - 'RoomParticipant', - 'CommunicationIdentifier', - 'CommunicationIdentifierKind', - 'CommunicationCloudEnvironment', - 'CommunicationUserIdentifier', - 'CommunicationUserProperties', - 'PhoneNumberIdentifier', - 'PhoneNumberProperties', - 'UnknownIdentifier', - 'MicrosoftTeamsAppIdentifier', - 'MicrosoftTeamsAppProperties', - 'MicrosoftTeamsUserIdentifier', - 'MicrosoftTeamsUserProperties' + "CommunicationRoom", + "ParticipantRole", + "RoomsClient", + "RoomParticipant", + "CommunicationIdentifier", + "CommunicationIdentifierKind", + "CommunicationCloudEnvironment", + "CommunicationUserIdentifier", + "CommunicationUserProperties", + "PhoneNumberIdentifier", + "PhoneNumberProperties", + "UnknownIdentifier", + "MicrosoftTeamsAppIdentifier", + "MicrosoftTeamsAppProperties", + "MicrosoftTeamsUserIdentifier", + "MicrosoftTeamsUserProperties", ] __VERSION__ = VERSION + def __getattr__(name): - if name == 'MicrosoftBotProperties': - warnings.warn(f"{name} is deprecated and should not be used. Please use MicrosoftTeamsAppProperties instead.", - DeprecationWarning) + if name == "MicrosoftBotProperties": + warnings.warn( + f"{name} is deprecated and should not be used. Please use MicrosoftTeamsAppProperties instead.", + DeprecationWarning, + ) return MicrosoftTeamsAppProperties - if name == 'MicrosoftBotIdentifier': - warnings.warn(f"{name} is deprecated and should not be used. Please use 'MicrosoftTeamsAppIdentifier' instead.", - DeprecationWarning) + if name == "MicrosoftBotIdentifier": + warnings.warn( + f"{name} is deprecated and should not be used. Please use 'MicrosoftTeamsAppIdentifier' instead.", + DeprecationWarning, + ) from ._shared.models import _MicrosoftBotIdentifier + return _MicrosoftBotIdentifier raise AttributeError(f"module 'azure.communication.rooms' has no attribute {name}") diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_api_versions.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_api_versions.py index ed828e445956..6eea3ac3e5e6 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_api_versions.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_api_versions.py @@ -6,8 +6,10 @@ from enum import Enum from azure.core import CaseInsensitiveEnumMeta + class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): V2023_06_14 = "2023-06-14" V2024_04_15 = "2024-04-15" + DEFAULT_VERSION = ApiVersion.V2024_04_15 diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_models/__init__.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_models/__init__.py index 479bc234cc25..b5c6d7bc72d5 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_models/__init__.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_models/__init__.py @@ -6,14 +6,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._models import ( - RoomParticipant, - ParticipantRole, - CommunicationRoom -) +from ._models import RoomParticipant, ParticipantRole, CommunicationRoom -__all__ = [ - "RoomParticipant", - "ParticipantRole", - "CommunicationRoom" -] +__all__ = ["RoomParticipant", "ParticipantRole", "CommunicationRoom"] diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_models/_models.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_models/_models.py index 2bc03879afde..5fa115a914e3 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_models/_models.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_models/_models.py @@ -10,10 +10,7 @@ from azure.core import CaseInsensitiveEnumMeta -from .._shared.models import ( - CommunicationIdentifier, - identifier_from_raw_id -) +from .._shared.models import CommunicationIdentifier, identifier_from_raw_id class ParticipantRole(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -34,6 +31,7 @@ class RoomParticipant: :ivar role: Role Name. :vartype role: Union[str, ParticipantRole] """ + @overload def __init__( self, @@ -50,6 +48,7 @@ def __init__( values are: "Presenter", "Attendee", and "Consumer". :paramtype role: str or ~azure.communication.rooms.models.ParticipantRole """ + @overload def __init__(self, mapping: Mapping[str, Any]) -> None: """ @@ -59,14 +58,14 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: if len(args) == 1: - self.communication_identifier = identifier_from_raw_id(args[0]['rawId']) - self.role = args[0]['role'] + self.communication_identifier = identifier_from_raw_id(args[0]["rawId"]) + self.role = args[0]["role"] elif args: raise TypeError(f"RoomParticipant.__init__() takes 2 positional arguments but {len(args) + 1} were given.") else: - self.communication_identifier = kwargs['communication_identifier'] - self.role = kwargs.get('role', ParticipantRole.ATTENDEE) - self.role=self.role or ParticipantRole.ATTENDEE + self.communication_identifier = kwargs["communication_identifier"] + self.role = kwargs.get("role", ParticipantRole.ATTENDEE) + self.role = self.role or ParticipantRole.ATTENDEE def __eq__(self, other): if isinstance(other, self.__class__): @@ -101,9 +100,8 @@ def __init__( *, valid_from: Optional[datetime] = None, valid_until: Optional[datetime] = None, - pstn_dial_out_enabled: Optional[bool] = None - ): - ... + pstn_dial_out_enabled: Optional[bool] = None, + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): """ @@ -113,11 +111,11 @@ def __init__(self, mapping: Mapping[str, Any]): def __init__(self, *args: Any, **kwargs: Any) -> None: if len(args) == 1: - self.id = args[0]['id'] - self.created_at = args[0]['createdAt'] - self.valid_from = args[0]['validFrom'] - self.valid_until = args[0]['validUntil'] - self.pstn_dial_out_enabled = args[0]['pstnDialOutEnabled'] + self.id = args[0]["id"] + self.created_at = args[0]["createdAt"] + self.valid_from = args[0]["validFrom"] + self.valid_until = args[0]["validUntil"] + self.pstn_dial_out_enabled = args[0]["pstnDialOutEnabled"] elif args: raise TypeError( f"CommunicationRoom.__init__() takes 2 positional arguments but {len(args) + 1} were given." @@ -125,9 +123,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: else: self.id = None self.created_at = None - self.valid_from = kwargs.get('valid_from') - self.valid_until = kwargs.get('valid_until') - self.pstn_dial_out_enabled = kwargs.get('pstn_dial_out_enabled') + self.valid_from = kwargs.get("valid_from") + self.valid_until = kwargs.get("valid_until") + self.pstn_dial_out_enabled = kwargs.get("pstn_dial_out_enabled") def __eq__(self, other): if isinstance(other, self.__class__): diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_rooms_client.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_rooms_client.py index 54b76a0d5af7..e14c69fc2b48 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_rooms_client.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_rooms_client.py @@ -10,10 +10,7 @@ from azure.core.paging import ItemPaged from azure.core.tracing.decorator import distributed_trace -from azure.communication.rooms._models import ( - RoomParticipant, - CommunicationRoom -) +from azure.communication.rooms._models import RoomParticipant, CommunicationRoom from azure.communication.rooms._shared.models import CommunicationIdentifier from ._generated._client import AzureCommunicationRoomsService from ._generated._serialization import Serializer @@ -37,21 +34,16 @@ class RoomsClient(object): Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - endpoint: str, - credential: Union[TokenCredential, AzureKeyCredential], - **kwargs - ) -> None: + + def __init__(self, endpoint: str, credential: Union[TokenCredential, AzureKeyCredential], **kwargs) -> None: try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError as exc: raise ValueError("Account URL must be a string.") from exc if not credential: - raise ValueError( - "invalid credential from connection string.") + raise ValueError("invalid credential from connection string.") if endpoint.endswith("/"): endpoint = endpoint[:-1] @@ -64,12 +56,11 @@ def __init__( api_version=self._api_version, authentication_policy=self._authentication_policy, sdk_moniker=SDK_MONIKER, - **kwargs) + **kwargs + ) @classmethod - def from_connection_string(cls, conn_str: str, - **kwargs - ) -> 'RoomsClient': + def from_connection_string(cls, conn_str: str, **kwargs) -> "RoomsClient": """Create RoomsClient from a Connection String. :param str conn_str: @@ -97,7 +88,7 @@ def create_room( valid_from: Optional[datetime] = None, valid_until: Optional[datetime] = None, pstn_dial_out_enabled: bool = False, - participants: Optional[List[RoomParticipant]]=None, + participants: Optional[List[RoomParticipant]] = None, **kwargs ) -> CommunicationRoom: """Create a new room. @@ -118,34 +109,27 @@ def create_room( "pstnDialOutEnabled": pstn_dial_out_enabled, } if participants: - create_room_request["participants"] ={ + create_room_request["participants"] = { p.communication_identifier.raw_id: {"role": p.role} for p in participants } _SERIALIZER = Serializer() - repeatability_request_id = str(uuid.uuid1()) + repeatability_request_id = str(uuid.uuid1()) repeatability_first_sent = _SERIALIZER.serialize_data(datetime.utcnow(), "rfc-1123") request_headers = kwargs.pop("headers", {}) - request_headers.update({ - "Repeatability-Request-Id": repeatability_request_id, - "Repeatability-First-Sent": repeatability_first_sent - }) + request_headers.update( + {"Repeatability-Request-Id": repeatability_request_id, "Repeatability-First-Sent": repeatability_first_sent} + ) create_room_response = self._rooms_service_client.rooms.create( - create_room_request=create_room_request, - headers = request_headers, - **kwargs ) + create_room_request=create_room_request, headers=request_headers, **kwargs + ) return CommunicationRoom(create_room_response) @distributed_trace - def delete_room( - self, - room_id: str, - **kwargs - ) -> None: - + def delete_room(self, room_id: str, **kwargs) -> None: """Delete room. :param room_id: Required. Id of room to be deleted @@ -184,15 +168,12 @@ def update_room( "pstnDialOutEnabled": pstn_dial_out_enabled, } update_room_response = self._rooms_service_client.rooms.update( - room_id=room_id, update_room_request=update_room_request, **kwargs) + room_id=room_id, update_room_request=update_room_request, **kwargs + ) return CommunicationRoom(update_room_response) @distributed_trace - def get_room( - self, - room_id: str, - **kwargs - ) -> CommunicationRoom: + def get_room(self, room_id: str, **kwargs) -> CommunicationRoom: """Get a valid room :param room_id: Required. Id of room to be fetched @@ -205,29 +186,17 @@ def get_room( return CommunicationRoom(get_room_response) @distributed_trace - def list_rooms( - self, - **kwargs - ) -> ItemPaged[CommunicationRoom]: + def list_rooms(self, **kwargs) -> ItemPaged[CommunicationRoom]: """List all rooms :returns: An iterator like instance of CommunicationRoom. :rtype: ~azure.core.paging.ItemPaged[~azure.communication.rooms.CommunicationRoom] :raises: ~azure.core.exceptions.HttpResponseError """ - return self._rooms_service_client.rooms.list( - cls=lambda rooms: [CommunicationRoom(r) for r in rooms], - **kwargs - ) + return self._rooms_service_client.rooms.list(cls=lambda rooms: [CommunicationRoom(r) for r in rooms], **kwargs) @distributed_trace - def add_or_update_participants( - self, - *, - room_id: str, - participants: List[RoomParticipant], - **kwargs - ) -> None: + def add_or_update_participants(self, *, room_id: str, participants: List[RoomParticipant], **kwargs) -> None: """Update participants to a room. It looks for the room participants based on their communication identifier and replace the existing participants with the value passed in this API. @@ -243,15 +212,12 @@ def add_or_update_participants( "participants": {p.communication_identifier.raw_id: {"role": p.role} for p in participants} } self._rooms_service_client.participants.update( - room_id=room_id, update_participants_request=update_participants_request, **kwargs) + room_id=room_id, update_participants_request=update_participants_request, **kwargs + ) @distributed_trace def remove_participants( - self, - *, - room_id: str, - participants: List[Union[RoomParticipant, CommunicationIdentifier]], - **kwargs + self, *, room_id: str, participants: List[Union[RoomParticipant, CommunicationIdentifier]], **kwargs ) -> None: """Remove participants from a room @@ -262,23 +228,18 @@ def remove_participants( :rtype: None :raises: ~azure.core.exceptions.HttpResponseError, ValueError """ - remove_participants_request = { - "participants": {} - } + remove_participants_request = {"participants": {}} for participant in participants: try: remove_participants_request["participants"][participant.communication_identifier.raw_id] = None except AttributeError: remove_participants_request["participants"][participant.raw_id] = None self._rooms_service_client.participants.update( - room_id=room_id, update_participants_request=remove_participants_request, **kwargs) + room_id=room_id, update_participants_request=remove_participants_request, **kwargs + ) @distributed_trace - def list_participants( - self, - room_id: str, - **kwargs - )-> ItemPaged[RoomParticipant]: + def list_participants(self, room_id: str, **kwargs) -> ItemPaged[RoomParticipant]: """Get participants of a room :param room_id: Required. Id of room whose participants to be fetched. @@ -288,9 +249,8 @@ def list_participants( :raises: ~azure.core.exceptions.HttpResponseError """ return self._rooms_service_client.participants.list( - room_id=room_id, - cls=lambda objs: [RoomParticipant(x) for x in objs], - **kwargs) + room_id=room_id, cls=lambda objs: [RoomParticipant(x) for x in objs], **kwargs + ) def __enter__(self) -> "RoomsClient": self._rooms_service_client.__enter__() diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/auth_policy_utils.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/auth_policy_utils.py index d89c33f1ba0f..571aa1865a61 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/auth_policy_utils.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/auth_policy_utils.py @@ -43,9 +43,7 @@ def get_authentication_policy( return AsyncBearerTokenCredentialPolicy( credential, "https://communication.azure.com//.default" # type: ignore ) - return BearerTokenCredentialPolicy( - credential, "https://communication.azure.com//.default" # type: ignore - ) + return BearerTokenCredentialPolicy(credential, "https://communication.azure.com//.default") # type: ignore if isinstance(credential, (AzureKeyCredential, str)): return HMACCredentialsPolicy(endpoint, credential, decode_url=decode_url) diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/models.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/models.py index 7b646472045c..43875e1197e5 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/models.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/models.py @@ -14,8 +14,11 @@ class DeprecatedEnumMeta(CaseInsensitiveEnumMeta): def __getattribute__(cls, item): if item.upper() == "MICROSOFT_BOT": - warnings.warn("MICROSOFT_BOT is deprecated and has been replaced by \ - MICROSOFT_TEAMS_APP identifier.", DeprecationWarning) + warnings.warn( + "MICROSOFT_BOT is deprecated and has been replaced by \ + MICROSOFT_TEAMS_APP identifier.", + DeprecationWarning, + ) item = "MICROSOFT_TEAMS_APP" return super().__getattribute__(item) @@ -47,14 +50,17 @@ class CommunicationCloudEnvironment(str, Enum, metaclass=CaseInsensitiveEnumMeta @runtime_checkable class CommunicationIdentifier(Protocol): """Communication Identifier.""" + @property def raw_id(self) -> str: """The raw ID of the identifier.""" ... + @property def kind(self) -> CommunicationIdentifierKind: """The type of identifier.""" ... + @property def properties(self) -> Mapping[str, Any]: """The properties of the identifier.""" @@ -83,12 +89,14 @@ def properties(self) -> Mapping[str, Any]: class CommunicationUserProperties(TypedDict): """Dictionary of properties for a CommunicationUserIdentifier.""" + id: str """ID of the Communication user as returned from Azure Communication Identity.""" class CommunicationUserIdentifier: """Represents a user in Azure Communication Service.""" + kind: Literal[CommunicationIdentifierKind.COMMUNICATION_USER] = CommunicationIdentifierKind.COMMUNICATION_USER """The type of identifier.""" properties: CommunicationUserProperties @@ -116,12 +124,14 @@ def __eq__(self, other): class PhoneNumberProperties(TypedDict): """Dictionary of properties for a PhoneNumberIdentifier.""" + value: str """The phone number in E.164 format.""" class PhoneNumberIdentifier: """Represents a phone number.""" + kind: Literal[CommunicationIdentifierKind.PHONE_NUMBER] = CommunicationIdentifierKind.PHONE_NUMBER """The type of identifier.""" properties: PhoneNumberProperties @@ -165,6 +175,7 @@ class UnknownIdentifier: It is not advisable to rely on the `kind` property with a value `unknown`, as it could become a new or existing distinct type in the future. """ + kind: Literal[CommunicationIdentifierKind.UNKNOWN] = CommunicationIdentifierKind.UNKNOWN """The type of identifier.""" properties: Mapping[str, Any] @@ -188,6 +199,7 @@ def __eq__(self, other): class MicrosoftTeamsUserProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsUserIdentifier.""" + user_id: str """The id of the Microsoft Teams user. If the user isn't anonymous, the id is the AAD object id of the user.""" is_anonymous: bool @@ -198,6 +210,7 @@ class MicrosoftTeamsUserProperties(TypedDict): class MicrosoftTeamsUserIdentifier: """Represents an identifier for a Microsoft Teams user.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_USER] = CommunicationIdentifierKind.MICROSOFT_TEAMS_USER """The type of identifier.""" properties: MicrosoftTeamsUserProperties @@ -246,6 +259,7 @@ def _format_raw_id(self, properties: MicrosoftTeamsUserProperties) -> str: class MicrosoftTeamsAppProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsAppIdentifier.""" + app_id: str """The id of the Microsoft Teams application.""" cloud: Union[CommunicationCloudEnvironment, str] @@ -254,6 +268,7 @@ class MicrosoftTeamsAppProperties(TypedDict): class _botbackcompatdict(dict): """Backwards compatible properties.""" + def __getitem__(self, __key: Any) -> Any: try: return super().__getitem__(__key) @@ -267,6 +282,7 @@ def __getitem__(self, __key: Any) -> Any: class MicrosoftTeamsAppIdentifier: """Represents an identifier for a Microsoft Teams application.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_APP] = CommunicationIdentifierKind.MICROSOFT_TEAMS_APP """The type of identifier.""" properties: MicrosoftTeamsAppProperties @@ -282,10 +298,13 @@ def __init__(self, app_id: str, **kwargs: Any) -> None: :keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed from the other properties. """ - self.properties = cast(MicrosoftTeamsAppProperties, _botbackcompatdict( - app_id=app_id, - cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, - )) + self.properties = cast( + MicrosoftTeamsAppProperties, + _botbackcompatdict( + app_id=app_id, + cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, + ), + ) raw_id: Optional[str] = kwargs.get("raw_id") self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties) @@ -323,7 +342,7 @@ def __init__(self, bot_id, **kwargs): """ warnings.warn( "The MicrosoftBotIdentifier is deprecated and has been replaced by MicrosoftTeamsAppIdentifier.", - DeprecationWarning + DeprecationWarning, ) super().__init__(bot_id, **kwargs) @@ -339,9 +358,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d :rtype: CommunicationIdentifier """ if raw_id.startswith(PHONE_NUMBER_PREFIX): - return PhoneNumberIdentifier( - value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id - ) + return PhoneNumberIdentifier(value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id) segments = raw_id.split(":", maxsplit=2) if len(segments) < 3: @@ -350,9 +367,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d prefix = f"{segments[0]}:{segments[1]}:" suffix = segments[2] if prefix == TEAMS_USER_ANONYMOUS_PREFIX: - return MicrosoftTeamsUserIdentifier( - user_id=suffix, is_anonymous=True, raw_id=raw_id - ) + return MicrosoftTeamsUserIdentifier(user_id=suffix, is_anonymous=True, raw_id=raw_id) if prefix == TEAMS_USER_PUBLIC_CLOUD_PREFIX: return MicrosoftTeamsUserIdentifier( user_id=suffix, diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/policy.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/policy.py index 2fd2e7426c73..79aa48136fd3 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/policy.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/policy.py @@ -50,9 +50,7 @@ def _compute_hmac( else: decoded_secret = base64.b64decode(self._access_key) - digest = hmac.new( - decoded_secret, value.encode("utf-8"), hashlib.sha256 - ).digest() + digest = hmac.new(decoded_secret, value.encode("utf-8"), hashlib.sha256).digest() return base64.b64encode(digest).decode("utf-8") @@ -101,22 +99,10 @@ def _sign_request(self, request): utc_now = get_current_utc_time() if request.http_request.body is None: request.http_request.body = "" - content_digest = hashlib.sha256( - (request.http_request.body.encode("utf-8")) - ).digest() + content_digest = hashlib.sha256((request.http_request.body.encode("utf-8"))).digest() content_hash = base64.b64encode(content_digest).decode("utf-8") - string_to_sign = ( - verb - + "\n" - + query_url - + "\n" - + utc_now - + ";" - + self._host - + ";" - + content_hash - ) + string_to_sign = verb + "\n" + query_url + "\n" + utc_now + ";" + self._host + ";" + content_hash signature = self._compute_hmac(string_to_sign) @@ -124,10 +110,7 @@ def _sign_request(self, request): "x-ms-date": utc_now, "x-ms-content-sha256": content_hash, "x-ms-return-client-request-id": "true", - "Authorization": "HMAC-SHA256 SignedHeaders=" - + signed_headers - + "&Signature=" - + signature, + "Authorization": "HMAC-SHA256 SignedHeaders=" + signed_headers + "&Signature=" + signature, } request.http_request.headers.update(signature_header) diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/user_credential.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/user_credential.py index c7c150052918..54603e7b32ce 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/user_credential.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/user_credential.py @@ -38,9 +38,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._lock = Condition(Lock()) self._some_thread_refreshing = False @@ -54,9 +52,7 @@ def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -80,9 +76,7 @@ def _update_token_and_reschedule(self): try: new_token = self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -109,12 +103,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() if timespan <= TIMEOUT_MAX: self._timer = Timer(timespan, self._update_token_and_reschedule) self._timer.daemon = True diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/user_credential_async.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/user_credential_async.py index dcd934aba464..15ad17da1a8c 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/user_credential_async.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/user_credential_async.py @@ -40,9 +40,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._async_mutex = Lock() if sys.version_info[:3] == (3, 10, 0): @@ -60,9 +58,7 @@ async def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -86,9 +82,7 @@ async def _update_token_and_reschedule(self): try: new_token = await self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") async with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -115,12 +109,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() self._timer = AsyncTimer(timespan, self._update_token_and_reschedule) self._timer.start() diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/utils.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/utils.py index 47da8a283e5f..8576c31ddc56 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/utils.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/_shared/utils.py @@ -87,9 +87,7 @@ def create_access_token(token): payload = json.loads(padded_base64_payload) return AccessToken( token, - _convert_datetime_to_utc_int( - datetime.fromtimestamp(payload["exp"], TZ_UTC) - ), + _convert_datetime_to_utc_int(datetime.fromtimestamp(payload["exp"], TZ_UTC)), ) except ValueError as val_error: raise ValueError(token_parse_err_msg) from val_error diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/aio/__init__.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/aio/__init__.py index d213ec0387a8..f022fbb8cd20 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/aio/__init__.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/aio/__init__.py @@ -1,5 +1,5 @@ from ._rooms_client_async import RoomsClient __all__ = [ - 'RoomsClient', + "RoomsClient", ] diff --git a/sdk/communication/azure-communication-rooms/azure/communication/rooms/aio/_rooms_client_async.py b/sdk/communication/azure-communication-rooms/azure/communication/rooms/aio/_rooms_client_async.py index c097db525d24..feab25246de4 100644 --- a/sdk/communication/azure-communication-rooms/azure/communication/rooms/aio/_rooms_client_async.py +++ b/sdk/communication/azure-communication-rooms/azure/communication/rooms/aio/_rooms_client_async.py @@ -12,10 +12,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.async_paging import AsyncItemPaged -from azure.communication.rooms._models import ( - RoomParticipant, - CommunicationRoom -) +from azure.communication.rooms._models import RoomParticipant, CommunicationRoom from azure.communication.rooms._shared.models import CommunicationIdentifier from .._generated.aio._client import AzureCommunicationRoomsService from .._generated._serialization import Serializer @@ -39,21 +36,16 @@ class RoomsClient(object): Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - endpoint: str, - credential: Union[AsyncTokenCredential, AzureKeyCredential], - **kwargs - ) -> None: + + def __init__(self, endpoint: str, credential: Union[AsyncTokenCredential, AzureKeyCredential], **kwargs) -> None: try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError as exc: raise ValueError("Account URL must be a string.") from exc if not credential: - raise ValueError( - "invalid credential from connection string.") + raise ValueError("invalid credential from connection string.") if endpoint.endswith("/"): endpoint = endpoint[:-1] @@ -66,12 +58,11 @@ def __init__( api_version=self._api_version, authentication_policy=self._authentication_policy, sdk_moniker=SDK_MONIKER, - **kwargs) + **kwargs + ) @classmethod - def from_connection_string(cls, conn_str: str, - **kwargs - ) -> 'RoomsClient': + def from_connection_string(cls, conn_str: str, **kwargs) -> "RoomsClient": """Create RoomsClient from a Connection String. :param str conn_str: @@ -99,7 +90,7 @@ async def create_room( valid_from: Optional[datetime] = None, valid_until: Optional[datetime] = None, pstn_dial_out_enabled: bool = False, - participants:Optional[List[RoomParticipant]] = None, + participants: Optional[List[RoomParticipant]] = None, **kwargs ) -> CommunicationRoom: """Create a new room. @@ -124,28 +115,22 @@ async def create_room( } _SERIALIZER = Serializer() - repeatability_request_id = str(uuid.uuid1()) + repeatability_request_id = str(uuid.uuid1()) repeatability_first_sent = Serializer().serialize_data(datetime.utcnow(), "rfc-1123") request_headers = kwargs.pop("headers", {}) - request_headers.update({ - "Repeatability-Request-Id": repeatability_request_id, - "Repeatability-First-Sent": repeatability_first_sent - }) + request_headers.update( + {"Repeatability-Request-Id": repeatability_request_id, "Repeatability-First-Sent": repeatability_first_sent} + ) create_room_response = await self._rooms_service_client.rooms.create( - create_room_request=create_room_request, - headers = request_headers, - **kwargs) + create_room_request=create_room_request, headers=request_headers, **kwargs + ) return CommunicationRoom(create_room_response) @distributed_trace_async - async def delete_room( - self, - room_id: str, - **kwargs - ) -> None: + async def delete_room(self, room_id: str, **kwargs) -> None: """Delete room. :param room_id: Required. Id of room to be deleted @@ -181,18 +166,15 @@ async def update_room( update_room_request = { "validFrom": valid_from, "validUntil": valid_until, - "pstnDialOutEnabled": pstn_dial_out_enabled + "pstnDialOutEnabled": pstn_dial_out_enabled, } update_room_response = await self._rooms_service_client.rooms.update( - room_id=room_id, update_room_request=update_room_request, **kwargs) + room_id=room_id, update_room_request=update_room_request, **kwargs + ) return CommunicationRoom(update_room_response) @distributed_trace_async - async def get_room( - self, - room_id: str, - **kwargs - ) -> CommunicationRoom: + async def get_room(self, room_id: str, **kwargs) -> CommunicationRoom: """Get a valid room :param room_id: Required. Id of room to be fetched @@ -205,30 +187,17 @@ async def get_room( return CommunicationRoom(get_room_response) @distributed_trace - def list_rooms( - self, - **kwargs - ) -> AsyncItemPaged[CommunicationRoom]: + def list_rooms(self, **kwargs) -> AsyncItemPaged[CommunicationRoom]: """List all rooms :returns: An iterator like instance of CommunicationRoom. :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.rooms.CommunicationRoom] :raises: ~azure.core.exceptions.HttpResponseError """ - return self._rooms_service_client.rooms.list( - cls=lambda rooms: [CommunicationRoom(r) for r in rooms], - **kwargs - ) - + return self._rooms_service_client.rooms.list(cls=lambda rooms: [CommunicationRoom(r) for r in rooms], **kwargs) @distributed_trace_async - async def add_or_update_participants( - self, - *, - room_id: str, - participants: List[RoomParticipant], - **kwargs - ) -> None: + async def add_or_update_participants(self, *, room_id: str, participants: List[RoomParticipant], **kwargs) -> None: """Update participants to a room. It looks for the room participants based on their communication identifier and replace those participants with the value passed in this API. @@ -244,15 +213,12 @@ async def add_or_update_participants( "participants": {p.communication_identifier.raw_id: {"role": p.role} for p in participants} } await self._rooms_service_client.participants.update( - room_id=room_id, update_participants_request=update_participants_request, **kwargs) + room_id=room_id, update_participants_request=update_participants_request, **kwargs + ) @distributed_trace_async async def remove_participants( - self, - *, - room_id: str, - participants: List[Union[RoomParticipant, CommunicationIdentifier]], - **kwargs + self, *, room_id: str, participants: List[Union[RoomParticipant, CommunicationIdentifier]], **kwargs ) -> None: """Remove participants from a room @@ -263,23 +229,18 @@ async def remove_participants( :rtype: None :raises: ~azure.core.exceptions.HttpResponseError, ValueError """ - remove_participants_request = { - "participants": {} - } + remove_participants_request = {"participants": {}} for participant in participants: try: remove_participants_request["participants"][participant.communication_identifier.raw_id] = None except AttributeError: remove_participants_request["participants"][participant.raw_id] = None await self._rooms_service_client.participants.update( - room_id=room_id, update_participants_request=remove_participants_request, **kwargs) + room_id=room_id, update_participants_request=remove_participants_request, **kwargs + ) @distributed_trace - def list_participants( - self, - room_id: str, - **kwargs - ) -> AsyncItemPaged[RoomParticipant]: + def list_participants(self, room_id: str, **kwargs) -> AsyncItemPaged[RoomParticipant]: """Get participants of a room :param room_id: Required. Id of room whose participants to be fetched. @@ -289,9 +250,7 @@ def list_participants( :raises: ~azure.core.exceptions.HttpResponseError """ return self._rooms_service_client.participants.list( - room_id=room_id, - cls=lambda objs: [RoomParticipant(x) for x in objs], - **kwargs + room_id=room_id, cls=lambda objs: [RoomParticipant(x) for x in objs], **kwargs ) async def __aenter__(self) -> "RoomsClient": diff --git a/sdk/communication/azure-communication-rooms/samples/rooms_client_sample.py b/sdk/communication/azure-communication-rooms/samples/rooms_client_sample.py index 77b9cce0b7c6..1e271955ab90 100644 --- a/sdk/communication/azure-communication-rooms/samples/rooms_client_sample.py +++ b/sdk/communication/azure-communication-rooms/samples/rooms_client_sample.py @@ -30,14 +30,11 @@ from datetime import datetime, timedelta from azure.core.exceptions import HttpResponseError from azure.communication.identity import CommunicationIdentityClient -from azure.communication.rooms import ( - ParticipantRole, - RoomsClient, - RoomParticipant -) +from azure.communication.rooms import ParticipantRole, RoomsClient, RoomParticipant sys.path.append("..") + class RoomsSample(object): def setUp(self): @@ -46,30 +43,28 @@ def setUp(self): self.rooms_client = RoomsClient.from_connection_string(self.connection_string) # [END auth_from_connection_string] - self.identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string) + self.identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) self.rooms = [] self.participant_1 = RoomParticipant( - communication_identifier=self.identity_client.create_user(), - role=ParticipantRole.PRESENTER) + communication_identifier=self.identity_client.create_user(), role=ParticipantRole.PRESENTER + ) self.participant_2 = RoomParticipant( - communication_identifier=self.identity_client.create_user(), - role=ParticipantRole.CONSUMER) + communication_identifier=self.identity_client.create_user(), role=ParticipantRole.CONSUMER + ) def tearDown(self): self.delete_room_all_rooms() def create_single_room(self): - valid_from = datetime.now() + valid_from = datetime.now() valid_until = valid_from + timedelta(weeks=4) participants = [self.participant_1] try: create_room_response = self.rooms_client.create_room( - valid_from=valid_from, - valid_until=valid_until, - participants=participants) + valid_from=valid_from, valid_until=valid_until, participants=participants + ) self.printRoom(response=create_room_response) # all created room to a list @@ -91,7 +86,7 @@ def create_single_room_with_default_attributes(self): # Starting in 1.1.0b1 release,create_room function also takes pstn_dial_out_enabled as parameter def create_room_with_pstn_attribute(self): - valid_from = datetime.now() + valid_from = datetime.now() valid_until = valid_from + timedelta(weeks=4) participants = [self.participant_1] pstn_dial_out_enabled = True @@ -101,7 +96,8 @@ def create_room_with_pstn_attribute(self): valid_from=valid_from, valid_until=valid_until, participants=participants, - pstn_dial_out_enabled=pstn_dial_out_enabled) + pstn_dial_out_enabled=pstn_dial_out_enabled, + ) self.printRoom(response=create_room_response) # all created room to a list @@ -112,11 +108,13 @@ def create_room_with_pstn_attribute(self): def update_single_room(self, room_id): # set attributes you want to change - valid_from = datetime.now() + valid_from = datetime.now() valid_until = valid_from + timedelta(weeks=7) try: - update_room_response = self.rooms_client.update_room(room_id=room_id, valid_from=valid_from, valid_until=valid_until) + update_room_response = self.rooms_client.update_room( + room_id=room_id, valid_from=valid_from, valid_until=valid_until + ) self.printRoom(response=update_room_response) except HttpResponseError as ex: print(ex) @@ -124,7 +122,7 @@ def update_single_room(self, room_id): # Starting in 1.1.0b1 release,update_room function also takes pstn_dial_out_enabled as parameter def update_room_with_pstn_attribute(self, room_id): # set attributes you want to change - valid_from = datetime.now() + valid_from = datetime.now() valid_until = valid_from + timedelta(weeks=7) pstn_dial_out_enabled = True @@ -133,7 +131,8 @@ def update_room_with_pstn_attribute(self, room_id): room_id=room_id, valid_from=valid_from, valid_until=valid_until, - pstn_dial_out_enabled=pstn_dial_out_enabled) + pstn_dial_out_enabled=pstn_dial_out_enabled, + ) self.printRoom(response=update_room_response) except HttpResponseError as ex: print(ex) @@ -141,9 +140,9 @@ def update_room_with_pstn_attribute(self, room_id): def add_or_update_participants(self, room_id): self.participant_1.role = ParticipantRole.ATTENDEE participants = [ - self.participant_1, # Update participant_1 role from Presenter to Attendee - self.participant_2 # Add participant_2 to room - ] + self.participant_1, # Update participant_1 role from Presenter to Attendee + self.participant_2, # Add participant_2 to room + ] try: self.rooms_client.add_or_update_participants(room_id=room_id, participants=participants) @@ -186,22 +185,22 @@ def printRoom(self, response): print("valid_until: ", response.valid_until) def convert_participant_list_to_string(self, participants): - result = '' + result = "" for p in participants: - result += "id: {}\n role: {}\n".format( - p.communication_identifier.properties["id"], p.role) + result += "id: {}\n role: {}\n".format(p.communication_identifier.properties["id"], p.role) return result -if __name__ == '__main__': + +if __name__ == "__main__": sample = RoomsSample() sample.setUp() sample.create_single_room() sample.create_single_room_with_default_attributes() if len(sample.rooms) > 0: - sample.get_room(room_id=sample.rooms[0] ) + sample.get_room(room_id=sample.rooms[0]) sample.update_single_room(room_id=sample.rooms[0]) sample.add_or_update_participants(room_id=sample.rooms[0]) sample.list_participants(room_id=sample.rooms[0]) sample.remove_participants(room_id=sample.rooms[0]) sample.get_room(room_id=sample.rooms[0]) - sample.tearDown() \ No newline at end of file + sample.tearDown() diff --git a/sdk/communication/azure-communication-rooms/samples/rooms_client_sample_async.py b/sdk/communication/azure-communication-rooms/samples/rooms_client_sample_async.py index 57e8604bdca4..4c70eb837173 100644 --- a/sdk/communication/azure-communication-rooms/samples/rooms_client_sample_async.py +++ b/sdk/communication/azure-communication-rooms/samples/rooms_client_sample_async.py @@ -32,13 +32,11 @@ from azure.core.exceptions import HttpResponseError from azure.communication.identity import CommunicationIdentityClient from azure.communication.rooms.aio import RoomsClient -from azure.communication.rooms import ( - RoomParticipant, - ParticipantRole -) +from azure.communication.rooms import RoomParticipant, ParticipantRole sys.path.append("..") + class RoomsSample(object): def setUp(self): @@ -47,30 +45,28 @@ def setUp(self): self.rooms_client = RoomsClient.from_connection_string(self.connection_string) # [END auth_from_connection_string_async] - self.identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_string) + self.identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string) self.rooms = [] self.participant_1 = RoomParticipant( - communication_identifier=self.identity_client.create_user(), - role=ParticipantRole.PRESENTER) + communication_identifier=self.identity_client.create_user(), role=ParticipantRole.PRESENTER + ) self.participant_2 = RoomParticipant( - communication_identifier=self.identity_client.create_user(), - role=ParticipantRole.CONSUMER) + communication_identifier=self.identity_client.create_user(), role=ParticipantRole.CONSUMER + ) async def tearDown(self): await self.delete_room_all_rooms() async def create_single_room(self): - valid_from = datetime.now() + valid_from = datetime.now() valid_until = valid_from + timedelta(weeks=4) participants = [self.participant_1] try: create_room_response = await self.rooms_client.create_room( - valid_from=valid_from, - valid_until=valid_until, - participants=participants) + valid_from=valid_from, valid_until=valid_until, participants=participants + ) self.printRoom(response=create_room_response) # all created room to a list @@ -94,7 +90,7 @@ async def create_single_room_with_default_attributes(self): # Starting in 1.1.0b1 release,create_room function also takes pstn_dial_out_enabled as parameter async def create_room_with_pstn_attribute(self): - valid_from = datetime.now() + valid_from = datetime.now() valid_until = valid_from + timedelta(weeks=4) participants = [self.participant_1] pstn_dial_out_enabled = True @@ -104,7 +100,8 @@ async def create_room_with_pstn_attribute(self): valid_from=valid_from, valid_until=valid_until, participants=participants, - pstn_dial_out_enabled=pstn_dial_out_enabled) + pstn_dial_out_enabled=pstn_dial_out_enabled, + ) self.printRoom(response=create_room_response) # all created room to a list @@ -115,19 +112,22 @@ async def create_room_with_pstn_attribute(self): async def update_single_room(self, room_id): # set attributes you want to change - valid_from = datetime.now() + valid_from = datetime.now() valid_until = valid_from + timedelta(weeks=7) try: - update_room_response = await self.rooms_client.update_room(room_id=room_id, valid_from=valid_from, valid_until=valid_until) + update_room_response = await self.rooms_client.update_room( + room_id=room_id, valid_from=valid_from, valid_until=valid_until + ) self.printRoom(response=update_room_response) except HttpResponseError as ex: print(ex) # Starting in 1.1.0b1 release,update_room function also takes pstn_dial_out_enabled as parameter + async def update_room_with_pstn_attribute(self, room_id): # set attributes you want to change - valid_from = datetime.now() + valid_from = datetime.now() valid_until = valid_from + timedelta(weeks=7) pstn_dial_out_enabled = True @@ -136,7 +136,8 @@ async def update_room_with_pstn_attribute(self, room_id): room_id=room_id, valid_from=valid_from, valid_until=valid_until, - pstn_dial_out_enabled=pstn_dial_out_enabled) + pstn_dial_out_enabled=pstn_dial_out_enabled, + ) self.printRoom(response=update_room_response) except HttpResponseError as ex: print(ex) @@ -144,9 +145,9 @@ async def update_room_with_pstn_attribute(self, room_id): async def add_or_update_participants(self, room_id): self.participant_1.role = ParticipantRole.ATTENDEE participants = [ - self.participant_1, # Update participant_1 role from Presenter to Attendee - self.participant_2 # Add participant_2 to room - ] + self.participant_1, # Update participant_1 role from Presenter to Attendee + self.participant_2, # Add participant_2 to room + ] try: await self.rooms_client.add_or_update_participants(room_id=room_id, participants=participants) @@ -189,19 +190,19 @@ def printRoom(self, response): print("valid_until: ", response.valid_until) async def convert_participant_list_to_string(self, participants): - result = '' + result = "" async for p in participants: - result += "id: {}\n role: {}\n".format( - p.communication_identifier.properties["id"], p.role) + result += "id: {}\n role: {}\n".format(p.communication_identifier.properties["id"], p.role) return result + async def main(): sample = RoomsSample() sample.setUp() await sample.create_single_room() await sample.create_single_room_with_default_attributes() if len(sample.rooms) > 0: - await sample.get_room(room_id=sample.rooms[0] ) + await sample.get_room(room_id=sample.rooms[0]) await sample.update_single_room(room_id=sample.rooms[0]) await sample.add_or_update_participants(room_id=sample.rooms[0]) await sample.list_participants(room_id=sample.rooms[0]) @@ -209,5 +210,6 @@ async def main(): await sample.get_room(room_id=sample.rooms[0]) await sample.tearDown() -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.run(main()) diff --git a/sdk/communication/azure-communication-rooms/setup.py b/sdk/communication/azure-communication-rooms/setup.py index c11634dc2c7a..89ad637d92b1 100644 --- a/sdk/communication/azure-communication-rooms/setup.py +++ b/sdk/communication/azure-communication-rooms/setup.py @@ -25,9 +25,7 @@ # Version extraction inspired from 'requests' with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: - version = re.search( - r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE - ).group(1) + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError("Cannot find version information") @@ -58,7 +56,7 @@ zip_safe=False, packages=find_packages( exclude=[ - 'tests', + "tests", # Exclude packages that will be covered by PEP420 or nspkg "azure", "azure.communication", @@ -70,7 +68,5 @@ ], python_requires=">=3.8", include_package_data=True, - extras_require={ - ":python_version<'3.8'": ["typing-extensions"] - } + extras_require={":python_version<'3.8'": ["typing-extensions"]}, ) diff --git a/sdk/communication/azure-communication-rooms/tests/_shared/utils.py b/sdk/communication/azure-communication-rooms/tests/_shared/utils.py index 955346bee1a6..69a0d2586209 100644 --- a/sdk/communication/azure-communication-rooms/tests/_shared/utils.py +++ b/sdk/communication/azure-communication-rooms/tests/_shared/utils.py @@ -20,7 +20,7 @@ def create_token_credential(): from .fake_token_credential import FakeTokenCredential return FakeTokenCredential() - + return get_credential() @@ -32,7 +32,7 @@ def async_create_token_credential(): from .async_fake_token_credential import AsyncFakeTokenCredential return AsyncFakeTokenCredential() - + return get_credential(is_async=True) diff --git a/sdk/communication/azure-communication-rooms/tests/acs_rooms_test_case.py b/sdk/communication/azure-communication-rooms/tests/acs_rooms_test_case.py index 077c2ec9ed5d..69f20a9bf77e 100644 --- a/sdk/communication/azure-communication-rooms/tests/acs_rooms_test_case.py +++ b/sdk/communication/azure-communication-rooms/tests/acs_rooms_test_case.py @@ -8,14 +8,14 @@ from devtools_testutils import AzureRecordedTestCase, is_live from azure.communication.rooms._shared.utils import parse_connection_str + class ACSRoomsTestCase(AzureRecordedTestCase): def setUp(self): if is_live(): - self.connection_str = os.getenv('COMMUNICATION_CONNECTION_STRING_ROOMS') + self.connection_str = os.getenv("COMMUNICATION_CONNECTION_STRING_ROOMS") self.endpoint, _ = parse_connection_str(self.connection_str) self._resource_name = self.endpoint.split(".")[0] else: self.connection_str = "endpoint=https://sanitized.communication.azure.com/;accesskey=fake===" self.endpoint, _ = parse_connection_str(self.connection_str) self._resource_name = self.endpoint.split(".")[0] - diff --git a/sdk/communication/azure-communication-rooms/tests/conftest.py b/sdk/communication/azure-communication-rooms/tests/conftest.py index 1de9f300d1b6..3fb28aa4157d 100644 --- a/sdk/communication/azure-communication-rooms/tests/conftest.py +++ b/sdk/communication/azure-communication-rooms/tests/conftest.py @@ -33,13 +33,19 @@ ) from azure.communication.rooms._shared.utils import parse_connection_str + @pytest.fixture(scope="session", autouse=True) def add_sanitizers(test_proxy): set_default_session_settings() - communication_connection_string = os.getenv("COMMUNICATION_CONNECTION_STRING_ROOMS", "endpoint=https://sanitized.communication.azure.com/;accesskey=fake===") + communication_connection_string = os.getenv( + "COMMUNICATION_CONNECTION_STRING_ROOMS", "endpoint=https://sanitized.communication.azure.com/;accesskey=fake===" + ) - add_general_string_sanitizer(target=communication_connection_string, value="endpoint=https://sanitized.communication.azure.com/;accesskey=fake===") + add_general_string_sanitizer( + target=communication_connection_string, + value="endpoint=https://sanitized.communication.azure.com/;accesskey=fake===", + ) endpoint, _ = parse_connection_str(communication_connection_string) add_general_string_sanitizer(target=endpoint, value="sanitized.communication.azure.com") add_header_regex_sanitizer(key="x-ms-content-sha256", value="sanitized") @@ -53,8 +59,7 @@ def add_sanitizers(test_proxy): add_header_regex_sanitizer(key="x-ms-client-request-id", value="sanitized") add_header_regex_sanitizer(key="x-ms-date", value="sanitized") add_header_regex_sanitizer(key="x-ms-request-id", value="sanitized") - add_header_regex_sanitizer( - key="Content-Security-Policy-Report-Only", value="sanitized") + add_header_regex_sanitizer(key="Content-Security-Policy-Report-Only", value="sanitized") add_header_regex_sanitizer(key="Repeatability-First-Sent", value="sanitized") add_header_regex_sanitizer(key="Repeatability-Request-ID", value="sanitized") diff --git a/sdk/communication/azure-communication-rooms/tests/test_hmac.py b/sdk/communication/azure-communication-rooms/tests/test_hmac.py index b67b0ff4db62..288648f536c0 100644 --- a/sdk/communication/azure-communication-rooms/tests/test_hmac.py +++ b/sdk/communication/azure-communication-rooms/tests/test_hmac.py @@ -7,19 +7,20 @@ from azure.communication.rooms._shared.policy import HMACCredentialsPolicy -class TestHMAC(): + +class TestHMAC: def test_correct_hmac(self): auth_policy = HMACCredentialsPolicy("contoso.communicationservices.azure.com", "pw==") sha_val = auth_policy._compute_hmac("banana") - #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="unit test with fake keys")] + # [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="unit test with fake keys")] assert sha_val == "88EC05aAS9iXnaimtNO78JLjiPtfWryQB/5QYEzEsu8=" def test_correct_utf16_hmac(self): auth_policy = HMACCredentialsPolicy("contoso.communicationservices.azure.com", "pw==") - sha_val = auth_policy._compute_hmac(u"😀") + sha_val = auth_policy._compute_hmac("😀") - #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="unit test with fake keys")] - assert sha_val == "1rudJKjn2Zi+3hRrBG29wIF6pD6YyAeQR1ZcFtXoKAU=" \ No newline at end of file + # [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="unit test with fake keys")] + assert sha_val == "1rudJKjn2Zi+3hRrBG29wIF6pD6YyAeQR1ZcFtXoKAU=" diff --git a/sdk/communication/azure-communication-rooms/tests/test_rooms_client.py b/sdk/communication/azure-communication-rooms/tests/test_rooms_client.py index 94db0859f4a0..628cbc379d3e 100644 --- a/sdk/communication/azure-communication-rooms/tests/test_rooms_client.py +++ b/sdk/communication/azure-communication-rooms/tests/test_rooms_client.py @@ -10,16 +10,13 @@ from azure.core.exceptions import HttpResponseError from azure.communication.identity import CommunicationIdentityClient -from azure.communication.rooms import ( - ParticipantRole, - RoomParticipant, - RoomsClient -) +from azure.communication.rooms import ParticipantRole, RoomParticipant, RoomsClient from azure.communication.rooms._shared.models import CommunicationUserIdentifier from _shared.utils import get_http_logging_policy from acs_rooms_test_case import ACSRoomsTestCase from devtools_testutils import is_live, add_general_regex_sanitizer, recorded_by_proxy + class TestRoomsClient(ACSRoomsTestCase): def setup_method(self): super().setUp() @@ -28,9 +25,7 @@ def setup_method(self): sanitizedId3 = "8:acs:sanitized3" sanitizedId4 = "8:acs:sanitized4" if is_live(): - self.identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_str) - + self.identity_client = CommunicationIdentityClient.from_connection_string(self.connection_str) self.id1 = self.identity_client.create_user().properties["id"] self.id2 = self.identity_client.create_user().properties["id"] @@ -47,27 +42,22 @@ def setup_method(self): self.id4 = sanitizedId4 self.rooms_client = RoomsClient.from_connection_string( - self.connection_str, - http_logging_policy=get_http_logging_policy() + self.connection_str, http_logging_policy=get_http_logging_policy() ) self.users = { - "john" : RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=ParticipantRole.PRESENTER + "john": RoomParticipant( + communication_identifier=CommunicationUserIdentifier(self.id1), role=ParticipantRole.PRESENTER ), - "fred" : RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2), - role=ParticipantRole.CONSUMER + "fred": RoomParticipant( + communication_identifier=CommunicationUserIdentifier(self.id2), role=ParticipantRole.CONSUMER + ), + "chris": RoomParticipant( + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.ATTENDEE ), - "chris" : RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.ATTENDEE - ) } self.rooms_client = RoomsClient.from_connection_string( - self.connection_str, - http_logging_policy=get_http_logging_policy() + self.connection_str, http_logging_policy=get_http_logging_policy() ) @recorded_by_proxy @@ -79,10 +69,7 @@ def test_create_room_no_attributes(self): @recorded_by_proxy def test_create_room_only_participants(self): # add john and chris to room - participants = [ - self.users["john"], - self.users["chris"] - ] + participants = [self.users["john"], self.users["chris"]] response = self.rooms_client.create_room(participants=participants) # delete created room @@ -93,7 +80,7 @@ def test_create_room_only_participants(self): @recorded_by_proxy def test_create_room_validUntil_seven_months(self): # room attributes - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(weeks=29) with pytest.raises(HttpResponseError) as ex: @@ -114,7 +101,7 @@ def test_create_room_valid_until_in_past(self): @recorded_by_proxy def test_create_room_correct_timerange(self): # room attributes - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(weeks=4) response = self.rooms_client.create_room(valid_from=valid_from, valid_until=valid_until) @@ -126,10 +113,8 @@ def test_create_room_correct_timerange(self): def test_create_room_incorrectMri(self): # room attributes participants = [ - RoomParticipant( - communication_identifier=CommunicationUserIdentifier("wrong_mri"), - role='Attendee'), - self.users["john"] + RoomParticipant(communication_identifier=CommunicationUserIdentifier("wrong_mri"), role="Attendee"), + self.users["john"], ] with pytest.raises(HttpResponseError) as ex: @@ -141,40 +126,40 @@ def test_create_room_incorrectMri(self): @recorded_by_proxy def test_create_room_all_attributes(self): # room attributes - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(weeks=4) - participants = [ - self.users["john"] - ] + participants = [self.users["john"]] - response = self.rooms_client.create_room(valid_from=valid_from, valid_until=valid_until, participants=participants) + response = self.rooms_client.create_room( + valid_from=valid_from, valid_until=valid_until, participants=participants + ) # delete created room self.rooms_client.delete_room(room_id=response.id) - self.verify_successful_room_response( - response=response, valid_from=valid_from, valid_until=valid_until) + self.verify_successful_room_response(response=response, valid_from=valid_from, valid_until=valid_until) @pytest.mark.live_test_only @recorded_by_proxy def test_get_room(self): # room attributes - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(weeks=2) # add john to room - participants = [ - self.users["john"] - ] + participants = [self.users["john"]] # create a room first - create_response = self.rooms_client.create_room(valid_from=valid_from, valid_until=valid_until, participants=participants) + create_response = self.rooms_client.create_room( + valid_from=valid_from, valid_until=valid_until, participants=participants + ) get_response = self.rooms_client.get_room(room_id=create_response.id) # delete created room self.rooms_client.delete_room(room_id=create_response.id) self.verify_successful_room_response( - response=get_response, valid_from=valid_from, valid_until=valid_until, room_id=create_response.id) + response=get_response, valid_from=valid_from, valid_until=valid_until, room_id=create_response.id + ) @recorded_by_proxy def test_get_invalid_format_roomId(self): @@ -193,15 +178,18 @@ def test_update_room_correct_timerange(self): create_response = self.rooms_client.create_room() # update room attributes - valid_from = datetime.now() + timedelta(days=3) - valid_until = datetime.now() + timedelta(weeks=4) + valid_from = datetime.now() + timedelta(days=3) + valid_until = datetime.now() + timedelta(weeks=4) - update_response = self.rooms_client.update_room(room_id=create_response.id, valid_from=valid_from, valid_until=valid_until) + update_response = self.rooms_client.update_room( + room_id=create_response.id, valid_from=valid_from, valid_until=valid_until + ) # delete created room self.rooms_client.delete_room(room_id=create_response.id) self.verify_successful_room_response( - response=update_response, valid_from=valid_from, valid_until=valid_until, room_id=create_response.id) + response=update_response, valid_from=valid_from, valid_until=valid_until, room_id=create_response.id + ) @pytest.mark.live_test_only @recorded_by_proxy @@ -213,12 +201,14 @@ def test_update_room_PstnDialOutEnabled(self): update_response = self.rooms_client.update_room(room_id=create_response.id, pstn_dial_out_enabled=True) self.verify_successful_room_response( - response=update_response, pstn_dial_out_enabled=True, room_id=create_response.id) + response=update_response, pstn_dial_out_enabled=True, room_id=create_response.id + ) update_response = self.rooms_client.update_room(room_id=create_response.id, pstn_dial_out_enabled=False) self.verify_successful_room_response( - response=update_response, pstn_dial_out_enabled=False, room_id=create_response.id) + response=update_response, pstn_dial_out_enabled=False, room_id=create_response.id + ) # delete created room self.rooms_client.delete_room(room_id=create_response.id) @@ -229,13 +219,20 @@ def test_update_room_PstnDialOutRemainsUnchanged(self): create_response = self.rooms_client.create_room(pstn_dial_out_enabled=True) # update room attributes - valid_from = datetime.now() + timedelta(days=3) - valid_until = datetime.now() + timedelta(weeks=4) + valid_from = datetime.now() + timedelta(days=3) + valid_until = datetime.now() + timedelta(weeks=4) # update room attributes - update_response = self.rooms_client.update_room(room_id=create_response.id, valid_from=valid_from, valid_until=valid_until) + update_response = self.rooms_client.update_room( + room_id=create_response.id, valid_from=valid_from, valid_until=valid_until + ) self.verify_successful_room_response( - response=update_response, valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=True, room_id=create_response.id) + response=update_response, + valid_from=valid_from, + valid_until=valid_until, + pstn_dial_out_enabled=True, + room_id=create_response.id, + ) # delete created room self.rooms_client.delete_room(room_id=create_response.id) @@ -244,7 +241,7 @@ def test_update_room_PstnDialOutRemainsUnchanged(self): def test_update_room_invalid_format_roomId(self): # try to update room with random room_id with pytest.raises(HttpResponseError) as ex: - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(days=4) self.rooms_client.update_room(room_id="invalid_id", valid_from=valid_from, valid_until=valid_until) # assert error is bad request @@ -258,8 +255,8 @@ def test_update_room_valid_until_in_past(self): with pytest.raises(HttpResponseError) as ex: # update room attributes - valid_from = datetime.now() - timedelta(days=3) - valid_until = datetime.now() - timedelta(weeks=1) + valid_from = datetime.now() - timedelta(days=3) + valid_until = datetime.now() - timedelta(weeks=1) self.rooms_client.update_room(room_id=create_response.id, valid_from=valid_from, valid_until=valid_until) # delete created room self.rooms_client.delete_room(room_id=create_response.id) @@ -274,7 +271,7 @@ def test_update_room_deleted_room(self): # delete the room self.rooms_client.delete_room(room_id=create_response.id) with pytest.raises(HttpResponseError) as ex: - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(days=4) self.rooms_client.update_room(room_id=create_response.id, valid_from=valid_from, valid_until=valid_until) @@ -288,49 +285,42 @@ def test_update_room_exceed_max_timerange(self): create_response = self.rooms_client.create_room() # update room attributes - valid_from = datetime.now() + timedelta(days=3) - valid_until = datetime.now() + timedelta(weeks=29) + valid_from = datetime.now() + timedelta(days=3) + valid_until = datetime.now() + timedelta(weeks=29) with pytest.raises(HttpResponseError) as ex: self.rooms_client.update_room(room_id=create_response.id, valid_from=valid_from, valid_until=valid_until) assert str(ex.value.status_code) == "400" assert ex.value.message is not None - # delete created room + # delete created room self.rooms_client.delete_room(room_id=create_response.id) @recorded_by_proxy def test_add_or_update_participants(self): # add john and chris to room - create_participants = [ - self.users["john"], - self.users["chris"] - ] + create_participants = [self.users["john"], self.users["chris"]] create_response = self.rooms_client.create_room(participants=create_participants) # update join to consumer and add fred to room self.users["john"].role = ParticipantRole.CONSUMER - add_or_update_participants = [ - self.users["john"], - self.users["fred"] - ] + add_or_update_participants = [self.users["john"], self.users["fred"]] expected_participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=ParticipantRole.CONSUMER + communication_identifier=CommunicationUserIdentifier(self.id1), role=ParticipantRole.CONSUMER ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.ATTENDEE ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2), - role=ParticipantRole.CONSUMER - ) + communication_identifier=CommunicationUserIdentifier(self.id2), role=ParticipantRole.CONSUMER + ), ] - self.rooms_client.add_or_update_participants(room_id=create_response.id, participants=add_or_update_participants) + self.rooms_client.add_or_update_participants( + room_id=create_response.id, participants=add_or_update_participants + ) update_response = self.rooms_client.list_participants(room_id=create_response.id) participants = [] for participant in update_response: @@ -344,31 +334,22 @@ def test_add_or_update_participants(self): @recorded_by_proxy def test_add_or_update_participants_with_null_role(self): create_participants = [ + RoomParticipant(communication_identifier=CommunicationUserIdentifier(self.id1), role=None), + RoomParticipant(communication_identifier=CommunicationUserIdentifier(self.id2)), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=None - ), - RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2) + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.PRESENTER ), - RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.PRESENTER - ) ] expected_participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier(self.id1), role=ParticipantRole.ATTENDEE ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier(self.id2), role=ParticipantRole.ATTENDEE ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.PRESENTER - ) + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.PRESENTER + ), ] # Check participants with null roles were added in created room @@ -383,40 +364,31 @@ def test_add_or_update_participants_with_null_role(self): # Check participants were added or updated properly add_or_update_participants = [ + RoomParticipant(communication_identifier=CommunicationUserIdentifier(self.id1), role=None), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=None - ), - RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2), - role=ParticipantRole.CONSUMER + communication_identifier=CommunicationUserIdentifier(self.id2), role=ParticipantRole.CONSUMER ), - RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3) - ), - RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id4) - )] + RoomParticipant(communication_identifier=CommunicationUserIdentifier(self.id3)), + RoomParticipant(communication_identifier=CommunicationUserIdentifier(self.id4)), + ] expected_participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier(self.id1), role=ParticipantRole.ATTENDEE ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2), - role=ParticipantRole.CONSUMER + communication_identifier=CommunicationUserIdentifier(self.id2), role=ParticipantRole.CONSUMER ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.ATTENDEE ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id4), - role=ParticipantRole.ATTENDEE - ) + communication_identifier=CommunicationUserIdentifier(self.id4), role=ParticipantRole.ATTENDEE + ), ] - self.rooms_client.add_or_update_participants(room_id=create_response.id, participants=add_or_update_participants) + self.rooms_client.add_or_update_participants( + room_id=create_response.id, participants=add_or_update_participants + ) update_response = self.rooms_client.list_participants(room_id=create_response.id) updated_participants = [] for participant in update_response: @@ -434,9 +406,9 @@ def test_add_or_update_participants_incorrectMri(self): participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier("wrong_mri"), - role=ParticipantRole.ATTENDEE), - self.users["john"] + communication_identifier=CommunicationUserIdentifier("wrong_mri"), role=ParticipantRole.ATTENDEE + ), + self.users["john"], ] # update room attributes @@ -453,9 +425,7 @@ def test_add_or_update_room_wrongRoleName(self): create_response = self.rooms_client.create_room() participants = [ - RoomParticipant( - communication_identifier=self.users["john"].communication_identifier, - role='Kafka'), + RoomParticipant(communication_identifier=self.users["john"].communication_identifier, role="Kafka"), ] # update room attributes @@ -469,21 +439,15 @@ def test_add_or_update_room_wrongRoleName(self): @recorded_by_proxy def test_remove_participants(self): # add john and chris to room - create_participants = [ - self.users["john"], - self.users["chris"] - ] + create_participants = [self.users["john"], self.users["chris"]] create_response = self.rooms_client.create_room(participants=create_participants) # participants to be removed - removed_participants = [ - self.users["john"].communication_identifier - ] + removed_participants = [self.users["john"].communication_identifier] expected_participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.ATTENDEE ) ] self.rooms_client.remove_participants(room_id=create_response.id, participants=removed_participants) @@ -501,22 +465,15 @@ def test_remove_participants(self): @recorded_by_proxy def test_remove_participant_who_do_not_exist(self): # add john and chris to room - create_participants = [ - self.users["john"], - self.users["chris"] - ] - remove_participants = [ - self.users["fred"].communication_identifier - ] + create_participants = [self.users["john"], self.users["chris"]] + remove_participants = [self.users["fred"].communication_identifier] expected_participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=ParticipantRole.PRESENTER + communication_identifier=CommunicationUserIdentifier(self.id1), role=ParticipantRole.PRESENTER ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.ATTENDEE - ) + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.ATTENDEE + ), ] create_response = self.rooms_client.create_room(participants=create_participants) self.rooms_client.remove_participants(room_id=create_response.id, participants=remove_participants) @@ -533,14 +490,11 @@ def test_remove_participant_who_do_not_exist(self): @recorded_by_proxy def test_remove_participant_wrong_mri(self): # add john and chris to room - create_participants = [ - self.users["john"], - self.users["chris"] - ] + create_participants = [self.users["john"], self.users["chris"]] remove_participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier("wrong_mri"), - role=ParticipantRole.ATTENDEE), + communication_identifier=CommunicationUserIdentifier("wrong_mri"), role=ParticipantRole.ATTENDEE + ), ] create_response = self.rooms_client.create_room(participants=create_participants) with pytest.raises(HttpResponseError) as ex: @@ -615,32 +569,44 @@ def test_create_room_pstn_dial_out_enabled(self): @recorded_by_proxy def test_create_room_timerange_pstn_dial_out_enabled(self): # room attributes - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(weeks=4) - response = self.rooms_client.create_room(valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=True) + response = self.rooms_client.create_room( + valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=True + ) - self.verify_successful_room_response(response=response, valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=True) + self.verify_successful_room_response( + response=response, valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=True + ) # delete created room self.rooms_client.delete_room(room_id=response.id) - response = self.rooms_client.create_room(valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=False) + response = self.rooms_client.create_room( + valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=False + ) - self.verify_successful_room_response(response=response, valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=False) + self.verify_successful_room_response( + response=response, valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=False + ) # delete created room self.rooms_client.delete_room(room_id=response.id) - def verify_successful_room_response(self, response, valid_from=None, valid_until=None, room_id=None, pstn_dial_out_enabled=None): + def verify_successful_room_response( + self, response, valid_from=None, valid_until=None, room_id=None, pstn_dial_out_enabled=None + ): if room_id is not None: assert room_id == response.id if valid_from is not None: assert valid_from.replace(tzinfo=None) == datetime.strptime( - response.valid_from, "%Y-%m-%dT%H:%M:%S.%f%z").replace(tzinfo=None) + response.valid_from, "%Y-%m-%dT%H:%M:%S.%f%z" + ).replace(tzinfo=None) if valid_until is not None: assert valid_until.replace(tzinfo=None) == datetime.strptime( - response.valid_until, "%Y-%m-%dT%H:%M:%S.%f%z").replace(tzinfo=None) + response.valid_until, "%Y-%m-%dT%H:%M:%S.%f%z" + ).replace(tzinfo=None) assert response.created_at is not None if pstn_dial_out_enabled is not None: assert pstn_dial_out_enabled == response.pstn_dial_out_enabled diff --git a/sdk/communication/azure-communication-rooms/tests/test_rooms_client_async.py b/sdk/communication/azure-communication-rooms/tests/test_rooms_client_async.py index 0da54ab00ee9..4ad59a0bb74d 100644 --- a/sdk/communication/azure-communication-rooms/tests/test_rooms_client_async.py +++ b/sdk/communication/azure-communication-rooms/tests/test_rooms_client_async.py @@ -11,10 +11,7 @@ from azure.communication.identity import CommunicationIdentityClient from azure.communication.rooms._shared.models import CommunicationUserIdentifier from azure.communication.rooms.aio import RoomsClient -from azure.communication.rooms import ( - ParticipantRole, - RoomParticipant -) +from azure.communication.rooms import ParticipantRole, RoomParticipant from acs_rooms_test_case import ACSRoomsTestCase from _shared.utils import get_http_logging_policy from devtools_testutils.aio import recorded_by_proxy_async @@ -30,9 +27,7 @@ def setup_method(self): sanitizedId3 = "8:acs:sanitized3" sanitizedId4 = "8:acs:sanitized4" if is_live(): - self.identity_client = CommunicationIdentityClient.from_connection_string( - self.connection_str) - + self.identity_client = CommunicationIdentityClient.from_connection_string(self.connection_str) self.id1 = self.identity_client.create_user().properties["id"] self.id2 = self.identity_client.create_user().properties["id"] @@ -49,23 +44,19 @@ def setup_method(self): self.id4 = sanitizedId4 self.rooms_client = RoomsClient.from_connection_string( - self.connection_str, - http_logging_policy=get_http_logging_policy() + self.connection_str, http_logging_policy=get_http_logging_policy() ) self.users = { - "john" : RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=ParticipantRole.PRESENTER - ), - "fred" : RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2), - role=ParticipantRole.CONSUMER - ), - "chris" : RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.ATTENDEE - ) - } + "john": RoomParticipant( + communication_identifier=CommunicationUserIdentifier(self.id1), role=ParticipantRole.PRESENTER + ), + "fred": RoomParticipant( + communication_identifier=CommunicationUserIdentifier(self.id2), role=ParticipantRole.CONSUMER + ), + "chris": RoomParticipant( + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.ATTENDEE + ), + } @recorded_by_proxy_async async def test_create_room_no_attributes_async(self): @@ -77,10 +68,7 @@ async def test_create_room_no_attributes_async(self): @recorded_by_proxy_async async def test_create_room_only_participants_async(self): # add john and chris to room - participants = [ - self.users["john"], - self.users["chris"] - ] + participants = [self.users["john"], self.users["chris"]] async with self.rooms_client: response = await self.rooms_client.create_room(participants=participants) @@ -92,7 +80,7 @@ async def test_create_room_only_participants_async(self): @recorded_by_proxy_async async def test_create_room_validUntil_seven_months_async(self): # room attributes - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(weeks=29) with pytest.raises(HttpResponseError) as ex: @@ -126,7 +114,7 @@ async def test_create_room_valid_until_in_past_async(self): @recorded_by_proxy_async async def test_create_room_correct_timerange_async(self): # room attributes - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(weeks=4) async with self.rooms_client: @@ -141,10 +129,9 @@ async def test_create_room_incorrectMri_async(self): # room attributes participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier("wrong_mri"), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier("wrong_mri"), role=ParticipantRole.ATTENDEE ), - self.users["john"] + self.users["john"], ] with pytest.raises(HttpResponseError) as ex: @@ -158,42 +145,42 @@ async def test_create_room_incorrectMri_async(self): @recorded_by_proxy_async async def test_create_room_all_attributes_async(self): # room attributes - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(weeks=4) # add john to room - participants = [ - self.users["john"] - ] + participants = [self.users["john"]] async with self.rooms_client: - response = await self.rooms_client.create_room(valid_from=valid_from, valid_until=valid_until, participants=participants) + response = await self.rooms_client.create_room( + valid_from=valid_from, valid_until=valid_until, participants=participants + ) # delete created room await self.rooms_client.delete_room(room_id=response.id) - self.verify_successful_room_response( - response=response, valid_from=valid_from, valid_until=valid_until) + self.verify_successful_room_response(response=response, valid_from=valid_from, valid_until=valid_until) @pytest.mark.live_test_only @recorded_by_proxy_async async def test_get_room_async(self): # room attributes - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(weeks=2) # add john to room - participants = [ - self.users["john"] - ] + participants = [self.users["john"]] async with self.rooms_client: # create a room first - create_response = await self.rooms_client.create_room(valid_from=valid_from, valid_until=valid_until, participants=participants) + create_response = await self.rooms_client.create_room( + valid_from=valid_from, valid_until=valid_until, participants=participants + ) get_response = await self.rooms_client.get_room(room_id=create_response.id) # delete created room await self.rooms_client.delete_room(room_id=create_response.id) self.verify_successful_room_response( - response=get_response, valid_from=valid_from, valid_until=valid_until, room_id=create_response.id) + response=get_response, valid_from=valid_from, valid_until=valid_until, room_id=create_response.id + ) @recorded_by_proxy_async async def test_get_invalid_format_roomId_async(self): @@ -212,11 +199,13 @@ async def test_update_room_exceed_max_timerange_async(self): create_response = await self.rooms_client.create_room() # update room attributes - valid_from = datetime.now() + timedelta(days=3) - valid_until = datetime.now() + timedelta(weeks=29) + valid_from = datetime.now() + timedelta(days=3) + valid_until = datetime.now() + timedelta(weeks=29) with pytest.raises(HttpResponseError) as ex: - await self.rooms_client.update_room(room_id=create_response.id, valid_from=valid_from, valid_until=valid_until) + await self.rooms_client.update_room( + room_id=create_response.id, valid_from=valid_from, valid_until=valid_until + ) # delete created room await self.rooms_client.delete_room(room_id=create_response.id) @@ -231,11 +220,13 @@ async def test_update_room_valid_until_in_past_async(self): create_response = await self.rooms_client.create_room() # update room attributes - valid_from = datetime.now() - timedelta(days=3) - valid_until = datetime.now() - timedelta(weeks=1) + valid_from = datetime.now() - timedelta(days=3) + valid_until = datetime.now() - timedelta(weeks=1) with pytest.raises(HttpResponseError) as ex: - await self.rooms_client.update_room(room_id=create_response.id, valid_from=valid_from, valid_until=valid_until) + await self.rooms_client.update_room( + room_id=create_response.id, valid_from=valid_from, valid_until=valid_until + ) # delete created room await self.rooms_client.delete_room(room_id=create_response.id) @@ -251,24 +242,29 @@ async def test_update_room_correct_timerange_async(self): create_response = await self.rooms_client.create_room() # update room attributes - valid_from = datetime.now() + timedelta(days=3) - valid_until = datetime.now() + timedelta(weeks=4) + valid_from = datetime.now() + timedelta(days=3) + valid_until = datetime.now() + timedelta(weeks=4) - update_response = await self.rooms_client.update_room(room_id=create_response.id, valid_from=valid_from, valid_until=valid_until) + update_response = await self.rooms_client.update_room( + room_id=create_response.id, valid_from=valid_from, valid_until=valid_until + ) # delete created room await self.rooms_client.delete_room(room_id=create_response.id) self.verify_successful_room_response( - response=update_response, valid_from=valid_from, valid_until=valid_until, room_id=create_response.id) + response=update_response, valid_from=valid_from, valid_until=valid_until, room_id=create_response.id + ) @recorded_by_proxy_async async def test_update_room_invalid_format_roomId_async(self): # try to update room with random room_id with pytest.raises(HttpResponseError) as ex: async with self.rooms_client: - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(days=4) - await self.rooms_client.update_room(room_id="invalid_id", valid_from=valid_from, valid_until=valid_until) + await self.rooms_client.update_room( + room_id="invalid_id", valid_from=valid_from, valid_until=valid_until + ) # assert error is bad request assert str(ex.value.status_code) == "400" @@ -284,9 +280,11 @@ async def test_update_room_deleted_room_async(self): await self.rooms_client.delete_room(room_id=create_response.id) with pytest.raises(HttpResponseError) as ex: - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(days=4) - await self.rooms_client.update_room(room_id=create_response.id, valid_from=valid_from, valid_until=valid_until) + await self.rooms_client.update_room( + room_id=create_response.id, valid_from=valid_from, valid_until=valid_until + ) # assert error is Resource not found assert str(ex.value.status_code) == "404" @@ -295,33 +293,26 @@ async def test_update_room_deleted_room_async(self): @recorded_by_proxy_async async def test_add_or_update_participant_async(self): # add john and chris to room - create_participants = [ - self.users["john"], - self.users["chris"] - ] + create_participants = [self.users["john"], self.users["chris"]] # update join to consumer and add fred to room self.users["john"].role = ParticipantRole.CONSUMER - update_participants = [ - self.users["john"], - self.users["fred"] - ] + update_participants = [self.users["john"], self.users["fred"]] expected_participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=ParticipantRole.CONSUMER + communication_identifier=CommunicationUserIdentifier(self.id1), role=ParticipantRole.CONSUMER ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2), - role=ParticipantRole.CONSUMER + communication_identifier=CommunicationUserIdentifier(self.id2), role=ParticipantRole.CONSUMER ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.ATTENDEE - ) + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.ATTENDEE + ), ] async with self.rooms_client: create_response = await self.rooms_client.create_room(participants=create_participants) - await self.rooms_client.add_or_update_participants(room_id=create_response.id, participants=update_participants) + await self.rooms_client.add_or_update_participants( + room_id=create_response.id, participants=update_participants + ) update_response = self.rooms_client.list_participants(room_id=create_response.id) participants = [] async for participant in update_response: @@ -335,32 +326,23 @@ async def test_add_or_update_participant_async(self): @recorded_by_proxy_async async def test_add_or_update_participant_with_null_roles_async(self): create_participants = [ + RoomParticipant(communication_identifier=CommunicationUserIdentifier(self.id1), role=None), + RoomParticipant(communication_identifier=CommunicationUserIdentifier(self.id2)), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=None - ), - RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2) + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.PRESENTER ), - RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.PRESENTER - ) ] expected_participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier(self.id1), role=ParticipantRole.ATTENDEE ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier(self.id2), role=ParticipantRole.ATTENDEE ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.PRESENTER - ) + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.PRESENTER + ), ] async with self.rooms_client: # Check participants with null roles were added in created room @@ -375,40 +357,31 @@ async def test_add_or_update_participant_with_null_roles_async(self): # Check participants were added or updated properly add_or_update_participants = [ + RoomParticipant(communication_identifier=CommunicationUserIdentifier(self.id1), role=None), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=None - ), - RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2), - role=ParticipantRole.CONSUMER - ), - RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3) + communication_identifier=CommunicationUserIdentifier(self.id2), role=ParticipantRole.CONSUMER ), - RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id4) - )] + RoomParticipant(communication_identifier=CommunicationUserIdentifier(self.id3)), + RoomParticipant(communication_identifier=CommunicationUserIdentifier(self.id4)), + ] expected_participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier(self.id1), role=ParticipantRole.ATTENDEE ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id2), - role=ParticipantRole.CONSUMER + communication_identifier=CommunicationUserIdentifier(self.id2), role=ParticipantRole.CONSUMER ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.ATTENDEE ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id4), - role=ParticipantRole.ATTENDEE - ) + communication_identifier=CommunicationUserIdentifier(self.id4), role=ParticipantRole.ATTENDEE + ), ] - await self.rooms_client.add_or_update_participants(room_id=create_response.id, participants=add_or_update_participants) + await self.rooms_client.add_or_update_participants( + room_id=create_response.id, participants=add_or_update_participants + ) update_response = self.rooms_client.list_participants(room_id=create_response.id) updated_participants = [] async for participant in update_response: @@ -427,14 +400,16 @@ async def test_add_or_update_participants_incorrectMri_async(self): participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier("wrong_mri"), - role=ParticipantRole.ATTENDEE), - self.users["john"] + communication_identifier=CommunicationUserIdentifier("wrong_mri"), role=ParticipantRole.ATTENDEE + ), + self.users["john"], ] # update room attributes with pytest.raises(HttpResponseError) as ex: - await self.rooms_client.add_or_update_participants(room_id=create_response.id, participants=participants) + await self.rooms_client.add_or_update_participants( + room_id=create_response.id, participants=participants + ) assert str(ex.value.status_code) == "400" assert ex.value.message is not None @@ -445,32 +420,26 @@ async def test_add_or_update_participants_wrongRoleName_async(self): create_response = await self.rooms_client.create_room() participants = [ - RoomParticipant( - communication_identifier=CommunicationUserIdentifier("chris"), - role='kafka'), - self.users["john"] + RoomParticipant(communication_identifier=CommunicationUserIdentifier("chris"), role="kafka"), + self.users["john"], ] # update room attributes with pytest.raises(HttpResponseError) as ex: - await self.rooms_client.add_or_update_participants(room_id=create_response.id, participants=participants) + await self.rooms_client.add_or_update_participants( + room_id=create_response.id, participants=participants + ) assert str(ex.value.status_code) == "400" assert ex.value.message is not None @recorded_by_proxy_async async def test_remove_participant_async(self): # add john and chris to room - create_participants = [ - self.users["john"], - self.users["chris"] - ] - remove_participants = [ - self.users["john"].communication_identifier - ] + create_participants = [self.users["john"], self.users["chris"]] + remove_participants = [self.users["john"].communication_identifier] expected_participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.ATTENDEE + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.ATTENDEE ) ] async with self.rooms_client: @@ -489,22 +458,15 @@ async def test_remove_participant_async(self): @recorded_by_proxy_async async def test_remove_participant_who_do_not_exist_async(self): # add john and chris to room - create_participants = [ - self.users["john"], - self.users["chris"] - ] - remove_participants = [ - self.users["fred"].communication_identifier - ] + create_participants = [self.users["john"], self.users["chris"]] + remove_participants = [self.users["fred"].communication_identifier] expected_participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id1), - role=ParticipantRole.PRESENTER + communication_identifier=CommunicationUserIdentifier(self.id1), role=ParticipantRole.PRESENTER ), RoomParticipant( - communication_identifier=CommunicationUserIdentifier(self.id3), - role=ParticipantRole.ATTENDEE - ) + communication_identifier=CommunicationUserIdentifier(self.id3), role=ParticipantRole.ATTENDEE + ), ] async with self.rooms_client: create_response = await self.rooms_client.create_room(participants=create_participants) @@ -527,8 +489,8 @@ async def test_remove_participant_wrong_mri_async(self): participants = [ RoomParticipant( - communication_identifier=CommunicationUserIdentifier("wrong_mri"), - role=ParticipantRole.ATTENDEE) + communication_identifier=CommunicationUserIdentifier("wrong_mri"), role=ParticipantRole.ATTENDEE + ) ] # update room attributes @@ -593,31 +555,37 @@ async def test_create_room_pstn_dial_out_enabled(self): await self.rooms_client.delete_room(room_id=response.id) self.verify_successful_room_response(response=response, pstn_dial_out_enabled=True) - @pytest.mark.live_test_only @recorded_by_proxy_async async def test_create_room_timerange_pstn_dial_out_enabled(self): # room attributes - valid_from = datetime.now() + timedelta(days=3) + valid_from = datetime.now() + timedelta(days=3) valid_until = valid_from + timedelta(weeks=4) async with self.rooms_client: - response = await self.rooms_client.create_room(valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=True) + response = await self.rooms_client.create_room( + valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=True + ) # delete created room await self.rooms_client.delete_room(room_id=response.id) - self.verify_successful_room_response(response=response, valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=True) - + self.verify_successful_room_response( + response=response, valid_from=valid_from, valid_until=valid_until, pstn_dial_out_enabled=True + ) - def verify_successful_room_response(self, response, valid_from=None, valid_until=None, room_id=None, pstn_dial_out_enabled=None): + def verify_successful_room_response( + self, response, valid_from=None, valid_until=None, room_id=None, pstn_dial_out_enabled=None + ): if room_id is not None: assert room_id == response.id if valid_from is not None: assert valid_from.replace(tzinfo=None) == datetime.strptime( - response.valid_from, "%Y-%m-%dT%H:%M:%S.%f%z").replace(tzinfo=None) + response.valid_from, "%Y-%m-%dT%H:%M:%S.%f%z" + ).replace(tzinfo=None) if valid_until is not None: assert valid_until.replace(tzinfo=None) == datetime.strptime( - response.valid_until, "%Y-%m-%dT%H:%M:%S.%f%z").replace(tzinfo=None) + response.valid_until, "%Y-%m-%dT%H:%M:%S.%f%z" + ).replace(tzinfo=None) if pstn_dial_out_enabled is not None: assert pstn_dial_out_enabled == response.pstn_dial_out_enabled assert response.created_at is not None @@ -625,4 +593,3 @@ def verify_successful_room_response(self, response, valid_from=None, valid_until assert response.valid_from is not None assert response.valid_until is not None assert response.pstn_dial_out_enabled is not None - diff --git a/sdk/communication/azure-communication-sms/azure/__init__.py b/sdk/communication/azure-communication-sms/azure/__init__.py index 69e3be50dac4..8db66d3d0f0f 100644 --- a/sdk/communication/azure-communication-sms/azure/__init__.py +++ b/sdk/communication/azure-communication-sms/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/communication/azure-communication-sms/azure/communication/__init__.py b/sdk/communication/azure-communication-sms/azure/communication/__init__.py index 69e3be50dac4..8db66d3d0f0f 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/__init__.py +++ b/sdk/communication/azure-communication-sms/azure/communication/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/__init__.py b/sdk/communication/azure-communication-sms/azure/communication/sms/__init__.py index f1e383aa3376..53984be18aa2 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/__init__.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/__init__.py @@ -3,6 +3,6 @@ from ._models import SmsSendResult __all__ = [ - 'SmsClient', - 'SmsSendResult', + "SmsClient", + "SmsSendResult", ] diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/__init__.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/__init__.py index 9b98a0a107d8..77317d7beb43 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/__init__.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/__init__.py @@ -7,10 +7,12 @@ # -------------------------------------------------------------------------- from ._azure_communication_sms_service import AzureCommunicationSMSService -__all__ = ['AzureCommunicationSMSService'] + +__all__ = ["AzureCommunicationSMSService"] try: from ._patch import patch_sdk # type: ignore + patch_sdk() except ImportError: pass diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/_azure_communication_sms_service.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/_azure_communication_sms_service.py index 0fee0dbd6f58..63b2e458c990 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/_azure_communication_sms_service.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/_azure_communication_sms_service.py @@ -37,7 +37,7 @@ def __init__( **kwargs # type: Any ): # type: (...) -> None - base_url = '{endpoint}' + base_url = "{endpoint}" self._config = AzureCommunicationSMSServiceConfiguration(endpoint, **kwargs) self._client = PipelineClient(base_url=base_url, config=self._config, **kwargs) @@ -46,8 +46,7 @@ def __init__( self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - self.sms = SmsOperations( - self._client, self._config, self._serialize, self._deserialize) + self.sms = SmsOperations(self._client, self._config, self._serialize, self._deserialize) def _send_request(self, http_request, **kwargs): # type: (HttpRequest, Any) -> HttpResponse @@ -60,7 +59,7 @@ def _send_request(self, http_request, **kwargs): :rtype: ~azure.core.pipeline.transport.HttpResponse """ path_format_arguments = { - 'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/_configuration.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/_configuration.py index 9d3154a1fa3b..2eb72b857a39 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/_configuration.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/_configuration.py @@ -17,6 +17,7 @@ VERSION = "unknown" + class AzureCommunicationSMSServiceConfiguration(Configuration): """Configuration for AzureCommunicationSMSService. @@ -39,20 +40,19 @@ def __init__( self.endpoint = endpoint self.api_version = "2021-03-07" - kwargs.setdefault('sdk_moniker', 'azurecommunicationsmsservice/{}'.format(VERSION)) + kwargs.setdefault("sdk_moniker", "azurecommunicationsmsservice/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/__init__.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/__init__.py index 1149dd8315fb..9a6c0d29715c 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/__init__.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/__init__.py @@ -7,4 +7,5 @@ # -------------------------------------------------------------------------- from ._azure_communication_sms_service import AzureCommunicationSMSService -__all__ = ['AzureCommunicationSMSService'] + +__all__ = ["AzureCommunicationSMSService"] diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/_azure_communication_sms_service.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/_azure_communication_sms_service.py index 9df4a63dd70e..3b7cd11b456a 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/_azure_communication_sms_service.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/_azure_communication_sms_service.py @@ -26,12 +26,8 @@ class AzureCommunicationSMSService(object): :type endpoint: str """ - def __init__( - self, - endpoint: str, - **kwargs: Any - ) -> None: - base_url = '{endpoint}' + def __init__(self, endpoint: str, **kwargs: Any) -> None: + base_url = "{endpoint}" self._config = AzureCommunicationSMSServiceConfiguration(endpoint, **kwargs) self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) @@ -40,8 +36,7 @@ def __init__( self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - self.sms = SmsOperations( - self._client, self._config, self._serialize, self._deserialize) + self.sms = SmsOperations(self._client, self._config, self._serialize, self._deserialize) async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: """Runs the network request through the client's chained policies. @@ -53,7 +48,7 @@ async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> Async :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse """ path_format_arguments = { - 'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/_configuration.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/_configuration.py index 77033099353f..50cf1a768dcc 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/_configuration.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/_configuration.py @@ -13,6 +13,7 @@ VERSION = "unknown" + class AzureCommunicationSMSServiceConfiguration(Configuration): """Configuration for AzureCommunicationSMSService. @@ -23,30 +24,23 @@ class AzureCommunicationSMSServiceConfiguration(Configuration): :type endpoint: str """ - def __init__( - self, - endpoint: str, - **kwargs: Any - ) -> None: + def __init__(self, endpoint: str, **kwargs: Any) -> None: if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") super(AzureCommunicationSMSServiceConfiguration, self).__init__(**kwargs) self.endpoint = endpoint self.api_version = "2021-03-07" - kwargs.setdefault('sdk_moniker', 'azurecommunicationsmsservice/{}'.format(VERSION)) + kwargs.setdefault("sdk_moniker", "azurecommunicationsmsservice/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/operations/__init__.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/operations/__init__.py index f9ce203e2885..83e4c171c3db 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/operations/__init__.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/operations/__init__.py @@ -9,5 +9,5 @@ from ._sms_operations import SmsOperations __all__ = [ - 'SmsOperations', + "SmsOperations", ] diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/operations/_sms_operations.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/operations/_sms_operations.py index 7ec83da71f2e..541970b1284d 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/operations/_sms_operations.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/aio/operations/_sms_operations.py @@ -8,15 +8,22 @@ from typing import Any, Callable, Dict, Generic, Optional, TypeVar import warnings -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from ... import models as _models -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class SmsOperations: """SmsOperations async operations. @@ -40,9 +47,7 @@ def __init__(self, client, config, serializer, deserializer) -> None: self._config = config async def send( - self, - send_message_request: "_models.SendMessageRequest", - **kwargs: Any + self, send_message_request: "_models.SendMessageRequest", **kwargs: Any ) -> "_models.SmsSendResponse": """Sends a SMS message from a phone number that belongs to the authenticated account. @@ -55,34 +60,32 @@ async def send( :rtype: ~azure.communication.sms.models.SmsSendResponse :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SmsSendResponse"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + cls = kwargs.pop("cls", None) # type: ClsType["_models.SmsSendResponse"] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) api_version = "2021-03-07" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL - url = self.send.metadata['url'] # type: ignore + url = self.send.metadata["url"] # type: ignore path_format_arguments = { - 'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + query_parameters["api-version"] = self._serialize.query("api_version", api_version, "str") # Construct headers header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + header_parameters["Content-Type"] = self._serialize.header("content_type", content_type, "str") + header_parameters["Accept"] = self._serialize.header("accept", accept, "str") body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(send_message_request, 'SendMessageRequest') - body_content_kwargs['content'] = body_content + body_content = self._serialize.body(send_message_request, "SendMessageRequest") + body_content_kwargs["content"] = body_content request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response @@ -91,10 +94,11 @@ async def send( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = self._deserialize('SmsSendResponse', pipeline_response) + deserialized = self._deserialize("SmsSendResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - send.metadata = {'url': '/sms'} # type: ignore + + send.metadata = {"url": "/sms"} # type: ignore diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/__init__.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/__init__.py index 74b2447dbed0..6524ffbcb3d2 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/__init__.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/__init__.py @@ -24,10 +24,10 @@ ) __all__ = [ - 'SendMessageRequest', - 'SmsRecipient', - 'SmsSendOptions', - 'SmsSendResponse', - 'SmsSendResponseItem', - 'SmsSendResponseItemRepeatabilityResult', + "SendMessageRequest", + "SmsRecipient", + "SmsSendOptions", + "SmsSendResponse", + "SmsSendResponseItem", + "SmsSendResponseItemRepeatabilityResult", ] diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/_models.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/_models.py index 3dd8dab3bef2..77b20f20b707 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/_models.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/_models.py @@ -28,27 +28,24 @@ class SendMessageRequest(msrest.serialization.Model): """ _validation = { - 'from_property': {'required': True}, - 'sms_recipients': {'required': True}, - 'message': {'required': True, 'max_length': 2048, 'min_length': 0}, + "from_property": {"required": True}, + "sms_recipients": {"required": True}, + "message": {"required": True, "max_length": 2048, "min_length": 0}, } _attribute_map = { - 'from_property': {'key': 'from', 'type': 'str'}, - 'sms_recipients': {'key': 'smsRecipients', 'type': '[SmsRecipient]'}, - 'message': {'key': 'message', 'type': 'str'}, - 'sms_send_options': {'key': 'smsSendOptions', 'type': 'SmsSendOptions'}, + "from_property": {"key": "from", "type": "str"}, + "sms_recipients": {"key": "smsRecipients", "type": "[SmsRecipient]"}, + "message": {"key": "message", "type": "str"}, + "sms_send_options": {"key": "smsSendOptions", "type": "SmsSendOptions"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): super(SendMessageRequest, self).__init__(**kwargs) - self.from_property = kwargs['from_property'] - self.sms_recipients = kwargs['sms_recipients'] - self.message = kwargs['message'] - self.sms_send_options = kwargs.get('sms_send_options', None) + self.from_property = kwargs["from_property"] + self.sms_recipients = kwargs["sms_recipients"] + self.message = kwargs["message"] + self.sms_send_options = kwargs.get("sms_send_options", None) class SmsRecipient(msrest.serialization.Model): @@ -72,23 +69,20 @@ class SmsRecipient(msrest.serialization.Model): """ _validation = { - 'to': {'required': True}, + "to": {"required": True}, } _attribute_map = { - 'to': {'key': 'to', 'type': 'str'}, - 'repeatability_request_id': {'key': 'repeatabilityRequestId', 'type': 'str'}, - 'repeatability_first_sent': {'key': 'repeatabilityFirstSent', 'type': 'str'}, + "to": {"key": "to", "type": "str"}, + "repeatability_request_id": {"key": "repeatabilityRequestId", "type": "str"}, + "repeatability_first_sent": {"key": "repeatabilityFirstSent", "type": "str"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): super(SmsRecipient, self).__init__(**kwargs) - self.to = kwargs['to'] - self.repeatability_request_id = kwargs.get('repeatability_request_id', None) - self.repeatability_first_sent = kwargs.get('repeatability_first_sent', None) + self.to = kwargs["to"] + self.repeatability_request_id = kwargs.get("repeatability_request_id", None) + self.repeatability_first_sent = kwargs.get("repeatability_first_sent", None) class SmsSendOptions(msrest.serialization.Model): @@ -105,21 +99,18 @@ class SmsSendOptions(msrest.serialization.Model): """ _validation = { - 'enable_delivery_report': {'required': True}, + "enable_delivery_report": {"required": True}, } _attribute_map = { - 'enable_delivery_report': {'key': 'enableDeliveryReport', 'type': 'bool'}, - 'tag': {'key': 'tag', 'type': 'str'}, + "enable_delivery_report": {"key": "enableDeliveryReport", "type": "bool"}, + "tag": {"key": "tag", "type": "str"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): super(SmsSendOptions, self).__init__(**kwargs) - self.enable_delivery_report = kwargs['enable_delivery_report'] - self.tag = kwargs.get('tag', None) + self.enable_delivery_report = kwargs["enable_delivery_report"] + self.tag = kwargs.get("tag", None) class SmsSendResponse(msrest.serialization.Model): @@ -132,19 +123,16 @@ class SmsSendResponse(msrest.serialization.Model): """ _validation = { - 'value': {'required': True}, + "value": {"required": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[SmsSendResponseItem]'}, + "value": {"key": "value", "type": "[SmsSendResponseItem]"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): super(SmsSendResponse, self).__init__(**kwargs) - self.value = kwargs['value'] + self.value = kwargs["value"] class SmsSendResponseItem(msrest.serialization.Model): @@ -170,28 +158,25 @@ class SmsSendResponseItem(msrest.serialization.Model): """ _validation = { - 'to': {'required': True}, - 'http_status_code': {'required': True}, - 'successful': {'required': True}, + "to": {"required": True}, + "http_status_code": {"required": True}, + "successful": {"required": True}, } _attribute_map = { - 'to': {'key': 'to', 'type': 'str'}, - 'message_id': {'key': 'messageId', 'type': 'str'}, - 'http_status_code': {'key': 'httpStatusCode', 'type': 'int'}, - 'repeatability_result': {'key': 'repeatabilityResult', 'type': 'str'}, - 'successful': {'key': 'successful', 'type': 'bool'}, - 'error_message': {'key': 'errorMessage', 'type': 'str'}, + "to": {"key": "to", "type": "str"}, + "message_id": {"key": "messageId", "type": "str"}, + "http_status_code": {"key": "httpStatusCode", "type": "int"}, + "repeatability_result": {"key": "repeatabilityResult", "type": "str"}, + "successful": {"key": "successful", "type": "bool"}, + "error_message": {"key": "errorMessage", "type": "str"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): super(SmsSendResponseItem, self).__init__(**kwargs) - self.to = kwargs['to'] - self.message_id = kwargs.get('message_id', None) - self.http_status_code = kwargs['http_status_code'] - self.repeatability_result = kwargs.get('repeatability_result', None) - self.successful = kwargs['successful'] - self.error_message = kwargs.get('error_message', None) + self.to = kwargs["to"] + self.message_id = kwargs.get("message_id", None) + self.http_status_code = kwargs["http_status_code"] + self.repeatability_result = kwargs.get("repeatability_result", None) + self.successful = kwargs["successful"] + self.error_message = kwargs.get("error_message", None) diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/_models_py3.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/_models_py3.py index 7934352a7708..3aeabd44e2d5 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/_models_py3.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/models/_models_py3.py @@ -32,16 +32,16 @@ class SendMessageRequest(msrest.serialization.Model): """ _validation = { - 'from_property': {'required': True}, - 'sms_recipients': {'required': True}, - 'message': {'required': True, 'max_length': 2048, 'min_length': 0}, + "from_property": {"required": True}, + "sms_recipients": {"required": True}, + "message": {"required": True, "max_length": 2048, "min_length": 0}, } _attribute_map = { - 'from_property': {'key': 'from', 'type': 'str'}, - 'sms_recipients': {'key': 'smsRecipients', 'type': '[SmsRecipient]'}, - 'message': {'key': 'message', 'type': 'str'}, - 'sms_send_options': {'key': 'smsSendOptions', 'type': 'SmsSendOptions'}, + "from_property": {"key": "from", "type": "str"}, + "sms_recipients": {"key": "smsRecipients", "type": "[SmsRecipient]"}, + "message": {"key": "message", "type": "str"}, + "sms_send_options": {"key": "smsSendOptions", "type": "SmsSendOptions"}, } def __init__( @@ -81,13 +81,13 @@ class SmsRecipient(msrest.serialization.Model): """ _validation = { - 'to': {'required': True}, + "to": {"required": True}, } _attribute_map = { - 'to': {'key': 'to', 'type': 'str'}, - 'repeatability_request_id': {'key': 'repeatabilityRequestId', 'type': 'str'}, - 'repeatability_first_sent': {'key': 'repeatabilityFirstSent', 'type': 'str'}, + "to": {"key": "to", "type": "str"}, + "repeatability_request_id": {"key": "repeatabilityRequestId", "type": "str"}, + "repeatability_first_sent": {"key": "repeatabilityFirstSent", "type": "str"}, } def __init__( @@ -118,21 +118,15 @@ class SmsSendOptions(msrest.serialization.Model): """ _validation = { - 'enable_delivery_report': {'required': True}, + "enable_delivery_report": {"required": True}, } _attribute_map = { - 'enable_delivery_report': {'key': 'enableDeliveryReport', 'type': 'bool'}, - 'tag': {'key': 'tag', 'type': 'str'}, + "enable_delivery_report": {"key": "enableDeliveryReport", "type": "bool"}, + "tag": {"key": "tag", "type": "str"}, } - def __init__( - self, - *, - enable_delivery_report: bool, - tag: Optional[str] = None, - **kwargs - ): + def __init__(self, *, enable_delivery_report: bool, tag: Optional[str] = None, **kwargs): super(SmsSendOptions, self).__init__(**kwargs) self.enable_delivery_report = enable_delivery_report self.tag = tag @@ -148,19 +142,14 @@ class SmsSendResponse(msrest.serialization.Model): """ _validation = { - 'value': {'required': True}, + "value": {"required": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[SmsSendResponseItem]'}, + "value": {"key": "value", "type": "[SmsSendResponseItem]"}, } - def __init__( - self, - *, - value: List["SmsSendResponseItem"], - **kwargs - ): + def __init__(self, *, value: List["SmsSendResponseItem"], **kwargs): super(SmsSendResponse, self).__init__(**kwargs) self.value = value @@ -188,18 +177,18 @@ class SmsSendResponseItem(msrest.serialization.Model): """ _validation = { - 'to': {'required': True}, - 'http_status_code': {'required': True}, - 'successful': {'required': True}, + "to": {"required": True}, + "http_status_code": {"required": True}, + "successful": {"required": True}, } _attribute_map = { - 'to': {'key': 'to', 'type': 'str'}, - 'message_id': {'key': 'messageId', 'type': 'str'}, - 'http_status_code': {'key': 'httpStatusCode', 'type': 'int'}, - 'repeatability_result': {'key': 'repeatabilityResult', 'type': 'str'}, - 'successful': {'key': 'successful', 'type': 'bool'}, - 'error_message': {'key': 'errorMessage', 'type': 'str'}, + "to": {"key": "to", "type": "str"}, + "message_id": {"key": "messageId", "type": "str"}, + "http_status_code": {"key": "httpStatusCode", "type": "int"}, + "repeatability_result": {"key": "repeatabilityResult", "type": "str"}, + "successful": {"key": "successful", "type": "bool"}, + "error_message": {"key": "errorMessage", "type": "str"}, } def __init__( diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/operations/__init__.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/operations/__init__.py index f9ce203e2885..83e4c171c3db 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/operations/__init__.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/operations/__init__.py @@ -9,5 +9,5 @@ from ._sms_operations import SmsOperations __all__ = [ - 'SmsOperations', + "SmsOperations", ] diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/operations/_sms_operations.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/operations/_sms_operations.py index 1f0d0640e125..59493486f33a 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/operations/_sms_operations.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_generated/operations/_sms_operations.py @@ -8,7 +8,13 @@ from typing import TYPE_CHECKING import warnings -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse @@ -18,9 +24,10 @@ # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Optional, TypeVar - T = TypeVar('T') + T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + class SmsOperations(object): """SmsOperations operations. @@ -60,34 +67,32 @@ def send( :rtype: ~azure.communication.sms.models.SmsSendResponse :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SmsSendResponse"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + cls = kwargs.pop("cls", None) # type: ClsType["_models.SmsSendResponse"] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) api_version = "2021-03-07" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL - url = self.send.metadata['url'] # type: ignore + url = self.send.metadata["url"] # type: ignore path_format_arguments = { - 'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + query_parameters["api-version"] = self._serialize.query("api_version", api_version, "str") # Construct headers header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + header_parameters["Content-Type"] = self._serialize.header("content_type", content_type, "str") + header_parameters["Accept"] = self._serialize.header("accept", accept, "str") body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(send_message_request, 'SendMessageRequest') - body_content_kwargs['content'] = body_content + body_content = self._serialize.body(send_message_request, "SendMessageRequest") + body_content_kwargs["content"] = body_content request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response @@ -96,10 +101,11 @@ def send( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = self._deserialize('SmsSendResponse', pipeline_response) + deserialized = self._deserialize("SmsSendResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - send.metadata = {'url': '/sms'} # type: ignore + + send.metadata = {"url": "/sms"} # type: ignore diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_models/__init__.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_models/__init__.py index 96cd579bc6e1..862c95470176 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_models/__init__.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_models/__init__.py @@ -11,6 +11,4 @@ except (SyntaxError, ImportError): from ._models import SmsSendResult # type: ignore -__all__ = [ - 'SmsSendResult' -] +__all__ = ["SmsSendResult"] diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_models/_models.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_models/_models.py index c6b703966efe..8266aff7e9dd 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_models/_models.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_models/_models.py @@ -28,26 +28,23 @@ class SmsSendResult(msrest.serialization.Model): """ _validation = { - 'to': {'required': True}, - 'http_status_code': {'required': True}, - 'successful': {'required': True}, + "to": {"required": True}, + "http_status_code": {"required": True}, + "successful": {"required": True}, } _attribute_map = { - 'to': {'key': 'to', 'type': 'str'}, - 'message_id': {'key': 'messageId', 'type': 'str'}, - 'http_status_code': {'key': 'httpStatusCode', 'type': 'int'}, - 'successful': {'key': 'successful', 'type': 'bool'}, - 'error_message': {'key': 'errorMessage', 'type': 'str'}, + "to": {"key": "to", "type": "str"}, + "message_id": {"key": "messageId", "type": "str"}, + "http_status_code": {"key": "httpStatusCode", "type": "int"}, + "successful": {"key": "successful", "type": "bool"}, + "error_message": {"key": "errorMessage", "type": "str"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): super(SmsSendResult, self).__init__(**kwargs) - self.to = kwargs['to'] - self.message_id = kwargs.get('message_id', None) - self.http_status_code = kwargs['http_status_code'] - self.successful = kwargs['successful'] - self.error_message = kwargs.get('error_message', None) + self.to = kwargs["to"] + self.message_id = kwargs.get("message_id", None) + self.http_status_code = kwargs["http_status_code"] + self.successful = kwargs["successful"] + self.error_message = kwargs.get("error_message", None) diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_models/_models_py3.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_models/_models_py3.py index cd3d27e53547..1fb9acabbb69 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_models/_models_py3.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_models/_models_py3.py @@ -30,17 +30,17 @@ class SmsSendResult(msrest.serialization.Model): """ _validation = { - 'to': {'required': True}, - 'http_status_code': {'required': True}, - 'successful': {'required': True}, + "to": {"required": True}, + "http_status_code": {"required": True}, + "successful": {"required": True}, } _attribute_map = { - 'to': {'key': 'to', 'type': 'str'}, - 'message_id': {'key': 'messageId', 'type': 'str'}, - 'http_status_code': {'key': 'httpStatusCode', 'type': 'int'}, - 'successful': {'key': 'successful', 'type': 'bool'}, - 'error_message': {'key': 'errorMessage', 'type': 'str'}, + "to": {"key": "to", "type": "str"}, + "message_id": {"key": "messageId", "type": "str"}, + "http_status_code": {"key": "httpStatusCode", "type": "int"}, + "successful": {"key": "successful", "type": "bool"}, + "error_message": {"key": "errorMessage", "type": "str"}, } def __init__( diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/auth_policy_utils.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/auth_policy_utils.py index 42175b377958..d28bc21548f4 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/auth_policy_utils.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/auth_policy_utils.py @@ -43,9 +43,7 @@ def get_authentication_policy( return AsyncBearerTokenCredentialPolicy( credential, "https://communication.azure.com//.default" # type: ignore ) - return BearerTokenCredentialPolicy( - credential, "https://communication.azure.com//.default" # type: ignore - ) + return BearerTokenCredentialPolicy(credential, "https://communication.azure.com//.default") # type: ignore if isinstance(credential, (AzureKeyCredential, str)): return HMACCredentialsPolicy(endpoint, credential, decode_url=decode_url) diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/models.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/models.py index 7b646472045c..43875e1197e5 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/models.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/models.py @@ -14,8 +14,11 @@ class DeprecatedEnumMeta(CaseInsensitiveEnumMeta): def __getattribute__(cls, item): if item.upper() == "MICROSOFT_BOT": - warnings.warn("MICROSOFT_BOT is deprecated and has been replaced by \ - MICROSOFT_TEAMS_APP identifier.", DeprecationWarning) + warnings.warn( + "MICROSOFT_BOT is deprecated and has been replaced by \ + MICROSOFT_TEAMS_APP identifier.", + DeprecationWarning, + ) item = "MICROSOFT_TEAMS_APP" return super().__getattribute__(item) @@ -47,14 +50,17 @@ class CommunicationCloudEnvironment(str, Enum, metaclass=CaseInsensitiveEnumMeta @runtime_checkable class CommunicationIdentifier(Protocol): """Communication Identifier.""" + @property def raw_id(self) -> str: """The raw ID of the identifier.""" ... + @property def kind(self) -> CommunicationIdentifierKind: """The type of identifier.""" ... + @property def properties(self) -> Mapping[str, Any]: """The properties of the identifier.""" @@ -83,12 +89,14 @@ def properties(self) -> Mapping[str, Any]: class CommunicationUserProperties(TypedDict): """Dictionary of properties for a CommunicationUserIdentifier.""" + id: str """ID of the Communication user as returned from Azure Communication Identity.""" class CommunicationUserIdentifier: """Represents a user in Azure Communication Service.""" + kind: Literal[CommunicationIdentifierKind.COMMUNICATION_USER] = CommunicationIdentifierKind.COMMUNICATION_USER """The type of identifier.""" properties: CommunicationUserProperties @@ -116,12 +124,14 @@ def __eq__(self, other): class PhoneNumberProperties(TypedDict): """Dictionary of properties for a PhoneNumberIdentifier.""" + value: str """The phone number in E.164 format.""" class PhoneNumberIdentifier: """Represents a phone number.""" + kind: Literal[CommunicationIdentifierKind.PHONE_NUMBER] = CommunicationIdentifierKind.PHONE_NUMBER """The type of identifier.""" properties: PhoneNumberProperties @@ -165,6 +175,7 @@ class UnknownIdentifier: It is not advisable to rely on the `kind` property with a value `unknown`, as it could become a new or existing distinct type in the future. """ + kind: Literal[CommunicationIdentifierKind.UNKNOWN] = CommunicationIdentifierKind.UNKNOWN """The type of identifier.""" properties: Mapping[str, Any] @@ -188,6 +199,7 @@ def __eq__(self, other): class MicrosoftTeamsUserProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsUserIdentifier.""" + user_id: str """The id of the Microsoft Teams user. If the user isn't anonymous, the id is the AAD object id of the user.""" is_anonymous: bool @@ -198,6 +210,7 @@ class MicrosoftTeamsUserProperties(TypedDict): class MicrosoftTeamsUserIdentifier: """Represents an identifier for a Microsoft Teams user.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_USER] = CommunicationIdentifierKind.MICROSOFT_TEAMS_USER """The type of identifier.""" properties: MicrosoftTeamsUserProperties @@ -246,6 +259,7 @@ def _format_raw_id(self, properties: MicrosoftTeamsUserProperties) -> str: class MicrosoftTeamsAppProperties(TypedDict): """Dictionary of properties for a MicrosoftTeamsAppIdentifier.""" + app_id: str """The id of the Microsoft Teams application.""" cloud: Union[CommunicationCloudEnvironment, str] @@ -254,6 +268,7 @@ class MicrosoftTeamsAppProperties(TypedDict): class _botbackcompatdict(dict): """Backwards compatible properties.""" + def __getitem__(self, __key: Any) -> Any: try: return super().__getitem__(__key) @@ -267,6 +282,7 @@ def __getitem__(self, __key: Any) -> Any: class MicrosoftTeamsAppIdentifier: """Represents an identifier for a Microsoft Teams application.""" + kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_APP] = CommunicationIdentifierKind.MICROSOFT_TEAMS_APP """The type of identifier.""" properties: MicrosoftTeamsAppProperties @@ -282,10 +298,13 @@ def __init__(self, app_id: str, **kwargs: Any) -> None: :keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed from the other properties. """ - self.properties = cast(MicrosoftTeamsAppProperties, _botbackcompatdict( - app_id=app_id, - cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, - )) + self.properties = cast( + MicrosoftTeamsAppProperties, + _botbackcompatdict( + app_id=app_id, + cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, + ), + ) raw_id: Optional[str] = kwargs.get("raw_id") self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties) @@ -323,7 +342,7 @@ def __init__(self, bot_id, **kwargs): """ warnings.warn( "The MicrosoftBotIdentifier is deprecated and has been replaced by MicrosoftTeamsAppIdentifier.", - DeprecationWarning + DeprecationWarning, ) super().__init__(bot_id, **kwargs) @@ -339,9 +358,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d :rtype: CommunicationIdentifier """ if raw_id.startswith(PHONE_NUMBER_PREFIX): - return PhoneNumberIdentifier( - value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id - ) + return PhoneNumberIdentifier(value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id) segments = raw_id.split(":", maxsplit=2) if len(segments) < 3: @@ -350,9 +367,7 @@ def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: d prefix = f"{segments[0]}:{segments[1]}:" suffix = segments[2] if prefix == TEAMS_USER_ANONYMOUS_PREFIX: - return MicrosoftTeamsUserIdentifier( - user_id=suffix, is_anonymous=True, raw_id=raw_id - ) + return MicrosoftTeamsUserIdentifier(user_id=suffix, is_anonymous=True, raw_id=raw_id) if prefix == TEAMS_USER_PUBLIC_CLOUD_PREFIX: return MicrosoftTeamsUserIdentifier( user_id=suffix, diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/policy.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/policy.py index 2fd2e7426c73..79aa48136fd3 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/policy.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/policy.py @@ -50,9 +50,7 @@ def _compute_hmac( else: decoded_secret = base64.b64decode(self._access_key) - digest = hmac.new( - decoded_secret, value.encode("utf-8"), hashlib.sha256 - ).digest() + digest = hmac.new(decoded_secret, value.encode("utf-8"), hashlib.sha256).digest() return base64.b64encode(digest).decode("utf-8") @@ -101,22 +99,10 @@ def _sign_request(self, request): utc_now = get_current_utc_time() if request.http_request.body is None: request.http_request.body = "" - content_digest = hashlib.sha256( - (request.http_request.body.encode("utf-8")) - ).digest() + content_digest = hashlib.sha256((request.http_request.body.encode("utf-8"))).digest() content_hash = base64.b64encode(content_digest).decode("utf-8") - string_to_sign = ( - verb - + "\n" - + query_url - + "\n" - + utc_now - + ";" - + self._host - + ";" - + content_hash - ) + string_to_sign = verb + "\n" + query_url + "\n" + utc_now + ";" + self._host + ";" + content_hash signature = self._compute_hmac(string_to_sign) @@ -124,10 +110,7 @@ def _sign_request(self, request): "x-ms-date": utc_now, "x-ms-content-sha256": content_hash, "x-ms-return-client-request-id": "true", - "Authorization": "HMAC-SHA256 SignedHeaders=" - + signed_headers - + "&Signature=" - + signature, + "Authorization": "HMAC-SHA256 SignedHeaders=" + signed_headers + "&Signature=" + signature, } request.http_request.headers.update(signature_header) diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/user_credential.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/user_credential.py index c7c150052918..54603e7b32ce 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/user_credential.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/user_credential.py @@ -38,9 +38,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._lock = Condition(Lock()) self._some_thread_refreshing = False @@ -54,9 +52,7 @@ def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -80,9 +76,7 @@ def _update_token_and_reschedule(self): try: new_token = self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -109,12 +103,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() if timespan <= TIMEOUT_MAX: self._timer = Timer(timespan, self._update_token_and_reschedule) self._timer.daemon = True diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/user_credential_async.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/user_credential_async.py index dcd934aba464..15ad17da1a8c 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/user_credential_async.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/user_credential_async.py @@ -40,9 +40,7 @@ def __init__(self, token: str, **kwargs: Any): self._token_refresher = kwargs.pop("token_refresher", None) self._proactive_refresh = kwargs.pop("proactive_refresh", False) if self._proactive_refresh and self._token_refresher is None: - raise ValueError( - "When 'proactive_refresh' is True, 'token_refresher' must not be None." - ) + raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") self._timer = None self._async_mutex = Lock() if sys.version_info[:3] == (3, 10, 0): @@ -60,9 +58,7 @@ async def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument :rtype: ~azure.core.credentials.AccessToken """ if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) + raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") if not self._token_refresher or not self._is_token_expiring_soon(self._token): return self._token @@ -86,9 +82,7 @@ async def _update_token_and_reschedule(self): try: new_token = await self._token_refresher() if not self._is_token_valid(new_token): - raise ValueError( - "The token returned from the token_refresher is expired." - ) + raise ValueError("The token returned from the token_refresher is expired.") async with self._lock: self._token = new_token self._some_thread_refreshing = False @@ -115,12 +109,7 @@ def _schedule_refresh(self): timespan = token_ttl // 2 else: # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = ( - token_ttl - - timedelta( - minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES - ).total_seconds() - ) + timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() self._timer = AsyncTimer(timespan, self._update_token_and_reschedule) self._timer.start() diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/utils.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/utils.py index 47da8a283e5f..8576c31ddc56 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/utils.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_shared/utils.py @@ -87,9 +87,7 @@ def create_access_token(token): payload = json.loads(padded_base64_payload) return AccessToken( token, - _convert_datetime_to_utc_int( - datetime.fromtimestamp(payload["exp"], TZ_UTC) - ), + _convert_datetime_to_utc_int(datetime.fromtimestamp(payload["exp"], TZ_UTC)), ) except ValueError as val_error: raise ValueError(token_parse_err_msg) from val_error diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/_sms_client.py b/sdk/communication/azure-communication-sms/azure/communication/sms/_sms_client.py index 2bb30b04bed4..91c920c673e4 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/_sms_client.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/_sms_client.py @@ -33,33 +33,33 @@ class SmsClient(object): # pylint: disable=client-accepts-api-version-keyword """ def __init__( - self, endpoint, # type: str - credential, # type: Union[TokenCredential, AzureKeyCredential] - **kwargs # type: Any + self, + endpoint, # type: str + credential, # type: Union[TokenCredential, AzureKeyCredential] + **kwargs # type: Any ): # type: (...) -> None try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError: raise ValueError("Account URL must be a string.") # pylint: disable=raise-missing-from if not credential: - raise ValueError( - "invalid credential from connection string.") + raise ValueError("invalid credential from connection string.") self._endpoint = endpoint self._authentication_policy = get_authentication_policy(endpoint, credential) self._sms_service_client = AzureCommunicationSMSService( - self._endpoint, - authentication_policy=self._authentication_policy, - sdk_moniker=SDK_MONIKER, - **kwargs) + self._endpoint, authentication_policy=self._authentication_policy, sdk_moniker=SDK_MONIKER, **kwargs + ) @classmethod - def from_connection_string(cls, conn_str, # type: str - **kwargs # type: Any - ): # type: (...) -> SmsClient + def from_connection_string( + cls, + conn_str, # type: str + **kwargs # type: Any + ): # type: (...) -> SmsClient """Create SmsClient from a Connection String. :param str conn_str: @@ -81,14 +81,16 @@ def from_connection_string(cls, conn_str, # type: str return cls(endpoint, access_key, **kwargs) @distributed_trace - def send(self, from_, # type: str - to, # type: Union[str, List[str]] - message, # type: str - *, - enable_delivery_report: bool = False, - tag: Optional[str] = None, - **kwargs: Any - ): # type: (...) -> [SmsSendResult] + def send( + self, + from_, # type: str + to, # type: Union[str, List[str]] + message, # type: str + *, + enable_delivery_report: bool = False, + tag: Optional[str] = None, + **kwargs: Any + ): # type: (...) -> [SmsSendResult] """Sends SMSs to phone numbers. :param str from_: The sender of the SMS. @@ -106,23 +108,20 @@ def send(self, from_, # type: str if isinstance(to, str): to = [to] - sms_send_options = SmsSendOptions( - enable_delivery_report=enable_delivery_report, - tag=tag - ) + sms_send_options = SmsSendOptions(enable_delivery_report=enable_delivery_report, tag=tag) request = SendMessageRequest( from_property=from_, sms_recipients=[ SmsRecipient( - to=p, - repeatability_request_id=str(uuid4()), - repeatability_first_sent=get_current_utc_time() - ) for p in to + to=p, repeatability_request_id=str(uuid4()), repeatability_first_sent=get_current_utc_time() + ) + for p in to ], message=message, sms_send_options=sms_send_options, - **kwargs) + **kwargs + ) return self._sms_service_client.sms.send( request, @@ -132,7 +131,9 @@ def send(self, from_, # type: str message_id=item.message_id, http_status_code=item.http_status_code, successful=item.successful, - error_message=item.error_message - ) for item in r.value + error_message=item.error_message, + ) + for item in r.value ], - **kwargs) + **kwargs + ) diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/aio/__init__.py b/sdk/communication/azure-communication-sms/azure/communication/sms/aio/__init__.py index 247030c2657e..2a8e9f7d5628 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/aio/__init__.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/aio/__init__.py @@ -1,5 +1,5 @@ from ._sms_client_async import SmsClient __all__ = [ - 'SmsClient', + "SmsClient", ] diff --git a/sdk/communication/azure-communication-sms/azure/communication/sms/aio/_sms_client_async.py b/sdk/communication/azure-communication-sms/azure/communication/sms/aio/_sms_client_async.py index b0c290e7288e..1f83c6a02685 100644 --- a/sdk/communication/azure-communication-sms/azure/communication/sms/aio/_sms_client_async.py +++ b/sdk/communication/azure-communication-sms/azure/communication/sms/aio/_sms_client_async.py @@ -32,33 +32,31 @@ class SmsClient(object): # pylint: disable=client-accepts-api-version-keyword :param Union[AsyncTokenCredential, AzureKeyCredential] credential: The credential we use to authenticate against the service. """ + def __init__( - self, - endpoint: str, - credential: Union[AsyncTokenCredential, AzureKeyCredential], - **kwargs: Any, - ) -> None: + self, + endpoint: str, + credential: Union[AsyncTokenCredential, AzureKeyCredential], + **kwargs: Any, + ) -> None: try: - if not endpoint.lower().startswith('http'): + if not endpoint.lower().startswith("http"): endpoint = "https://" + endpoint except AttributeError as e: raise ValueError("Account URL must be a string.") from e if not credential: - raise ValueError( - "invalid credential from connection string.") + raise ValueError("invalid credential from connection string.") self._endpoint = endpoint self._authentication_policy = get_authentication_policy(endpoint, credential, decode_url=True, is_async=True) self._sms_service_client = AzureCommunicationSMSService( - self._endpoint, - authentication_policy=self._authentication_policy, - sdk_moniker=SDK_MONIKER, - **kwargs) + self._endpoint, authentication_policy=self._authentication_policy, sdk_moniker=SDK_MONIKER, **kwargs + ) @classmethod - def from_connection_string(cls, conn_str: str, **kwargs: Any) -> 'SmsClient': + def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "SmsClient": """Create SmsClient from a Connection String. :param str conn_str: @@ -87,7 +85,7 @@ async def send( *, enable_delivery_report: bool = False, tag: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> List[SmsSendResult]: """Sends SMSs to phone numbers. @@ -105,23 +103,20 @@ async def send( if isinstance(to, str): to = [to] - sms_send_options = SmsSendOptions( - enable_delivery_report=enable_delivery_report, - tag=tag - ) + sms_send_options = SmsSendOptions(enable_delivery_report=enable_delivery_report, tag=tag) request = SendMessageRequest( from_property=from_, sms_recipients=[ SmsRecipient( - to=p, - repeatability_request_id=str(uuid4()), - repeatability_first_sent=get_current_utc_time() - ) for p in to + to=p, repeatability_request_id=str(uuid4()), repeatability_first_sent=get_current_utc_time() + ) + for p in to ], message=message, sms_send_options=sms_send_options, - **kwargs) + **kwargs, + ) return await self._sms_service_client.sms.send( request, @@ -131,12 +126,14 @@ async def send( message_id=item.message_id, http_status_code=item.http_status_code, successful=item.successful, - error_message=item.error_message - ) for item in r.value + error_message=item.error_message, + ) + for item in r.value ], - **kwargs) + **kwargs, + ) - async def __aenter__(self) -> 'SmsClient': + async def __aenter__(self) -> "SmsClient": await self._sms_service_client.__aenter__() return self diff --git a/sdk/communication/azure-communication-sms/samples/send_sms_to_multiple_recipients_sample.py b/sdk/communication/azure-communication-sms/samples/send_sms_to_multiple_recipients_sample.py index f63c2849d423..a40be2541f48 100644 --- a/sdk/communication/azure-communication-sms/samples/send_sms_to_multiple_recipients_sample.py +++ b/sdk/communication/azure-communication-sms/samples/send_sms_to_multiple_recipients_sample.py @@ -24,11 +24,12 @@ sys.path.append("..") + class SmsMultipleRecipientsSample(object): connection_string = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING") phone_number = os.getenv("SMS_PHONE_NUMBER") - + def send_sms_to_multiple_recipients(self): sms_client = SmsClient.from_connection_string(self.connection_string) @@ -37,17 +38,25 @@ def send_sms_to_multiple_recipients(self): from_=self.phone_number, to=[self.phone_number, self.phone_number], message="Hello World via SMS", - enable_delivery_report=True, # optional property - tag="custom-tag") # optional property - + enable_delivery_report=True, # optional property + tag="custom-tag", + ) # optional property + for sms_response in sms_responses: - if (sms_response.successful): - print("Message with message id {} was successful sent to {}" - .format(sms_response.message_id, sms_response.to)) + if sms_response.successful: + print( + "Message with message id {} was successful sent to {}".format( + sms_response.message_id, sms_response.to + ) + ) else: - print("Message failed to send to {} with the status code {} and error: {}" - .format(sms_response.to, sms_response.http_status_code, sms_response.error_message)) + print( + "Message failed to send to {} with the status code {} and error: {}".format( + sms_response.to, sms_response.http_status_code, sms_response.error_message + ) + ) + -if __name__ == '__main__': +if __name__ == "__main__": sample = SmsMultipleRecipientsSample() sample.send_sms_to_multiple_recipients() diff --git a/sdk/communication/azure-communication-sms/samples/send_sms_to_multiple_recipients_sample_async.py b/sdk/communication/azure-communication-sms/samples/send_sms_to_multiple_recipients_sample_async.py index 3458bafbf866..40984f90f72a 100644 --- a/sdk/communication/azure-communication-sms/samples/send_sms_to_multiple_recipients_sample_async.py +++ b/sdk/communication/azure-communication-sms/samples/send_sms_to_multiple_recipients_sample_async.py @@ -25,35 +25,44 @@ sys.path.append("..") + class SmsMultipleRecipientsSampleAsync(object): connection_string = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING") phone_number = os.getenv("SMS_PHONE_NUMBER") - + async def send_sms_to_multiple_recipients_async(self): sms_client = SmsClient.from_connection_string(self.connection_string) async with sms_client: try: - # calling send() with sms values + # calling send() with sms values sms_responses = await sms_client.send( from_=self.phone_number, to=[self.phone_number, self.phone_number], message="Hello World via SMS", - enable_delivery_report=True, # optional property - tag="custom-tag") # optional property - + enable_delivery_report=True, # optional property + tag="custom-tag", + ) # optional property + for sms_response in sms_responses: - if (sms_response.successful): - print("Message with message id {} was successful sent to {}" - .format(sms_response.message_id, sms_response.to)) + if sms_response.successful: + print( + "Message with message id {} was successful sent to {}".format( + sms_response.message_id, sms_response.to + ) + ) else: - print("Message failed to send to {} with the status code {} and error: {}" - .format(sms_response.to, sms_response.http_status_code, sms_response.error_message)) + print( + "Message failed to send to {} with the status code {} and error: {}".format( + sms_response.to, sms_response.http_status_code, sms_response.error_message + ) + ) except Exception: print(Exception) pass -if __name__ == '__main__': + +if __name__ == "__main__": sample = SmsMultipleRecipientsSampleAsync() asyncio.run(sample.send_sms_to_multiple_recipients_async()) diff --git a/sdk/communication/azure-communication-sms/samples/send_sms_to_single_recipient_sample.py b/sdk/communication/azure-communication-sms/samples/send_sms_to_single_recipient_sample.py index 6aaf66bbef34..6492e52e1bad 100644 --- a/sdk/communication/azure-communication-sms/samples/send_sms_to_single_recipient_sample.py +++ b/sdk/communication/azure-communication-sms/samples/send_sms_to_single_recipient_sample.py @@ -24,11 +24,12 @@ sys.path.append("..") + class SmsSingleRecipientSample(object): connection_string = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING") phone_number = os.getenv("SMS_PHONE_NUMBER") - + def send_sms_to_single_recipient(self): # [START auth_from_connection_string] sms_client = SmsClient.from_connection_string(self.connection_string) @@ -39,17 +40,23 @@ def send_sms_to_single_recipient(self): from_=self.phone_number, to=self.phone_number, message="Hello World via SMS", - enable_delivery_report=True, # optional property - tag="custom-tag") # optional property + enable_delivery_report=True, # optional property + tag="custom-tag", + ) # optional property sms_response = sms_responses[0] - - if (sms_response.successful): - print("Message with message id {} was successful sent to {}" - .format(sms_response.message_id, sms_response.to)) + + if sms_response.successful: + print( + "Message with message id {} was successful sent to {}".format(sms_response.message_id, sms_response.to) + ) else: - print("Message failed to send to {} with the status code {} and error: {}" - .format(sms_response.to, sms_response.http_status_code, sms_response.error_message)) + print( + "Message failed to send to {} with the status code {} and error: {}".format( + sms_response.to, sms_response.http_status_code, sms_response.error_message + ) + ) + -if __name__ == '__main__': +if __name__ == "__main__": sample = SmsSingleRecipientSample() sample.send_sms_to_single_recipient() diff --git a/sdk/communication/azure-communication-sms/samples/send_sms_to_single_recipient_sample_async.py b/sdk/communication/azure-communication-sms/samples/send_sms_to_single_recipient_sample_async.py index ee098ff572c8..9a59d4572d2d 100644 --- a/sdk/communication/azure-communication-sms/samples/send_sms_to_single_recipient_sample_async.py +++ b/sdk/communication/azure-communication-sms/samples/send_sms_to_single_recipient_sample_async.py @@ -25,11 +25,12 @@ sys.path.append("..") + class SmsSingleRecipientSampleAsync(object): connection_string = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING") phone_number = os.getenv("SMS_PHONE_NUMBER") - + async def send_sms_to_single_recipient_async(self): # [START auth_from_connection_string_async] sms_client = SmsClient.from_connection_string(self.connection_string) @@ -37,25 +38,33 @@ async def send_sms_to_single_recipient_async(self): async with sms_client: try: - # calling send() with sms values + # calling send() with sms values sms_responses = await sms_client.send( from_=self.phone_number, to=self.phone_number, message="Hello World via SMS", - enable_delivery_report=True, # optional property - tag="custom-tag") # optional property + enable_delivery_report=True, # optional property + tag="custom-tag", + ) # optional property sms_response = sms_responses[0] - - if (sms_response.successful): - print("Message with message id {} was successful sent to {}" - .format(sms_response.message_id, sms_response.to)) + + if sms_response.successful: + print( + "Message with message id {} was successful sent to {}".format( + sms_response.message_id, sms_response.to + ) + ) else: - print("Message failed to send to {} with the status code {} and error: {}" - .format(sms_response.to, sms_response.http_status_code, sms_response.error_message)) + print( + "Message failed to send to {} with the status code {} and error: {}".format( + sms_response.to, sms_response.http_status_code, sms_response.error_message + ) + ) except Exception: print(Exception) pass -if __name__ == '__main__': + +if __name__ == "__main__": sample = SmsSingleRecipientSampleAsync() asyncio.run(sample.send_sms_to_single_recipient_async()) diff --git a/sdk/communication/azure-communication-sms/samples/sms_token_credential_auth_sample.py b/sdk/communication/azure-communication-sms/samples/sms_token_credential_auth_sample.py index 8e6b918752e3..df21cba41ec9 100644 --- a/sdk/communication/azure-communication-sms/samples/sms_token_credential_auth_sample.py +++ b/sdk/communication/azure-communication-sms/samples/sms_token_credential_auth_sample.py @@ -26,11 +26,12 @@ sys.path.append("..") + class SmsTokenCredentialAuthSample(object): connection_string = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING") phone_number = os.getenv("SMS_PHONE_NUMBER") - + def sms_token_credential_auth(self): # To use Azure Active Directory Authentication (DefaultAzureCredential) make sure to have # AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET as env variables. @@ -38,19 +39,21 @@ def sms_token_credential_auth(self): sms_client = SmsClient(endpoint, DefaultAzureCredential()) # calling send() with sms values - sms_responses = sms_client.send( - from_=self.phone_number, - to=self.phone_number, - message="Hello World via SMS") + sms_responses = sms_client.send(from_=self.phone_number, to=self.phone_number, message="Hello World via SMS") sms_response = sms_responses[0] - - if (sms_response.successful): - print("Message with message id {} was successful sent to {}" - .format(sms_response.message_id, sms_response.to)) + + if sms_response.successful: + print( + "Message with message id {} was successful sent to {}".format(sms_response.message_id, sms_response.to) + ) else: - print("Message failed to send to {} with the status code {} and error: {}" - .format(sms_response.to, sms_response.http_status_code, sms_response.error_message)) + print( + "Message failed to send to {} with the status code {} and error: {}".format( + sms_response.to, sms_response.http_status_code, sms_response.error_message + ) + ) + -if __name__ == '__main__': +if __name__ == "__main__": sample = SmsTokenCredentialAuthSample() sample.sms_token_credential_auth() diff --git a/sdk/communication/azure-communication-sms/samples/sms_token_credential_auth_sample_async.py b/sdk/communication/azure-communication-sms/samples/sms_token_credential_auth_sample_async.py index 2c3dbd3f54fe..d9d1a07497c1 100644 --- a/sdk/communication/azure-communication-sms/samples/sms_token_credential_auth_sample_async.py +++ b/sdk/communication/azure-communication-sms/samples/sms_token_credential_auth_sample_async.py @@ -27,11 +27,12 @@ sys.path.append("..") + class SmsTokenCredentialAuthSampleAsync(object): connection_string = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING") phone_number = os.getenv("SMS_PHONE_NUMBER") - + async def sms_token_credential_auth_async(self): # To use Azure Active Directory Authentication (DefaultAzureCredential) make sure to have # AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET as env variables. @@ -42,21 +43,27 @@ async def sms_token_credential_auth_async(self): try: # calling send() with sms values sms_responses = await sms_client.send( - from_=self.phone_number, - to=self.phone_number, - message="Hello World via SMS") + from_=self.phone_number, to=self.phone_number, message="Hello World via SMS" + ) sms_response = sms_responses[0] - - if (sms_response.successful): - print("Message with message id {} was successful sent to {}" - .format(sms_response.message_id, sms_response.to)) + + if sms_response.successful: + print( + "Message with message id {} was successful sent to {}".format( + sms_response.message_id, sms_response.to + ) + ) else: - print("Message failed to send to {} with the status code {} and error: {}" - .format(sms_response.to, sms_response.http_status_code, sms_response.error_message)) + print( + "Message failed to send to {} with the status code {} and error: {}".format( + sms_response.to, sms_response.http_status_code, sms_response.error_message + ) + ) except Exception: print(Exception) pass -if __name__ == '__main__': + +if __name__ == "__main__": sample = SmsTokenCredentialAuthSampleAsync() asyncio.run(sample.sms_token_credential_auth_async()) diff --git a/sdk/communication/azure-communication-sms/setup.py b/sdk/communication/azure-communication-sms/setup.py index 9a97fd302039..c382dbd8f28a 100644 --- a/sdk/communication/azure-communication-sms/setup.py +++ b/sdk/communication/azure-communication-sms/setup.py @@ -14,64 +14,60 @@ PACKAGE_PPRINT_NAME = "Communication SMS" # a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace('-', '/') +package_folder_path = PACKAGE_NAME.replace("-", "/") # a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace('-', '.') +namespace_name = PACKAGE_NAME.replace("-", ".") # Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) +with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: - raise RuntimeError('Cannot find version information') + raise RuntimeError("Cannot find version information") -with open('README.md', encoding='utf-8') as f: +with open("README.md", encoding="utf-8") as f: long_description = f.read() setup( name=PACKAGE_NAME, version=version, - description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), - + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), # ensure that these are updated to reflect the package owners' information long_description=long_description, - long_description_content_type='text/markdown', - url='https://github.com/Azure/azure-sdk-for-python', + long_description_content_type="text/markdown", + url="https://github.com/Azure/azure-sdk-for-python", keywords="azure, azure sdk", - author='Microsoft Corporation', - author_email='azuresdkengsysadmins@microsoft.com', - - license='MIT License', + author="Microsoft Corporation", + author_email="azuresdkengsysadmins@microsoft.com", + license="MIT License", # ensure that the development status reflects the status of your package classifiers=[ "Development Status :: 5 - Production/Stable", - - 'Programming Language :: Python', + "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - 'License :: OSI Approved :: MIT License', + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: MIT License", ], - packages=find_packages(exclude=[ - 'tests', - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.communication' - ]), + packages=find_packages( + exclude=[ + "tests", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + "azure.communication", + ] + ), include_package_data=True, package_data={ - 'pytyped': ['py.typed'], + "pytyped": ["py.typed"], }, python_requires=">=3.8", install_requires=[ - 'azure-core>=1.27.0', - 'msrest>=0.7.1', + "azure-core>=1.27.0", + "msrest>=0.7.1", ], - extras_require={ - ":python_version<'3.8'": ["typing-extensions"] - } -) \ No newline at end of file + extras_require={":python_version<'3.8'": ["typing-extensions"]}, +) diff --git a/sdk/communication/azure-communication-sms/tests/acs_sms_test_case.py b/sdk/communication/azure-communication-sms/tests/acs_sms_test_case.py index c421eb1d14a5..42c57635c7da 100644 --- a/sdk/communication/azure-communication-sms/tests/acs_sms_test_case.py +++ b/sdk/communication/azure-communication-sms/tests/acs_sms_test_case.py @@ -7,6 +7,7 @@ from devtools_testutils import AzureRecordedTestCase, is_live from azure.communication.sms._shared.utils import parse_connection_str + class ACSSMSTestCase(AzureRecordedTestCase): def setUp(self): self.connection_str = self._get_connection_str() @@ -22,7 +23,7 @@ def setUp(self): def _get_connection_str(self): if self.is_playback(): return "endpoint=https://sanitized.communication.azure.com/;accesskey=fake===" - return os.getenv('COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING') + return os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING") def verify_successful_sms_response(self, sms_response): if self.is_live: diff --git a/sdk/communication/azure-communication-sms/tests/conftest.py b/sdk/communication/azure-communication-sms/tests/conftest.py index d3a5e5fac47e..1a8b02988fac 100644 --- a/sdk/communication/azure-communication-sms/tests/conftest.py +++ b/sdk/communication/azure-communication-sms/tests/conftest.py @@ -27,8 +27,14 @@ # cSpell:ignore ests import pytest import os -from devtools_testutils import test_proxy, add_header_regex_sanitizer, \ - set_default_session_settings, add_body_key_sanitizer, add_oauth_response_sanitizer, add_general_string_sanitizer +from devtools_testutils import ( + test_proxy, + add_header_regex_sanitizer, + set_default_session_settings, + add_body_key_sanitizer, + add_oauth_response_sanitizer, + add_general_string_sanitizer, +) from azure.communication.sms._shared.utils import parse_connection_str @@ -37,7 +43,7 @@ def add_sanitizers(test_proxy): set_default_session_settings() add_oauth_response_sanitizer() - connection_str = os.environ.get('COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING') + connection_str = os.environ.get("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING") if connection_str is not None: endpoint, _ = parse_connection_str(connection_str) resource_name = endpoint.split(".")[0] diff --git a/sdk/communication/azure-communication-sms/tests/test_hmac.py b/sdk/communication/azure-communication-sms/tests/test_hmac.py index c08a558efa63..3a69397d409c 100644 --- a/sdk/communication/azure-communication-sms/tests/test_hmac.py +++ b/sdk/communication/azure-communication-sms/tests/test_hmac.py @@ -7,6 +7,7 @@ from azure.communication.sms._shared.policy import HMACCredentialsPolicy + class TestHMAC: def test_correct_hmac(self): @@ -18,6 +19,6 @@ def test_correct_hmac(self): def test_correct_utf16_hmac(self): auth_policy = HMACCredentialsPolicy("contoso.communicationservices.azure.com", "pw==") - sha_val = auth_policy._compute_hmac(u"😀") + sha_val = auth_policy._compute_hmac("😀") - assert sha_val == "1rudJKjn2Zi+3hRrBG29wIF6pD6YyAeQR1ZcFtXoKAU=" \ No newline at end of file + assert sha_val == "1rudJKjn2Zi+3hRrBG29wIF6pD6YyAeQR1ZcFtXoKAU=" diff --git a/sdk/communication/azure-communication-sms/tests/test_sms_client.py b/sdk/communication/azure-communication-sms/tests/test_sms_client.py index 49b973b33f9a..05074c9b85d7 100644 --- a/sdk/communication/azure-communication-sms/tests/test_sms_client.py +++ b/sdk/communication/azure-communication-sms/tests/test_sms_client.py @@ -11,6 +11,7 @@ from unittest.mock import Mock, patch + class FakeTokenCredential(object): def __init__(self): self.token = AccessToken("Fake Token", 0) @@ -37,18 +38,21 @@ def test_send_message(self): raised = False def mock_send(*_, **__): - return mock_response(status_code=202, json_payload={ - "value": [ - { - "to": phone_number, - "messageId": "id", - "httpStatusCode": "202", - "errorMessage": "null", - "repeatabilityResult": "accepted", - "successful": "true" - } - ] - }) + return mock_response( + status_code=202, + json_payload={ + "value": [ + { + "to": phone_number, + "messageId": "id", + "httpStatusCode": "202", + "errorMessage": "null", + "repeatabilityResult": "accepted", + "successful": "true", + } + ] + }, + ) sms_client = SmsClient("https://endpoint", FakeTokenCredential(), transport=Mock(send=mock_send)) @@ -59,34 +63,28 @@ def mock_send(*_, **__): to=[phone_number], message="Hello World via SMS", enable_delivery_report=True, - tag="custom-tag") + tag="custom-tag", + ) sms_response = sms_responses[0] except: raised = True raise - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") self.assertEqual(phone_number, sms_response.to) self.assertIsNotNone(sms_response.message_id) self.assertEqual(202, sms_response.http_status_code) self.assertIsNotNone(sms_response.error_message) self.assertTrue(sms_response.successful) - @patch( - "azure.communication.sms._generated.operations._sms_operations.SmsOperations.send" - ) + @patch("azure.communication.sms._generated.operations._sms_operations.SmsOperations.send") def test_send_message_parameters(self, mock_send): phone_number = "+14255550123" msg = "Hello World via SMS" tag = "custom-tag" sms_client = SmsClient("https://endpoint", FakeTokenCredential()) - sms_client.send( - from_=phone_number, - to=[phone_number], - message=msg, - enable_delivery_report=True, - tag=tag) + sms_client.send(from_=phone_number, to=[phone_number], message=msg, enable_delivery_report=True, tag=tag) send_message_request = mock_send.call_args[0][0] self.assertEqual(phone_number, send_message_request.from_property) diff --git a/sdk/communication/azure-communication-sms/tests/test_sms_client_async.py b/sdk/communication/azure-communication-sms/tests/test_sms_client_async.py index c44a6578397d..5f8f7bad1218 100644 --- a/sdk/communication/azure-communication-sms/tests/test_sms_client_async.py +++ b/sdk/communication/azure-communication-sms/tests/test_sms_client_async.py @@ -11,6 +11,7 @@ from unittest.mock import Mock, patch + class FakeTokenCredential(object): def __init__(self): self.token = AccessToken("Fake Token", 0) @@ -37,18 +38,21 @@ async def test_send_message_async(self): raised = False async def mock_send(*_, **__): - return mock_response(status_code=202, json_payload={ - "value": [ - { - "to": phone_number, - "messageId": "id", - "httpStatusCode": "202", - "errorMessage": "null", - "repeatabilityResult": "accepted", - "successful": "true" - } - ] - }) + return mock_response( + status_code=202, + json_payload={ + "value": [ + { + "to": phone_number, + "messageId": "id", + "httpStatusCode": "202", + "errorMessage": "null", + "repeatabilityResult": "accepted", + "successful": "true", + } + ] + }, + ) sms_client = SmsClient("https://endpoint", FakeTokenCredential(), transport=Mock(send=mock_send)) @@ -59,34 +63,28 @@ async def mock_send(*_, **__): to=[phone_number], message="Hello World via SMS", enable_delivery_report=True, - tag="custom-tag") + tag="custom-tag", + ) sms_response = sms_responses[0] except: raised = True raise - self.assertFalse(raised, 'Expected is no excpetion raised') + self.assertFalse(raised, "Expected is no excpetion raised") self.assertEqual(phone_number, sms_response.to) self.assertIsNotNone(sms_response.message_id) self.assertEqual(202, sms_response.http_status_code) self.assertIsNotNone(sms_response.error_message) self.assertTrue(sms_response.successful) - @patch( - "azure.communication.sms._generated.aio.operations._sms_operations.SmsOperations.send" - ) + @patch("azure.communication.sms._generated.aio.operations._sms_operations.SmsOperations.send") async def test_send_message_parameters_async(self, mock_send): phone_number = "+14255550123" msg = "Hello World via SMS" tag = "custom-tag" sms_client = SmsClient("https://endpoint", FakeTokenCredential()) - await sms_client.send( - from_=phone_number, - to=[phone_number], - message=msg, - enable_delivery_report=True, - tag=tag) + await sms_client.send(from_=phone_number, to=[phone_number], message=msg, enable_delivery_report=True, tag=tag) send_message_request = mock_send.call_args[0][0] self.assertEqual(phone_number, send_message_request.from_property) diff --git a/sdk/communication/azure-communication-sms/tests/test_sms_client_e2e.py b/sdk/communication/azure-communication-sms/tests/test_sms_client_e2e.py index 2c6cf791c6de..243010b95507 100644 --- a/sdk/communication/azure-communication-sms/tests/test_sms_client_e2e.py +++ b/sdk/communication/azure-communication-sms/tests/test_sms_client_e2e.py @@ -12,6 +12,7 @@ from acs_sms_test_case import ACSSMSTestCase from azure.communication.sms import SmsClient + class TestClient(ACSSMSTestCase): def setup_method(self): super().setUp() @@ -23,10 +24,7 @@ def test_send_sms_single(self): sms_client = self.create_client_from_connection_string() # calling send() with sms values - sms_responses = sms_client.send( - from_=self.phone_number, - to=self.phone_number, - message="Hello World via SMS") + sms_responses = sms_client.send(from_=self.phone_number, to=self.phone_number, message="Hello World via SMS") assert len(sms_responses) == 1 self.verify_successful_sms_response(sms_responses[0]) @@ -41,7 +39,8 @@ def test_send_sms_multiple_with_options(self): to=[self.phone_number, self.phone_number], message="Hello World via SMS", enable_delivery_report=True, # optional property - tag="custom-tag") # optional property + tag="custom-tag", + ) # optional property assert len(sms_responses) == 2 @@ -54,17 +53,10 @@ def test_send_sms_from_managed_identity(self): credential = FakeTokenCredential() else: credential = DefaultAzureCredential() - sms_client = SmsClient( - self.endpoint, - credential, - http_logging_policy=get_http_logging_policy() - ) + sms_client = SmsClient(self.endpoint, credential, http_logging_policy=get_http_logging_policy()) # calling send() with sms values - sms_responses = sms_client.send( - from_=self.phone_number, - to=[self.phone_number], - message="Hello World via SMS") + sms_responses = sms_client.send(from_=self.phone_number, to=[self.phone_number], message="Hello World via SMS") assert len(sms_responses) == 1 @@ -76,13 +68,9 @@ def test_send_sms_fake_from_phone_number(self): with pytest.raises(HttpResponseError) as ex: # calling send() with sms values - sms_client.send( - from_="+15550000000", - to=[self.phone_number], - message="Hello World via SMS") + sms_client.send(from_="+15550000000", to=[self.phone_number], message="Hello World via SMS") - assert str( - ex.value.status_code) == "401" + assert str(ex.value.status_code) == "401" assert ex.value.message is not None @recorded_by_proxy @@ -91,9 +79,8 @@ def test_send_sms_fake_to_phone_number(self): with pytest.raises(HttpResponseError) as ex: sms_responses = sms_client.send( - from_=self.phone_number, - to=["Ad155500000000000"], - message="Hello World via SMS") + from_=self.phone_number, to=["Ad155500000000000"], message="Hello World via SMS" + ) assert str(ex.value.status_code == "400") @@ -103,10 +90,7 @@ def test_send_sms_unauthorized_from_phone_number(self): with pytest.raises(HttpResponseError) as ex: # calling send() with sms values - sms_client.send( - from_="+14255550123", - to=[self.phone_number], - message="Hello World via SMS") + sms_client.send(from_="+14255550123", to=[self.phone_number], message="Hello World via SMS") assert str(ex.value.status_code) == "401" assert ex.value.message is not None @@ -118,15 +102,13 @@ def test_send_sms_unique_message_ids(self): # calling send() with sms values sms_responses_1 = sms_client.send( - from_=self.phone_number, - to=[self.phone_number], - message="Hello World via SMS") + from_=self.phone_number, to=[self.phone_number], message="Hello World via SMS" + ) # calling send() again with the same sms values sms_responses_2 = sms_client.send( - from_=self.phone_number, - to=[self.phone_number], - message="Hello World via SMS") + from_=self.phone_number, to=[self.phone_number], message="Hello World via SMS" + ) self.verify_successful_sms_response(sms_responses_1[0]) self.verify_successful_sms_response(sms_responses_2[0]) @@ -142,7 +124,4 @@ def verify_successful_sms_response(self, sms_response): assert sms_response.successful def create_client_from_connection_string(self): - return SmsClient.from_connection_string( - self.connection_str, - http_logging_policy=get_http_logging_policy() - ) + return SmsClient.from_connection_string(self.connection_str, http_logging_policy=get_http_logging_policy()) diff --git a/sdk/communication/azure-communication-sms/tests/test_sms_client_e2e_async.py b/sdk/communication/azure-communication-sms/tests/test_sms_client_e2e_async.py index b84e2c404ea8..16f96a835b70 100644 --- a/sdk/communication/azure-communication-sms/tests/test_sms_client_e2e_async.py +++ b/sdk/communication/azure-communication-sms/tests/test_sms_client_e2e_async.py @@ -13,6 +13,7 @@ from azure.identity.aio import DefaultAzureCredential from devtools_testutils.fake_credentials_async import AsyncFakeCredential + @pytest.mark.asyncio class TestClientAsync(ACSSMSTestCase): def setup_method(self): @@ -25,9 +26,8 @@ async def test_send_sms_single_async(self): async with sms_client: # calling send() with sms values sms_responses = await sms_client.send( - from_=self.phone_number, - to=self.phone_number, - message="Hello World via SMS") + from_=self.phone_number, to=self.phone_number, message="Hello World via SMS" + ) assert len(sms_responses) == 1 @@ -44,7 +44,8 @@ async def test_send_sms_multiple_with_options_async(self): to=[self.phone_number, self.phone_number], message="Hello World via SMS", enable_delivery_report=True, # optional property - tag="custom-tag") # optional property + tag="custom-tag", + ) # optional property assert len(sms_responses) == 2 @@ -57,18 +58,13 @@ async def test_send_sms_from_managed_identity_async(self): credential = AsyncFakeCredential() else: credential = DefaultAzureCredential() - sms_client = SmsClient( - self.endpoint, - credential, - http_logging_policy=get_http_logging_policy() - ) + sms_client = SmsClient(self.endpoint, credential, http_logging_policy=get_http_logging_policy()) async with sms_client: # calling send() with sms values sms_responses = await sms_client.send( - from_=self.phone_number, - to=[self.phone_number], - message="Hello World via SMS") + from_=self.phone_number, to=[self.phone_number], message="Hello World via SMS" + ) assert len(sms_responses) == 1 @@ -81,13 +77,9 @@ async def test_send_sms_fake_from_phone_number_async(self): with pytest.raises(HttpResponseError) as ex: async with sms_client: # calling send() with sms values - await sms_client.send( - from_="+15550000000", - to=[self.phone_number], - message="Hello World via SMS") + await sms_client.send(from_="+15550000000", to=[self.phone_number], message="Hello World via SMS") - assert str( - ex.value.status_code) == "401" + assert str(ex.value.status_code) == "401" assert ex.value.message is not None @recorded_by_proxy_async @@ -96,10 +88,7 @@ async def test_send_sms_fake_to_phone_number_async(self): with pytest.raises(HttpResponseError) as ex: async with sms_client: - await sms_client.send( - from_=self.phone_number, - to=["Ad155500000000000"], - message="Hello World via SMS") + await sms_client.send(from_=self.phone_number, to=["Ad155500000000000"], message="Hello World via SMS") assert str(ex.value.status_code == "400") @@ -110,10 +99,7 @@ async def test_send_sms_unauthorized_from_phone_number_async(self): with pytest.raises(HttpResponseError) as ex: async with sms_client: # calling send() with sms values - await sms_client.send( - from_="+14255550123", - to=[self.phone_number], - message="Hello World via SMS") + await sms_client.send(from_="+14255550123", to=[self.phone_number], message="Hello World via SMS") assert str(ex.value.status_code) == "401" assert ex.value.message is not None @@ -126,15 +112,13 @@ async def test_send_sms_unique_message_ids_async(self): async with sms_client: # calling send() with sms values sms_responses_1 = await sms_client.send( - from_=self.phone_number, - to=[self.phone_number], - message="Hello World via SMS") + from_=self.phone_number, to=[self.phone_number], message="Hello World via SMS" + ) # calling send() again with the same sms values sms_responses_2 = await sms_client.send( - from_=self.phone_number, - to=[self.phone_number], - message="Hello World via SMS") + from_=self.phone_number, to=[self.phone_number], message="Hello World via SMS" + ) self.verify_successful_sms_response(sms_responses_1[0]) self.verify_successful_sms_response(sms_responses_2[0]) @@ -142,7 +126,4 @@ async def test_send_sms_unique_message_ids_async(self): assert sms_responses_1[0].message_id != sms_responses_2[0].message_id def create_client_from_connection_string(self): - return SmsClient.from_connection_string( - self.connection_str, - http_logging_policy=get_http_logging_policy() - ) + return SmsClient.from_connection_string(self.connection_str, http_logging_policy=get_http_logging_policy()) diff --git a/sdk/communication/azure-communication-sms/tests/unittest_helpers.py b/sdk/communication/azure-communication-sms/tests/unittest_helpers.py index 9d24a0aa86eb..3bc29f4ede4b 100644 --- a/sdk/communication/azure-communication-sms/tests/unittest_helpers.py +++ b/sdk/communication/azure-communication-sms/tests/unittest_helpers.py @@ -7,6 +7,7 @@ from unittest import mock + def mock_response(status_code=200, headers=None, json_payload=None): response = mock.Mock(status_code=status_code, headers=headers or {}) if json_payload is not None: diff --git a/sdk/communication/azure-mgmt-communication/azure/mgmt/communication/_patch.py b/sdk/communication/azure-mgmt-communication/azure/mgmt/communication/_patch.py index f99e77fef986..17dbc073e01b 100644 --- a/sdk/communication/azure-mgmt-communication/azure/mgmt/communication/_patch.py +++ b/sdk/communication/azure-mgmt-communication/azure/mgmt/communication/_patch.py @@ -25,6 +25,7 @@ # # -------------------------------------------------------------------------- + # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): diff --git a/sdk/communication/azure-mgmt-communication/azure/mgmt/communication/aio/_patch.py b/sdk/communication/azure-mgmt-communication/azure/mgmt/communication/aio/_patch.py index f99e77fef986..17dbc073e01b 100644 --- a/sdk/communication/azure-mgmt-communication/azure/mgmt/communication/aio/_patch.py +++ b/sdk/communication/azure-mgmt-communication/azure/mgmt/communication/aio/_patch.py @@ -25,6 +25,7 @@ # # -------------------------------------------------------------------------- + # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): diff --git a/sdk/communication/azure-mgmt-communication/setup.py b/sdk/communication/azure-mgmt-communication/setup.py index b35088f3e2a1..2ab6f53c3299 100644 --- a/sdk/communication/azure-mgmt-communication/setup.py +++ b/sdk/communication/azure-mgmt-communication/setup.py @@ -22,9 +22,11 @@ # Version extraction inspired from 'requests' with open( - os.path.join(package_folder_path, "version.py") - if os.path.exists(os.path.join(package_folder_path, "version.py")) - else os.path.join(package_folder_path, "_version.py"), + ( + os.path.join(package_folder_path, "version.py") + if os.path.exists(os.path.join(package_folder_path, "version.py")) + else os.path.join(package_folder_path, "_version.py") + ), "r", ) as fd: version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) diff --git a/sdk/communication/azure-mgmt-communication/tests/conftest.py b/sdk/communication/azure-mgmt-communication/tests/conftest.py index 587e126e50b0..85d1adc3301c 100644 --- a/sdk/communication/azure-mgmt-communication/tests/conftest.py +++ b/sdk/communication/azure-mgmt-communication/tests/conftest.py @@ -35,6 +35,7 @@ load_dotenv() + @pytest.fixture(scope="session", autouse=True) def add_sanitizers(test_proxy): subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") @@ -47,4 +48,4 @@ def add_sanitizers(test_proxy): add_general_regex_sanitizer(regex=client_secret, value="00000000-0000-0000-0000-000000000000") add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") add_header_regex_sanitizer(key="Cookie", value="cookie;") - add_body_key_sanitizer(json_path="$..access_token", value="access_token") \ No newline at end of file + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication.py b/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication.py index 55ad06bbaf68..7a3d638a9303 100644 --- a/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication.py +++ b/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication.py @@ -1,10 +1,10 @@ # coding: utf-8 -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- import unittest import pytest @@ -21,6 +21,7 @@ DISABLE_MGMT_TESTS = True DISABLE_REASON = "Temporary issue causing the tests to fail" + class MgmtCommunicationTest(AzureMgmtTestCase): def setUp(self): @@ -36,13 +37,10 @@ def test_communication_crud(self, resource_group): resource_name = self.get_resource_name("test-resource-crud") resource = CommunicationServiceResource( - location=COMMUNICATION_SERVICE_LOCATION, - data_location = COMMUNICATION_SERVICE_DATA_LOCATION + location=COMMUNICATION_SERVICE_LOCATION, data_location=COMMUNICATION_SERVICE_DATA_LOCATION ) resource = self.communication_client.communication_service.begin_create_or_update( - GROUP_NAME, - resource_name, - resource + GROUP_NAME, resource_name, resource ).result() self.assertEqual(resource.name, resource_name) @@ -53,10 +51,7 @@ def test_communication_crud(self, resource_group): self.assertIsNone(resource.notification_hub_id) self.assertIsNone(resource.tags) - resource = self.communication_client.communication_service.get( - GROUP_NAME, - resource_name - ) + resource = self.communication_client.communication_service.get(GROUP_NAME, resource_name) self.assertEqual(resource.name, resource_name) self.assertEqual(resource.provisioning_state, "Succeeded") self.assertIsNotNone(resource.immutable_resource_id) @@ -65,11 +60,9 @@ def test_communication_crud(self, resource_group): self.assertIsNone(resource.notification_hub_id) self.assertIsNone(resource.tags) - tags = {"tags": {"tag1": "tag1val", "tag2": "tag2val"} } + tags = {"tags": {"tag1": "tag1val", "tag2": "tag2val"}} resource = self.communication_client.communication_service.update( - GROUP_NAME, - resource_name, - TaggedResource(**tags) + GROUP_NAME, resource_name, TaggedResource(**tags) ) self.assertEqual(resource.name, resource_name) self.assertEqual(resource.provisioning_state, "Succeeded") @@ -89,29 +82,22 @@ def test_communication_crud(self, resource_group): key_type = {"key_type": "Primary"} keys_regenerated_primary = self.communication_client.communication_service.regenerate_key( - GROUP_NAME, - resource_name, - RegenerateKeyParameters(**key_type) + GROUP_NAME, resource_name, RegenerateKeyParameters(**key_type) ) self.assertNotEqual(keys.primary_key, keys_regenerated_primary.primary_key) self.assertNotEqual(keys.primary_connection_string, keys_regenerated_primary.primary_connection_string) key_type = {"key_type": "Secondary"} keys_regenerated_secondary = self.communication_client.communication_service.regenerate_key( - GROUP_NAME, - resource_name, - RegenerateKeyParameters(**key_type) + GROUP_NAME, resource_name, RegenerateKeyParameters(**key_type) ) self.assertNotEqual(keys.secondary_key, keys_regenerated_secondary.secondary_key) self.assertNotEqual(keys.secondary_connection_string, keys_regenerated_secondary.secondary_connection_string) # Delete can take a long time to return when running live. Disable polling requirement until we can determine why. - self.communication_client.communication_service.begin_delete( - GROUP_NAME, - resource_name, - polling = False - ) + self.communication_client.communication_service.begin_delete(GROUP_NAME, resource_name, polling=False) + -#------------------------------------------------------------------------------ -if __name__ == '__main__': +# ------------------------------------------------------------------------------ +if __name__ == "__main__": unittest.main() diff --git a/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication_list_resources.py b/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication_list_resources.py index b499d8dc6c94..837bb23b568f 100644 --- a/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication_list_resources.py +++ b/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication_list_resources.py @@ -1,10 +1,10 @@ # coding: utf-8 -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- import unittest import pytest @@ -21,6 +21,7 @@ DISABLE_MGMT_TESTS = True DISABLE_REASON = "Temporary issue causing the tests to fail" + class MgmtCommunicationTest(AzureMgmtTestCase): def setUp(self): @@ -36,13 +37,10 @@ def test_communication_list_by_subscription(self, resource_group): resource_name = self.get_resource_name("test-resource-list-by-subscription") resource = CommunicationServiceResource( - location=COMMUNICATION_SERVICE_LOCATION, - data_location = COMMUNICATION_SERVICE_DATA_LOCATION + location=COMMUNICATION_SERVICE_LOCATION, data_location=COMMUNICATION_SERVICE_DATA_LOCATION ) resource = self.communication_client.communication_service.begin_create_or_update( - GROUP_NAME, - resource_name, - resource + GROUP_NAME, resource_name, resource ).result() self.assertEqual(resource.name, resource_name) @@ -70,13 +68,10 @@ def test_communication_list_by_rg(self, resource_group): resource_name = self.get_resource_name("test-resource-list-by-rg") resource = CommunicationServiceResource( - location=COMMUNICATION_SERVICE_LOCATION, - data_location = COMMUNICATION_SERVICE_DATA_LOCATION + location=COMMUNICATION_SERVICE_LOCATION, data_location=COMMUNICATION_SERVICE_DATA_LOCATION ) resource = self.communication_client.communication_service.begin_create_or_update( - GROUP_NAME, - resource_name, - resource + GROUP_NAME, resource_name, resource ).result() self.assertEqual(resource.name, resource_name) @@ -97,6 +92,7 @@ def test_communication_list_by_rg(self, resource_group): resource_found = True self.assertTrue(resource_found) -#------------------------------------------------------------------------------ -if __name__ == '__main__': + +# ------------------------------------------------------------------------------ +if __name__ == "__main__": unittest.main() diff --git a/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication_notification_hub.py b/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication_notification_hub.py index 97bf153ae701..ac0c104c8209 100644 --- a/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication_notification_hub.py +++ b/sdk/communication/azure-mgmt-communication/tests/disable_test_mgmt_communication_notification_hub.py @@ -1,10 +1,10 @@ # coding: utf-8 -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- import unittest import time import pytest @@ -24,6 +24,7 @@ DISABLE_MGMT_TESTS = True DISABLE_REASON = "Temporary issue causing the tests to fail" + class MgmtCommunicationTest(AzureMgmtTestCase): def setUp(self): @@ -45,72 +46,52 @@ def test_communication_link_notif_hub(self, resource_group): # Create the Notification Hubs resource that will be linked to the Communication Service resource self.notificationhubs_client.namespaces.create_or_update( - GROUP_NAME, - namespace_name, - { - "location": AZURE_LOCATION - } - ) - namespace = self.notificationhubs_client.namespaces.get( - GROUP_NAME, - namespace_name + GROUP_NAME, namespace_name, {"location": AZURE_LOCATION} ) + namespace = self.notificationhubs_client.namespaces.get(GROUP_NAME, namespace_name) while namespace.status == "Created": if self.is_live == True: time.sleep(30) - namespace = self.notificationhubs_client.namespaces.get( - GROUP_NAME, - namespace_name - ) + namespace = self.notificationhubs_client.namespaces.get(GROUP_NAME, namespace_name) notification_hubs = self.notificationhubs_client.notification_hubs.create_or_update( - GROUP_NAME, - namespace_name, - notification_hub_name, - { - "location": AZURE_LOCATION - } + GROUP_NAME, namespace_name, notification_hub_name, {"location": AZURE_LOCATION} ) # Create auth rule - authorization_rule = { "properties": { "rights": [ "Listen" ] } } + authorization_rule = {"properties": {"rights": ["Listen"]}} authorization_rule_name = "TestMgmtCommunicationLinkNotificationHub" self.notificationhubs_client.notification_hubs.create_or_update_authorization_rule( GROUP_NAME, namespace_name, notification_hub_name, authorization_rule_name, - SharedAccessAuthorizationRuleCreateOrUpdateParameters(**authorization_rule) + SharedAccessAuthorizationRuleCreateOrUpdateParameters(**authorization_rule), ) # Obtain connection string keys = self.notificationhubs_client.notification_hubs.list_keys( - GROUP_NAME, - namespace_name, - notification_hub_name, - authorization_rule_name + GROUP_NAME, namespace_name, notification_hub_name, authorization_rule_name ) notification_hub_connection_string = keys.primary_connection_string # Create Communication Service resource for test resource = CommunicationServiceResource( - location=COMMUNICATION_SERVICE_LOCATION, - data_location = COMMUNICATION_SERVICE_DATA_LOCATION + location=COMMUNICATION_SERVICE_LOCATION, data_location=COMMUNICATION_SERVICE_DATA_LOCATION ) resource = self.communication_client.communication_service.begin_create_or_update( - GROUP_NAME, - resource_name, - resource + GROUP_NAME, resource_name, resource ).result() # Link Notification Hub's connection string to Communication Service linked_notification_hub = self.communication_client.communication_service.link_notification_hub( GROUP_NAME, resource_name, - { 'resource_id': notification_hubs.id, 'connection_string': notification_hub_connection_string } + {"resource_id": notification_hubs.id, "connection_string": notification_hub_connection_string}, ) self.assertIsNotNone(linked_notification_hub.resource_id) self.assertEqual(linked_notification_hub.resource_id, notification_hubs.id) -#------------------------------------------------------------------------------ -if __name__ == '__main__': + +# ------------------------------------------------------------------------------ +if __name__ == "__main__": unittest.main() diff --git a/sdk/communication/azure-mgmt-communication/tests/test_cli_mgmt_communication.py b/sdk/communication/azure-mgmt-communication/tests/test_cli_mgmt_communication.py index 85a71562b49b..9e6a323899dd 100644 --- a/sdk/communication/azure-mgmt-communication/tests/test_cli_mgmt_communication.py +++ b/sdk/communication/azure-mgmt-communication/tests/test_cli_mgmt_communication.py @@ -1,14 +1,15 @@ # coding: utf-8 -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- from azure.mgmt.communication import CommunicationServiceManagementClient from devtools_testutils import AzureMgmtRecordedTestCase, ResourceGroupPreparer, recorded_by_proxy + class TestMgmtCommunication(AzureMgmtRecordedTestCase): def setup_method(self, method): @@ -22,4 +23,3 @@ def test_list_by_resource_group(self, resource_group): @recorded_by_proxy def test_list_operations(self): assert list(self.client.operations.list()) - \ No newline at end of file