diff --git a/sdk/eventgrid/azure-eventgrid/CHANGELOG.md b/sdk/eventgrid/azure-eventgrid/CHANGELOG.md index 3a99607a128e..7619f52c83d7 100644 --- a/sdk/eventgrid/azure-eventgrid/CHANGELOG.md +++ b/sdk/eventgrid/azure-eventgrid/CHANGELOG.md @@ -1,5 +1,13 @@ # Release History +## 4.20.1b1 (2024-04-24) + +This is a Beta of the EventGridClient + +### Bug Fixes + +- Fixed serialization issues with CloudEvent and CNCF Cloud Event + ## 4.20.0b1 (2024-04-11) ### Features Added diff --git a/sdk/eventgrid/azure-eventgrid/azure/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/__init__.py index 0d1f7edf5dc6..d55ccad1f573 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py index f6da3df3d6bc..dbb47f36735d 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py @@ -17,8 +17,9 @@ except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'EventGridClient', + "EventGridClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py index a7b6c85bbe3e..2d43c8ce7ea4 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py @@ -22,13 +22,14 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential + class EventGridClient(EventGridClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword """Azure Messaging EventGrid Client. :param endpoint: The host name of the namespace, e.g. namespaceName1.westus-1.eventgrid.azure.net. Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Is either a + :param credential: Credential used to authenticate requests to the service. Is either a AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential @@ -38,30 +39,33 @@ class EventGridClient(EventGridClientOperationsMixin): # pylint: disable=client :paramtype api_version: str """ - def __init__( - self, - endpoint: str, - credential: Union[AzureKeyCredential, "TokenCredential"], - **kwargs: Any - ) -> None: - _endpoint = '{endpoint}' + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + _endpoint = "{endpoint}" self._config = EventGridClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) - _policies = kwargs.pop('policies', None) + _policies = kwargs.pop("policies", None) if _policies is None: - _policies = [policies.RequestIdPolicy(**kwargs),self._config.headers_policy,self._config.user_agent_policy,self._config.proxy_policy,policies.ContentDecodePolicy(**kwargs),self._config.redirect_policy,self._config.retry_policy,self._config.authentication_policy,self._config.custom_hook_policy,self._config.logging_policy,policies.DistributedTracingPolicy(**kwargs),policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None,self._config.http_logging_policy] + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - - def send_request( - self, - request: HttpRequest, *, stream: bool = False, - **kwargs: Any - ) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -81,7 +85,7 @@ 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) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_configuration.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_configuration.py index a615bd59224d..9f9f76551394 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_configuration.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_configuration.py @@ -18,7 +18,7 @@ from azure.core.credentials import TokenCredential -class EventGridClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class EventGridClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for EventGridClient. Note that all parameters used to create this instance are saved as instance @@ -27,7 +27,7 @@ class EventGridClientConfiguration: # pylint: disable=too-many-instance-attri :param endpoint: The host name of the namespace, e.g. namespaceName1.westus-1.eventgrid.azure.net. Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Is either a + :param credential: Credential used to authenticate requests to the service. Is either a AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential @@ -37,13 +37,8 @@ class EventGridClientConfiguration: # pylint: disable=too-many-instance-attri :paramtype api_version: str """ - def __init__( - self, - endpoint: str, - credential: Union[AzureKeyCredential, "TokenCredential"], - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop('api_version', "2023-10-01-preview") + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2023-10-01-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -53,30 +48,29 @@ def __init__( self.endpoint = endpoint self.credential = credential self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://eventgrid.azure.net/.default']) - kwargs.setdefault('sdk_moniker', 'eventgrid/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://eventgrid.azure.net/.default"]) + kwargs.setdefault("sdk_moniker", "eventgrid/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _infer_policy(self, **kwargs): if isinstance(self.credential, AzureKeyCredential): - return policies.AzureKeyCredentialPolicy(self.credential, "Authorization", prefix="SharedAccessKey", **kwargs) - if hasattr(self.credential, 'get_token'): + return policies.AzureKeyCredentialPolicy( + self.credential, "Authorization", prefix="SharedAccessKey", **kwargs + ) + if hasattr(self.credential, "get_token"): return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) raise TypeError(f"Unsupported credential: {self.credential}") - 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.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**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.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_event_mappings.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_event_mappings.py index bb1644791288..59fbfed265e6 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_event_mappings.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_event_mappings.py @@ -7,6 +7,7 @@ from enum import Enum from azure.core import CaseInsensitiveEnumMeta + # pylint: disable=line-too-long # pylint: disable=enum-must-be-uppercase class SystemEventNames(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -15,487 +16,518 @@ class SystemEventNames(str, Enum, metaclass=CaseInsensitiveEnumMeta): Azure Event Grid. To check the list of recognizable system topics, visit https://docs.microsoft.com/azure/event-grid/system-topics. """ + # These names at the top are 'corrected' aliases of duplicate values that appear below, which are # deprecated but maintained for backwards compatibility. - AcsChatMemberAddedToThreadWithUserEventName = 'Microsoft.Communication.ChatMemberAddedToThreadWithUser' + AcsChatMemberAddedToThreadWithUserEventName = "Microsoft.Communication.ChatMemberAddedToThreadWithUser" - ResourceWriteFailureEventName = 'Microsoft.Resources.ResourceWriteFailure' + ResourceWriteFailureEventName = "Microsoft.Resources.ResourceWriteFailure" - IoTHubDeviceDeletedEventName = 'Microsoft.Devices.DeviceDeleted' + IoTHubDeviceDeletedEventName = "Microsoft.Devices.DeviceDeleted" - IoTHubDeviceDisconnectedEventName = 'Microsoft.Devices.DeviceDisconnected' + IoTHubDeviceDisconnectedEventName = "Microsoft.Devices.DeviceDisconnected" - ResourceDeleteFailureEventName = 'Microsoft.Resources.ResourceDeleteFailure' + ResourceDeleteFailureEventName = "Microsoft.Resources.ResourceDeleteFailure" - ResourceDeleteCancelEventName = 'Microsoft.Resources.ResourceDeleteCancel' + ResourceDeleteCancelEventName = "Microsoft.Resources.ResourceDeleteCancel" - AcsChatThreadParticipantAddedEventName = 'Microsoft.Communication.ChatThreadParticipantAdded' + AcsChatThreadParticipantAddedEventName = "Microsoft.Communication.ChatThreadParticipantAdded" - ResourceDeleteSuccessEventName = 'Microsoft.Resources.ResourceDeleteSuccess' + ResourceDeleteSuccessEventName = "Microsoft.Resources.ResourceDeleteSuccess" - EventGridSubscriptionValidationEventName = 'Microsoft.EventGrid.SubscriptionValidationEvent' + EventGridSubscriptionValidationEventName = "Microsoft.EventGrid.SubscriptionValidationEvent" - ResourceWriteSuccessEventName = 'Microsoft.Resources.ResourceWriteSuccess' + ResourceWriteSuccessEventName = "Microsoft.Resources.ResourceWriteSuccess" - ResourceActionSuccessEventName = 'Microsoft.Resources.ResourceActionSuccess' + ResourceActionSuccessEventName = "Microsoft.Resources.ResourceActionSuccess" - ResourceWriteCancelEventName = 'Microsoft.Resources.ResourceWriteCancel' + ResourceWriteCancelEventName = "Microsoft.Resources.ResourceWriteCancel" - ResourceActionFailureEventName = 'Microsoft.Resources.ResourceActionFailure' + ResourceActionFailureEventName = "Microsoft.Resources.ResourceActionFailure" - AcsChatMemberRemovedFromThreadWithUserEventName = 'Microsoft.Communication.ChatMemberRemovedFromThreadWithUser' + AcsChatMemberRemovedFromThreadWithUserEventName = "Microsoft.Communication.ChatMemberRemovedFromThreadWithUser" - IoTHubDeviceConnectedEventName = 'Microsoft.Devices.DeviceConnected' + IoTHubDeviceConnectedEventName = "Microsoft.Devices.DeviceConnected" - EventGridSubscriptionDeletedEventName = 'Microsoft.EventGrid.SubscriptionDeletedEvent' + EventGridSubscriptionDeletedEventName = "Microsoft.EventGrid.SubscriptionDeletedEvent" - AcsChatThreadParticipantRemovedEventName = 'Microsoft.Communication.ChatThreadParticipantRemoved' + AcsChatThreadParticipantRemovedEventName = "Microsoft.Communication.ChatThreadParticipantRemoved" - ResourceActionCancelEventName = 'Microsoft.Resources.ResourceActionCancel' + ResourceActionCancelEventName = "Microsoft.Resources.ResourceActionCancel" - IoTHubDeviceCreatedEventName = 'Microsoft.Devices.DeviceCreated' + IoTHubDeviceCreatedEventName = "Microsoft.Devices.DeviceCreated" # Aliases end here - AcsAdvancedMessageDeliveryStatusUpdatedEventName = 'Microsoft.Communication.AdvancedMessageDeliveryStatusUpdated' + AcsAdvancedMessageDeliveryStatusUpdatedEventName = "Microsoft.Communication.AdvancedMessageDeliveryStatusUpdated" - AcsAdvancedMessageReceivedEventName = 'Microsoft.Communication.AdvancedMessageReceived' + AcsAdvancedMessageReceivedEventName = "Microsoft.Communication.AdvancedMessageReceived" - AcsChatMessageDeletedEventName = 'Microsoft.Communication.ChatMessageDeleted' + AcsChatMessageDeletedEventName = "Microsoft.Communication.ChatMessageDeleted" - AcsChatMessageDeletedInThreadEventName = 'Microsoft.Communication.ChatMessageDeletedInThread' + AcsChatMessageDeletedInThreadEventName = "Microsoft.Communication.ChatMessageDeletedInThread" - AcsChatMessageEditedEventName = 'Microsoft.Communication.ChatMessageEdited' + AcsChatMessageEditedEventName = "Microsoft.Communication.ChatMessageEdited" - AcsChatMessageEditedInThreadEventName = 'Microsoft.Communication.ChatMessageEditedInThread' + AcsChatMessageEditedInThreadEventName = "Microsoft.Communication.ChatMessageEditedInThread" - AcsChatMessageReceivedEventName = 'Microsoft.Communication.ChatMessageReceived' + AcsChatMessageReceivedEventName = "Microsoft.Communication.ChatMessageReceived" - AcsChatMessageReceivedInThreadEventName = 'Microsoft.Communication.ChatMessageReceivedInThread' + AcsChatMessageReceivedInThreadEventName = "Microsoft.Communication.ChatMessageReceivedInThread" - AcsChatParticipantAddedToThreadEventName = 'Microsoft.Communication.ChatThreadParticipantAdded' + AcsChatParticipantAddedToThreadEventName = "Microsoft.Communication.ChatThreadParticipantAdded" - AcsChatParticipantAddedToThreadWithUserEventName = 'Microsoft.Communication.ChatParticipantAddedToThreadWithUser' + AcsChatParticipantAddedToThreadWithUserEventName = "Microsoft.Communication.ChatParticipantAddedToThreadWithUser" - AcsChatParticipantRemovedFromThreadEventName = 'Microsoft.Communication.ChatThreadParticipantRemoved' + AcsChatParticipantRemovedFromThreadEventName = "Microsoft.Communication.ChatThreadParticipantRemoved" - AcsChatParticipantRemovedFromThreadWithUserEventName = 'Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser' + AcsChatParticipantRemovedFromThreadWithUserEventName = ( + "Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser" + ) - AcsChatThreadCreatedEventName = 'Microsoft.Communication.ChatThreadCreated' + AcsChatThreadCreatedEventName = "Microsoft.Communication.ChatThreadCreated" - AcsChatThreadCreatedWithUserEventName = 'Microsoft.Communication.ChatThreadCreatedWithUser' + AcsChatThreadCreatedWithUserEventName = "Microsoft.Communication.ChatThreadCreatedWithUser" - AcsChatThreadDeletedEventName = 'Microsoft.Communication.ChatThreadDeleted' + AcsChatThreadDeletedEventName = "Microsoft.Communication.ChatThreadDeleted" - AcsChatThreadPropertiesUpdatedEventName = 'Microsoft.Communication.ChatThreadPropertiesUpdated' + AcsChatThreadPropertiesUpdatedEventName = "Microsoft.Communication.ChatThreadPropertiesUpdated" - AcsChatThreadPropertiesUpdatedPerUserEventName = 'Microsoft.Communication.ChatThreadPropertiesUpdatedPerUser' + AcsChatThreadPropertiesUpdatedPerUserEventName = "Microsoft.Communication.ChatThreadPropertiesUpdatedPerUser" - AcsChatThreadWithUserDeletedEventName = 'Microsoft.Communication.ChatThreadWithUserDeleted' + AcsChatThreadWithUserDeletedEventName = "Microsoft.Communication.ChatThreadWithUserDeleted" - AcsEmailDeliveryReportReceivedEventName = 'Microsoft.Communication.EmailDeliveryReportReceived' + AcsEmailDeliveryReportReceivedEventName = "Microsoft.Communication.EmailDeliveryReportReceived" - AcsEmailEngagementTrackingReportReceivedEventName = 'Microsoft.Communication.EmailEngagementTrackingReportReceived' + AcsEmailEngagementTrackingReportReceivedEventName = "Microsoft.Communication.EmailEngagementTrackingReportReceived" - AcsIncomingCallEventName = 'Microsoft.Communication.IncomingCall' + AcsIncomingCallEventName = "Microsoft.Communication.IncomingCall" - AcsRecordingFileStatusUpdatedEventName = 'Microsoft.Communication.RecordingFileStatusUpdated' + AcsRecordingFileStatusUpdatedEventName = "Microsoft.Communication.RecordingFileStatusUpdated" - AcsRouterJobCancelledEventName = 'Microsoft.Communication.RouterJobCancelled' + AcsRouterJobCancelledEventName = "Microsoft.Communication.RouterJobCancelled" - AcsRouterJobClassificationFailedEventName = 'Microsoft.Communication.RouterJobClassificationFailed' + AcsRouterJobClassificationFailedEventName = "Microsoft.Communication.RouterJobClassificationFailed" - AcsRouterJobClassifiedEventName = 'Microsoft.Communication.RouterJobClassified' + AcsRouterJobClassifiedEventName = "Microsoft.Communication.RouterJobClassified" - AcsRouterJobClosedEventName = 'Microsoft.Communication.RouterJobClosed' + AcsRouterJobClosedEventName = "Microsoft.Communication.RouterJobClosed" - AcsRouterJobCompletedEventName = 'Microsoft.Communication.RouterJobCompleted' + AcsRouterJobCompletedEventName = "Microsoft.Communication.RouterJobCompleted" - AcsRouterJobDeletedEventName = 'Microsoft.Communication.RouterJobDeleted' + AcsRouterJobDeletedEventName = "Microsoft.Communication.RouterJobDeleted" - AcsRouterJobExceptionTriggeredEventName = 'Microsoft.Communication.RouterJobExceptionTriggered' + AcsRouterJobExceptionTriggeredEventName = "Microsoft.Communication.RouterJobExceptionTriggered" - AcsRouterJobQueuedEventName = 'Microsoft.Communication.RouterJobQueued' + AcsRouterJobQueuedEventName = "Microsoft.Communication.RouterJobQueued" - AcsRouterJobReceivedEventName = 'Microsoft.Communication.RouterJobReceived' + AcsRouterJobReceivedEventName = "Microsoft.Communication.RouterJobReceived" - AcsRouterJobSchedulingFailedEventName = 'Microsoft.Communication.RouterJobSchedulingFailed' + AcsRouterJobSchedulingFailedEventName = "Microsoft.Communication.RouterJobSchedulingFailed" - AcsRouterJobUnassignedEventName = 'Microsoft.Communication.RouterJobUnassigned' + AcsRouterJobUnassignedEventName = "Microsoft.Communication.RouterJobUnassigned" - AcsRouterJobWaitingForActivationEventName = 'Microsoft.Communication.RouterJobWaitingForActivation' + AcsRouterJobWaitingForActivationEventName = "Microsoft.Communication.RouterJobWaitingForActivation" - AcsRouterJobWorkerSelectorsExpiredEventName = 'Microsoft.Communication.RouterJobWorkerSelectorsExpired' + AcsRouterJobWorkerSelectorsExpiredEventName = "Microsoft.Communication.RouterJobWorkerSelectorsExpired" - AcsRouterWorkerDeletedEventName = 'Microsoft.Communication.RouterWorkerDeleted' + AcsRouterWorkerDeletedEventName = "Microsoft.Communication.RouterWorkerDeleted" - AcsRouterWorkerDeregisteredEventName = 'Microsoft.Communication.RouterWorkerDeregistered' + AcsRouterWorkerDeregisteredEventName = "Microsoft.Communication.RouterWorkerDeregistered" - AcsRouterWorkerOfferAcceptedEventName = 'Microsoft.Communication.RouterWorkerOfferAccepted' + AcsRouterWorkerOfferAcceptedEventName = "Microsoft.Communication.RouterWorkerOfferAccepted" - AcsRouterWorkerOfferDeclinedEventName = 'Microsoft.Communication.RouterWorkerOfferDeclined' + AcsRouterWorkerOfferDeclinedEventName = "Microsoft.Communication.RouterWorkerOfferDeclined" - AcsRouterWorkerOfferExpiredEventName = 'Microsoft.Communication.RouterWorkerOfferExpired' + AcsRouterWorkerOfferExpiredEventName = "Microsoft.Communication.RouterWorkerOfferExpired" - AcsRouterWorkerOfferIssuedEventName = 'Microsoft.Communication.RouterWorkerOfferIssued' + AcsRouterWorkerOfferIssuedEventName = "Microsoft.Communication.RouterWorkerOfferIssued" - AcsRouterWorkerOfferRevokedEventName = 'Microsoft.Communication.RouterWorkerOfferRevoked' + AcsRouterWorkerOfferRevokedEventName = "Microsoft.Communication.RouterWorkerOfferRevoked" - AcsRouterWorkerRegisteredEventName = 'Microsoft.Communication.RouterWorkerRegistered' + AcsRouterWorkerRegisteredEventName = "Microsoft.Communication.RouterWorkerRegistered" - AcsRouterWorkerUpdatedEventName = 'Microsoft.Communication.RouterWorkerUpdated' + AcsRouterWorkerUpdatedEventName = "Microsoft.Communication.RouterWorkerUpdated" - AcsSmsDeliveryReportReceivedEventName = 'Microsoft.Communication.SMSDeliveryReportReceived' + AcsSmsDeliveryReportReceivedEventName = "Microsoft.Communication.SMSDeliveryReportReceived" - AcsSmsReceivedEventName = 'Microsoft.Communication.SMSReceived' + AcsSmsReceivedEventName = "Microsoft.Communication.SMSReceived" - AcsUserDisconnectedEventName = 'Microsoft.Communication.UserDisconnected' + AcsUserDisconnectedEventName = "Microsoft.Communication.UserDisconnected" - ApiCenterApiDefinitionAddedEventName = 'Microsoft.ApiCenter.ApiDefinitionAdded' + ApiCenterApiDefinitionAddedEventName = "Microsoft.ApiCenter.ApiDefinitionAdded" - ApiCenterApiDefinitionUpdatedEventName = 'Microsoft.ApiCenter.ApiDefinitionUpdated' + ApiCenterApiDefinitionUpdatedEventName = "Microsoft.ApiCenter.ApiDefinitionUpdated" - ApiManagementApiCreatedEventName = 'Microsoft.ApiManagement.APICreated' + ApiManagementApiCreatedEventName = "Microsoft.ApiManagement.APICreated" - ApiManagementApiDeletedEventName = 'Microsoft.ApiManagement.APIDeleted' + ApiManagementApiDeletedEventName = "Microsoft.ApiManagement.APIDeleted" - ApiManagementApiReleaseCreatedEventName = 'Microsoft.ApiManagement.APIReleaseCreated' + ApiManagementApiReleaseCreatedEventName = "Microsoft.ApiManagement.APIReleaseCreated" - ApiManagementApiReleaseDeletedEventName = 'Microsoft.ApiManagement.APIReleaseDeleted' + ApiManagementApiReleaseDeletedEventName = "Microsoft.ApiManagement.APIReleaseDeleted" - ApiManagementApiReleaseUpdatedEventName = 'Microsoft.ApiManagement.APIReleaseUpdated' + ApiManagementApiReleaseUpdatedEventName = "Microsoft.ApiManagement.APIReleaseUpdated" - ApiManagementApiUpdatedEventName = 'Microsoft.ApiManagement.APIUpdated' + ApiManagementApiUpdatedEventName = "Microsoft.ApiManagement.APIUpdated" - ApiManagementGatewayApiAddedEventName = 'Microsoft.ApiManagement.GatewayAPIAdded' + ApiManagementGatewayApiAddedEventName = "Microsoft.ApiManagement.GatewayAPIAdded" - ApiManagementGatewayApiRemovedEventName = 'Microsoft.ApiManagement.GatewayAPIRemoved' + ApiManagementGatewayApiRemovedEventName = "Microsoft.ApiManagement.GatewayAPIRemoved" - ApiManagementGatewayCertificateAuthorityCreatedEventName = 'Microsoft.ApiManagement.GatewayCertificateAuthorityCreated' + ApiManagementGatewayCertificateAuthorityCreatedEventName = ( + "Microsoft.ApiManagement.GatewayCertificateAuthorityCreated" + ) - ApiManagementGatewayCertificateAuthorityDeletedEventName = 'Microsoft.ApiManagement.GatewayCertificateAuthorityDeleted' + ApiManagementGatewayCertificateAuthorityDeletedEventName = ( + "Microsoft.ApiManagement.GatewayCertificateAuthorityDeleted" + ) - ApiManagementGatewayCertificateAuthorityUpdatedEventName = 'Microsoft.ApiManagement.GatewayCertificateAuthorityUpdated' + ApiManagementGatewayCertificateAuthorityUpdatedEventName = ( + "Microsoft.ApiManagement.GatewayCertificateAuthorityUpdated" + ) - ApiManagementGatewayCreatedEventName = 'Microsoft.ApiManagement.GatewayCreated' + ApiManagementGatewayCreatedEventName = "Microsoft.ApiManagement.GatewayCreated" - ApiManagementGatewayDeletedEventName = 'Microsoft.ApiManagement.GatewayDeleted' + ApiManagementGatewayDeletedEventName = "Microsoft.ApiManagement.GatewayDeleted" - ApiManagementGatewayHostnameConfigurationCreatedEventName = 'Microsoft.ApiManagement.GatewayHostnameConfigurationCreated' + ApiManagementGatewayHostnameConfigurationCreatedEventName = ( + "Microsoft.ApiManagement.GatewayHostnameConfigurationCreated" + ) - ApiManagementGatewayHostnameConfigurationDeletedEventName = 'Microsoft.ApiManagement.GatewayHostnameConfigurationDeleted' + ApiManagementGatewayHostnameConfigurationDeletedEventName = ( + "Microsoft.ApiManagement.GatewayHostnameConfigurationDeleted" + ) - ApiManagementGatewayHostnameConfigurationUpdatedEventName = 'Microsoft.ApiManagement.GatewayHostnameConfigurationUpdated' + ApiManagementGatewayHostnameConfigurationUpdatedEventName = ( + "Microsoft.ApiManagement.GatewayHostnameConfigurationUpdated" + ) - ApiManagementGatewayUpdatedEventName = 'Microsoft.ApiManagement.GatewayUpdated' + ApiManagementGatewayUpdatedEventName = "Microsoft.ApiManagement.GatewayUpdated" - ApiManagementProductCreatedEventName = 'Microsoft.ApiManagement.ProductCreated' + ApiManagementProductCreatedEventName = "Microsoft.ApiManagement.ProductCreated" - ApiManagementProductDeletedEventName = 'Microsoft.ApiManagement.ProductDeleted' + ApiManagementProductDeletedEventName = "Microsoft.ApiManagement.ProductDeleted" - ApiManagementProductUpdatedEventName = 'Microsoft.ApiManagement.ProductUpdated' + ApiManagementProductUpdatedEventName = "Microsoft.ApiManagement.ProductUpdated" - ApiManagementSubscriptionCreatedEventName = 'Microsoft.ApiManagement.SubscriptionCreated' + ApiManagementSubscriptionCreatedEventName = "Microsoft.ApiManagement.SubscriptionCreated" - ApiManagementSubscriptionDeletedEventName = 'Microsoft.ApiManagement.SubscriptionDeleted' + ApiManagementSubscriptionDeletedEventName = "Microsoft.ApiManagement.SubscriptionDeleted" - ApiManagementSubscriptionUpdatedEventName = 'Microsoft.ApiManagement.SubscriptionUpdated' + ApiManagementSubscriptionUpdatedEventName = "Microsoft.ApiManagement.SubscriptionUpdated" - ApiManagementUserCreatedEventName = 'Microsoft.ApiManagement.UserCreated' + ApiManagementUserCreatedEventName = "Microsoft.ApiManagement.UserCreated" - ApiManagementUserDeletedEventName = 'Microsoft.ApiManagement.UserDeleted' + ApiManagementUserDeletedEventName = "Microsoft.ApiManagement.UserDeleted" - ApiManagementUserUpdatedEventName = 'Microsoft.ApiManagement.UserUpdated' + ApiManagementUserUpdatedEventName = "Microsoft.ApiManagement.UserUpdated" - AppConfigurationKeyValueDeletedEventName = 'Microsoft.AppConfiguration.KeyValueDeleted' + AppConfigurationKeyValueDeletedEventName = "Microsoft.AppConfiguration.KeyValueDeleted" - AppConfigurationKeyValueModifiedEventName = 'Microsoft.AppConfiguration.KeyValueModified' + AppConfigurationKeyValueModifiedEventName = "Microsoft.AppConfiguration.KeyValueModified" - AppConfigurationSnapshotCreatedEventName = 'Microsoft.AppConfiguration.SnapshotCreated' + AppConfigurationSnapshotCreatedEventName = "Microsoft.AppConfiguration.SnapshotCreated" - AppConfigurationSnapshotModifiedEventName = 'Microsoft.AppConfiguration.SnapshotModified' + AppConfigurationSnapshotModifiedEventName = "Microsoft.AppConfiguration.SnapshotModified" - AvsClusterCreatedEventName = 'Microsoft.AVS.ClusterCreated' + AvsClusterCreatedEventName = "Microsoft.AVS.ClusterCreated" - AvsClusterDeletedEventName = 'Microsoft.AVS.ClusterDeleted' + AvsClusterDeletedEventName = "Microsoft.AVS.ClusterDeleted" - AvsClusterFailedEventName = 'Microsoft.AVS.ClusterFailed' + AvsClusterFailedEventName = "Microsoft.AVS.ClusterFailed" - AvsClusterUpdatedEventName = 'Microsoft.AVS.ClusterUpdated' + AvsClusterUpdatedEventName = "Microsoft.AVS.ClusterUpdated" - AvsClusterUpdatingEventName = 'Microsoft.AVS.ClusterUpdating' + AvsClusterUpdatingEventName = "Microsoft.AVS.ClusterUpdating" - AvsPrivateCloudFailedEventName = 'Microsoft.AVS.PrivateCloudFailed' + AvsPrivateCloudFailedEventName = "Microsoft.AVS.PrivateCloudFailed" - AvsPrivateCloudUpdatedEventName = 'Microsoft.AVS.PrivateCloudUpdated' + AvsPrivateCloudUpdatedEventName = "Microsoft.AVS.PrivateCloudUpdated" - AvsPrivateCloudUpdatingEventName = 'Microsoft.AVS.PrivateCloudUpdating' + AvsPrivateCloudUpdatingEventName = "Microsoft.AVS.PrivateCloudUpdating" - AvsScriptExecutionCancelledEventName = 'Microsoft.AVS.ScriptExecutionCancelled' + AvsScriptExecutionCancelledEventName = "Microsoft.AVS.ScriptExecutionCancelled" - AvsScriptExecutionFailedEventName = 'Microsoft.AVS.ScriptExecutionFailed' + AvsScriptExecutionFailedEventName = "Microsoft.AVS.ScriptExecutionFailed" - AvsScriptExecutionFinishedEventName = 'Microsoft.AVS.ScriptExecutionFinished' + AvsScriptExecutionFinishedEventName = "Microsoft.AVS.ScriptExecutionFinished" - AvsScriptExecutionStartedEventName = 'Microsoft.AVS.ScriptExecutionStarted' + AvsScriptExecutionStartedEventName = "Microsoft.AVS.ScriptExecutionStarted" - ContainerRegistryChartDeletedEventName = 'Microsoft.ContainerRegistry.ChartDeleted' + ContainerRegistryChartDeletedEventName = "Microsoft.ContainerRegistry.ChartDeleted" - ContainerRegistryChartPushedEventName = 'Microsoft.ContainerRegistry.ChartPushed' + ContainerRegistryChartPushedEventName = "Microsoft.ContainerRegistry.ChartPushed" - ContainerRegistryImageDeletedEventName = 'Microsoft.ContainerRegistry.ImageDeleted' + ContainerRegistryImageDeletedEventName = "Microsoft.ContainerRegistry.ImageDeleted" - ContainerRegistryImagePushedEventName = 'Microsoft.ContainerRegistry.ImagePushed' + ContainerRegistryImagePushedEventName = "Microsoft.ContainerRegistry.ImagePushed" - ContainerServiceClusterSupportEndedEventName = 'Microsoft.ContainerService.ClusterSupportEnded' + ContainerServiceClusterSupportEndedEventName = "Microsoft.ContainerService.ClusterSupportEnded" - ContainerServiceClusterSupportEndingEventName = 'Microsoft.ContainerService.ClusterSupportEnding' + ContainerServiceClusterSupportEndingEventName = "Microsoft.ContainerService.ClusterSupportEnding" - ContainerServiceNewKubernetesVersionAvailableEventName = 'Microsoft.ContainerService.NewKubernetesVersionAvailable' + ContainerServiceNewKubernetesVersionAvailableEventName = "Microsoft.ContainerService.NewKubernetesVersionAvailable" - ContainerServiceNodePoolRollingFailedEventName = 'Microsoft.ContainerService.NodePoolRollingFailed' + ContainerServiceNodePoolRollingFailedEventName = "Microsoft.ContainerService.NodePoolRollingFailed" - ContainerServiceNodePoolRollingStartedEventName = 'Microsoft.ContainerService.NodePoolRollingStarted' + ContainerServiceNodePoolRollingStartedEventName = "Microsoft.ContainerService.NodePoolRollingStarted" - ContainerServiceNodePoolRollingSucceededEventName = 'Microsoft.ContainerService.NodePoolRollingSucceeded' + ContainerServiceNodePoolRollingSucceededEventName = "Microsoft.ContainerService.NodePoolRollingSucceeded" - DataBoxCopyCompletedEventName = 'Microsoft.DataBox.CopyCompleted' + DataBoxCopyCompletedEventName = "Microsoft.DataBox.CopyCompleted" - DataBoxCopyStartedEventName = 'Microsoft.DataBox.CopyStarted' + DataBoxCopyStartedEventName = "Microsoft.DataBox.CopyStarted" - DataBoxOrderCompletedEventName = 'Microsoft.DataBox.OrderCompleted' + DataBoxOrderCompletedEventName = "Microsoft.DataBox.OrderCompleted" - EventGridMQTTClientCreatedOrUpdatedEventName = 'Microsoft.EventGrid.MQTTClientCreatedOrUpdated' + EventGridMQTTClientCreatedOrUpdatedEventName = "Microsoft.EventGrid.MQTTClientCreatedOrUpdated" - EventGridMQTTClientDeletedEventName = 'Microsoft.EventGrid.MQTTClientDeleted' + EventGridMQTTClientDeletedEventName = "Microsoft.EventGrid.MQTTClientDeleted" - EventGridMQTTClientSessionConnectedEventName = 'Microsoft.EventGrid.MQTTClientSessionConnected' + EventGridMQTTClientSessionConnectedEventName = "Microsoft.EventGrid.MQTTClientSessionConnected" - EventGridMQTTClientSessionDisconnectedEventName = 'Microsoft.EventGrid.MQTTClientSessionDisconnected' + EventGridMQTTClientSessionDisconnectedEventName = "Microsoft.EventGrid.MQTTClientSessionDisconnected" - EventHubCaptureFileCreatedEventName = 'Microsoft.EventHub.CaptureFileCreated' + EventHubCaptureFileCreatedEventName = "Microsoft.EventHub.CaptureFileCreated" - HealthcareDicomImageCreatedEventName = 'Microsoft.HealthcareApis.DicomImageCreated' + HealthcareDicomImageCreatedEventName = "Microsoft.HealthcareApis.DicomImageCreated" - HealthcareDicomImageDeletedEventName = 'Microsoft.HealthcareApis.DicomImageDeleted' + HealthcareDicomImageDeletedEventName = "Microsoft.HealthcareApis.DicomImageDeleted" - HealthcareDicomImageUpdatedEventName = 'Microsoft.HealthcareApis.DicomImageUpdated' + HealthcareDicomImageUpdatedEventName = "Microsoft.HealthcareApis.DicomImageUpdated" - HealthcareFhirResourceCreatedEventName = 'Microsoft.HealthcareApis.FhirResourceCreated' + HealthcareFhirResourceCreatedEventName = "Microsoft.HealthcareApis.FhirResourceCreated" - HealthcareFhirResourceDeletedEventName = 'Microsoft.HealthcareApis.FhirResourceDeleted' + HealthcareFhirResourceDeletedEventName = "Microsoft.HealthcareApis.FhirResourceDeleted" - HealthcareFhirResourceUpdatedEventName = 'Microsoft.HealthcareApis.FhirResourceUpdated' + HealthcareFhirResourceUpdatedEventName = "Microsoft.HealthcareApis.FhirResourceUpdated" - IotHubDeviceConnectedEventName = 'Microsoft.Devices.DeviceConnected' + IotHubDeviceConnectedEventName = "Microsoft.Devices.DeviceConnected" - IotHubDeviceCreatedEventName = 'Microsoft.Devices.DeviceCreated' + IotHubDeviceCreatedEventName = "Microsoft.Devices.DeviceCreated" - IotHubDeviceDeletedEventName = 'Microsoft.Devices.DeviceDeleted' + IotHubDeviceDeletedEventName = "Microsoft.Devices.DeviceDeleted" - IotHubDeviceDisconnectedEventName = 'Microsoft.Devices.DeviceDisconnected' + IotHubDeviceDisconnectedEventName = "Microsoft.Devices.DeviceDisconnected" - IotHubDeviceTelemetryEventName = 'Microsoft.Devices.DeviceTelemetry' + IotHubDeviceTelemetryEventName = "Microsoft.Devices.DeviceTelemetry" - KeyVaultCertificateExpiredEventName = 'Microsoft.KeyVault.CertificateExpired' + KeyVaultCertificateExpiredEventName = "Microsoft.KeyVault.CertificateExpired" - KeyVaultCertificateNearExpiryEventName = 'Microsoft.KeyVault.CertificateNearExpiry' + KeyVaultCertificateNearExpiryEventName = "Microsoft.KeyVault.CertificateNearExpiry" - KeyVaultCertificateNewVersionCreatedEventName = 'Microsoft.KeyVault.CertificateNewVersionCreated' + KeyVaultCertificateNewVersionCreatedEventName = "Microsoft.KeyVault.CertificateNewVersionCreated" - KeyVaultKeyExpiredEventName = 'Microsoft.KeyVault.KeyExpired' + KeyVaultKeyExpiredEventName = "Microsoft.KeyVault.KeyExpired" - KeyVaultKeyNearExpiryEventName = 'Microsoft.KeyVault.KeyNearExpiry' + KeyVaultKeyNearExpiryEventName = "Microsoft.KeyVault.KeyNearExpiry" - KeyVaultKeyNewVersionCreatedEventName = 'Microsoft.KeyVault.KeyNewVersionCreated' + KeyVaultKeyNewVersionCreatedEventName = "Microsoft.KeyVault.KeyNewVersionCreated" - KeyVaultSecretExpiredEventName = 'Microsoft.KeyVault.SecretExpired' + KeyVaultSecretExpiredEventName = "Microsoft.KeyVault.SecretExpired" - KeyVaultSecretNearExpiryEventName = 'Microsoft.KeyVault.SecretNearExpiry' + KeyVaultSecretNearExpiryEventName = "Microsoft.KeyVault.SecretNearExpiry" - KeyVaultSecretNewVersionCreatedEventName = 'Microsoft.KeyVault.SecretNewVersionCreated' + KeyVaultSecretNewVersionCreatedEventName = "Microsoft.KeyVault.SecretNewVersionCreated" - KeyVaultVaultAccessPolicyChangedEventName = 'Microsoft.KeyVault.VaultAccessPolicyChanged' + KeyVaultVaultAccessPolicyChangedEventName = "Microsoft.KeyVault.VaultAccessPolicyChanged" - MachineLearningServicesDatasetDriftDetectedEventName = 'Microsoft.MachineLearningServices.DatasetDriftDetected' + MachineLearningServicesDatasetDriftDetectedEventName = "Microsoft.MachineLearningServices.DatasetDriftDetected" - MachineLearningServicesModelDeployedEventName = 'Microsoft.MachineLearningServices.ModelDeployed' + MachineLearningServicesModelDeployedEventName = "Microsoft.MachineLearningServices.ModelDeployed" - MachineLearningServicesModelRegisteredEventName = 'Microsoft.MachineLearningServices.ModelRegistered' + MachineLearningServicesModelRegisteredEventName = "Microsoft.MachineLearningServices.ModelRegistered" - MachineLearningServicesRunCompletedEventName = 'Microsoft.MachineLearningServices.RunCompleted' + MachineLearningServicesRunCompletedEventName = "Microsoft.MachineLearningServices.RunCompleted" - MachineLearningServicesRunStatusChangedEventName = 'Microsoft.MachineLearningServices.RunStatusChanged' + MachineLearningServicesRunStatusChangedEventName = "Microsoft.MachineLearningServices.RunStatusChanged" - MapsGeofenceEnteredEventName = 'Microsoft.Maps.GeofenceEntered' + MapsGeofenceEnteredEventName = "Microsoft.Maps.GeofenceEntered" - MapsGeofenceExitedEventName = 'Microsoft.Maps.GeofenceExited' + MapsGeofenceExitedEventName = "Microsoft.Maps.GeofenceExited" - MapsGeofenceResultEventName = 'Microsoft.Maps.GeofenceResult' + MapsGeofenceResultEventName = "Microsoft.Maps.GeofenceResult" - MediaJobCanceledEventName = 'Microsoft.Media.JobCanceled' + MediaJobCanceledEventName = "Microsoft.Media.JobCanceled" - MediaJobCancelingEventName = 'Microsoft.Media.JobCanceling' + MediaJobCancelingEventName = "Microsoft.Media.JobCanceling" - MediaJobErroredEventName = 'Microsoft.Media.JobErrored' + MediaJobErroredEventName = "Microsoft.Media.JobErrored" - MediaJobFinishedEventName = 'Microsoft.Media.JobFinished' + MediaJobFinishedEventName = "Microsoft.Media.JobFinished" - MediaJobOutputCanceledEventName = 'Microsoft.Media.JobOutputCanceled' + MediaJobOutputCanceledEventName = "Microsoft.Media.JobOutputCanceled" - MediaJobOutputCancelingEventName = 'Microsoft.Media.JobOutputCanceling' + MediaJobOutputCancelingEventName = "Microsoft.Media.JobOutputCanceling" - MediaJobOutputErroredEventName = 'Microsoft.Media.JobOutputErrored' + MediaJobOutputErroredEventName = "Microsoft.Media.JobOutputErrored" - MediaJobOutputFinishedEventName = 'Microsoft.Media.JobOutputFinished' + MediaJobOutputFinishedEventName = "Microsoft.Media.JobOutputFinished" - MediaJobOutputProcessingEventName = 'Microsoft.Media.JobOutputProcessing' + MediaJobOutputProcessingEventName = "Microsoft.Media.JobOutputProcessing" - MediaJobOutputProgressEventName = 'Microsoft.Media.JobOutputProgress' + MediaJobOutputProgressEventName = "Microsoft.Media.JobOutputProgress" - MediaJobOutputScheduledEventName = 'Microsoft.Media.JobOutputScheduled' + MediaJobOutputScheduledEventName = "Microsoft.Media.JobOutputScheduled" - MediaJobOutputStateChangeEventName = 'Microsoft.Media.JobOutputStateChange' + MediaJobOutputStateChangeEventName = "Microsoft.Media.JobOutputStateChange" - MediaJobProcessingEventName = 'Microsoft.Media.JobProcessing' + MediaJobProcessingEventName = "Microsoft.Media.JobProcessing" - MediaJobScheduledEventName = 'Microsoft.Media.JobScheduled' + MediaJobScheduledEventName = "Microsoft.Media.JobScheduled" - MediaJobStateChangeEventName = 'Microsoft.Media.JobStateChange' + MediaJobStateChangeEventName = "Microsoft.Media.JobStateChange" - MediaLiveEventChannelArchiveHeartbeatEventName = 'Microsoft.Media.LiveEventChannelArchiveHeartbeat' + MediaLiveEventChannelArchiveHeartbeatEventName = "Microsoft.Media.LiveEventChannelArchiveHeartbeat" - MediaLiveEventConnectionRejectedEventName = 'Microsoft.Media.LiveEventConnectionRejected' + MediaLiveEventConnectionRejectedEventName = "Microsoft.Media.LiveEventConnectionRejected" - MediaLiveEventEncoderConnectedEventName = 'Microsoft.Media.LiveEventEncoderConnected' + MediaLiveEventEncoderConnectedEventName = "Microsoft.Media.LiveEventEncoderConnected" - MediaLiveEventEncoderDisconnectedEventName = 'Microsoft.Media.LiveEventEncoderDisconnected' + MediaLiveEventEncoderDisconnectedEventName = "Microsoft.Media.LiveEventEncoderDisconnected" - MediaLiveEventIncomingDataChunkDroppedEventName = 'Microsoft.Media.LiveEventIncomingDataChunkDropped' + MediaLiveEventIncomingDataChunkDroppedEventName = "Microsoft.Media.LiveEventIncomingDataChunkDropped" - MediaLiveEventIncomingStreamReceivedEventName = 'Microsoft.Media.LiveEventIncomingStreamReceived' + MediaLiveEventIncomingStreamReceivedEventName = "Microsoft.Media.LiveEventIncomingStreamReceived" - MediaLiveEventIncomingStreamsOutOfSyncEventName = 'Microsoft.Media.LiveEventIncomingStreamsOutOfSync' + MediaLiveEventIncomingStreamsOutOfSyncEventName = "Microsoft.Media.LiveEventIncomingStreamsOutOfSync" - MediaLiveEventIncomingVideoStreamsOutOfSyncEventName = 'Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync' + MediaLiveEventIncomingVideoStreamsOutOfSyncEventName = "Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync" - MediaLiveEventIngestHeartbeatEventName = 'Microsoft.Media.LiveEventIngestHeartbeat' + MediaLiveEventIngestHeartbeatEventName = "Microsoft.Media.LiveEventIngestHeartbeat" - MediaLiveEventTrackDiscontinuityDetectedEventName = 'Microsoft.Media.LiveEventTrackDiscontinuityDetected' + MediaLiveEventTrackDiscontinuityDetectedEventName = "Microsoft.Media.LiveEventTrackDiscontinuityDetected" - PolicyInsightsPolicyStateChangedEventName = 'Microsoft.PolicyInsights.PolicyStateChanged' + PolicyInsightsPolicyStateChangedEventName = "Microsoft.PolicyInsights.PolicyStateChanged" - PolicyInsightsPolicyStateCreatedEventName = 'Microsoft.PolicyInsights.PolicyStateCreated' + PolicyInsightsPolicyStateCreatedEventName = "Microsoft.PolicyInsights.PolicyStateCreated" - PolicyInsightsPolicyStateDeletedEventName = 'Microsoft.PolicyInsights.PolicyStateDeleted' + PolicyInsightsPolicyStateDeletedEventName = "Microsoft.PolicyInsights.PolicyStateDeleted" - RedisExportRDBCompletedEventName = 'Microsoft.Cache.ExportRDBCompleted' + RedisExportRDBCompletedEventName = "Microsoft.Cache.ExportRDBCompleted" - RedisImportRDBCompletedEventName = 'Microsoft.Cache.ImportRDBCompleted' + RedisImportRDBCompletedEventName = "Microsoft.Cache.ImportRDBCompleted" - RedisPatchingCompletedEventName = 'Microsoft.Cache.PatchingCompleted' + RedisPatchingCompletedEventName = "Microsoft.Cache.PatchingCompleted" - RedisScalingCompletedEventName = 'Microsoft.Cache.ScalingCompleted' + RedisScalingCompletedEventName = "Microsoft.Cache.ScalingCompleted" - ResourceActionCancelName = 'Microsoft.Resources.ResourceActionCancel' + ResourceActionCancelName = "Microsoft.Resources.ResourceActionCancel" - ResourceActionFailureName = 'Microsoft.Resources.ResourceActionFailure' + ResourceActionFailureName = "Microsoft.Resources.ResourceActionFailure" - ResourceActionSuccessName = 'Microsoft.Resources.ResourceActionSuccess' + ResourceActionSuccessName = "Microsoft.Resources.ResourceActionSuccess" - ResourceDeleteCancelName = 'Microsoft.Resources.ResourceDeleteCancel' + ResourceDeleteCancelName = "Microsoft.Resources.ResourceDeleteCancel" - ResourceDeleteFailureName = 'Microsoft.Resources.ResourceDeleteFailure' + ResourceDeleteFailureName = "Microsoft.Resources.ResourceDeleteFailure" - ResourceDeleteSuccessName = 'Microsoft.Resources.ResourceDeleteSuccess' + ResourceDeleteSuccessName = "Microsoft.Resources.ResourceDeleteSuccess" - ResourceNotificationsHealthResourcesAnnotatedEventName = 'Microsoft.ResourceNotifications.HealthResources.ResourceAnnotated' + ResourceNotificationsHealthResourcesAnnotatedEventName = ( + "Microsoft.ResourceNotifications.HealthResources.ResourceAnnotated" + ) - ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventName = 'Microsoft.ResourceNotifications.HealthResources.AvailabilityStatusChanged' + ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventName = ( + "Microsoft.ResourceNotifications.HealthResources.AvailabilityStatusChanged" + ) - ResourceNotificationsResourceManagementCreatedOrUpdatedEventName = 'Microsoft.ResourceNotifications.Resources.CreatedOrUpdated' + ResourceNotificationsResourceManagementCreatedOrUpdatedEventName = ( + "Microsoft.ResourceNotifications.Resources.CreatedOrUpdated" + ) - ResourceNotificationsResourceManagementDeletedEventName = 'Microsoft.ResourceNotifications.Resources.Deleted' + ResourceNotificationsResourceManagementDeletedEventName = "Microsoft.ResourceNotifications.Resources.Deleted" - ResourceWriteCancelName = 'Microsoft.Resources.ResourceWriteCancel' + ResourceWriteCancelName = "Microsoft.Resources.ResourceWriteCancel" - ResourceWriteFailureName = 'Microsoft.Resources.ResourceWriteFailure' + ResourceWriteFailureName = "Microsoft.Resources.ResourceWriteFailure" - ResourceWriteSuccessName = 'Microsoft.Resources.ResourceWriteSuccess' + ResourceWriteSuccessName = "Microsoft.Resources.ResourceWriteSuccess" - ServiceBusActiveMessagesAvailablePeriodicNotificationsEventName = 'Microsoft.ServiceBus.ActiveMessagesAvailablePeriodicNotifications' + ServiceBusActiveMessagesAvailablePeriodicNotificationsEventName = ( + "Microsoft.ServiceBus.ActiveMessagesAvailablePeriodicNotifications" + ) - ServiceBusActiveMessagesAvailableWithNoListenersEventName = 'Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners' + ServiceBusActiveMessagesAvailableWithNoListenersEventName = ( + "Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners" + ) - ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventName = 'Microsoft.ServiceBus.DeadletterMessagesAvailablePeriodicNotifications' + ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventName = ( + "Microsoft.ServiceBus.DeadletterMessagesAvailablePeriodicNotifications" + ) - ServiceBusDeadletterMessagesAvailableWithNoListenersEventName = 'Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListeners' + ServiceBusDeadletterMessagesAvailableWithNoListenersEventName = ( + "Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListeners" + ) - SignalRServiceClientConnectionConnectedEventName = 'Microsoft.SignalRService.ClientConnectionConnected' + SignalRServiceClientConnectionConnectedEventName = "Microsoft.SignalRService.ClientConnectionConnected" - SignalRServiceClientConnectionDisconnectedEventName = 'Microsoft.SignalRService.ClientConnectionDisconnected' + SignalRServiceClientConnectionDisconnectedEventName = "Microsoft.SignalRService.ClientConnectionDisconnected" - StorageAsyncOperationInitiatedEventName = 'Microsoft.Storage.AsyncOperationInitiated' + StorageAsyncOperationInitiatedEventName = "Microsoft.Storage.AsyncOperationInitiated" - StorageBlobCreatedEventName = 'Microsoft.Storage.BlobCreated' + StorageBlobCreatedEventName = "Microsoft.Storage.BlobCreated" - StorageBlobDeletedEventName = 'Microsoft.Storage.BlobDeleted' + StorageBlobDeletedEventName = "Microsoft.Storage.BlobDeleted" - StorageBlobInventoryPolicyCompletedEventName = 'Microsoft.Storage.BlobInventoryPolicyCompleted' + StorageBlobInventoryPolicyCompletedEventName = "Microsoft.Storage.BlobInventoryPolicyCompleted" - StorageBlobRenamedEventName = 'Microsoft.Storage.BlobRenamed' + StorageBlobRenamedEventName = "Microsoft.Storage.BlobRenamed" - StorageBlobTierChangedEventName = 'Microsoft.Storage.BlobTierChanged' + StorageBlobTierChangedEventName = "Microsoft.Storage.BlobTierChanged" - StorageDirectoryCreatedEventName = 'Microsoft.Storage.DirectoryCreated' + StorageDirectoryCreatedEventName = "Microsoft.Storage.DirectoryCreated" - StorageDirectoryDeletedEventName = 'Microsoft.Storage.DirectoryDeleted' + StorageDirectoryDeletedEventName = "Microsoft.Storage.DirectoryDeleted" - StorageDirectoryRenamedEventName = 'Microsoft.Storage.DirectoryRenamed' + StorageDirectoryRenamedEventName = "Microsoft.Storage.DirectoryRenamed" - StorageLifecyclePolicyCompletedEventName = 'Microsoft.Storage.LifecyclePolicyCompleted' + StorageLifecyclePolicyCompletedEventName = "Microsoft.Storage.LifecyclePolicyCompleted" - StorageTaskAssignmentCompletedEventName = 'Microsoft.Storage.StorageTaskAssignmentCompleted' + StorageTaskAssignmentCompletedEventName = "Microsoft.Storage.StorageTaskAssignmentCompleted" - StorageTaskAssignmentQueuedEventName = 'Microsoft.Storage.StorageTaskAssignmentQueued' + StorageTaskAssignmentQueuedEventName = "Microsoft.Storage.StorageTaskAssignmentQueued" - StorageTaskCompletedEventName = 'Microsoft.Storage.StorageTaskCompleted' + StorageTaskCompletedEventName = "Microsoft.Storage.StorageTaskCompleted" - StorageTaskQueuedEventName = 'Microsoft.Storage.StorageTaskQueued' + StorageTaskQueuedEventName = "Microsoft.Storage.StorageTaskQueued" - SubscriptionDeletedEventName = 'Microsoft.EventGrid.SubscriptionDeletedEvent' + SubscriptionDeletedEventName = "Microsoft.EventGrid.SubscriptionDeletedEvent" - SubscriptionValidationEventName = 'Microsoft.EventGrid.SubscriptionValidationEvent' + SubscriptionValidationEventName = "Microsoft.EventGrid.SubscriptionValidationEvent" - WebAppServicePlanUpdatedEventName = 'Microsoft.Web.AppServicePlanUpdated' + WebAppServicePlanUpdatedEventName = "Microsoft.Web.AppServicePlanUpdated" - WebAppUpdatedEventName = 'Microsoft.Web.AppUpdated' + WebAppUpdatedEventName = "Microsoft.Web.AppUpdated" - WebBackupOperationCompletedEventName = 'Microsoft.Web.BackupOperationCompleted' + WebBackupOperationCompletedEventName = "Microsoft.Web.BackupOperationCompleted" - WebBackupOperationFailedEventName = 'Microsoft.Web.BackupOperationFailed' + WebBackupOperationFailedEventName = "Microsoft.Web.BackupOperationFailed" - WebBackupOperationStartedEventName = 'Microsoft.Web.BackupOperationStarted' + WebBackupOperationStartedEventName = "Microsoft.Web.BackupOperationStarted" - WebRestoreOperationCompletedEventName = 'Microsoft.Web.RestoreOperationCompleted' + WebRestoreOperationCompletedEventName = "Microsoft.Web.RestoreOperationCompleted" - WebRestoreOperationFailedEventName = 'Microsoft.Web.RestoreOperationFailed' + WebRestoreOperationFailedEventName = "Microsoft.Web.RestoreOperationFailed" - WebRestoreOperationStartedEventName = 'Microsoft.Web.RestoreOperationStarted' + WebRestoreOperationStartedEventName = "Microsoft.Web.RestoreOperationStarted" - WebSlotSwapCompletedEventName = 'Microsoft.Web.SlotSwapCompleted' + WebSlotSwapCompletedEventName = "Microsoft.Web.SlotSwapCompleted" - WebSlotSwapFailedEventName = 'Microsoft.Web.SlotSwapFailed' + WebSlotSwapFailedEventName = "Microsoft.Web.SlotSwapFailed" - WebSlotSwapStartedEventName = 'Microsoft.Web.SlotSwapStarted' + WebSlotSwapStartedEventName = "Microsoft.Web.SlotSwapStarted" - WebSlotSwapWithPreviewCancelledEventName = 'Microsoft.Web.SlotSwapWithPreviewCancelled' + WebSlotSwapWithPreviewCancelledEventName = "Microsoft.Web.SlotSwapWithPreviewCancelled" - WebSlotSwapWithPreviewStartedEventName = 'Microsoft.Web.SlotSwapWithPreviewStarted' + WebSlotSwapWithPreviewStartedEventName = "Microsoft.Web.SlotSwapWithPreviewStarted" - ContainerRegistryArtifactEventName = 'Microsoft.AppConfiguration.KeyValueModified' + ContainerRegistryArtifactEventName = "Microsoft.AppConfiguration.KeyValueModified" - KeyVaultAccessPolicyChangedEventName = 'Microsoft.KeyVault.VaultAccessPolicyChanged' + KeyVaultAccessPolicyChangedEventName = "Microsoft.KeyVault.VaultAccessPolicyChanged" - ContainerRegistryEventName = 'Microsoft.ContainerRegistry.ChartPushed' + ContainerRegistryEventName = "Microsoft.ContainerRegistry.ChartPushed" - ServiceBusDeadletterMessagesAvailableWithNoListenerEventName = 'Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListeners' + ServiceBusDeadletterMessagesAvailableWithNoListenerEventName = ( + "Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListeners" + ) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_client.py index d1897c866468..f3ad2db7363a 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_client.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_client.py @@ -28,18 +28,12 @@ class EventGridPublisherClient( :paramtype api_version: str """ - def __init__( - self, **kwargs: Any - ) -> None: # pylint: disable=missing-client-constructor-parameter-credential + def __init__(self, **kwargs: Any) -> None: # pylint: disable=missing-client-constructor-parameter-credential _endpoint = "https://{topicHostname}" self._config = EventGridPublisherClientConfiguration(**kwargs) - self._client: PipelineClient = PipelineClient( - base_url=_endpoint, config=self._config, **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 diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_configuration.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_configuration.py index 5077ede3b176..d105970e51f9 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_configuration.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_configuration.py @@ -20,9 +20,7 @@ VERSION = "unknown" -class EventGridPublisherClientConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes +class EventGridPublisherClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for EventGridPublisherClient. Note that all parameters used to create this instance are saved as instance @@ -42,24 +40,12 @@ def __init__(self, **kwargs: Any) -> None: 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/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/_operations.py index f1db47f93f7a..0ba43ddc6003 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/_operations.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/_operations.py @@ -37,9 +37,7 @@ from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object 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 @@ -49,12 +47,8 @@ def build_event_grid_publisher_publish_events_request(**kwargs: Any) -> HttpRequ _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: Literal["2018-01-01"] = kwargs.pop( - "api_version", _params.pop("api-version", "2018-01-01") - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) # Construct URL _url = "/api/events" @@ -63,13 +57,9 @@ def build_event_grid_publisher_publish_events_request(**kwargs: Any) -> HttpRequ # 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") - return HttpRequest( - method="POST", url=_url, params=_params, headers=_headers, **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_event_grid_publisher_publish_cloud_event_events_request( @@ -78,12 +68,8 @@ def build_event_grid_publisher_publish_cloud_event_events_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: Literal["2018-01-01"] = kwargs.pop( - "api_version", _params.pop("api-version", "2018-01-01") - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) # Construct URL _url = "/api/events" @@ -92,13 +78,9 @@ def build_event_grid_publisher_publish_cloud_event_events_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") - return HttpRequest( - method="POST", url=_url, params=_params, headers=_headers, json=json, **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, json=json, **kwargs) def build_event_grid_publisher_publish_custom_event_events_request( @@ -107,12 +89,8 @@ def build_event_grid_publisher_publish_custom_event_events_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: Literal["2018-01-01"] = kwargs.pop( - "api_version", _params.pop("api-version", "2018-01-01") - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) # Construct URL _url = "/api/events" @@ -121,13 +99,9 @@ def build_event_grid_publisher_publish_custom_event_events_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") - return HttpRequest( - method="POST", url=_url, params=_params, headers=_headers, **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class EventGridPublisherClientOperationsMixin(EventGridPublisherClientMixinABC): @@ -212,9 +186,7 @@ def publish_events( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" @@ -234,25 +206,19 @@ def publish_events( # pylint: disable=inconsistent-return-statements params=_params, ) path_format_arguments = { - "topicHostname": self._serialize.url( - "topic_hostname", topic_hostname, "str", skip_quote=True - ), + "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "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 if response.status_code not in [200]: - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if cls: @@ -286,9 +252,7 @@ def publish_cloud_event_events( # pylint: disable=inconsistent-return-statement content_type: str = kwargs.pop( "content_type", - _headers.pop( - "Content-Type", "application/cloudevents-batch+json; charset=utf-8" - ), + _headers.pop("Content-Type", "application/cloudevents-batch+json; charset=utf-8"), ) cls: ClsType[None] = kwargs.pop("cls", None) @@ -302,25 +266,19 @@ def publish_cloud_event_events( # pylint: disable=inconsistent-return-statement params=_params, ) path_format_arguments = { - "topicHostname": self._serialize.url( - "topic_hostname", topic_hostname, "str", skip_quote=True - ), + "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "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 if response.status_code not in [200]: - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if cls: @@ -404,9 +362,7 @@ def publish_custom_event_events( # pylint: disable=inconsistent-return-statemen _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[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" @@ -426,25 +382,19 @@ def publish_custom_event_events( # pylint: disable=inconsistent-return-statemen params=_params, ) path_format_arguments = { - "topicHostname": self._serialize.url( - "topic_hostname", topic_hostname, "str", skip_quote=True - ), + "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "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 if response.status_code not in [200]: - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if cls: diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/_patch.py index d400d2d124e2..f7dd32510333 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_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/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_patch.py index d400d2d124e2..f7dd32510333 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_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/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_serialization.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_serialization.py index 615a169a649a..1e7a11b1d256 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_serialization.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_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", {}) @@ -709,9 +683,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): continue 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 @@ -733,9 +705,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): @@ -756,9 +726,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) @@ -798,12 +766,7 @@ def query(self, name, data, data_type, **kwargs): # Treat the list aside, since we don't want to encode the div separator if data_type.startswith("["): internal_data_type = data_type[1:-1] - data = [ - self.serialize_data(d, internal_data_type, **kwargs) - if d is not None - else "" - for d in data - ] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] if not kwargs.get("skip_quote", False): data = [quote(str(d), safe="") for d in data] return str(self.serialize_iter(data, internal_data_type, **kwargs)) @@ -975,9 +938,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" @@ -1009,9 +970,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: serialized[self.serialize_unicode(key)] = None @@ -1020,9 +979,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 @@ -1068,9 +1025,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 @@ -1287,9 +1242,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 @@ -1382,10 +1335,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: @@ -1393,9 +1343,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) @@ -1424,9 +1372,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] @@ -1439,9 +1385,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 = { @@ -1497,11 +1441,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: @@ -1511,9 +1451,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 @@ -1567,10 +1505,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): @@ -1650,21 +1585,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 @@ -1679,17 +1608,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)) @@ -1726,17 +1647,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 @@ -1767,16 +1682,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): @@ -1788,9 +1697,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"} @@ -2022,9 +1929,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=None, defaultday=None) @@ -2039,9 +1944,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 @@ -2057,10 +1960,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/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_client.py index b094add0dc06..f81ce4181ad6 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_client.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_client.py @@ -28,25 +28,17 @@ class EventGridPublisherClient( :paramtype api_version: str """ - def __init__( - self, **kwargs: Any - ) -> None: # pylint: disable=missing-client-constructor-parameter-credential + def __init__(self, **kwargs: Any) -> None: # pylint: disable=missing-client-constructor-parameter-credential _endpoint = "https://{topicHostname}" self._config = EventGridPublisherClientConfiguration(**kwargs) - self._client: AsyncPipelineClient = AsyncPipelineClient( - base_url=_endpoint, config=self._config, **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 - 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 diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_configuration.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_configuration.py index 06deaef1eb5c..52c2f3551ad7 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_configuration.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_configuration.py @@ -20,9 +20,7 @@ VERSION = "unknown" -class EventGridPublisherClientConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes +class EventGridPublisherClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for EventGridPublisherClient. Note that all parameters used to create this instance are saved as instance @@ -42,26 +40,12 @@ def __init__(self, **kwargs: Any) -> None: 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/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/_operations.py index fe65e0c6cf06..ba6dc3ff67e5 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/_operations.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/_operations.py @@ -37,9 +37,7 @@ from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object 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 EventGridPublisherClientOperationsMixin(EventGridPublisherClientMixinABC): @@ -69,12 +67,7 @@ async def publish_events( # pylint: disable=inconsistent-return-statements @overload async def publish_events( # pylint: disable=inconsistent-return-statements - self, - topic_hostname: str, - events: IO, - *, - content_type: str = "application/json", - **kwargs: Any + self, topic_hostname: str, events: IO, *, content_type: str = "application/json", **kwargs: Any ) -> None: """Publishes a batch of events to an Azure Event Grid topic. @@ -93,10 +86,7 @@ async def publish_events( # pylint: disable=inconsistent-return-statements @distributed_trace_async async def publish_events( # pylint: disable=inconsistent-return-statements - self, - topic_hostname: str, - events: Union[List[_models.EventGridEvent], IO], - **kwargs: Any + self, topic_hostname: str, events: Union[List[_models.EventGridEvent], IO], **kwargs: Any ) -> None: """Publishes a batch of events to an Azure Event Grid topic. @@ -124,9 +114,7 @@ async def publish_events( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" @@ -146,9 +134,7 @@ async def publish_events( # pylint: disable=inconsistent-return-statements params=_params, ) path_format_arguments = { - "topicHostname": self._serialize.url( - "topic_hostname", topic_hostname, "str", skip_quote=True - ), + "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) @@ -160,9 +146,7 @@ async def publish_events( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response if response.status_code not in [200]: - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if cls: @@ -196,9 +180,7 @@ async def publish_cloud_event_events( # pylint: disable=inconsistent-return-sta content_type: str = kwargs.pop( "content_type", - _headers.pop( - "Content-Type", "application/cloudevents-batch+json; charset=utf-8" - ), + _headers.pop("Content-Type", "application/cloudevents-batch+json; charset=utf-8"), ) cls: ClsType[None] = kwargs.pop("cls", None) @@ -212,9 +194,7 @@ async def publish_cloud_event_events( # pylint: disable=inconsistent-return-sta params=_params, ) path_format_arguments = { - "topicHostname": self._serialize.url( - "topic_hostname", topic_hostname, "str", skip_quote=True - ), + "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) @@ -226,9 +206,7 @@ async def publish_cloud_event_events( # pylint: disable=inconsistent-return-sta response = pipeline_response.http_response if response.status_code not in [200]: - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if cls: @@ -236,12 +214,7 @@ async def publish_cloud_event_events( # pylint: disable=inconsistent-return-sta @overload async def publish_custom_event_events( # pylint: disable=inconsistent-return-statements - self, - topic_hostname: str, - events: List[JSON], - *, - content_type: str = "application/json", - **kwargs: Any + self, topic_hostname: str, events: List[JSON], *, content_type: str = "application/json", **kwargs: Any ) -> None: """Publishes a batch of events to an Azure Event Grid topic. @@ -260,12 +233,7 @@ async def publish_custom_event_events( # pylint: disable=inconsistent-return-st @overload async def publish_custom_event_events( # pylint: disable=inconsistent-return-statements - self, - topic_hostname: str, - events: IO, - *, - content_type: str = "application/json", - **kwargs: Any + self, topic_hostname: str, events: IO, *, content_type: str = "application/json", **kwargs: Any ) -> None: """Publishes a batch of events to an Azure Event Grid topic. @@ -312,9 +280,7 @@ async def publish_custom_event_events( # pylint: disable=inconsistent-return-st _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[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" @@ -334,9 +300,7 @@ async def publish_custom_event_events( # pylint: disable=inconsistent-return-st params=_params, ) path_format_arguments = { - "topicHostname": self._serialize.url( - "topic_hostname", topic_hostname, "str", skip_quote=True - ), + "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) @@ -348,9 +312,7 @@ async def publish_custom_event_events( # pylint: disable=inconsistent-return-st response = pipeline_response.http_response if response.status_code not in [200]: - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if cls: diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/_patch.py index d400d2d124e2..f7dd32510333 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_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/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_patch.py index d400d2d124e2..f7dd32510333 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_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/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/_models.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/_models.py index 5b7573872822..1308cb0f76e1 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/_models.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/_models.py @@ -291,9 +291,7 @@ class SubscriptionValidationResponse(_serialization.Model): "validation_response": {"key": "validationResponse", "type": "str"}, } - def __init__( - self, *, validation_response: Optional[str] = None, **kwargs: Any - ) -> None: + def __init__(self, *, validation_response: Optional[str] = None, **kwargs: Any) -> None: """ :keyword validation_response: The validation response sent by the subscriber to Azure Event Grid to complete the validation of an event subscription. diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/_patch.py index d400d2d124e2..f7dd32510333 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_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/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_helpers.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_helpers.py index 0e7f08461e26..d28317777391 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_helpers.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_helpers.py @@ -27,6 +27,7 @@ if TYPE_CHECKING: from datetime import datetime + def generate_sas( endpoint: str, shared_access_key: str, @@ -55,16 +56,12 @@ def generate_sas( :caption: Generate a shared access signature. """ - full_endpoint = "{}?apiVersion={}".format( - endpoint, api_version - ) + full_endpoint = "{}?apiVersion={}".format(endpoint, api_version) encoded_resource = quote(full_endpoint, safe=constants.SAFE_ENCODE) encoded_expiration_utc = quote(str(expiration_date_utc), safe=constants.SAFE_ENCODE) unsigned_sas = "r={}&e={}".format(encoded_resource, encoded_expiration_utc) - signature = quote( - _generate_hmac(shared_access_key, unsigned_sas), safe=constants.SAFE_ENCODE - ) + signature = quote(_generate_hmac(shared_access_key, unsigned_sas), safe=constants.SAFE_ENCODE) signed_sas = "{}&s={}".format(unsigned_sas, signature) return signed_sas @@ -77,21 +74,15 @@ def _generate_hmac(key, message): return base64.b64encode(hmac_new) -def _get_authentication_policy( - credential, bearer_token_policy=BearerTokenCredentialPolicy -): +def _get_authentication_policy(credential, bearer_token_policy=BearerTokenCredentialPolicy): if credential is None: raise ValueError("Parameter 'self._credential' must not be None.") if hasattr(credential, "get_token"): return bearer_token_policy(credential, constants.DEFAULT_EVENTGRID_SCOPE) if isinstance(credential, AzureKeyCredential): - return AzureKeyCredentialPolicy( - credential=credential, name=constants.EVENTGRID_KEY_HEADER - ) + return AzureKeyCredentialPolicy(credential=credential, name=constants.EVENTGRID_KEY_HEADER) if isinstance(credential, AzureSasCredential): - return EventGridSasCredentialPolicy( - credential=credential, name=constants.EVENTGRID_TOKEN_HEADER - ) + return EventGridSasCredentialPolicy(credential=credential, name=constants.EVENTGRID_TOKEN_HEADER) raise ValueError( "The provided credential should be an instance of a TokenCredential, AzureSasCredential or AzureKeyCredential" ) @@ -147,10 +138,11 @@ def _cloud_event_to_generated(cloud_event, **kwargs): datacontenttype=cloud_event.datacontenttype, subject=cloud_event.subject, additional_properties=cloud_event.extensions, - **kwargs + **kwargs, ) -def _from_cncf_events(event): # pylint: disable=inconsistent-return-statements + +def _from_cncf_events(event): # pylint: disable=inconsistent-return-statements """This takes in a CNCF cloudevent and returns a dictionary. If cloud events library is not installed, the event is returned back. @@ -175,13 +167,13 @@ def _from_cncf_events(event): # pylint: disable=inconsistent-return-statements def _build_request(endpoint, content_type, events, *, channel_name=None, api_version=constants.DEFAULT_API_VERSION): serialize = Serializer() header_parameters: Dict[str, Any] = {} - header_parameters['Content-Type'] = serialize.header("content_type", content_type, 'str') + header_parameters["Content-Type"] = serialize.header("content_type", content_type, "str") if channel_name: header_parameters["aeg-channel-name"] = channel_name query_parameters: Dict[str, Any] = {} - query_parameters['api-version'] = serialize.query("api_version", api_version, 'str') + query_parameters["api-version"] = serialize.query("api_version", api_version, "str") body = serialize.body(events, "[object]") if body is None: @@ -190,8 +182,6 @@ def _build_request(endpoint, content_type, events, *, channel_name=None, api_ver data = json.dumps(body) header_parameters["Content-Length"] = str(len(data)) - request = HttpRequest( - method="POST", url=endpoint, headers=header_parameters, data=data - ) + request = HttpRequest(method="POST", url=endpoint, headers=header_parameters, data=data) request.format_parameters(query_parameters) return request diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_messaging_shared.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_messaging_shared.py index c37971d694ff..107ebc6d670d 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_messaging_shared.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_messaging_shared.py @@ -13,7 +13,8 @@ import json -def _get_json_content(obj): # pylint: disable=inconsistent-return-statements + +def _get_json_content(obj): # pylint: disable=inconsistent-return-statements """Event mixin to have methods that are common to different Event types like CloudEvent, EventGridEvent etc. @@ -38,7 +39,7 @@ def _get_json_content(obj): # pylint: disable=inconsistent-return-statements return json.loads(next(obj.body)) except ValueError as err: raise ValueError(msg) from err - except: # pylint: disable=bare-except + except: # pylint: disable=bare-except try: return json.loads(obj) except ValueError as err: diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_policies.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_policies.py index 6feda49c6f36..d4f2dcfd5638 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_policies.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_policies.py @@ -36,8 +36,7 @@ def on_request(self, request): return if ( - request.http_request.headers["content-type"] - == CloudEventDistributedTracingPolicy._CONTENT_TYPE + request.http_request.headers["content-type"] == CloudEventDistributedTracingPolicy._CONTENT_TYPE and traceparent is not None ): body = json.loads(request.http_request.body) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_publisher_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_publisher_client.py index 409644f893dc..75d3c8227055 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_publisher_client.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_publisher_client.py @@ -71,9 +71,7 @@ ListEventType = Union[List[CloudEvent], List[EventGridEvent], List[Dict]] -class EventGridPublisherClient( - object -): # pylint: disable=client-accepts-api-version-keyword +class EventGridPublisherClient(object): # pylint: disable=client-accepts-api-version-keyword """EventGridPublisherClient publishes events to an EventGrid topic or domain. It can be used to publish either an EventGridEvent, a CloudEvent or a Custom Schema. @@ -105,13 +103,13 @@ class EventGridPublisherClient( """ def __init__( - self, - endpoint: str, - credential: Union["AzureKeyCredential", "AzureSasCredential", "TokenCredential"], - *, - api_version: Optional[str] = None, - **kwargs: Any - ) -> None: + self, + endpoint: str, + credential: Union["AzureKeyCredential", "AzureSasCredential", "TokenCredential"], + *, + api_version: Optional[str] = None, + **kwargs: Any + ) -> None: self._endpoint = endpoint self._client = EventGridPublisherClientImpl( policies=EventGridPublisherClient._policies(credential, **kwargs), **kwargs @@ -141,9 +139,7 @@ def _policies(credential, **kwargs): return policies @distributed_trace - def send( - self, events: SendType, *, channel_name: Optional[str] = None, **kwargs: Any - ) -> None: + def send(self, events: SendType, *, channel_name: Optional[str] = None, **kwargs: Any) -> None: """Sends events to a topic or a domain specified during the client initialization. A single instance or a list of dictionaries, CloudEvents or EventGridEvents are accepted. @@ -216,9 +212,7 @@ def send( content_type = kwargs.pop("content_type", "application/json; charset=utf-8") if isinstance(events[0], CloudEvent) or _is_cloud_event(events[0]): try: - events = [ - _cloud_event_to_generated(e, **kwargs) for e in events - ] # pylint: disable=protected-access + events = [_cloud_event_to_generated(e, **kwargs) for e in events] # pylint: disable=protected-access except AttributeError: ## this is either a dictionary or a CNCF cloud event events = [_from_cncf_events(e) for e in events] @@ -228,8 +222,9 @@ def send( _eventgrid_data_typecheck(event) response = self._client.send_request( # pylint: disable=protected-access _build_request( - self._endpoint,content_type, events, channel_name=channel_name, api_version=self._api_version), - **kwargs + self._endpoint, content_type, events, channel_name=channel_name, api_version=self._api_version + ), + **kwargs ) error_map = { 401: ClientAuthenticationError, @@ -237,9 +232,7 @@ def send( 409: ResourceExistsError, } if response.status_code != 200: - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) def close(self): diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/_publisher_client_async.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/_publisher_client_async.py index 692451987fd7..ed70d6cdd6ad 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/_publisher_client_async.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/_publisher_client_async.py @@ -99,9 +99,7 @@ class EventGridPublisherClient: # pylint: disable=client-accepts-api-version-ke def __init__( self, endpoint: str, - credential: Union[ - "AsyncTokenCredential", AzureKeyCredential, AzureSasCredential - ], + credential: Union["AsyncTokenCredential", AzureKeyCredential, AzureSasCredential], *, api_version: Optional[str] = None, **kwargs: Any @@ -114,14 +112,9 @@ def __init__( @staticmethod def _policies( - credential: Union[ - AzureKeyCredential, AzureSasCredential, "AsyncTokenCredential" - ], - **kwargs: Any + credential: Union[AzureKeyCredential, AzureSasCredential, "AsyncTokenCredential"], **kwargs: Any ) -> List[Any]: - auth_policy = _get_authentication_policy( - credential, AsyncBearerTokenCredentialPolicy - ) + auth_policy = _get_authentication_policy(credential, AsyncBearerTokenCredentialPolicy) sdk_moniker = "eventgridpublisherclient/{}".format(VERSION) policies = [ RequestIdPolicy(**kwargs), @@ -141,9 +134,7 @@ def _policies( return policies @distributed_trace_async - async def send( - self, events: SendType, *, channel_name: Optional[str] = None, **kwargs: Any - ) -> None: + async def send(self, events: SendType, *, channel_name: Optional[str] = None, **kwargs: Any) -> None: """Sends events to a topic or a domain specified during the client initialization. A single instance or a list of dictionaries, CloudEvents or EventGridEvents are accepted. @@ -216,9 +207,7 @@ async def send( content_type = kwargs.pop("content_type", "application/json; charset=utf-8") if isinstance(events[0], CloudEvent) or _is_cloud_event(events[0]): try: - events = [ - _cloud_event_to_generated(e, **kwargs) for e in events - ] # pylint: disable=protected-access + events = [_cloud_event_to_generated(e, **kwargs) for e in events] # pylint: disable=protected-access except AttributeError: ## this is either a dictionary or a CNCF cloud event events = [_from_cncf_events(e) for e in events] @@ -227,8 +216,9 @@ async def send( for event in events: _eventgrid_data_typecheck(event) response = await self._client.send_request( # pylint: disable=protected-access - _build_request(self._endpoint, content_type, events, - channel_name=channel_name, api_version=self._api_version), + _build_request( + self._endpoint, content_type, events, channel_name=channel_name, api_version=self._api_version + ), **kwargs ) error_map = { @@ -237,9 +227,7 @@ async def send( 409: ResourceExistsError, } if response.status_code != 200: - map_error( - status_code=response.status_code, response=response, error_map=error_map - ) + map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) async def __aenter__(self) -> "EventGridPublisherClient": diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py index f10ebfb873b4..4b0f59f73e4c 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py @@ -13,7 +13,6 @@ import logging import base64 import re -import copy import typing import enum import email.utils @@ -324,17 +323,9 @@ def _get_type_alias_type(module_name: str, alias_name: str): def _get_model(module_name: str, model_name: str): - models = { - k: v - for k, v in sys.modules[module_name].__dict__.items() - if isinstance(v, type) - } + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} module_end = module_name.rsplit(".", 1)[0] - models.update({ - k: v - for k, v in sys.modules[module_end].__dict__.items() - if isinstance(v, type) - }) + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) if isinstance(model_name, str): model_name = model_name.split(".")[-1] if model_name not in models: @@ -347,7 +338,7 @@ def _get_model(module_name: str, model_name: str): class _MyMutableMapping(MutableMapping[str, typing.Any]): # pylint: disable=unsubscriptable-object def __init__(self, data: typing.Dict[str, typing.Any]) -> None: - self._data = copy.deepcopy(data) + self._data = data def __contains__(self, key: typing.Any) -> bool: return key in self._data @@ -386,16 +377,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: @@ -412,12 +400,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: @@ -550,7 +536,9 @@ def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: @classmethod def _get_discriminator(cls, exist_discriminators) -> typing.Optional[str]: for v in cls.__dict__.values(): - if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: # pylint: disable=protected-access + if ( + isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators + ): # pylint: disable=protected-access return v._rest_name # pylint: disable=protected-access return None @@ -560,9 +548,7 @@ def _deserialize(cls, data, exist_discriminators): return cls(data) discriminator = cls._get_discriminator(exist_discriminators) exist_discriminators.append(discriminator) - mapped_cls = cls.__mapping__.get( - data.get(discriminator), cls - ) # pyright: ignore # pylint: disable=no-member + mapped_cls = cls.__mapping__.get(data.get(discriminator), cls) # pyright: ignore # pylint: disable=no-member if mapped_cls == cls: return cls(data) return mapped_cls._deserialize(data, exist_discriminators) # pylint: disable=protected-access @@ -583,7 +569,9 @@ def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing. continue is_multipart_file_input = False try: - is_multipart_file_input = next(rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k)._is_multipart_file_input + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input except StopIteration: pass result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) @@ -594,18 +582,63 @@ def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: if v is None or isinstance(v, _Null): return None if isinstance(v, (list, tuple, set)): - return type(v)( - Model._as_dict_value(x, exclude_readonly=exclude_readonly) - for x in v - ) + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) if isinstance(v, dict): - return { - dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) - for dk, dv in v.items() - } + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: typing.Dict[typing.Any, typing.Any], +): + if obj is None: + return obj + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: typing.List[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, R0912 annotation: typing.Any, module: typing.Optional[str], @@ -633,11 +666,6 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, if rf: rf._is_model = True - def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): - if _is_model(obj): - return obj - return _deserialize(model_deserializer, obj) - return functools.partial(_deserialize_model, annotation) # pyright: ignore except Exception: pass @@ -656,11 +684,6 @@ def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore ) - def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): - if obj is None: - return obj - return _deserialize_with_callable(if_obj_deserializer, obj) - return functools.partial(_deserialize_with_optional, if_obj_deserializer) except AttributeError: pass @@ -670,18 +693,10 @@ def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Calla deserializers = [ _get_deserialize_callable_from_annotation(arg, module, rf) for arg in sorted( - annotation.__args__, key=lambda x: hasattr(x, "__name__") and x.__name__ == "str" # pyright: ignore - ) + annotation.__args__, key=lambda x: hasattr(x, "__name__") and x.__name__ == "str" # pyright: ignore + ) ] - def _deserialize_with_union(deserializers, obj): - for deserializer in deserializers: - try: - return _deserialize(deserializer, obj) - except DeserializationError: - pass - raise DeserializationError() - return functools.partial(_deserialize_with_union, deserializers) try: @@ -690,20 +705,10 @@ def _deserialize_with_union(deserializers, obj): annotation.__args__[1], module, rf # pyright: ignore ) - def _deserialize_dict( - value_deserializer: typing.Optional[typing.Callable], - obj: typing.Dict[typing.Any, typing.Any], - ): - if obj is None: - return obj - return { - k: _deserialize(value_deserializer, v, module) - for k, v in obj.items() - } - return functools.partial( _deserialize_dict, value_deserializer, + module, ) except (AttributeError, IndexError): pass @@ -711,34 +716,16 @@ def _deserialize_dict( if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore if len(annotation.__args__) > 1: # pyright: ignore - def _deserialize_multiple_sequence( - entry_deserializers: typing.List[typing.Optional[typing.Callable]], - obj, - ): - if obj is None: - return obj - return type(obj)( - _deserialize(deserializer, entry, module) - for entry, deserializer in zip(obj, entry_deserializers) - ) - entry_deserializers = [ - _get_deserialize_callable_from_annotation(dt, module, rf) for dt in annotation.__args__ # pyright: ignore + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore ] - return functools.partial(_deserialize_multiple_sequence, entry_deserializers) + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) deserializer = _get_deserialize_callable_from_annotation( annotation.__args__[0], module, rf # pyright: ignore ) - def _deserialize_sequence( - deserializer: typing.Optional[typing.Callable], - obj, - ): - if obj is None: - return obj - return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) - - return functools.partial(_deserialize_sequence, deserializer) + return functools.partial(_deserialize_sequence, deserializer, module) except (TypeError, IndexError, AttributeError, SyntaxError): pass @@ -870,7 +857,14 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, ) -> typing.Any: - return _RestField(name=name, type=type, visibility=visibility, default=default, format=format, is_multipart_file_input=is_multipart_file_input) + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + ) def rest_discriminator( diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py index 5d63b0e4eaa0..51cf0e7ac905 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py @@ -11,8 +11,9 @@ from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'EventGridClientOperationsMixin', + "EventGridClientOperationsMixin", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py index a2706730432d..66228ba73e21 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py @@ -9,9 +9,16 @@ from io import IOBase import json import sys -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error +from typing import Any, Callable, Dict, IO, List, Optional, Type, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace @@ -27,8 +34,8 @@ from collections.abc import MutableMapping else: from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -T = TypeVar('T') +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() @@ -36,73 +43,59 @@ def build_event_grid_publish_cloud_event_request( # pylint: disable=name-too-long - topic_name: str, - **kwargs: Any + topic_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop('content_type') - api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-10-01-preview")) - accept = _headers.pop('Accept', "application/json") + content_type: str = kwargs.pop("content_type") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01-preview")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/topics/{topicName}:publish" path_format_arguments = { - "topicName": _SERIALIZER.url("topic_name", topic_name, 'str'), + "topicName": _SERIALIZER.url("topic_name", topic_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _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 - ) + _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) def build_event_grid_publish_cloud_events_request( # pylint: disable=name-too-long - topic_name: str, - **kwargs: Any + topic_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop('content_type') - api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-10-01-preview")) - accept = _headers.pop('Accept', "application/json") + content_type: str = kwargs.pop("content_type") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01-preview")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/topics/{topicName}:publish" path_format_arguments = { - "topicName": _SERIALIZER.url("topic_name", topic_name, 'str'), + "topicName": _SERIALIZER.url("topic_name", topic_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _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 - ) + _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) def build_event_grid_receive_cloud_events_request( # pylint: disable=name-too-long @@ -116,73 +109,59 @@ def build_event_grid_receive_cloud_events_request( # pylint: disable=name-too-l _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-preview")) - accept = _headers.pop('Accept', "application/json") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01-preview")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:receive" path_format_arguments = { - "topicName": _SERIALIZER.url("topic_name", topic_name, 'str'), - "eventSubscriptionName": _SERIALIZER.url("event_subscription_name", event_subscription_name, 'str'), + "topicName": _SERIALIZER.url("topic_name", topic_name, "str"), + "eventSubscriptionName": _SERIALIZER.url("event_subscription_name", event_subscription_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if max_events is not None: - _params['maxEvents'] = _SERIALIZER.query("max_events", max_events, 'int') + _params["maxEvents"] = _SERIALIZER.query("max_events", max_events, "int") if max_wait_time is not None: - _params['maxWaitTime'] = _SERIALIZER.query("max_wait_time", max_wait_time, 'int') + _params["maxWaitTime"] = _SERIALIZER.query("max_wait_time", max_wait_time, "int") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_event_grid_acknowledge_cloud_events_request( # pylint: disable=name-too-long - topic_name: str, - event_subscription_name: str, - **kwargs: Any + topic_name: str, event_subscription_name: str, **kwargs: Any ) -> HttpRequest: _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-preview")) - accept = _headers.pop('Accept', "application/json") + 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-preview")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:acknowledge" path_format_arguments = { - "topicName": _SERIALIZER.url("topic_name", topic_name, 'str'), - "eventSubscriptionName": _SERIALIZER.url("event_subscription_name", event_subscription_name, 'str'), + "topicName": _SERIALIZER.url("topic_name", topic_name, "str"), + "eventSubscriptionName": _SERIALIZER.url("event_subscription_name", event_subscription_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + _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) def build_event_grid_release_cloud_events_request( # pylint: disable=name-too-long @@ -195,123 +174,99 @@ def build_event_grid_release_cloud_events_request( # pylint: disable=name-too-l _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-preview")) - accept = _headers.pop('Accept', "application/json") + 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-preview")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:release" path_format_arguments = { - "topicName": _SERIALIZER.url("topic_name", topic_name, 'str'), - "eventSubscriptionName": _SERIALIZER.url("event_subscription_name", event_subscription_name, 'str'), + "topicName": _SERIALIZER.url("topic_name", topic_name, "str"), + "eventSubscriptionName": _SERIALIZER.url("event_subscription_name", event_subscription_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if release_delay_in_seconds is not None: - _params['releaseDelayInSeconds'] = _SERIALIZER.query("release_delay_in_seconds", release_delay_in_seconds, 'int') + _params["releaseDelayInSeconds"] = _SERIALIZER.query( + "release_delay_in_seconds", release_delay_in_seconds, "int" + ) # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + _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) def build_event_grid_reject_cloud_events_request( # pylint: disable=name-too-long - topic_name: str, - event_subscription_name: str, - **kwargs: Any + topic_name: str, event_subscription_name: str, **kwargs: Any ) -> HttpRequest: _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-preview")) - accept = _headers.pop('Accept', "application/json") + 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-preview")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:reject" path_format_arguments = { - "topicName": _SERIALIZER.url("topic_name", topic_name, 'str'), - "eventSubscriptionName": _SERIALIZER.url("event_subscription_name", event_subscription_name, 'str'), + "topicName": _SERIALIZER.url("topic_name", topic_name, "str"), + "eventSubscriptionName": _SERIALIZER.url("event_subscription_name", event_subscription_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + _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) def build_event_grid_renew_cloud_event_locks_request( # pylint: disable=name-too-long - topic_name: str, - event_subscription_name: str, - **kwargs: Any + topic_name: str, event_subscription_name: str, **kwargs: Any ) -> HttpRequest: _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-preview")) - accept = _headers.pop('Accept', "application/json") + 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-preview")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:renewLock" path_format_arguments = { - "topicName": _SERIALIZER.url("topic_name", topic_name, 'str'), - "eventSubscriptionName": _SERIALIZER.url("event_subscription_name", event_subscription_name, 'str'), + "topicName": _SERIALIZER.url("topic_name", topic_name, "str"), + "eventSubscriptionName": _SERIALIZER.url("event_subscription_name", event_subscription_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + _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) -class EventGridClientOperationsMixin( - EventGridClientMixinABC -): + +class EventGridClientOperationsMixin(EventGridClientMixinABC): @distributed_trace def _publish_cloud_event( # pylint: disable=protected-access - self, - topic_name: str, - event: _models._models.CloudEvent, - **kwargs: Any + self, topic_name: str, event: _models._models.CloudEvent, **kwargs: Any ) -> _models._models.PublishResult: # pylint: disable=line-too-long """Publish Single Cloud Event to namespace topic. In case of success, the server responds with an @@ -352,20 +307,23 @@ def _publish_cloud_event( # pylint: disable=protected-access generated, in RFC3339 format. } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop('content_type', _headers.pop('content-type', "application/cloudevents+json; charset=utf-8")) - cls: ClsType[_models._models.PublishResult] = kwargs.pop( # pylint: disable=protected-access - 'cls', None + content_type: str = kwargs.pop( + "content_type", _headers.pop("content-type", "application/cloudevents+json; charset=utf-8") ) + cls: ClsType[_models._models.PublishResult] = kwargs.pop("cls", None) # pylint: disable=protected-access - _content = event + _content = json.dumps(event, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_event_grid_publish_cloud_event_request( topic_name=topic_name, @@ -376,22 +334,20 @@ def _publish_cloud_event( # pylint: disable=protected-access 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 = kwargs.pop("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 if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -399,23 +355,17 @@ def _publish_cloud_event( # pylint: disable=protected-access deserialized = response.iter_bytes() else: deserialized = _deserialize( - _models._models.PublishResult, # pylint: disable=protected-access - response.json() + _models._models.PublishResult, response.json() # pylint: disable=protected-access ) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @distributed_trace def _publish_cloud_events( # pylint: disable=protected-access - self, - topic_name: str, - events: List[_models._models.CloudEvent], - **kwargs: Any + self, topic_name: str, events: List[_models._models.CloudEvent], **kwargs: Any ) -> _models._models.PublishResult: # pylint: disable=line-too-long """Publish Batch Cloud Event to namespace topic. In case of success, the server responds with an @@ -460,20 +410,23 @@ def _publish_cloud_events( # pylint: disable=protected-access } ] """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop('content_type', _headers.pop('content-type', "application/cloudevents-batch+json; charset=utf-8")) - cls: ClsType[_models._models.PublishResult] = kwargs.pop( # pylint: disable=protected-access - 'cls', None + content_type: str = kwargs.pop( + "content_type", _headers.pop("content-type", "application/cloudevents-batch+json; charset=utf-8") ) + cls: ClsType[_models._models.PublishResult] = kwargs.pop("cls", None) # pylint: disable=protected-access - _content = events + _content = json.dumps(events, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_event_grid_publish_cloud_events_request( topic_name=topic_name, @@ -484,22 +437,20 @@ def _publish_cloud_events( # pylint: disable=protected-access 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 = kwargs.pop("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 if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -507,17 +458,14 @@ def _publish_cloud_events( # pylint: disable=protected-access deserialized = response.iter_bytes() else: deserialized = _deserialize( - _models._models.PublishResult, # pylint: disable=protected-access - response.json() + _models._models.PublishResult, response.json() # pylint: disable=protected-access ) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @distributed_trace def _receive_cloud_events( # pylint: disable=protected-access self, @@ -591,19 +539,19 @@ def _receive_cloud_events( # pylint: disable=protected-access ] } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.ReceiveResult] = kwargs.pop( # pylint: disable=protected-access - 'cls', None - ) + cls: ClsType[_models._models.ReceiveResult] = kwargs.pop("cls", None) # pylint: disable=protected-access - _request = build_event_grid_receive_cloud_events_request( topic_name=topic_name, event_subscription_name=event_subscription_name, @@ -614,22 +562,20 @@ def _receive_cloud_events( # pylint: disable=protected-access 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 = kwargs.pop("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 if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -637,17 +583,14 @@ def _receive_cloud_events( # pylint: disable=protected-access deserialized = response.iter_bytes() else: deserialized = _deserialize( - _models._models.ReceiveResult, # pylint: disable=protected-access - response.json() + _models._models.ReceiveResult, response.json() # pylint: disable=protected-access ) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @overload def _acknowledge_cloud_events( # pylint: disable=protected-access self, @@ -657,8 +600,7 @@ def _acknowledge_cloud_events( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AcknowledgeResult: - ... + ) -> _models.AcknowledgeResult: ... @overload def _acknowledge_cloud_events( self, @@ -668,8 +610,7 @@ def _acknowledge_cloud_events( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AcknowledgeResult: - ... + ) -> _models.AcknowledgeResult: ... @overload def _acknowledge_cloud_events( self, @@ -679,8 +620,7 @@ def _acknowledge_cloud_events( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AcknowledgeResult: - ... + ) -> _models.AcknowledgeResult: ... @distributed_trace def _acknowledge_cloud_events( @@ -745,18 +685,19 @@ def _acknowledge_cloud_events( ] } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _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.AcknowledgeResult] = kwargs.pop( - 'cls', None - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AcknowledgeResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -775,43 +716,36 @@ def _acknowledge_cloud_events( 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 = kwargs.pop("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 if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models.AcknowledgeResult, - response.json() - ) + deserialized = _deserialize(_models.AcknowledgeResult, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @overload @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, ) # pylint: disable=protected-access def _release_cloud_events( # pylint: disable=protected-access self, @@ -822,11 +756,10 @@ def _release_cloud_events( # pylint: disable=protected-access release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.ReleaseResult: - ... + ) -> _models.ReleaseResult: ... @overload @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, ) def _release_cloud_events( self, @@ -837,11 +770,10 @@ def _release_cloud_events( release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.ReleaseResult: - ... + ) -> _models.ReleaseResult: ... @overload @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, ) def _release_cloud_events( self, @@ -852,12 +784,11 @@ def _release_cloud_events( release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.ReleaseResult: - ... + ) -> _models.ReleaseResult: ... @distributed_trace @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, ) def _release_cloud_events( self, @@ -925,18 +856,19 @@ def _release_cloud_events( ] } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _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.ReleaseResult] = kwargs.pop( - 'cls', None - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ReleaseResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -956,40 +888,33 @@ def _release_cloud_events( 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 = kwargs.pop("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 if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models.ReleaseResult, - response.json() - ) + deserialized = _deserialize(_models.ReleaseResult, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @overload def _reject_cloud_events( # pylint: disable=protected-access self, @@ -999,8 +924,7 @@ def _reject_cloud_events( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RejectResult: - ... + ) -> _models.RejectResult: ... @overload def _reject_cloud_events( self, @@ -1010,8 +934,7 @@ def _reject_cloud_events( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RejectResult: - ... + ) -> _models.RejectResult: ... @overload def _reject_cloud_events( self, @@ -1021,8 +944,7 @@ def _reject_cloud_events( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RejectResult: - ... + ) -> _models.RejectResult: ... @distributed_trace def _reject_cloud_events( @@ -1086,18 +1008,19 @@ def _reject_cloud_events( ] } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _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.RejectResult] = kwargs.pop( - 'cls', None - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RejectResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -1116,43 +1039,37 @@ def _reject_cloud_events( 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 = kwargs.pop("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 if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models.RejectResult, - response.json() - ) + deserialized = _deserialize(_models.RejectResult, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @overload @api_version_validation( method_added_on="2023-10-01-preview", + params_added_on={"2023-10-01-preview": ["accept"]}, ) # pylint: disable=protected-access def _renew_cloud_event_locks( # pylint: disable=protected-access self, @@ -1162,11 +1079,11 @@ def _renew_cloud_event_locks( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RenewCloudEventLocksResult: - ... + ) -> _models.RenewCloudEventLocksResult: ... @overload @api_version_validation( method_added_on="2023-10-01-preview", + params_added_on={"2023-10-01-preview": ["accept"]}, ) def _renew_cloud_event_locks( self, @@ -1176,11 +1093,11 @@ def _renew_cloud_event_locks( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RenewCloudEventLocksResult: - ... + ) -> _models.RenewCloudEventLocksResult: ... @overload @api_version_validation( method_added_on="2023-10-01-preview", + params_added_on={"2023-10-01-preview": ["accept"]}, ) def _renew_cloud_event_locks( self, @@ -1190,12 +1107,12 @@ def _renew_cloud_event_locks( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RenewCloudEventLocksResult: - ... + ) -> _models.RenewCloudEventLocksResult: ... @distributed_trace @api_version_validation( method_added_on="2023-10-01-preview", + params_added_on={"2023-10-01-preview": ["accept"]}, ) def _renew_cloud_event_locks( self, @@ -1260,18 +1177,19 @@ def _renew_cloud_event_locks( ] } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _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.RenewCloudEventLocksResult] = kwargs.pop( - 'cls', None - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RenewCloudEventLocksResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -1290,36 +1208,29 @@ def _renew_cloud_event_locks( 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 = kwargs.pop("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 if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models.RenewCloudEventLocksResult, - response.json() - ) + deserialized = _deserialize(_models.RenewCloudEventLocksResult, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py index f1e16a2909ef..4cb6fb5264fb 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py @@ -12,7 +12,6 @@ Any, Callable, Dict, - IO, List, Optional, TypeVar, @@ -22,12 +21,8 @@ ) from azure.core.exceptions import ( - ClientAuthenticationError, HttpResponseError, - ResourceExistsError, ResourceNotFoundError, - ResourceNotModifiedError, - map_error, ) from azure.core.messaging import CloudEvent from azure.core.tracing.decorator import distributed_trace @@ -36,18 +31,23 @@ from azure.core.utils import case_insensitive_dict from ._operations import EventGridClientOperationsMixin as OperationsMixin -from .._model_base import _deserialize from ..models._patch import ( ReceiveResult, ReceiveDetails, ) from .. import models as _models -from ..models._models import AcknowledgeOptions, ReleaseOptions, RejectOptions, RenewLockOptions +from ..models._models import ( + AcknowledgeOptions, + ReleaseOptions, + RejectOptions, + RenewLockOptions, + CloudEvent as InternalCloudEvent, +) from .._validation import api_version_validation from .._legacy import EventGridEvent -from .._legacy._helpers import _from_cncf_events, _is_eventgrid_event +from .._legacy._helpers import _from_cncf_events, _is_eventgrid_event, _is_cloud_event from .._serialization import Serializer if sys.version_info >= (3, 9): @@ -57,9 +57,7 @@ JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object 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 @@ -98,9 +96,7 @@ def use_standard_only(func): @wraps(func) def wrapper(self, *args, **kwargs): if self._level == "Basic": # pylint: disable=protected-access - raise ValueError( - "The basic client is not supported for this operation." - ) + raise ValueError("The basic client is not supported for this operation.") return func(self, *args, **kwargs) return wrapper @@ -119,8 +115,7 @@ def wrapper(self, *args: Any, **kwargs: Any) -> T: arg: level for level, arguments in kwargs_mapping.items() for arg in arguments - if arg - in kwargs.keys() # pylint: disable=consider-iterating-dictionary + if arg in kwargs.keys() # pylint: disable=consider-iterating-dictionary and selected_client_level != level } @@ -154,8 +149,8 @@ def send( ) -> None: """Send events to the Event Grid Basic Service. - :param event: The event to send. - :type event: CloudEvent or List[CloudEvent] or EventGridEvent or List[EventGridEvent] + :param events: The event to send. + :type events: CloudEvent or List[CloudEvent] or EventGridEvent or List[EventGridEvent] or Dict[str, Any] or List[Dict[str, Any]] or CNCFCloudEvent or List[CNCFCloudEvent] :keyword channel_name: The name of the channel to send the event to. :paramtype channel_name: str or None @@ -182,8 +177,8 @@ def send( :param topic_name: The name of the topic to send the event to. :type topic_name: str - :param event: The event to send. - :type event: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] + :param events: The event to send. + :type events: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] :keyword binary_mode: Whether to send the event in binary mode. If not specified, the default value is False. :paramtype binary_mode: bool @@ -203,13 +198,13 @@ def send( } ) @distributed_trace - def send(self, *args, **kwargs) -> None: + def send(self, *args, **kwargs) -> None: # pylint: disable=docstring-should-be-keyword, docstring-missing-param """Send events to the Event Grid Service. :param topic_name: The name of the topic to send the event to. :type topic_name: str - :param event: The event to send. - :type event: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] + :param events: The event to send. + :type events: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] or CNCFCloudEvent or List[CNCFCloudEvent] or EventGridEvent or List[EventGridEvent] :keyword binary_mode: Whether to send the event in binary mode. If not specified, the default value is False. @@ -260,9 +255,7 @@ def send(self, *args, **kwargs) -> None: elif len(args) == 1: if events is not None: if topic_name is not None: - raise ValueError( - "topic_name is already passed as a keyword argument." - ) + raise ValueError("topic_name is already passed as a keyword argument.") topic_name = args[0] else: events = args[0] @@ -275,7 +268,6 @@ def send(self, *args, **kwargs) -> None: self._send_binary(topic_name, events, **kwargs) else: # If not binary_mode send whatever event is passed - # If a cloud event dict, convert to CloudEvent for serializing try: if isinstance(events, dict): @@ -286,9 +278,7 @@ def send(self, *args, **kwargs) -> None: pass if self._level == "Standard": - kwargs["content_type"] = kwargs.get( - "content_type", "application/cloudevents-batch+json; charset=utf-8" - ) + kwargs["content_type"] = kwargs.get("content_type", "application/cloudevents-batch+json; charset=utf-8") if not isinstance(events, list): events = [events] @@ -307,29 +297,39 @@ def send(self, *args, **kwargs) -> None: self._http_response_error_handler(exception, "Basic") raise exception - def _send_binary(self, topic_name, events, **kwargs): + def _send_binary(self, topic_name, event, **kwargs): # If data is passed as a dictionary, make sure it is a CloudEvent + if isinstance(event, list): + raise TypeError("Binary mode is only supported for type CloudEvent.") # pylint: disable=raise-missing-from try: - if isinstance(events, dict): - events = CloudEvent.from_dict(events) + if not isinstance(event, CloudEvent): + try: + # Convert to CloudEvent if it is a dictionary + event = CloudEvent.from_dict(event) + except AttributeError: + # Convert to CloudEvent if it is a CNCF CloudEvent dict + event = CloudEvent.from_dict(_from_cncf_events(event)) except AttributeError: - raise TypeError( # pylint: disable=raise-missing-from - "Binary mode is only supported for type CloudEvent." - ) + raise TypeError("Binary mode is only supported for type CloudEvent.") # pylint: disable=raise-missing-from # If data is a cloud event, convert to an HTTP Request in binary mode # Content type becomes the data content type - if isinstance(events, CloudEvent): - self._publish(topic_name, events, self._config.api_version, **kwargs) + if isinstance(event, CloudEvent): + http_request = _to_http_request( + topic_name=topic_name, + api_version=self._config.api_version, + event=event, + **kwargs, + ) else: raise TypeError("Binary mode is only supported for type CloudEvent.") + self.send_request(http_request, **kwargs) + def _http_response_error_handler(self, exception, level): if isinstance(exception, HttpResponseError): if exception.status_code == 400: - raise HttpResponseError( - "Invalid event data. Please check the data and try again." - ) from exception + raise HttpResponseError("Invalid event data. Please check the data and try again.") from exception if exception.status_code == 404: raise ResourceNotFoundError( "Resource not found. " @@ -338,82 +338,6 @@ def _http_response_error_handler(self, exception, level): ) from exception raise exception - def _publish( - self, - topic_name: str, - event: Any, - api_version: str, - **kwargs: Any, - ) -> None: - - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models._models.PublishResult] = kwargs.pop( - "cls", None - ) # pylint: disable=protected-access - - content_type = kwargs.pop( # pylint: disable=unused-variable - "content_type", None - ) - # Given that we know the cloud event is binary mode, we can convert it to a HTTP request - http_request = _to_http_request( - topic_name=topic_name, - api_version=api_version, - headers=_headers, - params=_params, - event=event, - **kwargs, - ) - - _stream = kwargs.pop("stream", False) - - path_format_arguments = { - "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 - ) - - pipeline_response: PipelineResponse = ( - self._client._pipeline.run( # pylint: disable=protected-access - http_request, stream=_stream, **kwargs - ) - ) - - response = pipeline_response.http_response - - 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 - ) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize( - _models._models.PublishResult, # pylint: disable=protected-access - response.json(), - ) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - @use_standard_only @distributed_trace def receive_cloud_events( @@ -622,12 +546,12 @@ def _to_http_request(topic_name: str, **kwargs: Any) -> HttpRequest: _content = event.data else: raise TypeError( - "CloudEvent data must be bytes when in binary mode." + "CloudEvent data must be bytes when in binary mode. " "Did you forget to call `json.dumps()` and/or `encode()` on CloudEvent data?" ) except AttributeError as exc: raise TypeError( - "Binary mode is not supported for batch CloudEvents." + "Binary mode is not supported for batch CloudEvents. " " Set `binary_mode` to False when passing in a batch of CloudEvents." ) from exc @@ -636,9 +560,7 @@ def _to_http_request(topic_name: str, **kwargs: Any) -> HttpRequest: raise ValueError("CloudEvent datacontenttype must be set when in binary mode.") content_type: str = event.datacontenttype - api_version: str = kwargs.pop( - "api_version", _params.pop("api-version", "2023-10-01-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -660,24 +582,18 @@ def _to_http_request(topic_name: str, **kwargs: Any) -> HttpRequest: _headers["ce-source"] = _SERIALIZER.header("ce-source", event.source, "str") _headers["ce-type"] = _SERIALIZER.header("ce-type", event.type, "str") if event.specversion: - _headers["ce-specversion"] = _SERIALIZER.header( - "ce-specversion", event.specversion, "str" - ) + _headers["ce-specversion"] = _SERIALIZER.header("ce-specversion", event.specversion, "str") if event.id: _headers["ce-id"] = _SERIALIZER.header("ce-id", event.id, "str") if event.time: _headers["ce-time"] = _SERIALIZER.header("ce-time", event.time, "str") if event.dataschema: - _headers["ce-dataschema"] = _SERIALIZER.header( - "ce-dataschema", event.dataschema, "str" - ) + _headers["ce-dataschema"] = _SERIALIZER.header("ce-dataschema", event.dataschema, "str") if event.subject: _headers["ce-subject"] = _SERIALIZER.header("ce-subject", event.subject, "str") if event.extensions: for extension, value in event.extensions.items(): - _headers[f"ce-{extension}"] = _SERIALIZER.header( - "ce-extensions", value, "str" - ) + _headers[f"ce-{extension}"] = _SERIALIZER.header("ce-extensions", value, "str") return HttpRequest( method="POST", @@ -690,56 +606,43 @@ def _to_http_request(topic_name: str, **kwargs: Any) -> HttpRequest: def _serialize_events(events): - if isinstance(events[0], CloudEvent): - internal_body_list = [] - for item in events: - internal_body_list.append(_serialize_cloud_event(item)) - return json.dumps(internal_body_list) - try: - serialize = Serializer() - body = serialize.body(events, "[object]") - if body is None: - data = None - else: - data = json.dumps(body) - - return data - except AttributeError: - return events - - -def _serialize_cloud_event(event): - try: - data = {} - # CloudEvent required fields but validate they are not set to None - if event.type: - data["type"] = _SERIALIZER.body(event.type, "str") - if event.specversion: - data["specversion"] = _SERIALIZER.body(event.specversion, "str") - if event.source: - data["source"] = _SERIALIZER.body(event.source, "str") - if event.id: - data["id"] = _SERIALIZER.body(event.id, "str") - - # Check if data is bytes and serialize to base64 - if isinstance(event.data, bytes): - data["data_base64"] = _SERIALIZER.serialize_bytearray(event.data) - elif event.data: - data["data"] = _SERIALIZER.body(event.data, "str") - - if event.subject: - data["subject"] = _SERIALIZER.body(event.subject, "str") - if event.time: - data["time"] = _SERIALIZER.body(event.time, "str") - if event.datacontenttype: - data["datacontenttype"] = _SERIALIZER.body(event.datacontenttype, "str") - if event.extensions: - for extension, value in event.extensions.items(): - data[extension] = _SERIALIZER.body(value, "str") - - return data - except AttributeError: - return [_from_cncf_events(e) for e in event] + if isinstance(events[0], CloudEvent) or _is_cloud_event(events[0]): + # Try to serialize cloud events + try: + internal_body_list = [] + for item in events: + internal_body_list.append(_serialize_cloud_event(item)) + return internal_body_list + except AttributeError: + # Try to serialize CNCF Cloud Events + return [_from_cncf_events(e) for e in events] + else: + # Does not conform to format, send as is + return json.dumps(events) + + +def _serialize_cloud_event(cloud_event): + data_kwargs = {} + + if isinstance(cloud_event.data, bytes): + data_kwargs["data_base64"] = cloud_event.data + else: + data_kwargs["data"] = cloud_event.data + + internal_event = InternalCloudEvent( + id=cloud_event.id, + source=cloud_event.source, + type=cloud_event.type, + specversion=cloud_event.specversion, + time=cloud_event.time, + dataschema=cloud_event.dataschema, + datacontenttype=cloud_event.datacontenttype, + subject=cloud_event.subject, + **data_kwargs, + ) + if cloud_event.extensions: + internal_event.update(cloud_event.extensions) + return internal_event __all__: List[str] = [ diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_patch.py index cadec781c7cb..c4075dd2d3e3 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_patch.py @@ -47,8 +47,8 @@ class EventGridClient(InternalEventGridClient): :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential or ~azure.core.credentials.TokenCredential :keyword api_version: The API version to use for this operation. Default value for namespaces is - "2023-10-01-preview". Default value for basic is "2018-01-01". Note that overriding this default value may result in unsupported - behavior. + "2023-10-01-preview". Default value for basic is "2018-01-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str or None :keyword level: The level of client to use. Known values are `Standard` and `Basic`. Default value is `Standard`. @@ -78,9 +78,7 @@ def __init__( self._send = self._client.send # type:ignore[attr-defined] elif level == ClientLevel.STANDARD: if isinstance(credential, AzureSasCredential): - raise TypeError( - "SAS token authentication is not supported for the standard client." - ) + raise TypeError("SAS token authentication is not supported for the standard client.") super().__init__( endpoint=endpoint, credential=credential, @@ -90,9 +88,7 @@ def __init__( self._send = self._publish_cloud_events else: - raise ValueError( - "Unknown client level. Known values are `Standard` and `Basic`." - ) + raise ValueError("Unknown client level. Known values are `Standard` and `Basic`.") self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py index 75e26c415d2c..2f781d740827 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py @@ -349,9 +349,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. @@ -540,7 +538,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, type]]=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -748,7 +746,7 @@ def query(self, name, data, data_type, **kwargs): # Treat the list aside, since we don't want to encode the div separator if data_type.startswith("["): internal_data_type = data_type[1:-1] - do_quote = not kwargs.get('skip_quote', False) + do_quote = not kwargs.get("skip_quote", False) return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization @@ -907,12 +905,8 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): raise serialized.append(None) - if kwargs.get('do_quote', False): - serialized = [ - '' if s is None else quote(str(s), safe='') - for s - in serialized - ] + if kwargs.get("do_quote", False): + 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] @@ -1369,7 +1363,7 @@ class Deserializer(object): 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]]=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_validation.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_validation.py index 102dea177140..752b2822f9d3 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_validation.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_validation.py @@ -6,6 +6,7 @@ # -------------------------------------------------------------------------- import functools + def api_version_validation(**kwargs): params_added_on = kwargs.pop("params_added_on", {}) method_added_on = kwargs.pop("method_added_on", "") @@ -33,11 +34,17 @@ def wrapper(*args, **kwargs): if parameter in kwargs and api_version > client_api_version } if unsupported: - raise ValueError("".join([ - f"'{param}' is not available in API version {client_api_version}. " - f"Use service API version {version} or newer.\n" - for param, version in unsupported.items() - ])) + raise ValueError( + "".join( + [ + f"'{param}' is not available in API version {client_api_version}. " + f"Use service API version {version} or newer.\n" + for param, version in unsupported.items() + ] + ) + ) return func(*args, **kwargs) + return wrapper + return decorator diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_vendor.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_vendor.py index 682fa0a3f71f..59d8335b5c63 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_vendor.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_vendor.py @@ -16,12 +16,11 @@ from ._serialization import Deserializer, Serializer -class EventGridClientMixinABC( - ABC -): + +class EventGridClientMixinABC(ABC): """DO NOT use this class. It is for internal typing use only.""" + _client: "PipelineClient" _config: EventGridClientConfiguration _serialize: "Serializer" _deserialize: "Deserializer" - diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_version.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_version.py index 4997406f0693..b578abb501c0 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_version.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "4.20.0b1" +VERSION = "4.20.1b1" diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py index 149d797cbe4e..906ab81c5705 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py @@ -14,8 +14,9 @@ except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'EventGridClient', + "EventGridClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py index 064da9dbacfb..60d39e9d6ade 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py @@ -22,13 +22,14 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential + class EventGridClient(EventGridClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword """Azure Messaging EventGrid Client. :param endpoint: The host name of the namespace, e.g. namespaceName1.westus-1.eventgrid.azure.net. Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Is either a + :param credential: Credential used to authenticate requests to the service. Is either a AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential @@ -39,28 +40,35 @@ class EventGridClient(EventGridClientOperationsMixin): # pylint: disable=client """ def __init__( - self, - endpoint: str, - credential: Union[AzureKeyCredential, "AsyncTokenCredential"], - **kwargs: Any + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: - _endpoint = '{endpoint}' + _endpoint = "{endpoint}" self._config = EventGridClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) - _policies = kwargs.pop('policies', None) + _policies = kwargs.pop("policies", None) if _policies is None: - _policies = [policies.RequestIdPolicy(**kwargs),self._config.headers_policy,self._config.user_agent_policy,self._config.proxy_policy,policies.ContentDecodePolicy(**kwargs),self._config.redirect_policy,self._config.retry_policy,self._config.authentication_policy,self._config.custom_hook_policy,self._config.logging_policy,policies.DistributedTracingPolicy(**kwargs),policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None,self._config.http_logging_policy] + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - def send_request( - self, - request: HttpRequest, *, stream: bool = False, - **kwargs: Any + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -81,7 +89,7 @@ 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) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_configuration.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_configuration.py index 847e9019f9dc..4e99a4348f83 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_configuration.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_configuration.py @@ -18,7 +18,7 @@ from azure.core.credentials_async import AsyncTokenCredential -class EventGridClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class EventGridClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for EventGridClient. Note that all parameters used to create this instance are saved as instance @@ -27,7 +27,7 @@ class EventGridClientConfiguration: # pylint: disable=too-many-instance-attri :param endpoint: The host name of the namespace, e.g. namespaceName1.westus-1.eventgrid.azure.net. Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Is either a + :param credential: Credential used to authenticate requests to the service. Is either a AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential @@ -38,12 +38,9 @@ class EventGridClientConfiguration: # pylint: disable=too-many-instance-attri """ def __init__( - self, - endpoint: str, - credential: Union[AzureKeyCredential, "AsyncTokenCredential"], - **kwargs: Any + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: - api_version: str = kwargs.pop('api_version', "2023-10-01-preview") + api_version: str = kwargs.pop("api_version", "2023-10-01-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -53,30 +50,29 @@ def __init__( self.endpoint = endpoint self.credential = credential self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://eventgrid.azure.net/.default']) - kwargs.setdefault('sdk_moniker', 'eventgrid/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://eventgrid.azure.net/.default"]) + kwargs.setdefault("sdk_moniker", "eventgrid/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _infer_policy(self, **kwargs): if isinstance(self.credential, AzureKeyCredential): - return policies.AzureKeyCredentialPolicy(self.credential, "Authorization", prefix="SharedAccessKey", **kwargs) - if hasattr(self.credential, 'get_token'): + return policies.AzureKeyCredentialPolicy( + self.credential, "Authorization", prefix="SharedAccessKey", **kwargs + ) + if hasattr(self.credential, "get_token"): return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) raise TypeError(f"Unsupported credential: {self.credential}") - 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.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**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.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py index 5d63b0e4eaa0..51cf0e7ac905 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py @@ -11,8 +11,9 @@ from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'EventGridClientOperationsMixin', + "EventGridClientOperationsMixin", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py index 8640bcff8730..51895d2634b3 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py @@ -9,9 +9,16 @@ from io import IOBase import json import sys -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error +from typing import Any, Callable, Dict, IO, List, Optional, Type, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async @@ -19,7 +26,15 @@ from ... import models as _models from ..._model_base import SdkJSONEncoder, _deserialize -from ..._operations._operations import build_event_grid_acknowledge_cloud_events_request, build_event_grid_publish_cloud_event_request, build_event_grid_publish_cloud_events_request, build_event_grid_receive_cloud_events_request, build_event_grid_reject_cloud_events_request, build_event_grid_release_cloud_events_request, build_event_grid_renew_cloud_event_locks_request +from ..._operations._operations import ( + build_event_grid_acknowledge_cloud_events_request, + build_event_grid_publish_cloud_event_request, + build_event_grid_publish_cloud_events_request, + build_event_grid_receive_cloud_events_request, + build_event_grid_reject_cloud_events_request, + build_event_grid_release_cloud_events_request, + build_event_grid_renew_cloud_event_locks_request, +) from ..._validation import api_version_validation from .._vendor import EventGridClientMixinABC @@ -27,20 +42,16 @@ from collections.abc import MutableMapping else: from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -T = TypeVar('T') +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class EventGridClientOperationsMixin( - EventGridClientMixinABC -): + +class EventGridClientOperationsMixin(EventGridClientMixinABC): @distributed_trace_async async def _publish_cloud_event( # pylint: disable=protected-access - self, - topic_name: str, - event: _models._models.CloudEvent, - **kwargs: Any + self, topic_name: str, event: _models._models.CloudEvent, **kwargs: Any ) -> _models._models.PublishResult: # pylint: disable=line-too-long """Publish Single Cloud Event to namespace topic. In case of success, the server responds with an @@ -81,20 +92,23 @@ async def _publish_cloud_event( # pylint: disable=protected-access generated, in RFC3339 format. } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop('content_type', _headers.pop('content-type', "application/cloudevents+json; charset=utf-8")) - cls: ClsType[_models._models.PublishResult] = kwargs.pop( # pylint: disable=protected-access - 'cls', None + content_type: str = kwargs.pop( + "content_type", _headers.pop("content-type", "application/cloudevents+json; charset=utf-8") ) + cls: ClsType[_models._models.PublishResult] = kwargs.pop("cls", None) # pylint: disable=protected-access - _content = event + _content = json.dumps(event, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_event_grid_publish_cloud_event_request( topic_name=topic_name, @@ -105,22 +119,20 @@ async def _publish_cloud_event( # pylint: disable=protected-access 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 = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, - stream=_stream, - **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -128,23 +140,17 @@ async def _publish_cloud_event( # pylint: disable=protected-access deserialized = response.iter_bytes() else: deserialized = _deserialize( - _models._models.PublishResult, # pylint: disable=protected-access - response.json() + _models._models.PublishResult, response.json() # pylint: disable=protected-access ) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @distributed_trace_async async def _publish_cloud_events( # pylint: disable=protected-access - self, - topic_name: str, - events: List[_models._models.CloudEvent], - **kwargs: Any + self, topic_name: str, events: List[_models._models.CloudEvent], **kwargs: Any ) -> _models._models.PublishResult: # pylint: disable=line-too-long """Publish Batch Cloud Event to namespace topic. In case of success, the server responds with an @@ -189,20 +195,23 @@ async def _publish_cloud_events( # pylint: disable=protected-access } ] """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop('content_type', _headers.pop('content-type', "application/cloudevents-batch+json; charset=utf-8")) - cls: ClsType[_models._models.PublishResult] = kwargs.pop( # pylint: disable=protected-access - 'cls', None + content_type: str = kwargs.pop( + "content_type", _headers.pop("content-type", "application/cloudevents-batch+json; charset=utf-8") ) + cls: ClsType[_models._models.PublishResult] = kwargs.pop("cls", None) # pylint: disable=protected-access - _content = events + _content = json.dumps(events, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_event_grid_publish_cloud_events_request( topic_name=topic_name, @@ -213,22 +222,20 @@ async def _publish_cloud_events( # pylint: disable=protected-access 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 = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, - stream=_stream, - **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -236,17 +243,14 @@ async def _publish_cloud_events( # pylint: disable=protected-access deserialized = response.iter_bytes() else: deserialized = _deserialize( - _models._models.PublishResult, # pylint: disable=protected-access - response.json() + _models._models.PublishResult, response.json() # pylint: disable=protected-access ) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @distributed_trace_async async def _receive_cloud_events( # pylint: disable=protected-access self, @@ -320,19 +324,19 @@ async def _receive_cloud_events( # pylint: disable=protected-access ] } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.ReceiveResult] = kwargs.pop( # pylint: disable=protected-access - 'cls', None - ) + cls: ClsType[_models._models.ReceiveResult] = kwargs.pop("cls", None) # pylint: disable=protected-access - _request = build_event_grid_receive_cloud_events_request( topic_name=topic_name, event_subscription_name=event_subscription_name, @@ -343,22 +347,20 @@ async def _receive_cloud_events( # pylint: disable=protected-access 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 = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, - stream=_stream, - **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -366,17 +368,14 @@ async def _receive_cloud_events( # pylint: disable=protected-access deserialized = response.iter_bytes() else: deserialized = _deserialize( - _models._models.ReceiveResult, # pylint: disable=protected-access - response.json() + _models._models.ReceiveResult, response.json() # pylint: disable=protected-access ) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @overload async def _acknowledge_cloud_events( # pylint: disable=protected-access self, @@ -386,8 +385,7 @@ async def _acknowledge_cloud_events( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AcknowledgeResult: - ... + ) -> _models.AcknowledgeResult: ... @overload async def _acknowledge_cloud_events( self, @@ -397,8 +395,7 @@ async def _acknowledge_cloud_events( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AcknowledgeResult: - ... + ) -> _models.AcknowledgeResult: ... @overload async def _acknowledge_cloud_events( self, @@ -408,8 +405,7 @@ async def _acknowledge_cloud_events( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AcknowledgeResult: - ... + ) -> _models.AcknowledgeResult: ... @distributed_trace_async async def _acknowledge_cloud_events( @@ -474,18 +470,19 @@ async def _acknowledge_cloud_events( ] } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _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.AcknowledgeResult] = kwargs.pop( - 'cls', None - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AcknowledgeResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -504,43 +501,36 @@ async def _acknowledge_cloud_events( 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 = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, - stream=_stream, - **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models.AcknowledgeResult, - response.json() - ) + deserialized = _deserialize(_models.AcknowledgeResult, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @overload @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, ) # pylint: disable=protected-access async def _release_cloud_events( # pylint: disable=protected-access self, @@ -551,11 +541,10 @@ async def _release_cloud_events( # pylint: disable=protected-access release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.ReleaseResult: - ... + ) -> _models.ReleaseResult: ... @overload @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, ) async def _release_cloud_events( self, @@ -566,11 +555,10 @@ async def _release_cloud_events( release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.ReleaseResult: - ... + ) -> _models.ReleaseResult: ... @overload @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, ) async def _release_cloud_events( self, @@ -581,12 +569,11 @@ async def _release_cloud_events( release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.ReleaseResult: - ... + ) -> _models.ReleaseResult: ... @distributed_trace_async @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, ) async def _release_cloud_events( self, @@ -654,18 +641,19 @@ async def _release_cloud_events( ] } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _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.ReleaseResult] = kwargs.pop( - 'cls', None - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ReleaseResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -685,40 +673,33 @@ async def _release_cloud_events( 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 = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, - stream=_stream, - **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models.ReleaseResult, - response.json() - ) + deserialized = _deserialize(_models.ReleaseResult, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @overload async def _reject_cloud_events( # pylint: disable=protected-access self, @@ -728,8 +709,7 @@ async def _reject_cloud_events( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RejectResult: - ... + ) -> _models.RejectResult: ... @overload async def _reject_cloud_events( self, @@ -739,8 +719,7 @@ async def _reject_cloud_events( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RejectResult: - ... + ) -> _models.RejectResult: ... @overload async def _reject_cloud_events( self, @@ -750,8 +729,7 @@ async def _reject_cloud_events( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RejectResult: - ... + ) -> _models.RejectResult: ... @distributed_trace_async async def _reject_cloud_events( @@ -815,18 +793,19 @@ async def _reject_cloud_events( ] } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _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.RejectResult] = kwargs.pop( - 'cls', None - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RejectResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -845,43 +824,37 @@ async def _reject_cloud_events( 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 = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, - stream=_stream, - **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models.RejectResult, - response.json() - ) + deserialized = _deserialize(_models.RejectResult, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - @overload @api_version_validation( method_added_on="2023-10-01-preview", + params_added_on={"2023-10-01-preview": ["accept"]}, ) # pylint: disable=protected-access async def _renew_cloud_event_locks( # pylint: disable=protected-access self, @@ -891,11 +864,11 @@ async def _renew_cloud_event_locks( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RenewCloudEventLocksResult: - ... + ) -> _models.RenewCloudEventLocksResult: ... @overload @api_version_validation( method_added_on="2023-10-01-preview", + params_added_on={"2023-10-01-preview": ["accept"]}, ) async def _renew_cloud_event_locks( self, @@ -905,11 +878,11 @@ async def _renew_cloud_event_locks( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RenewCloudEventLocksResult: - ... + ) -> _models.RenewCloudEventLocksResult: ... @overload @api_version_validation( method_added_on="2023-10-01-preview", + params_added_on={"2023-10-01-preview": ["accept"]}, ) async def _renew_cloud_event_locks( self, @@ -919,12 +892,12 @@ async def _renew_cloud_event_locks( *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RenewCloudEventLocksResult: - ... + ) -> _models.RenewCloudEventLocksResult: ... @distributed_trace_async @api_version_validation( method_added_on="2023-10-01-preview", + params_added_on={"2023-10-01-preview": ["accept"]}, ) async def _renew_cloud_event_locks( self, @@ -989,18 +962,19 @@ async def _renew_cloud_event_locks( ] } """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _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.RenewCloudEventLocksResult] = kwargs.pop( - 'cls', None - ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RenewCloudEventLocksResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -1019,36 +993,29 @@ async def _renew_cloud_event_locks( 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 = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, - stream=_stream, - **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models.RenewCloudEventLocksResult, - response.json() - ) + deserialized = _deserialize(_models.RenewCloudEventLocksResult, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - - diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py index 20c46b61de31..0d96149e63cf 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py @@ -5,27 +5,21 @@ """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List, overload, Union, Any, Optional, Callable, Dict, TypeVar, IO +from typing import List, overload, Union, Any, Optional, Callable, Dict, TypeVar import sys from azure.core.messaging import CloudEvent from azure.core.exceptions import ( - ClientAuthenticationError, HttpResponseError, - ResourceExistsError, ResourceNotFoundError, - ResourceNotModifiedError, - map_error, ) from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.pipeline import PipelineResponse from azure.core.rest import HttpRequest, AsyncHttpResponse -from azure.core.utils import case_insensitive_dict from ...models._patch import ReceiveResult, ReceiveDetails from ..._operations._patch import _to_http_request, use_standard_only from ._operations import EventGridClientOperationsMixin as OperationsMixin from ... import models as _models from ...models._models import AcknowledgeOptions, ReleaseOptions, RejectOptions, RenewLockOptions -from ..._model_base import _deserialize from ..._validation import api_version_validation from ..._operations._patch import ( @@ -36,7 +30,7 @@ ) from ..._legacy import EventGridEvent -from ..._legacy._helpers import _is_eventgrid_event +from ..._legacy._helpers import _is_eventgrid_event, _from_cncf_events if sys.version_info >= (3, 9): from collections.abc import MutableMapping @@ -44,9 +38,7 @@ from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object 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 EventGridClientOperationsMixin(OperationsMixin): @@ -62,8 +54,8 @@ async def send( ) -> None: """Send events to the Event Grid Basic Service. - :param event: The event to send. - :type event: CloudEvent or List[CloudEvent] or EventGridEvent or List[EventGridEvent] + :param events: The event to send. + :type events: CloudEvent or List[CloudEvent] or EventGridEvent or List[EventGridEvent] or Dict[str, Any] or List[Dict[str, Any]] or CNCFCloudEvent or List[CNCFCloudEvent] :keyword channel_name: The name of the channel to send the event to. :paramtype channel_name: str or None @@ -90,8 +82,8 @@ async def send( :param topic_name: The name of the topic to send the event to. :type topic_name: str - :param event: The event to send. - :type event: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] + :param events: The event to send. + :type events: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] :keyword binary_mode: Whether to send the event in binary mode. If not specified, the default value is False. :paramtype binary_mode: bool @@ -111,13 +103,13 @@ async def send( } ) @distributed_trace_async - async def send(self, *args, **kwargs) -> None: + async def send(self, *args, **kwargs) -> None: # pylint: disable=docstring-should-be-keyword, docstring-missing-param """Send events to the Event Grid Namespace Service. :param topic_name: The name of the topic to send the event to. :type topic_name: str - :param event: The event to send. - :type event: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] + :param events: The event to send. + :type events: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] :keyword binary_mode: Whether to send the event in binary mode. If not specified, the default value is False. :paramtype binary_mode: bool @@ -167,9 +159,7 @@ async def send(self, *args, **kwargs) -> None: elif len(args) == 1: if events is not None: if topic_name is not None: - raise ValueError( - "topic_name is already passed as a keyword argument." - ) + raise ValueError("topic_name is already passed as a keyword argument.") topic_name = args[0] else: events = args[0] @@ -189,13 +179,11 @@ async def send(self, *args, **kwargs) -> None: events = CloudEvent.from_dict(events) if isinstance(events, list) and isinstance(events[0], dict): events = [CloudEvent.from_dict(e) for e in events] - except Exception: # pylint: disable=broad-except + except Exception: # pylint: disable=broad-except pass if self._level == "Standard": - kwargs["content_type"] = kwargs.get( - "content_type", "application/cloudevents-batch+json; charset=utf-8" - ) + kwargs["content_type"] = kwargs.get("content_type", "application/cloudevents-batch+json; charset=utf-8") if not isinstance(events, list): events = [events] @@ -214,28 +202,37 @@ async def send(self, *args, **kwargs) -> None: self._http_response_error_handler(exception, "Basic") raise exception - async def _send_binary(self, topic_name: str, events: Any, **kwargs: Any) -> None: + async def _send_binary(self, topic_name: str, event: Any, **kwargs: Any) -> None: # If data is passed as a dictionary, make sure it is a CloudEvent + if isinstance(event, list): + raise TypeError("Binary mode is only supported for type CloudEvent.") # pylint: disable=raise-missing-from try: - if isinstance(events, dict): - events = CloudEvent.from_dict(events) - except AttributeError: - raise TypeError("Binary mode is only supported for type CloudEvent.") # pylint: disable=raise-missing-from + if not isinstance(event, CloudEvent): + try: + event = CloudEvent.from_dict(event) + except AttributeError: + event = CloudEvent.from_dict(_from_cncf_events(event)) - # If data is a cloud event, convert to an HTTP Request in binary mode - if isinstance(events, CloudEvent): - await self._publish( - topic_name, events, self._config.api_version, **kwargs + except AttributeError: + raise TypeError("Binary mode is only supported for type CloudEvent.") # pylint: disable=raise-missing-from + + if isinstance(event, CloudEvent): + http_request = _to_http_request( + topic_name=topic_name, + api_version=self._config.api_version, + event=event, + **kwargs, ) else: raise TypeError("Binary mode is only supported for type CloudEvent.") + # If data is a cloud event, convert to an HTTP Request in binary mode + await self.send_request(http_request, **kwargs) + def _http_response_error_handler(self, exception, level): if isinstance(exception, HttpResponseError): if exception.status_code == 400: - raise HttpResponseError( - "Invalid event data. Please check the data and try again." - ) from exception + raise HttpResponseError("Invalid event data. Please check the data and try again.") from exception if exception.status_code == 404: raise ResourceNotFoundError( "Resource not found. " @@ -321,9 +318,7 @@ async def acknowledge_cloud_events( :raises ~azure.core.exceptions.HttpResponseError: """ options = AcknowledgeOptions(lock_tokens=lock_tokens) - return await super()._acknowledge_cloud_events( - topic_name, subscription_name, options, **kwargs - ) + return await super()._acknowledge_cloud_events(topic_name, subscription_name, options, **kwargs) @use_standard_only @distributed_trace_async @@ -390,9 +385,7 @@ async def reject_cloud_events( :raises ~azure.core.exceptions.HttpResponseError: """ options = RejectOptions(lock_tokens=lock_tokens) - return await super()._reject_cloud_events( - topic_name, subscription_name, options, **kwargs - ) + return await super()._reject_cloud_events(topic_name, subscription_name, options, **kwargs) @use_standard_only @distributed_trace_async @@ -424,78 +417,7 @@ async def renew_cloud_event_locks( :raises ~azure.core.exceptions.HttpResponseError: """ options = RenewLockOptions(lock_tokens=lock_tokens) - return await super()._renew_cloud_event_locks( - topic_name, subscription_name, options, **kwargs - ) - - async def _publish( - self, topic_name: str, event: Any, api_version, **kwargs: Any - ) -> None: - - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models._models.PublishResult] = kwargs.pop( - "cls", None - ) # pylint: disable=protected-access - - content_type = kwargs.pop("content_type", None) # pylint: disable=unused-variable - # Given that we know the cloud event is binary mode, we can convert it to a HTTP request - http_request = _to_http_request( - topic_name=topic_name, - api_version=api_version, - headers=_headers, - params=_params, - event=event, - **kwargs, - ) - - _stream = kwargs.pop("stream", False) - - path_format_arguments = { - "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", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - http_request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - 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 - ) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize( - _models._models.PublishResult, # pylint: disable=protected-access - response.json(), - ) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + return await super()._renew_cloud_event_locks(topic_name, subscription_name, options, **kwargs) __all__: List[str] = [ diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_patch.py index b0a6a7dd9253..ebfe920d986d 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_patch.py @@ -33,8 +33,8 @@ class EventGridClient(InternalEventGridClient): :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential or ~azure.core.credentials_async.AsyncTokenCredential :keyword api_version: The API version to use for this operation. Default value for namespaces is - "2023-10-01-preview". Default value for basic is "2018-01-01". Note that overriding this default value may result in unsupported - behavior. + "2023-10-01-preview". Default value for basic is "2018-01-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str or None :keyword level: The level of client to use. Known values include: "Basic", "Standard". Default value is "Standard". @@ -46,9 +46,7 @@ class EventGridClient(InternalEventGridClient): def __init__( self, endpoint: str, - credential: Union[ - AzureKeyCredential, AzureSasCredential, "AsyncTokenCredential" - ], + credential: Union[AzureKeyCredential, AzureSasCredential, "AsyncTokenCredential"], *, api_version: Optional[str] = None, level: Union[str, ClientLevel] = "Standard", @@ -59,17 +57,12 @@ def __init__( if level == ClientLevel.BASIC: self._client = EventGridPublisherClient( # type: ignore[assignment] - endpoint, - credential, - api_version=api_version or DEFAULT_BASIC_API_VERSION, - **kwargs + endpoint, credential, api_version=api_version or DEFAULT_BASIC_API_VERSION, **kwargs ) self._send = self._client.send # type: ignore[attr-defined] elif level == ClientLevel.STANDARD: if isinstance(credential, AzureSasCredential): - raise TypeError( - "SAS token authentication is not supported for the standard client." - ) + raise TypeError("SAS token authentication is not supported for the standard client.") super().__init__( endpoint=endpoint, @@ -79,9 +72,7 @@ def __init__( ) self._send = self._publish_cloud_events else: - raise ValueError( - "Unknown client level. Known values are `Standard` and `Basic`." - ) + raise ValueError("Unknown client level. Known values are `Standard` and `Basic`.") self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_vendor.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_vendor.py index 2f5401a3a2ee..35bd45e3dc6b 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_vendor.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_vendor.py @@ -16,12 +16,11 @@ from .._serialization import Deserializer, Serializer -class EventGridClientMixinABC( - ABC -): + +class EventGridClientMixinABC(ABC): """DO NOT use this class. It is for internal typing use only.""" + _client: "AsyncPipelineClient" _config: EventGridClientConfiguration _serialize: "Serializer" _deserialize: "Deserializer" - diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py index 2bf8ba7809c7..370a6e7b643d 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py @@ -16,13 +16,14 @@ from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'AcknowledgeResult', - 'FailedLockToken', - 'RejectResult', - 'ReleaseResult', - 'RenewCloudEventLocksResult', - 'ReleaseDelay', + "AcknowledgeResult", + "FailedLockToken", + "RejectResult", + "ReleaseResult", + "RenewCloudEventLocksResult", + "ReleaseDelay", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_enums.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_enums.py index 74f1f5e2eaf7..69e6eeb024ea 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_enums.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_enums.py @@ -11,8 +11,7 @@ class ReleaseDelay(int, Enum, metaclass=CaseInsensitiveEnumMeta): - """Supported delays for release operation. - """ + """Supported delays for release operation.""" BY0_SECONDS = 0 """Release the event after 0 seconds.""" diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py index c7fb2c8270fa..ec8f8df9a975 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py @@ -31,9 +31,6 @@ class AcknowledgeOptions(_model_base.Model): """Array of lock tokens. Required.""" - - - class AcknowledgeResult(_model_base.Model): """The result of the Acknowledge operation. @@ -54,15 +51,13 @@ class AcknowledgeResult(_model_base.Model): succeeded_lock_tokens: List[str] = rest_field(name="succeededLockTokens") """Array of lock tokens for the successfully acknowledged cloud events. Required.""" - @overload def __init__( self, *, failed_lock_tokens: List["_models.FailedLockToken"], succeeded_lock_tokens: List[str], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -71,10 +66,8 @@ def __init__(self, mapping: Mapping[str, Any]): :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) - - class BrokerProperties(_model_base.Model): @@ -94,9 +87,6 @@ class BrokerProperties(_model_base.Model): """The attempt count for delivering the event. Required.""" - - - class CloudEvent(_model_base.Model): """Properties of an event published to an Azure Messaging EventGrid Namespace topic using the CloudEvent 1.0 Schema. @@ -153,9 +143,6 @@ class CloudEvent(_model_base.Model): source).""" - - - class Error(_model_base.Model): """The error object. @@ -186,9 +173,6 @@ class Error(_model_base.Model): """An object containing more specific information than the current object about the error.""" - - - class FailedLockToken(_model_base.Model): """Failed LockToken information. @@ -206,15 +190,13 @@ class FailedLockToken(_model_base.Model): error: "_models._models.Error" = rest_field() """Error information of the failed operation result for the lock token in the request. Required.""" - @overload def __init__( self, *, lock_token: str, error: "_models._models.Error", - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -223,10 +205,8 @@ def __init__(self, mapping: Mapping[str, Any]): :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) - - class InnerError(_model_base.Model): @@ -246,17 +226,8 @@ class InnerError(_model_base.Model): """Inner error.""" - - - class PublishResult(_model_base.Model): - """The result of the Publish operation. - - """ - - - - + """The result of the Publish operation.""" class ReceiveDetails(_model_base.Model): @@ -276,9 +247,6 @@ class ReceiveDetails(_model_base.Model): """Cloud Event details. Required.""" - - - class ReceiveResult(_model_base.Model): """Details of the Receive operation response. @@ -292,9 +260,6 @@ class ReceiveResult(_model_base.Model): """Array of receive responses, one per cloud event. Required.""" - - - class RejectOptions(_model_base.Model): """Array of lock tokens for the corresponding received Cloud Events to be rejected. @@ -308,9 +273,6 @@ class RejectOptions(_model_base.Model): """Array of lock tokens. Required.""" - - - class RejectResult(_model_base.Model): """The result of the Reject operation. @@ -331,15 +293,13 @@ class RejectResult(_model_base.Model): succeeded_lock_tokens: List[str] = rest_field(name="succeededLockTokens") """Array of lock tokens for the successfully rejected cloud events. Required.""" - @overload def __init__( self, *, failed_lock_tokens: List["_models.FailedLockToken"], succeeded_lock_tokens: List[str], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -348,10 +308,8 @@ def __init__(self, mapping: Mapping[str, Any]): :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) - - class ReleaseOptions(_model_base.Model): @@ -367,9 +325,6 @@ class ReleaseOptions(_model_base.Model): """Array of lock tokens. Required.""" - - - class ReleaseResult(_model_base.Model): """The result of the Release operation. @@ -390,15 +345,13 @@ class ReleaseResult(_model_base.Model): succeeded_lock_tokens: List[str] = rest_field(name="succeededLockTokens") """Array of lock tokens for the successfully released cloud events. Required.""" - @overload def __init__( self, *, failed_lock_tokens: List["_models.FailedLockToken"], succeeded_lock_tokens: List[str], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -407,10 +360,8 @@ def __init__(self, mapping: Mapping[str, Any]): :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) - - class RenewCloudEventLocksResult(_model_base.Model): @@ -432,15 +383,13 @@ class RenewCloudEventLocksResult(_model_base.Model): succeeded_lock_tokens: List[str] = rest_field(name="succeededLockTokens") """Array of lock tokens for the successfully renewed locks. Required.""" - @overload def __init__( self, *, failed_lock_tokens: List["_models.FailedLockToken"], succeeded_lock_tokens: List[str], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -449,10 +398,8 @@ def __init__(self, mapping: Mapping[str, Any]): :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) - - class RenewLockOptions(_model_base.Model): @@ -466,6 +413,3 @@ class RenewLockOptions(_model_base.Model): lock_tokens: List[str] = rest_field(name="lockTokens") """Array of lock tokens. Required.""" - - - diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py index ee8fa6387b70..2d1ee31d0d01 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py @@ -41,9 +41,7 @@ def __init__(self, mapping: Mapping[str, Any]): :type mapping: Mapping[str, Any] """ - def __init__( # pylint: disable=useless-super-delegation - self, *args: Any, **kwargs: Any - ) -> None: + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) @@ -70,9 +68,7 @@ def __init__(self, mapping: Mapping[str, Any]): :type mapping: Mapping[str, Any] """ - def __init__( # pylint: disable=useless-super-delegation - self, *args: Any, **kwargs: Any - ) -> None: + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) @@ -102,9 +98,7 @@ def __init__(self, mapping: Mapping[str, Any]): :type mapping: Mapping[str, Any] """ - def __init__( # pylint: disable=useless-super-delegation - self, *args: Any, **kwargs: Any - ) -> None: + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py index 0bed8a6ddc74..24c452d0701d 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py @@ -34,33 +34,23 @@ client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) -cloud_event_reject = CloudEvent( - data="reject", source="https://example.com", type="example" -) -cloud_event_release = CloudEvent( - data="release", source="https://example.com", type="example" -) -cloud_event_ack = CloudEvent( - data="acknowledge", source="https://example.com", type="example" -) +cloud_event_reject = CloudEvent(data="reject", source="https://example.com", type="example") +cloud_event_release = CloudEvent(data="release", source="https://example.com", type="example") +cloud_event_ack = CloudEvent(data="acknowledge", source="https://example.com", type="example") async def run(): async with client: # Publish a CloudEvent try: - await client.send( - topic_name=TOPIC_NAME, events=cloud_event_reject - ) + await client.send(topic_name=TOPIC_NAME, events=cloud_event_reject) except HttpResponseError: raise # Publish a list of CloudEvents try: list_of_cloud_events = [cloud_event_release, cloud_event_ack] - await client.send( - topic_name=TOPIC_NAME, events=list_of_cloud_events - ) + await client.send(topic_name=TOPIC_NAME, events=list_of_cloud_events) except HttpResponseError: raise diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_binary_mode_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_binary_mode_async.py index 23ddeb5abd90..1e13aaee8f39 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_binary_mode_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_binary_mode_async.py @@ -40,11 +40,21 @@ async def run(): # Publish a CloudEvent try: # Publish CloudEvent in binary mode with str encoded as bytes - cloud_event_dict = {"data":b"HI", "source":"https://example.com", "type":"example", "datacontenttype":"text/plain"} + cloud_event_dict = { + "data": b"HI", + "source": "https://example.com", + "type": "example", + "datacontenttype": "text/plain", + } await client.send(topic_name=TOPIC_NAME, events=cloud_event_dict, binary_mode=True) # Publish CloudEvent in binary mode with json encoded as bytes - cloud_event = CloudEvent(data=json.dumps({"hello":"data"}).encode("utf-8"), source="https://example.com", type="example", datacontenttype="application/json") + cloud_event = CloudEvent( + data=json.dumps({"hello": "data"}).encode("utf-8"), + source="https://example.com", + type="example", + datacontenttype="application/json", + ) await client.send(topic_name=TOPIC_NAME, events=cloud_event, binary_mode=True) receive_result = await client.receive_cloud_events( @@ -60,5 +70,6 @@ async def run(): except HttpResponseError: raise + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(run()) diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_operation_async.py index aae84b550ecc..57469077a263 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_operation_async.py @@ -50,12 +50,9 @@ async def run(): except HttpResponseError: raise - # Publish a CloudEvent try: - cloud_event = CloudEvent( - data="HI", source="https://example.com", type="example" - ) + cloud_event = CloudEvent(data="HI", source="https://example.com", type="example") await client.send(topic_name=TOPIC_NAME, events=cloud_event) except HttpResponseError: raise @@ -63,9 +60,7 @@ async def run(): # Publish a list of CloudEvents try: list_of_cloud_events = [cloud_event, cloud_event] - await client.send( - topic_name=TOPIC_NAME, events=list_of_cloud_events - ) + await client.send(topic_name=TOPIC_NAME, events=list_of_cloud_events) except HttpResponseError: raise diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py index 04cd15696d9e..3b95910942df 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py @@ -42,7 +42,9 @@ async def run(): await client.send(topic_name=TOPIC_NAME, events=cloud_event) # Receive CloudEvents and parse out lock tokens - receive_result = await client.receive_cloud_events(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10) + receive_result = await client.receive_cloud_events( + topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10 + ) lock_tokens_to_release = [] for item in receive_result.value: lock_tokens_to_release.append(item.broker_properties.lock_token) @@ -57,5 +59,6 @@ async def run(): except HttpResponseError: raise + if __name__ == "__main__": - asyncio.get_event_loop().run_until_complete(run()) \ No newline at end of file + asyncio.get_event_loop().run_until_complete(run()) diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py index f0946c2bcd57..ef3a25bf0419 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py @@ -42,7 +42,9 @@ async def run(): await client.send(topic_name=TOPIC_NAME, events=cloud_event) # Receive CloudEvents and parse out lock tokens - receive_result = await client.receive_cloud_events(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + receive_result = await client.receive_cloud_events( + topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15 + ) lock_tokens_to_release = [] for item in receive_result.value: lock_tokens_to_release.append(item.broker_properties.lock_token) @@ -59,7 +61,9 @@ async def run(): print("Released Event:", release_events) # Receive CloudEvents again - receive_result = await client.receive_cloud_events(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + receive_result = await client.receive_cloud_events( + topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15 + ) print("Received events after release:", receive_result.value) # Acknowledge a LockToken that was released @@ -72,5 +76,6 @@ async def run(): except HttpResponseError: raise + if __name__ == "__main__": - asyncio.get_event_loop().run_until_complete(run()) \ No newline at end of file + asyncio.get_event_loop().run_until_complete(run()) diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py index 349f18991ee0..7844f9a2c3a8 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py @@ -31,6 +31,7 @@ # Create a client client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) + async def run(): # Renew a lockToken try: @@ -44,5 +45,6 @@ async def run(): except HttpResponseError: raise + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(run()) diff --git a/sdk/eventgrid/azure-eventgrid/samples/consume_samples/consume_cloud_events_from_storage_queue.py b/sdk/eventgrid/azure-eventgrid/samples/consume_samples/consume_cloud_events_from_storage_queue.py index 17e110122a95..86fbfaf2b77e 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/consume_samples/consume_cloud_events_from_storage_queue.py +++ b/sdk/eventgrid/azure-eventgrid/samples/consume_samples/consume_cloud_events_from_storage_queue.py @@ -24,9 +24,9 @@ queue_name = os.environ["STORAGE_QUEUE_NAME"] with QueueServiceClient.from_connection_string(connection_str) as qsc: - payload = qsc.get_queue_client( - queue=queue_name, message_decode_policy=BinaryBase64DecodePolicy() - ).peek_messages(max_messages=32) + payload = qsc.get_queue_client(queue=queue_name, message_decode_policy=BinaryBase64DecodePolicy()).peek_messages( + max_messages=32 + ) ## deserialize payload into a list of typed Events events: List[CloudEvent] = [CloudEvent.from_json(msg) for msg in payload] diff --git a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_custom_topic_sample.py b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_custom_topic_sample.py index 9a04a87df6d9..1b2db9f0cff4 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_custom_topic_sample.py +++ b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_custom_topic_sample.py @@ -44,9 +44,7 @@ def publish_event(): event_list = [] # list of events to publish # create events and append to list for j in range(randint(1, 1)): - sample_members = sample( - services, k=randint(1, 4) - ) # select random subset of team members + sample_members = sample(services, k=randint(1, 4)) # select random subset of team members data_dict = {"team": sample_members} event = CloudEvent( type="Azure.Sdk.Sample", diff --git a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_domain_topic_sample.py b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_domain_topic_sample.py index d30969af523b..dc26284119ce 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_domain_topic_sample.py +++ b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_domain_topic_sample.py @@ -46,9 +46,7 @@ def publish_event(): # create events and append to list for j in range(randint(1, 3)): - sample_members = sample( - services, k=randint(1, 4) - ) # select random subset of team members + sample_members = sample(services, k=randint(1, 4)) # select random subset of team members event = CloudEvent( type="Azure.Sdk.Demo", source="domainname", diff --git a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_event_grid_events_to_custom_topic_sample.py b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_event_grid_events_to_custom_topic_sample.py index 1f00e36dcf18..3e4a85c77c90 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_event_grid_events_to_custom_topic_sample.py +++ b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_event_grid_events_to_custom_topic_sample.py @@ -42,9 +42,7 @@ def publish_event(): event_list = [] # list of events to publish # create events and append to list for j in range(randint(1, 3)): - sample_members = sample( - services, k=randint(1, 4) - ) # select random subset of team members + sample_members = sample(services, k=randint(1, 4)) # select random subset of team members event = EventGridEvent( subject="Door1", data={"team": sample_members}, diff --git a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_with_shared_access_signature_sample.py b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_with_shared_access_signature_sample.py index 4afdeebc182b..0ac2a6b894c9 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_with_shared_access_signature_sample.py +++ b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_with_shared_access_signature_sample.py @@ -48,9 +48,7 @@ def publish_event(): event_list = [] # list of events to publish # create events and append to list for j in range(randint(1, 3)): - sample_members = sample( - services, k=randint(1, 4) - ) # select random subset of team members + sample_members = sample(services, k=randint(1, 4)) # select random subset of team members event = CloudEvent( type="Azure.Sdk.Demo", source="https://egdemo.dev/demowithsignature", diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py index 68b9ea7962d6..31416d97aef5 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py @@ -34,15 +34,9 @@ client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) -cloud_event_reject = CloudEvent( - data="reject", source="https://example.com", type="example" -) -cloud_event_release = CloudEvent( - data="release", source="https://example.com", type="example" -) -cloud_event_ack = CloudEvent( - data="acknowledge", source="https://example.com", type="example" -) +cloud_event_reject = CloudEvent(data="reject", source="https://example.com", type="example") +cloud_event_release = CloudEvent(data="release", source="https://example.com", type="example") +cloud_event_ack = CloudEvent(data="acknowledge", source="https://example.com", type="example") # Publish a CloudEvent try: diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_binary_mode.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_binary_mode.py index 8a6a0188a184..d6c2130bbd9d 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_binary_mode.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_binary_mode.py @@ -37,20 +37,30 @@ # Publish a CloudEvent try: # Publish CloudEvent in binary mode with str encoded as bytes - cloud_event_dict = {"data":b"HI", "source":"https://example.com", "type":"example", "datacontenttype":"text/plain"} + cloud_event_dict = { + "data": b"HI", + "source": "https://example.com", + "type": "example", + "datacontenttype": "text/plain", + } client.send(topic_name=TOPIC_NAME, events=cloud_event_dict, binary_mode=True) # Publish CloudEvent in binary mode with json encoded as bytes - cloud_event = CloudEvent(data=json.dumps({"hello":"data"}).encode("utf-8"), source="https://example.com", type="example", datacontenttype="application/json") + cloud_event = CloudEvent( + data=json.dumps({"hello": "data"}).encode("utf-8"), + source="https://example.com", + type="example", + datacontenttype="application/json", + ) client.send(topic_name=TOPIC_NAME, events=cloud_event, binary_mode=True) # Receive a CloudEvent - receive_result = client.receive_cloud_events(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=100) + receive_result = client.receive_cloud_events( + topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=100 + ) for receive_details in receive_result.value: cloud_event_received = receive_details.event print("CloudEvent: ", cloud_event_received) print("CloudEvent data: ", cloud_event_received.data) except HttpResponseError: raise - - diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py index 438f88c7b570..6ad93259494b 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py @@ -39,7 +39,9 @@ client.send(topic_name=TOPIC_NAME, events=cloud_event) # Receive CloudEvents and parse out lock tokens - receive_result = client.receive_cloud_events(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10) + receive_result = client.receive_cloud_events( + topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10 + ) lock_tokens_to_renew = [] for item in receive_result.value: lock_tokens_to_renew.append(item.broker_properties.lock_token) diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py index 0951efb50a7c..f96132b4c565 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py @@ -39,7 +39,9 @@ client.send(topic_name=TOPIC_NAME, events=cloud_event) # Receive CloudEvents and parse out lock tokens - receive_result = client.receive_cloud_events(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + receive_result = client.receive_cloud_events( + topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15 + ) lock_tokens_to_release = [] for item in receive_result.value: lock_tokens_to_release.append(item.broker_properties.lock_token) @@ -56,7 +58,9 @@ print("Released Event:", release_events) # Receive CloudEvents again - receive_result = client.receive_cloud_events(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + receive_result = client.receive_cloud_events( + topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15 + ) print("Received events after release:", receive_result.value) # Acknowledge a LockToken that was released diff --git a/sdk/eventgrid/azure-eventgrid/setup.py b/sdk/eventgrid/azure-eventgrid/setup.py index ad121db2982c..ee29cfadd35d 100644 --- a/sdk/eventgrid/azure-eventgrid/setup.py +++ b/sdk/eventgrid/azure-eventgrid/setup.py @@ -62,8 +62,8 @@ "azure.eventgrid": ["py.typed"], }, install_requires=[ - "isodate<1.0.0,>=0.6.1", - "azure-core<2.0.0,>=1.30.0", + "isodate>=0.6.1", + "azure-core>=1.30.0", "typing-extensions>=4.6.0", ], python_requires=">=3.8", diff --git a/sdk/eventgrid/azure-eventgrid/swagger/_constants.py b/sdk/eventgrid/azure-eventgrid/swagger/_constants.py index b9ba703da2e4..0a2cfc4503c7 100644 --- a/sdk/eventgrid/azure-eventgrid/swagger/_constants.py +++ b/sdk/eventgrid/azure-eventgrid/swagger/_constants.py @@ -29,7 +29,7 @@ "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/eventgrid/data-plane/Microsoft.Web/stable/2018-01-01/Web.json", "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/eventgrid/data-plane/Microsoft.HealthcareApis/stable/2018-01-01/HealthcareApis.json", "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/eventgrid/data-plane/Microsoft.ApiCenter/stable/2018-01-01/ApiCenter.json", - ] +] ####################################################### @@ -64,9 +64,21 @@ "ServiceBusDeadletterMessagesAvailableWithNoListenerEventName": "Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListeners", } -EXCEPTIONS = ['ContainerRegistryArtifactEventData', 'ContainerRegistryEventData', 'ContainerServiceClusterSupportEventData', 'ContainerServiceNodePoolRollingEventData', - 'EventGridMQTTClientEventData', 'AppConfigurationSnapshotEventData', 'HealthResourcesResourceEventData', 'AcsRouterJobEventData', 'AcsRouterWorkerEventData', 'AcsRouterEventData', - 'AvsClusterEventData', 'AvsPrivateCloudEventData', 'AvsScriptExecutionEventData', "AcsMessageEventData" - ] +EXCEPTIONS = [ + "ContainerRegistryArtifactEventData", + "ContainerRegistryEventData", + "ContainerServiceClusterSupportEventData", + "ContainerServiceNodePoolRollingEventData", + "EventGridMQTTClientEventData", + "AppConfigurationSnapshotEventData", + "HealthResourcesResourceEventData", + "AcsRouterJobEventData", + "AcsRouterWorkerEventData", + "AcsRouterEventData", + "AvsClusterEventData", + "AvsPrivateCloudEventData", + "AvsScriptExecutionEventData", + "AcsMessageEventData", +] NAMING_CHANGES = ["AcsMessageDeliveryStatusUpdatedEventName", "AcsMessageReceivedEventName"] diff --git a/sdk/eventgrid/azure-eventgrid/swagger/postprocess_eventnames.py b/sdk/eventgrid/azure-eventgrid/swagger/postprocess_eventnames.py index f1a2cd34d400..842afcc14797 100644 --- a/sdk/eventgrid/azure-eventgrid/swagger/postprocess_eventnames.py +++ b/sdk/eventgrid/azure-eventgrid/swagger/postprocess_eventnames.py @@ -12,8 +12,8 @@ def extract(definitions): return tups = [] for event in definitions: - if event.endswith('Data') and event not in EXCEPTIONS: - key, txt = "Name".join(event.rsplit('Data', 1)), definitions[event]['description'] + if event.endswith("Data") and event not in EXCEPTIONS: + key, txt = "Name".join(event.rsplit("Data", 1)), definitions[event]["description"] if key in NAMING_CHANGES: key = key.replace("Acs", "AcsAdvanced") try: @@ -32,9 +32,7 @@ def extract(definitions): def generate_enum_content(tuples): - print( - "# These names at the top are 'corrected' aliases of duplicate values that appear below, which are" - ) + print("# These names at the top are 'corrected' aliases of duplicate values that appear below, which are") print("# deprecated but maintained for backwards compatibility.") for k, v in backward_compat.items(): print(k + " = '" + v + "'\n") diff --git a/sdk/eventgrid/azure-eventgrid/tests/conftest.py b/sdk/eventgrid/azure-eventgrid/tests/conftest.py index 0676dd77c87d..d95ebca3e613 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/conftest.py +++ b/sdk/eventgrid/azure-eventgrid/tests/conftest.py @@ -26,13 +26,21 @@ import os import pytest from urllib.parse import urlparse -from devtools_testutils import add_general_string_sanitizer, test_proxy, add_body_key_sanitizer, add_header_regex_sanitizer, add_oauth_response_sanitizer, add_body_regex_sanitizer +from devtools_testutils import ( + add_general_string_sanitizer, + test_proxy, + add_body_key_sanitizer, + add_header_regex_sanitizer, + add_oauth_response_sanitizer, + add_body_regex_sanitizer, +) from devtools_testutils.sanitizers import ( add_remove_header_sanitizer, add_general_regex_sanitizer, set_custom_default_matcher, ) + @pytest.fixture(scope="session", autouse=True) def add_sanitizers(test_proxy): # this can be reverted to set_bodiless_matcher() after tests are re-recorded and don't contain these headers @@ -70,9 +78,9 @@ def add_sanitizers(test_proxy): eventgrid_topic_key = os.getenv("EVENTGRID_TOPIC_KEY", "sanitized") eventgrid_topic_endpoint = os.getenv("EVENTGRID_TOPIC_ENDPOINT", "sanitized") - eventgrid_partner_channel_name=os.getenv("EVENTGRID_PARTNER_CHANNEL_NAME", "sanitized") - eventgrid_partner_namespace_topic_endpoint=os.getenv("EVENTGRID_PARTNER_NAMESPACE_TOPIC_ENDPOINT", "sanitized") - eventgrid_partner_namespace_topic_key=os.getenv("EVENTGRID_PARTNER_NAMESPACE_TOPIC_KEY", "sanitized") + eventgrid_partner_channel_name = os.getenv("EVENTGRID_PARTNER_CHANNEL_NAME", "sanitized") + eventgrid_partner_namespace_topic_endpoint = os.getenv("EVENTGRID_PARTNER_NAMESPACE_TOPIC_ENDPOINT", "sanitized") + eventgrid_partner_namespace_topic_key = os.getenv("EVENTGRID_PARTNER_NAMESPACE_TOPIC_KEY", "sanitized") # Need to santize namespace for eventgrid_topic: try: @@ -85,4 +93,3 @@ def add_sanitizers(test_proxy): add_general_string_sanitizer(target=eventgrid_client_id, value="00000000-0000-0000-0000-000000000000") add_general_string_sanitizer(target=eventgrid_client_secret, value="sanitized") add_general_string_sanitizer(target=tenant_id, value="00000000-0000-0000-0000-000000000000") - diff --git a/sdk/eventgrid/azure-eventgrid/tests/eventgrid_preparer.py b/sdk/eventgrid/azure-eventgrid/tests/eventgrid_preparer.py index 1343179da503..6b8fcb2b73fc 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/eventgrid_preparer.py +++ b/sdk/eventgrid/azure-eventgrid/tests/eventgrid_preparer.py @@ -16,15 +16,9 @@ ID_JSON_FIELD = JsonField(source_field="customId") TOPIC_JSON_FIELD = JsonField(source_field="customTopic") EVENT_TIME_JSON_FIELD = JsonField(source_field="customEventTime") -EVENT_TYPE_JSON_FIELD_WITH_DEFAULT = JsonFieldWithDefault( - source_field="customEventType", default_value="" -) -SUBJECT_JSON_FIELD_WITH_DEFAULT = JsonFieldWithDefault( - source_field="customSubject", default_value="" -) -DATA_VERSION_JSON_FIELD_WITH_DEFAULT = JsonFieldWithDefault( - source_field="customDataVersion", default_value="" -) +EVENT_TYPE_JSON_FIELD_WITH_DEFAULT = JsonFieldWithDefault(source_field="customEventType", default_value="") +SUBJECT_JSON_FIELD_WITH_DEFAULT = JsonFieldWithDefault(source_field="customSubject", default_value="") +DATA_VERSION_JSON_FIELD_WITH_DEFAULT = JsonFieldWithDefault(source_field="customDataVersion", default_value="") CUSTOM_JSON_INPUT_SCHEMA_MAPPING = JsonInputSchemaMapping( id=ID_JSON_FIELD, topic=TOPIC_JSON_FIELD, @@ -54,4 +48,4 @@ eventgrid_key="fakekeyfakekeyfakekeyfakekeyfakekeyfakekeyA=", eventgrid_topic_name="faketopic", eventgrid_event_subscription_name="fakesub", -) \ No newline at end of file +) diff --git a/sdk/eventgrid/azure-eventgrid/tests/perfstress_tests/send.py b/sdk/eventgrid/azure-eventgrid/tests/perfstress_tests/send.py index 5ad2958c9b8c..f08902d3aaec 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/perfstress_tests/send.py +++ b/sdk/eventgrid/azure-eventgrid/tests/perfstress_tests/send.py @@ -25,21 +25,15 @@ def __init__(self, arguments): endpoint = self.get_from_env("EG_TOPIC_HOSTNAME") # Create clients - self.publisher_client = SyncPublisherClient( - endpoint=endpoint, credential=AzureKeyCredential(topic_key) - ) - self.async_publisher_client = AsyncPublisherClient( - endpoint=endpoint, credential=AzureKeyCredential(topic_key) - ) + self.publisher_client = SyncPublisherClient(endpoint=endpoint, credential=AzureKeyCredential(topic_key)) + self.async_publisher_client = AsyncPublisherClient(endpoint=endpoint, credential=AzureKeyCredential(topic_key)) self.event_list = [] for _ in range(self.args.num_events): self.event_list.append( EventGridEvent( event_type="Contoso.Items.ItemReceived", - data={ - "services": ["EventGrid", "ServiceBus", "EventHubs", "Storage"] - }, + data={"services": ["EventGrid", "ServiceBus", "EventHubs", "Storage"]}, subject="Door1", data_version="2.0", ) diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_cloud_event_tracing.py b/sdk/eventgrid/azure-eventgrid/tests/test_cloud_event_tracing.py index 87d08b9fdbc7..bf1ba4ac12fe 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_cloud_event_tracing.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_cloud_event_tracing.py @@ -43,9 +43,7 @@ def test_cloud_event_policy_copies(self): def test_cloud_event_policy_no_copy_if_trace_exists(self): policy = CloudEventDistributedTracingPolicy() - cloud_storage_dict.update( - {"traceparent": "exists", "tracestate": "state_exists"} - ) + cloud_storage_dict.update({"traceparent": "exists", "tracestate": "state_exists"}) body = json.dumps([cloud_storage_dict]) universal_request = HttpRequest("POST", "http://127.0.0.1/", data=body) universal_request.headers["content-type"] = _content_type diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_cncf_events.py b/sdk/eventgrid/azure-eventgrid/tests/test_cncf_events.py index dca0af806cb3..e7052226447d 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_cncf_events.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_cncf_events.py @@ -13,16 +13,12 @@ class TestEventGridPublisherClientCncf(AzureRecordedTestCase): def create_eg_publisher_client(self, endpoint): credential = self.get_credential(EventGridPublisherClient) - client = self.create_client_from_credential( - EventGridPublisherClient, credential=credential, endpoint=endpoint - ) + client = self.create_client_from_credential(EventGridPublisherClient, credential=credential, endpoint=endpoint) return client @EventGridPreparer() @recorded_by_proxy - def test_send_cncf_data_dict( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cncf_data_dict(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", @@ -42,9 +38,7 @@ def callback(request): @EventGridPreparer() @recorded_by_proxy - def test_send_cncf_data_base64_using_data( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cncf_data_base64_using_data(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", @@ -62,9 +56,7 @@ def callback(request): @EventGridPreparer() @recorded_by_proxy - def test_send_cncf_data_none( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cncf_data_none(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", @@ -76,9 +68,7 @@ def test_send_cncf_data_none( @EventGridPreparer() @recorded_by_proxy - def test_send_cncf_data_str( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cncf_data_str(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", @@ -96,9 +86,7 @@ def callback(request): @EventGridPreparer() @recorded_by_proxy - def test_send_cncf_data_as_list( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cncf_data_as_list(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", @@ -110,9 +98,7 @@ def test_send_cncf_data_as_list( @EventGridPreparer() @recorded_by_proxy - def test_send_cncf_data_with_extensions( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cncf_data_with_extensions(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_cncf_events_async.py b/sdk/eventgrid/azure-eventgrid/tests/test_cncf_events_async.py index a421181f4d82..247317ce074c 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_cncf_events_async.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_cncf_events_async.py @@ -15,17 +15,13 @@ class TestEventGridPublisherClientCncf(AzureRecordedTestCase): def create_eg_publisher_client(self, endpoint): credential = self.get_credential(EventGridPublisherClient, is_async=True) - client = self.create_client_from_credential( - EventGridPublisherClient, credential=credential, endpoint=endpoint - ) + client = self.create_client_from_credential(EventGridPublisherClient, credential=credential, endpoint=endpoint) return client @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cncf_data_dict_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cncf_data_dict_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", @@ -46,9 +42,7 @@ def callback(request): @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cncf_data_base64_using_data_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cncf_data_base64_using_data_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", @@ -67,9 +61,7 @@ def callback(request): @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cncf_data_none_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cncf_data_none_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", @@ -82,9 +74,7 @@ async def test_send_cncf_data_none_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cncf_data_str_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cncf_data_str_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", @@ -103,9 +93,7 @@ def callback(request): @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cncf_data_as_list_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cncf_data_as_list_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", @@ -118,9 +106,7 @@ async def test_send_cncf_data_as_list_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cncf_data_with_extensions_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cncf_data_with_extensions_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) attributes = { "type": "com.example.sampletype1", diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_dual_client.py b/sdk/eventgrid/azure-eventgrid/tests/test_dual_client.py index f05ab6841345..d5fff9e9008a 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_dual_client.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_dual_client.py @@ -15,71 +15,85 @@ from eventgrid_preparer import EventGridPreparer +def _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name, level): + if level == "Standard": + events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_events=100) + tokens = [] + for detail in events.value: + token = detail.broker_properties.lock_token + tokens.append(token) + ack_result = client.acknowledge_cloud_events( + eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=tokens + ) + class ArgPasser: def __call__(self, fn): def _preparer(test_class, level, **kwargs): fn(test_class, level, **kwargs) + return _preparer + class TestEGDualClient(AzureRecordedTestCase): def create_eg_client(self, endpoint, key, level): - client = EventGridClient( - endpoint=endpoint, credential=AzureKeyCredential(key), level=level - ) + client = EventGridClient(endpoint=endpoint, credential=AzureKeyCredential(key), level=level) return client - @pytest.mark.live_test_only() @pytest.mark.parametrize("level", ["Standard", "Basic"]) @EventGridPreparer() @ArgPasser() @recorded_by_proxy - def test_create_client_publish(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_create_client_publish( + self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) - + from xml.etree import ElementTree as ET + xml_string = """test""" - tree = xml_string.encode('utf-8') + tree = xml_string.encode("utf-8") event = CloudEvent( type="Contoso.Items.ItemReceived", source="source", subject="MySubject", data=tree, datacontenttype="text/xml", - extensions={"extension1": "value1", "extension2": "value2"} + extensions={"extension1": "value1", "extension2": "value2"}, ) - if level=="Basic": + if level == "Basic": with pytest.raises(ValueError): - client.send( - topic_name=eventgrid_topic_name, events=event, binary_mode=True - ) + client.send(topic_name=eventgrid_topic_name, events=event, binary_mode=True) else: - client.send( - topic_name=eventgrid_topic_name, events=event, binary_mode=True - ) + client.send(topic_name=eventgrid_topic_name, events=event, binary_mode=True) + + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name, level) @pytest.mark.live_test_only() @pytest.mark.parametrize("level", ["Standard", "Basic"]) @EventGridPreparer() @ArgPasser() @recorded_by_proxy - def test_create_client_receive(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_create_client_receive( + self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) - + from xml.etree import ElementTree as ET + xml_string = """test""" - tree = xml_string.encode('utf-8') + tree = xml_string.encode("utf-8") event = CloudEvent( type="Contoso.Items.ItemReceived", source="source", subject="MySubject", data=tree, datacontenttype="text/xml", - extensions={"extension1": "value1", "extension2": "value2"} + extensions={"extension1": "value1", "extension2": "value2"}, ) - if level=="Basic": + if level == "Basic": with pytest.raises(ValueError): client.receive_cloud_events( topic_name=eventgrid_topic_name, subscription_name=eventgrid_event_subscription_name @@ -89,132 +103,172 @@ def test_create_client_receive(self, level, eventgrid_endpoint, eventgrid_key, e topic_name=eventgrid_topic_name, subscription_name=eventgrid_event_subscription_name ) + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name, level) + + @pytest.mark.live_test_only() @pytest.mark.parametrize("level", ["Standard", "Basic"]) @EventGridPreparer() @ArgPasser() @recorded_by_proxy - def test_create_client_publish_event(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, - eventgrid_topic_key, eventgrid_topic_endpoint): - if level=="Basic": + def test_create_client_publish_event( + self, + level, + eventgrid_endpoint, + eventgrid_key, + eventgrid_topic_name, + eventgrid_event_subscription_name, + eventgrid_topic_key, + eventgrid_topic_endpoint, + ): + if level == "Basic": client = self.create_eg_client(eventgrid_topic_endpoint, eventgrid_topic_key, level=level) else: client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) - + event = EventGridEvent( id="7f7d", subject="MySubject", - data={ - "test": "data" - }, + data={"test": "data"}, event_type="Contoso.Items.ItemReceived", - data_version="1.0" + data_version="1.0", ) - if level=="Basic": - client.send( - events=event - ) + if level == "Basic": + client.send(events=event) else: with pytest.raises(TypeError): - client.send( - topic_name=eventgrid_topic_name, events=event - ) + client.send(topic_name=eventgrid_topic_name, events=event) + + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name, level) + @pytest.mark.live_test_only() @pytest.mark.parametrize("level", ["Standard", "Basic"]) @EventGridPreparer() @ArgPasser() @recorded_by_proxy - def test_create_client_cloud_event(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, - eventgrid_cloud_event_topic_key, eventgrid_cloud_event_topic_endpoint): - if level=="Basic": - client = self.create_eg_client(eventgrid_cloud_event_topic_endpoint, eventgrid_cloud_event_topic_key, level=level) + def test_create_client_cloud_event( + self, + level, + eventgrid_endpoint, + eventgrid_key, + eventgrid_topic_name, + eventgrid_event_subscription_name, + eventgrid_cloud_event_topic_key, + eventgrid_cloud_event_topic_endpoint, + ): + if level == "Basic": + client = self.create_eg_client( + eventgrid_cloud_event_topic_endpoint, eventgrid_cloud_event_topic_key, level=level + ) else: client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) - + event = CloudEvent( type="Contoso.Items.ItemReceived", source="source", subject="MySubject", data={"test": "data"}, datacontenttype="application/json", - extensions={"extension1": "value1", "extension2": "value2"} + extensions={"extension1": "value1", "extension2": "value2"}, ) - client.send( - topic_name=eventgrid_topic_name, events=event - ) + client.send(topic_name=eventgrid_topic_name, events=event) + + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name, level) + @pytest.mark.live_test_only() @pytest.mark.parametrize("level", ["Standard", "Basic"]) @EventGridPreparer() @ArgPasser() @recorded_by_proxy - def test_create_client_channel_name(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, - eventgrid_partner_namespace_topic_key, eventgrid_partner_namespace_topic_endpoint, eventgrid_partner_channel_name): - - client = self.create_eg_client(eventgrid_partner_namespace_topic_endpoint, eventgrid_partner_namespace_topic_key, level=level) - + def test_create_client_channel_name( + self, + level, + eventgrid_endpoint, + eventgrid_key, + eventgrid_topic_name, + eventgrid_event_subscription_name, + eventgrid_partner_namespace_topic_key, + eventgrid_partner_namespace_topic_endpoint, + eventgrid_partner_channel_name, + ): + + client = self.create_eg_client( + eventgrid_partner_namespace_topic_endpoint, eventgrid_partner_namespace_topic_key, level=level + ) + event = CloudEvent( type="Contoso.Items.ItemReceived", source="source", subject="MySubject", data={"test": "data"}, datacontenttype="application/json", - extensions={"extension1": "value1", "extension2": "value2"} + extensions={"extension1": "value1", "extension2": "value2"}, ) - if level=="Standard": + if level == "Standard": with pytest.raises(ValueError): - client.send( - topic_name=eventgrid_topic_name, events=event, channel_name=eventgrid_partner_channel_name - ) + client.send(topic_name=eventgrid_topic_name, events=event, channel_name=eventgrid_partner_channel_name) else: - client.send( - topic_name=eventgrid_topic_name, events=event, channel_name=eventgrid_partner_channel_name - ) + client.send(topic_name=eventgrid_topic_name, events=event, channel_name=eventgrid_partner_channel_name) + + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name, level) + @pytest.mark.live_test_only() @pytest.mark.parametrize("level", ["Standard", "Basic"]) @EventGridPreparer() @ArgPasser() @recorded_by_proxy - def test_publish_endpoint(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): - + def test_publish_endpoint( + self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): + client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) - + event = CloudEvent( type="Contoso.Items.ItemReceived", source="source", subject="MySubject", data={"test": "data"}, datacontenttype="application/json", - extensions={"extension1": "value1", "extension2": "value2"} + extensions={"extension1": "value1", "extension2": "value2"}, ) - if level=="Basic": + if level == "Basic": with pytest.raises(ResourceNotFoundError): - client.send( - topic_name=eventgrid_topic_name, events=event - ) + client.send(topic_name=eventgrid_topic_name, events=event) else: - client.send( - topic_name=eventgrid_topic_name, events=event - ) + client.send(topic_name=eventgrid_topic_name, events=event) + + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name, level) + @pytest.mark.live_test_only() @pytest.mark.parametrize("level", ["Standard", "Basic"]) @EventGridPreparer() @ArgPasser() @recorded_by_proxy - def test_publish_cncf_events(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, - eventgrid_cloud_event_topic_key, eventgrid_cloud_event_topic_endpoint): - if level=="Basic": - client = self.create_eg_client(eventgrid_cloud_event_topic_endpoint, eventgrid_cloud_event_topic_key, level=level) + def test_publish_cncf_events( + self, + level, + eventgrid_endpoint, + eventgrid_key, + eventgrid_topic_name, + eventgrid_event_subscription_name, + eventgrid_cloud_event_topic_key, + eventgrid_cloud_event_topic_endpoint, + ): + if level == "Basic": + client = self.create_eg_client( + eventgrid_cloud_event_topic_endpoint, eventgrid_cloud_event_topic_key, level=level + ) else: client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) - + attributes = { "type": "com.example.sampletype1", "source": "https://example.com/event-producer", @@ -222,51 +276,68 @@ def test_publish_cncf_events(self, level, eventgrid_endpoint, eventgrid_key, eve data = {"message": "Hello World!"} cloud_event = CNCFCloudEvent(attributes, data) - if level==ClientLevel.STANDARD: - with pytest.raises(HttpResponseError): - client.send( - topic_name=eventgrid_topic_name, events=cloud_event - ) - else: - client.send( - topic_name=eventgrid_topic_name, events=cloud_event - ) - + client.send(topic_name=eventgrid_topic_name, events=cloud_event) + + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name, level) + + @pytest.mark.live_test_only() @pytest.mark.parametrize("level", ["Standard", "Basic"]) @EventGridPreparer() @ArgPasser() @recorded_by_proxy - def test_create_client_cloud_event_dict(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, - eventgrid_cloud_event_topic_key, eventgrid_cloud_event_topic_endpoint): - if level=="Basic": - client = self.create_eg_client(eventgrid_cloud_event_topic_endpoint, eventgrid_cloud_event_topic_key, level=level) + def test_create_client_cloud_event_dict( + self, + level, + eventgrid_endpoint, + eventgrid_key, + eventgrid_topic_name, + eventgrid_event_subscription_name, + eventgrid_cloud_event_topic_key, + eventgrid_cloud_event_topic_endpoint, + ): + if level == "Basic": + client = self.create_eg_client( + eventgrid_cloud_event_topic_endpoint, eventgrid_cloud_event_topic_key, level=level + ) else: client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) - - event = {"type": "Contoso.Items.ItemReceived", + + event = { + "type": "Contoso.Items.ItemReceived", "source": "source", "subject": "MySubject", "data": {"test": "data"}, "datacontenttype": "application/json", - "extensions": {"extension1": "value1", "extension2": "value2"}} + "extension1": "value1", + "extension2": "value2", + } + + client.send(topic_name=eventgrid_topic_name, events=event) + + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name, level) - client.send( - topic_name=eventgrid_topic_name, events=event - ) @pytest.mark.live_test_only() @pytest.mark.parametrize("level", ["Standard", "Basic"]) @EventGridPreparer() @ArgPasser() @recorded_by_proxy - def test_create_client_publish_event_dict(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, - eventgrid_topic_key, eventgrid_topic_endpoint): - if level=="Basic": + def test_create_client_publish_event_dict( + self, + level, + eventgrid_endpoint, + eventgrid_key, + eventgrid_topic_name, + eventgrid_event_subscription_name, + eventgrid_topic_key, + eventgrid_topic_endpoint, + ): + if level == "Basic": client = self.create_eg_client(eventgrid_topic_endpoint, eventgrid_topic_key, level=level) else: client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) - + event = { "eventType": "Contoso.Items.ItemReceived", "data": {"itemSku": "Contoso Item SKU #1"}, @@ -276,12 +347,11 @@ def test_create_client_publish_event_dict(self, level, eventgrid_endpoint, event "eventTime": datetime.now(), } - if level==ClientLevel.STANDARD: + if level == ClientLevel.STANDARD: with pytest.raises(TypeError): - client.send( - topic_name=eventgrid_topic_name, events=event - ) + client.send(topic_name=eventgrid_topic_name, events=event) else: - client.send( - topic_name=eventgrid_topic_name, events=event - ) \ No newline at end of file + client.send(topic_name=eventgrid_topic_name, events=event) + + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name, level) + diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py index 19a90030a072..9a6b3517fdd0 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py @@ -14,79 +14,73 @@ from eventgrid_preparer import EventGridPreparer +def _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name): + events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_events=100) + tokens = [] + for detail in events.value: + token = detail.broker_properties.lock_token + tokens.append(token) + ack = client.acknowledge_cloud_events( + eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=tokens + ) class TestEGClientExceptions(AzureRecordedTestCase): def create_eg_client(self, endpoint, key): - client = EventGridClient( - endpoint=endpoint, credential=AzureKeyCredential(key) - ) + client = EventGridClient(endpoint=endpoint, credential=AzureKeyCredential(key)) return client - @pytest.mark.live_test_only() @EventGridPreparer() @recorded_by_proxy - def test_publish_binary_mode_xml(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_publish_binary_mode_xml( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) - + from xml.etree import ElementTree as ET + xml_string = """test""" - tree = xml_string.encode('utf-8') + tree = xml_string.encode("utf-8") event = CloudEvent( type="Contoso.Items.ItemReceived", source="source", subject="MySubject", data=tree, datacontenttype="text/xml", - extensions={"extension1": "value1", "extension2": "value2"} + extensions={"extension1": "value1", "extension2": "value2"}, ) - client.send( - topic_name=eventgrid_topic_name, events=event, binary_mode=True - ) + client.send(topic_name=eventgrid_topic_name, events=event, binary_mode=True) time.sleep(5) - events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) - - tokens = [] - for detail in events.value: - token = detail.broker_properties.lock_token - tokens.append(token) - rejected_result = client.reject_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=tokens) - - + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name) @pytest.mark.live_test_only() @EventGridPreparer() @recorded_by_proxy - def test_publish_binary_mode_cloud_event(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_publish_binary_mode_cloud_event( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) event = CloudEvent( type="Contoso.Items.ItemReceived", source="source", subject="MySubject", - data=b'this is binary data', - datacontenttype='text/plain' - ) - - client.send( - topic_name= eventgrid_topic_name, events=event, binary_mode=True + data=b"this is binary data", + datacontenttype="text/plain", ) - events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) - - tokens = [] - for detail in events.value: - token = detail.broker_properties.lock_token - tokens.append(token) - rejected_result = client.reject_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=tokens) + client.send(topic_name=eventgrid_topic_name, events=event, binary_mode=True) + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name) @EventGridPreparer() @recorded_by_proxy - def test_publish_binary_mode_incorrect_cloud_event(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_publish_binary_mode_incorrect_cloud_event( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) event = CloudEvent( @@ -94,17 +88,17 @@ def test_publish_binary_mode_incorrect_cloud_event(self, eventgrid_endpoint, eve source="source", subject="MySubject", data={"key": "value"}, - datacontenttype='text/plain' + datacontenttype="text/plain", ) with pytest.raises(TypeError): - client.send( - topic_name=eventgrid_topic_name, events=event, binary_mode=True - ) + client.send(topic_name=eventgrid_topic_name, events=event, binary_mode=True) @EventGridPreparer() @recorded_by_proxy - def test_publish_binary_mode_list_cloud_event(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_publish_binary_mode_list_cloud_event( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) event = CloudEvent( @@ -112,18 +106,18 @@ def test_publish_binary_mode_list_cloud_event(self, eventgrid_endpoint, eventgri source="source", subject="MySubject", data={"key": "value"}, - datacontenttype='text/plain' + datacontenttype="text/plain", ) with pytest.raises(TypeError): - client.send( - topic_name=eventgrid_topic_name, events=[event], binary_mode=True - ) + client.send(topic_name=eventgrid_topic_name, events=[event], binary_mode=True) @pytest.mark.live_test_only() @EventGridPreparer() @recorded_by_proxy - def test_publish_binary_mode_combinations(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_publish_binary_mode_combinations( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) event = CloudEvent( @@ -131,79 +125,107 @@ def test_publish_binary_mode_combinations(self, eventgrid_endpoint, eventgrid_ke source="source", subject="MySubject", data=b"hello", - datacontenttype='text/plain' + datacontenttype="text/plain", ) - dict_event = {"type": "Contoso.Items.ItemReceived", "source": "source", "subject": "MySubject", "data": b"hello", "datacontenttype": "text/plain"} + dict_event = { + "type": "Contoso.Items.ItemReceived", + "source": "source", + "subject": "MySubject", + "data": b"hello", + "datacontenttype": "text/plain", + } - - client.send( - topic_name=eventgrid_topic_name, events=event, binary_mode=True - ) + client.send(topic_name=eventgrid_topic_name, events=event, binary_mode=True) - client.send( - topic_name=eventgrid_topic_name, events=dict_event, binary_mode=True - ) - - events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) - tokens = [] - for detail in events.value: - token = detail.broker_properties.lock_token - tokens.append(token) - rejected_result = client.reject_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=tokens) + client.send(topic_name=eventgrid_topic_name, events=dict_event, binary_mode=True) + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name) @pytest.mark.live_test_only() @EventGridPreparer() @recorded_by_proxy - def test_publish_receive_cloud_event(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_publish_receive_cloud_event( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) event = CloudEvent( type="Contoso.Items.ItemReceived", source="source", subject="MySubject", - data=b'this is binary data', + data=b"this is binary data", ) - client.send( - topic_name=eventgrid_topic_name, events=[event] - ) + client.send(topic_name=eventgrid_topic_name, events=[event]) time.sleep(5) - events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) + events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_events=1) lock_token = events.value[0].broker_properties.lock_token - ack = client.acknowledge_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=[lock_token]) + ack = client.acknowledge_cloud_events( + eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=[lock_token] + ) assert len(ack.succeeded_lock_tokens) == 1 assert len(ack.failed_lock_tokens) == 0 @pytest.mark.live_test_only() @EventGridPreparer() @recorded_by_proxy - def test_publish_release_cloud_event(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_publish_release_cloud_event( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) event = CloudEvent( type="Contoso.Items.ItemReceived", source="source", subject="MySubject", - data=b'this is binary data', + data=b"this is binary data", ) - client.send( - topic_name=eventgrid_topic_name, events=[event] - ) - - time.sleep(5) + client.send(topic_name=eventgrid_topic_name, events=[event]) events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_events=1) lock_token = events.value[0].broker_properties.lock_token - ack = client.release_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=[lock_token]) + ack = client.release_cloud_events( + eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=[lock_token] + ) assert len(ack.succeeded_lock_tokens) == 1 assert len(ack.failed_lock_tokens) == 0 events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_events=1) - assert events.value[0].broker_properties.delivery_count > 1 \ No newline at end of file + assert events.value[0].broker_properties.delivery_count > 1 + + client.reject_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=[events.value[0].broker_properties.lock_token]) + + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name) + + + @pytest.mark.live_test_only() + @EventGridPreparer() + @recorded_by_proxy + def test_receive_type( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): + client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) + + event = CloudEvent( + type="Contoso.Items.ItemReceived", + source="source", + subject="MySubject", + data={"key": "value"}, + ) + + client.send(topic_name=eventgrid_topic_name, events=event) + + time.sleep(5) + + events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_events=1) + data = events.value[0].event.data + + assert isinstance(data, dict) + + _clean_up(client, eventgrid_topic_name, eventgrid_event_subscription_name) diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py index 2751e0615d23..6dab23edf38b 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py @@ -18,9 +18,7 @@ class TestEGClientExceptions(AzureRecordedTestCase): def create_eg_client(self, endpoint, key): - client = EventGridClient( - endpoint=endpoint, credential=AzureKeyCredential(key) - ) + client = EventGridClient(endpoint=endpoint, credential=AzureKeyCredential(key)) return client @EventGridPreparer() @@ -38,7 +36,7 @@ def test_publish_cloud_event_bad_request(self, eventgrid_endpoint, eventgrid_key client.send(topic_name=eventgrid_topic_name, events=[event]) @EventGridPreparer() - @recorded_by_proxy + @recorded_by_proxy def test_publish_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) event = CloudEvent( @@ -61,54 +59,54 @@ def test_receive_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key, @EventGridPreparer() @recorded_by_proxy - def test_receive_cloud_event_max_events_negative(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_receive_cloud_event_max_events_negative( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(HttpResponseError): - client.receive_cloud_events( - eventgrid_topic_name, eventgrid_event_subscription_name, max_events=-20 - ) + client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_events=-20) @EventGridPreparer() @recorded_by_proxy - def test_receive_cloud_event_timeout_negative(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_receive_cloud_event_timeout_negative( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(HttpResponseError): - client.receive_cloud_events( - eventgrid_topic_name, eventgrid_event_subscription_name, max_wait_time=-20 - ) + client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_wait_time=-20) @EventGridPreparer() @recorded_by_proxy - def test_receive_cloud_event_timeout_max_value(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_receive_cloud_event_timeout_max_value( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(HttpResponseError): - client.receive_cloud_events( - eventgrid_topic_name, eventgrid_event_subscription_name, max_wait_time=121 - ) + client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_wait_time=121) @EventGridPreparer() @recorded_by_proxy - def test_receive_cloud_event_timeout_min_value(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_receive_cloud_event_timeout_min_value( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(HttpResponseError): - client.receive_cloud_events( - eventgrid_topic_name, eventgrid_event_subscription_name, max_wait_time=9 - ) + client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_wait_time=9) @EventGridPreparer() @recorded_by_proxy - def test_acknowledge_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key, eventgrid_event_subscription_name): + def test_acknowledge_cloud_event_not_found( + self, eventgrid_endpoint, eventgrid_key, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(ResourceNotFoundError): lock_tokens = ["faketoken"] - client.acknowledge_cloud_events( - "faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens - ) + client.acknowledge_cloud_events("faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens) @EventGridPreparer() @recorded_by_proxy @@ -117,9 +115,7 @@ def test_release_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key, with pytest.raises(ResourceNotFoundError): lock_tokens = ["faketoken"] - client.release_cloud_events( - "faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens - ) + client.release_cloud_events("faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens) @EventGridPreparer() @recorded_by_proxy @@ -128,13 +124,13 @@ def test_reject_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key, e lock_tokens = ["faketoken"] with pytest.raises(ResourceNotFoundError): - client.reject_cloud_events( - "faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens - ) + client.reject_cloud_events("faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens) @EventGridPreparer() @recorded_by_proxy - def test_acknowledge_cloud_event_invalid_token(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_acknowledge_cloud_event_invalid_token( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) lock_tokens = ["faketoken"] @@ -148,7 +144,9 @@ def test_acknowledge_cloud_event_invalid_token(self, eventgrid_endpoint, eventgr @EventGridPreparer() @recorded_by_proxy - def test_release_cloud_event_invalid_token(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_release_cloud_event_invalid_token( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) lock_tokens = ["faketoken"] @@ -162,7 +160,9 @@ def test_release_cloud_event_invalid_token(self, eventgrid_endpoint, eventgrid_k @EventGridPreparer() @recorded_by_proxy - def test_reject_cloud_event_invalid_token(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + def test_reject_cloud_event_invalid_token( + self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name + ): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) lock_tokens = ["faketoken"] diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_eg_event_get_bytes.py b/sdk/eventgrid/azure-eventgrid/tests/test_eg_event_get_bytes.py index 4e1910b1bbad..bbd5ad4ac0f4 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_eg_event_get_bytes.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_eg_event_get_bytes.py @@ -135,9 +135,7 @@ def test_get_bytes_storage_queue_wrong_content(): string = "This is a random string which must fail" obj = MockQueueMessage(content=string) - with pytest.raises( - ValueError, match="Failed to load JSON content from the object." - ): + with pytest.raises(ValueError, match="Failed to load JSON content from the object."): _get_json_content(obj) @@ -172,9 +170,7 @@ def test_get_bytes_servicebus_wrong_content(): sequence_number=11219, lock_token="233146e3-d5a6-45eb-826f-691d82fb8b13", ) - with pytest.raises( - ValueError, match="Failed to load JSON content from the object." - ): + with pytest.raises(ValueError, match="Failed to load JSON content from the object."): dict = _get_json_content(obj) @@ -188,9 +184,7 @@ def test_get_bytes_eventhubs(): def test_get_bytes_eventhubs_wrong_content(): obj = MockEventhubData(body=MockEhBody(data="random string")) - with pytest.raises( - ValueError, match="Failed to load JSON content from the object." - ): + with pytest.raises(ValueError, match="Failed to load JSON content from the object."): dict = _get_json_content(obj) diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_eg_publisher_client.py b/sdk/eventgrid/azure-eventgrid/tests/test_eg_publisher_client.py index c939ee1d8bc8..69aac887821f 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_eg_publisher_client.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_eg_publisher_client.py @@ -35,9 +35,7 @@ class TestEventGridPublisherClient(AzureRecordedTestCase): def create_eg_publisher_client(self, endpoint): credential = self.get_credential(EventGridPublisherClient) - client = self.create_client_from_credential( - EventGridPublisherClient, credential=credential, endpoint=endpoint - ) + client = self.create_client_from_credential(EventGridPublisherClient, credential=credential, endpoint=endpoint) return client @EventGridPreparer() @@ -54,9 +52,7 @@ def test_send_event_grid_event_data_dict(self, eventgrid_topic_endpoint): @EventGridPreparer() @recorded_by_proxy - def test_send_event_grid_event_fails_without_full_url( - self, eventgrid_topic_key, eventgrid_topic_endpoint - ): + def test_send_event_grid_event_fails_without_full_url(self, eventgrid_topic_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_key) parsed_url = urlparse(eventgrid_topic_endpoint) client = EventGridPublisherClient(parsed_url.netloc, akc_credential) @@ -101,9 +97,7 @@ def test_send_event_grid_event_data_str(self, eventgrid_topic_endpoint): @EventGridPreparer() @recorded_by_proxy - def test_send_event_grid_event_data_bytes( - self, eventgrid_topic_endpoint - ): + def test_send_event_grid_event_data_bytes(self, eventgrid_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_topic_endpoint) eg_event = EventGridEvent( subject="sample", @@ -116,9 +110,7 @@ def test_send_event_grid_event_data_bytes( @EventGridPreparer() @recorded_by_proxy - def test_send_event_grid_event_dict_data_bytes( - self, eventgrid_topic_endpoint - ): + def test_send_event_grid_event_dict_data_bytes(self, eventgrid_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_topic_endpoint) eg_event = { "subject": "sample", @@ -149,9 +141,7 @@ def test_send_event_grid_event_dict_data_dict(self, eventgrid_topic_endpoint): @EventGridPreparer() @recorded_by_proxy - def test_send_cloud_event_data_dict( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cloud_event_data_dict(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent( source="http://samplesource.dev", @@ -163,13 +153,9 @@ def test_send_cloud_event_data_dict( @pytest.mark.skip("https://github.com/Azure/azure-sdk-for-python/issues/16993") @EventGridPreparer() @recorded_by_proxy - def test_send_cloud_event_data_NULL( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cloud_event_data_NULL(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) - cloud_event = CloudEvent( - source="http://samplesource.dev", data=NULL, type="Sample.Cloud.Event" - ) + cloud_event = CloudEvent(source="http://samplesource.dev", data=NULL, type="Sample.Cloud.Event") def callback(request): req = json.loads(request.http_request.body) @@ -179,9 +165,7 @@ def callback(request): @EventGridPreparer() @recorded_by_proxy - def test_send_cloud_event_data_base64_using_data( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cloud_event_data_base64_using_data(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent( source="http://samplesource.dev", @@ -197,9 +181,7 @@ def callback(request): client.send(cloud_event, raw_response_hook=callback) def test_send_cloud_event_fails_on_providing_data_and_b64(self): - with pytest.raises( - ValueError, match="Unexpected keyword arguments data_base64.*" - ): + with pytest.raises(ValueError, match="Unexpected keyword arguments data_base64.*"): cloud_event = CloudEvent( source="http://samplesource.dev", data_base64=b"cloudevent", @@ -209,20 +191,14 @@ def test_send_cloud_event_fails_on_providing_data_and_b64(self): @EventGridPreparer() @recorded_by_proxy - def test_send_cloud_event_data_none( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cloud_event_data_none(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) - cloud_event = CloudEvent( - source="http://samplesource.dev", data=None, type="Sample.Cloud.Event" - ) + cloud_event = CloudEvent(source="http://samplesource.dev", data=None, type="Sample.Cloud.Event") client.send(cloud_event) @EventGridPreparer() @recorded_by_proxy - def test_send_cloud_event_data_str( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cloud_event_data_str(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent( source="http://samplesource.dev", @@ -233,9 +209,7 @@ def test_send_cloud_event_data_str( @EventGridPreparer() @recorded_by_proxy - def test_send_cloud_event_data_bytes( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cloud_event_data_bytes(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent( source="http://samplesource.dev", @@ -246,9 +220,7 @@ def test_send_cloud_event_data_bytes( @EventGridPreparer() @recorded_by_proxy - def test_send_cloud_event_data_as_list( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cloud_event_data_as_list(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent( source="http://samplesource.dev", @@ -259,9 +231,7 @@ def test_send_cloud_event_data_as_list( @EventGridPreparer() @recorded_by_proxy - def test_send_cloud_event_data_with_extensions( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cloud_event_data_with_extensions(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent( source="http://samplesource.dev", @@ -277,9 +247,7 @@ def test_send_cloud_event_data_with_extensions( @EventGridPreparer() @recorded_by_proxy - def test_send_cloud_event_dict( - self, eventgrid_cloud_event_topic_endpoint - ): + def test_send_cloud_event_dict(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event1 = { "id": "1234", @@ -294,9 +262,7 @@ def test_send_cloud_event_dict( @recorded_by_proxy def test_send_signature_credential(self, eventgrid_topic_key, eventgrid_topic_endpoint): expiration_date_utc = dt.datetime.now(UTC()) + timedelta(hours=1) - signature = generate_sas( - eventgrid_topic_endpoint, eventgrid_topic_key, expiration_date_utc - ) + signature = generate_sas(eventgrid_topic_endpoint, eventgrid_topic_key, expiration_date_utc) credential = AzureSasCredential(signature) client = EventGridPublisherClient(eventgrid_topic_endpoint, credential) eg_event = EventGridEvent( @@ -310,16 +276,12 @@ def test_send_signature_credential(self, eventgrid_topic_key, eventgrid_topic_en @EventGridPreparer() @recorded_by_proxy def test_send_NONE_credential(self, eventgrid_topic_endpoint): - with pytest.raises( - ValueError, match="Parameter 'self._credential' must not be None." - ): + with pytest.raises(ValueError, match="Parameter 'self._credential' must not be None."): client = EventGridPublisherClient(eventgrid_topic_endpoint, None) @EventGridPreparer() @recorded_by_proxy - def test_send_custom_schema_event( - self, eventgrid_custom_event_topic_endpoint - ): + def test_send_custom_schema_event(self, eventgrid_custom_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_custom_event_topic_endpoint) custom_event = { "customSubject": "sample", @@ -333,9 +295,7 @@ def test_send_custom_schema_event( @EventGridPreparer() @recorded_by_proxy - def test_send_custom_schema_event_as_list( - self, eventgrid_custom_event_topic_endpoint - ): + def test_send_custom_schema_event_as_list(self, eventgrid_custom_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_custom_event_topic_endpoint) custom_event1 = { "customSubject": "sample", @@ -380,11 +340,14 @@ def test_send_token_credential(self, eventgrid_topic_endpoint): @pytest.mark.live_test_only @EventGridPreparer() @recorded_by_proxy - def test_send_partner_namespace(self, eventgrid_partner_namespace_topic_endpoint, eventgrid_partner_namespace_topic_key, eventgrid_partner_channel_name): + def test_send_partner_namespace( + self, + eventgrid_partner_namespace_topic_endpoint, + eventgrid_partner_namespace_topic_key, + eventgrid_partner_channel_name, + ): credential = AzureKeyCredential(eventgrid_partner_namespace_topic_key) - client = EventGridPublisherClient( - eventgrid_partner_namespace_topic_endpoint, credential - ) + client = EventGridPublisherClient(eventgrid_partner_namespace_topic_endpoint, credential) cloud_event = CloudEvent( source="http://samplesource.dev", data="cloudevent", diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_eg_publisher_client_async.py b/sdk/eventgrid/azure-eventgrid/tests/test_eg_publisher_client_async.py index c483097183c7..3eee77aa3ce2 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_eg_publisher_client_async.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_eg_publisher_client_async.py @@ -31,17 +31,13 @@ class TestEventGridPublisherClient(AzureRecordedTestCase): def create_eg_publisher_client(self, endpoint): credential = self.get_credential(EventGridPublisherClient, is_async=True) - client = self.create_client_from_credential( - EventGridPublisherClient, credential=credential, endpoint=endpoint - ) + client = self.create_client_from_credential(EventGridPublisherClient, credential=credential, endpoint=endpoint) return client @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_event_grid_event_data_dict_async( - self, eventgrid_topic_endpoint - ): + async def test_send_event_grid_event_data_dict_async(self, eventgrid_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_topic_endpoint) eg_event = EventGridEvent( subject="sample", @@ -54,9 +50,7 @@ async def test_send_event_grid_event_data_dict_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_event_grid_event_data_as_list_async( - self, eventgrid_topic_endpoint - ): + async def test_send_event_grid_event_data_as_list_async(self, eventgrid_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_topic_endpoint) eg_event1 = EventGridEvent( subject="sample", @@ -93,9 +87,7 @@ async def test_send_event_grid_event_fails_without_full_url_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_event_grid_event_data_str_async( - self, eventgrid_topic_endpoint - ): + async def test_send_event_grid_event_data_str_async(self, eventgrid_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_topic_endpoint) eg_event = EventGridEvent( subject="sample", @@ -108,9 +100,7 @@ async def test_send_event_grid_event_data_str_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_event_grid_event_data_bytes_async( - self, eventgrid_topic_endpoint - ): + async def test_send_event_grid_event_data_bytes_async(self, eventgrid_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_topic_endpoint) eg_event = EventGridEvent( subject="sample", @@ -124,9 +114,7 @@ async def test_send_event_grid_event_data_bytes_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_event_grid_event_dict_data_bytes_async( - self, eventgrid_topic_endpoint - ): + async def test_send_event_grid_event_dict_data_bytes_async(self, eventgrid_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_topic_endpoint) eg_event = { "subject": "sample", @@ -142,36 +130,25 @@ async def test_send_event_grid_event_dict_data_bytes_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cloud_event_data_dict_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cloud_event_data_dict_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent( - source = "http://samplesource.dev", - data = {"sample": "cloudevent"}, - type="Sample.Cloud.Event" - ) + source="http://samplesource.dev", data={"sample": "cloudevent"}, type="Sample.Cloud.Event" + ) await client.send(cloud_event) - @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio async def test_send_cloud_event_data_str(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) - cloud_event = CloudEvent( - source = "http://samplesource.dev", - data = "cloudevent", - type="Sample.Cloud.Event" - ) + cloud_event = CloudEvent(source="http://samplesource.dev", data="cloudevent", type="Sample.Cloud.Event") await client.send(cloud_event) @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cloud_event_data_str_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cloud_event_data_str_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent( source="http://samplesource.dev", @@ -183,9 +160,7 @@ async def test_send_cloud_event_data_str_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cloud_event_data_bytes_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cloud_event_data_bytes_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent( source="http://samplesource.dev", @@ -197,9 +172,7 @@ async def test_send_cloud_event_data_bytes_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cloud_event_data_as_list_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cloud_event_data_as_list_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent( source="http://samplesource.dev", @@ -211,9 +184,7 @@ async def test_send_cloud_event_data_as_list_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cloud_event_data_with_extensions_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cloud_event_data_with_extensions_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent( source="http://samplesource.dev", @@ -230,9 +201,7 @@ async def test_send_cloud_event_data_with_extensions_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cloud_event_dict_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cloud_event_dict_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) cloud_event1 = { "id": "1234", @@ -246,26 +215,18 @@ async def test_send_cloud_event_dict_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cloud_event_data_none_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cloud_event_data_none_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) - cloud_event = CloudEvent( - source="http://samplesource.dev", data=None, type="Sample.Cloud.Event" - ) + cloud_event = CloudEvent(source="http://samplesource.dev", data=None, type="Sample.Cloud.Event") await client.send(cloud_event) @pytest.mark.skip("https://github.com/Azure/azure-sdk-for-python/issues/16993") @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_cloud_event_data_NULL_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_cloud_event_data_NULL_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) - cloud_event = CloudEvent( - source="http://samplesource.dev", data=NULL, type="Sample.Cloud.Event" - ) + cloud_event = CloudEvent(source="http://samplesource.dev", data=NULL, type="Sample.Cloud.Event") def callback(request): req = json.loads(request.http_request.body) @@ -276,13 +237,9 @@ def callback(request): @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_signature_credential_async( - self, eventgrid_topic_key, eventgrid_topic_endpoint - ): + async def test_send_signature_credential_async(self, eventgrid_topic_key, eventgrid_topic_endpoint): expiration_date_utc = dt.datetime.now(UTC()) + timedelta(hours=1) - signature = generate_sas( - eventgrid_topic_endpoint, eventgrid_topic_key, expiration_date_utc - ) + signature = generate_sas(eventgrid_topic_endpoint, eventgrid_topic_key, expiration_date_utc) credential = AzureSasCredential(signature) client = EventGridPublisherClient(eventgrid_topic_endpoint, credential) eg_event = EventGridEvent( @@ -296,9 +253,7 @@ async def test_send_signature_credential_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_custom_schema_event_async( - self, eventgrid_custom_event_topic_endpoint - ): + async def test_send_custom_schema_event_async(self, eventgrid_custom_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_custom_event_topic_endpoint) custom_event = { "customSubject": "sample", @@ -313,9 +268,7 @@ async def test_send_custom_schema_event_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_custom_schema_event_as_list_async( - self, eventgrid_custom_event_topic_endpoint - ): + async def test_send_custom_schema_event_as_list_async(self, eventgrid_custom_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_custom_event_topic_endpoint) custom_event1 = { "customSubject": "sample", @@ -338,9 +291,7 @@ async def test_send_custom_schema_event_as_list_async( @EventGridPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_send_and_close_async_session_async( - self, eventgrid_cloud_event_topic_endpoint - ): + async def test_send_and_close_async_session_async(self, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_cloud_event_topic_endpoint) async with client: # this throws if client can't close cloud_event = CloudEvent( @@ -354,9 +305,7 @@ async def test_send_and_close_async_session_async( @EventGridPreparer() @recorded_by_proxy_async def test_send_NONE_credential_async(self, eventgrid_topic_endpoint): - with pytest.raises( - ValueError, match="Parameter 'self._credential' must not be None." - ): + with pytest.raises(ValueError, match="Parameter 'self._credential' must not be None."): client = EventGridPublisherClient(eventgrid_topic_endpoint, None) @pytest.mark.live_test_only @@ -377,11 +326,14 @@ async def test_send_token_credential_async(self, eventgrid_topic_endpoint): @pytest.mark.live_test_only @EventGridPreparer() @recorded_by_proxy_async - async def test_send_partner_namespace_async(self, eventgrid_partner_namespace_topic_endpoint, eventgrid_partner_namespace_topic_key, eventgrid_partner_channel_name): + async def test_send_partner_namespace_async( + self, + eventgrid_partner_namespace_topic_endpoint, + eventgrid_partner_namespace_topic_key, + eventgrid_partner_channel_name, + ): credential = AzureKeyCredential(eventgrid_partner_namespace_topic_key) - client = EventGridPublisherClient( - eventgrid_partner_namespace_topic_endpoint, credential - ) + client = EventGridPublisherClient(eventgrid_partner_namespace_topic_endpoint, credential) cloud_event = CloudEvent( source="http://samplesource.dev", data="cloudevent", @@ -392,6 +344,4 @@ def callback(request): req = request.http_request.headers assert req.get("aeg-channel-name") == eventgrid_partner_channel_name - await client.send( - cloud_event, channel_name=eventgrid_partner_channel_name, raw_request_hook=callback - ) + await client.send(cloud_event, channel_name=eventgrid_partner_channel_name, raw_request_hook=callback) diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_exceptions.py b/sdk/eventgrid/azure-eventgrid/tests/test_exceptions.py index a6cddbd4bc1e..a19b3dd8e1a1 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_exceptions.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_exceptions.py @@ -38,9 +38,7 @@ class TestEventGridPublisherClientExceptions(AzureMgmtRecordedTestCase): def create_eg_publisher_client(self, endpoint): credential = self.get_credential(EventGridPublisherClient) - client = self.create_client_from_credential( - EventGridPublisherClient, credential=credential, endpoint=endpoint - ) + client = self.create_client_from_credential(EventGridPublisherClient, credential=credential, endpoint=endpoint) return client @EventGridPreparer() @@ -82,9 +80,7 @@ def test_raise_on_bad_resource(self): def test_raise_on_large_payload(self, eventgrid_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_topic_endpoint) - path = os.path.abspath( - os.path.join(os.path.abspath(__file__), "..", "./large_data.json") - ) + path = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "./large_data.json")) with open(path) as json_file: data = json.load(json_file) eg_event = EventGridEvent( diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_exceptions_async.py b/sdk/eventgrid/azure-eventgrid/tests/test_exceptions_async.py index d69eb481f763..461c17453482 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_exceptions_async.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_exceptions_async.py @@ -42,9 +42,7 @@ class TestEventGridPublisherClientExceptionsAsync(AzureRecordedTestCase): def create_eg_publisher_client(self, endpoint): credential = self.get_credential(EventGridPublisherClient, is_async=True) - client = self.create_client_from_credential( - EventGridPublisherClient, credential=credential, endpoint=endpoint - ) + client = self.create_client_from_credential(EventGridPublisherClient, credential=credential, endpoint=endpoint) return client @EventGridPreparer() @@ -90,9 +88,7 @@ async def test_raise_on_bad_resource(self): async def test_raise_on_large_payload(self, eventgrid_topic_endpoint): client = self.create_eg_publisher_client(eventgrid_topic_endpoint) - path = os.path.abspath( - os.path.join(os.path.abspath(__file__), "..", "./large_data.json") - ) + path = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "./large_data.json")) with open(path) as json_file: data = json.load(json_file) eg_event = EventGridEvent( diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_serialization.py b/sdk/eventgrid/azure-eventgrid/tests/test_serialization.py index a83caf6954ae..cebc392e4dea 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_serialization.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_serialization.py @@ -104,10 +104,7 @@ def test_event_grid_event_raises_on_no_data(self): def test_import_from_system_events(self): var = SystemEventNames.AcsChatMemberAddedToThreadWithUserEventName assert var == "Microsoft.Communication.ChatMemberAddedToThreadWithUser" - assert ( - SystemEventNames.KeyVaultKeyNearExpiryEventName - == "Microsoft.KeyVault.KeyNearExpiry" - ) + assert SystemEventNames.KeyVaultKeyNearExpiryEventName == "Microsoft.KeyVault.KeyNearExpiry" var = SystemEventNames.ServiceBusActiveMessagesAvailableWithNoListenersEventName assert var == "Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners" var = SystemEventNames.AcsChatThreadParticipantAddedEventName @@ -131,23 +128,9 @@ def test_servicebus_system_events_alias(self): SystemEventNames.ServiceBusDeadletterMessagesAvailableWithNoListenerEventName == SystemEventNames.ServiceBusDeadletterMessagesAvailableWithNoListenersEventName ) - assert ( - SystemEventNames.ServiceBusDeadletterMessagesAvailableWithNoListenerEventName - == val - ) - assert ( - SystemEventNames.ServiceBusDeadletterMessagesAvailableWithNoListenersEventName - == val - ) - assert ( - SystemEventNames(val) - == SystemEventNames.ServiceBusDeadletterMessagesAvailableWithNoListenerEventName - ) - assert ( - SystemEventNames(val) - == SystemEventNames.ServiceBusDeadletterMessagesAvailableWithNoListenersEventName - ) + assert SystemEventNames.ServiceBusDeadletterMessagesAvailableWithNoListenerEventName == val + assert SystemEventNames.ServiceBusDeadletterMessagesAvailableWithNoListenersEventName == val + assert SystemEventNames(val) == SystemEventNames.ServiceBusDeadletterMessagesAvailableWithNoListenerEventName + assert SystemEventNames(val) == SystemEventNames.ServiceBusDeadletterMessagesAvailableWithNoListenersEventName with pytest.raises(ValueError): - SystemEventNames( - "Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener" - ) + SystemEventNames("Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener") diff --git a/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py b/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py index 2824d8a2251b..f597ca727f2a 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py +++ b/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py @@ -10,21 +10,24 @@ from azure.eventgrid.models import * from azure.core.messaging import CloudEvent + class MyTestClass(object): def __init__(self, name): self.name = name + def __str__(self): return self.name - -class TestEGClientExceptions(): - + + +class TestEGClientExceptions: + def test_binary_request_format(self): event = CloudEvent( type="Contoso.Items.ItemReceived", source="source", subject="MySubject", - data=b'this is binary data', - datacontenttype="application/json" + data=b"this is binary data", + datacontenttype="application/json", ) request = _to_http_request("https://MYTOPIC.westus2-1.eventgrid.azure.net/api/events", event=event) @@ -39,9 +42,9 @@ def test_binary_request_format_with_extensions_and_datacontenttype(self): type="Contoso.Items.ItemReceived", source="source", subject="MySubject", - data=b'this is my data', + data=b"this is my data", datacontenttype="application/json", - extensions={"extension1": "value1", "extension2": "value2"} + extensions={"extension1": "value1", "extension2": "value2"}, ) request = _to_http_request("https://MYTOPIC.westus2-1.eventgrid.azure.net/api/events", event=event) @@ -60,9 +63,8 @@ def test_class_binary_request_format_error(self): subject="MySubject", data=test_class, datacontenttype="application/json", - extensions={"extension1": "value1", "extension2": "value2"} + extensions={"extension1": "value1", "extension2": "value2"}, ) with pytest.raises(TypeError): _to_http_request("https://MYTOPIC.westus2-1.eventgrid.azure.net/api/events", event=event) -