Skip to content

Commit 92747dd

Browse files
author
Rakshith Bhyravabhotla
authored
[eventgrid] Black formatting and tests suite (#16989)
* Black formatting * tests * recordings * test
1 parent 878e384 commit 92747dd

14 files changed

+352
-181
lines changed

sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,11 @@
1010
from ._models import CloudEvent, EventGridEvent
1111
from ._version import VERSION
1212

13-
__all__ = ['EventGridPublisherClient', 'CloudEvent',
14-
'EventGridEvent', 'generate_sas', 'SystemEventNames'
15-
]
13+
__all__ = [
14+
"EventGridPublisherClient",
15+
"CloudEvent",
16+
"EventGridEvent",
17+
"generate_sas",
18+
"SystemEventNames",
19+
]
1620
__version__ = VERSION

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_constants.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
# Licensed under the MIT License. See License.txt in the project root for license information.
44
# --------------------------------------------------------------------------------------------
55

6-
EVENTGRID_KEY_HEADER = 'aeg-sas-key'
7-
EVENTGRID_TOKEN_HEADER = 'aeg-sas-token'
6+
EVENTGRID_KEY_HEADER = "aeg-sas-key"
7+
EVENTGRID_TOKEN_HEADER = "aeg-sas-token"
88
DEFAULT_API_VERSION = "2018-01-01"
9-
SAFE_ENCODE = '~()*!.\''
9+
SAFE_ENCODE = "~()*!.'"

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_event_mappings.py

+89-31
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,52 @@
44
# --------------------------------------------------------------------------------------------
55
from enum import Enum
66

7+
78
class SystemEventNames(str, Enum):
89
"""
910
This enum represents the names of the various event types for the system events published to
1011
Azure Event Grid. To check the list of recognizable system topics,
1112
visit https://docs.microsoft.com/azure/event-grid/system-topics.
1213
"""
13-
ACSChatMemberAddedToThreadWithUserEventName = "Microsoft.Communication.ChatMemberAddedToThreadWithUser"
14-
ACSChatMemberRemovedFromThreadWithUserEventName = "Microsoft.Communication.ChatMemberRemovedFromThreadWithUser"
14+
15+
ACSChatMemberAddedToThreadWithUserEventName = (
16+
"Microsoft.Communication.ChatMemberAddedToThreadWithUser"
17+
)
18+
ACSChatMemberRemovedFromThreadWithUserEventName = (
19+
"Microsoft.Communication.ChatMemberRemovedFromThreadWithUser"
20+
)
1521
ACSChatMessageDeletedEventName = "Microsoft.Communication.ChatMessageDeleted"
1622
ACSChatMessageEditedEventName = "Microsoft.Communication.ChatMessageEdited"
1723
ACSChatMessageReceivedEventName = "Microsoft.Communication.ChatMessageReceived"
18-
ACSChatThreadCreatedWithUserEventName = "Microsoft.Communication.ChatThreadCreatedWithUser"
19-
ACSChatThreadPropertiesUpdatedPerUserEventName = "Microsoft.Communication.ChatThreadPropertiesUpdatedPerUser"
20-
ACSChatThreadWithUserDeletedEventName = "Microsoft.Communication.ChatThreadWithUserDeleted"
21-
ACSSMSDeliveryReportReceivedEventName = "Microsoft.Communication.SMSDeliveryReportReceived"
24+
ACSChatThreadCreatedWithUserEventName = (
25+
"Microsoft.Communication.ChatThreadCreatedWithUser"
26+
)
27+
ACSChatThreadPropertiesUpdatedPerUserEventName = (
28+
"Microsoft.Communication.ChatThreadPropertiesUpdatedPerUser"
29+
)
30+
ACSChatThreadWithUserDeletedEventName = (
31+
"Microsoft.Communication.ChatThreadWithUserDeleted"
32+
)
33+
ACSSMSDeliveryReportReceivedEventName = (
34+
"Microsoft.Communication.SMSDeliveryReportReceived"
35+
)
2236
ACSSMSReceivedEventName = "Microsoft.Communication.SMSReceived"
23-
AppConfigurationKeyValueDeletedEventName = "Microsoft.AppConfiguration.KeyValueDeleted"
24-
AppConfigurationKeyValueModifiedEventName = "Microsoft.AppConfiguration.KeyValueModified"
37+
AppConfigurationKeyValueDeletedEventName = (
38+
"Microsoft.AppConfiguration.KeyValueDeleted"
39+
)
40+
AppConfigurationKeyValueModifiedEventName = (
41+
"Microsoft.AppConfiguration.KeyValueModified"
42+
)
2543
ContainerRegistryChartDeletedEventName = "Microsoft.ContainerRegistry.ChartDeleted"
2644
ContainerRegistryChartPushedEventName = "Microsoft.ContainerRegistry.ChartPushed"
2745
ContainerRegistryImageDeletedEventName = "Microsoft.ContainerRegistry.ImageDeleted"
2846
ContainerRegistryImagePushedEventName = "Microsoft.ContainerRegistry.ImagePushed"
29-
EventGridSubscriptionDeletedEventName = "Microsoft.EventGrid.SubscriptionDeletedEvent"
30-
EventGridSubscriptionValidationEventName = "Microsoft.EventGrid.SubscriptionValidationEvent"
47+
EventGridSubscriptionDeletedEventName = (
48+
"Microsoft.EventGrid.SubscriptionDeletedEvent"
49+
)
50+
EventGridSubscriptionValidationEventName = (
51+
"Microsoft.EventGrid.SubscriptionValidationEvent"
52+
)
3153
EventHubCaptureFileCreatedEventName = "Microsoft.EventHub.CaptureFileCreated"
3254
IoTHubDeviceConnectedEventName = "Microsoft.Devices.DeviceConnected"
3355
IoTHubDeviceCreatedEventName = "Microsoft.Devices.DeviceCreated"
@@ -37,18 +59,32 @@ class SystemEventNames(str, Enum):
3759
KeyVaultAccessPolicyChangedEventName = "Microsoft.KeyVault.VaultAccessPolicyChanged"
3860
KeyVaultCertificateExpiredEventName = "Microsoft.KeyVault.CertificateExpired"
3961
KeyVaultCertificateNearExpiryEventName = "Microsoft.KeyVault.CertificateNearExpiry"
40-
KeyVaultCertificateNewVersionCreatedEventName = "Microsoft.KeyVault.CertificateNewVersionCreated"
62+
KeyVaultCertificateNewVersionCreatedEventName = (
63+
"Microsoft.KeyVault.CertificateNewVersionCreated"
64+
)
4165
KeyVaultKeyExpiredEventName = "Microsoft.KeyVault.KeyExpired"
4266
KeyVaultKeyNearExpiryEventName = "Microsoft.KeyVault.KeyNearExpiry"
4367
KeyVaultKeyNewVersionCreatedEventName = "Microsoft.KeyVault.KeyNewVersionCreated"
4468
KeyVaultSecretExpiredEventName = "Microsoft.KeyVault.SecretExpired"
4569
KeyVaultSecretNearExpiryEventName = "Microsoft.KeyVault.SecretNearExpiry"
46-
KeyVaultSecretNewVersionCreatedEventName = "Microsoft.KeyVault.SecretNewVersionCreated"
47-
MachineLearningServicesDatasetDriftDetectedEventName = "Microsoft.MachineLearningServices.DatasetDriftDetected"
48-
MachineLearningServicesModelDeployedEventName = "Microsoft.MachineLearningServices.ModelDeployed"
49-
MachineLearningServicesModelRegisteredEventName = "Microsoft.MachineLearningServices.ModelRegistered"
50-
MachineLearningServicesRunCompletedEventName = "Microsoft.MachineLearningServices.RunCompleted"
51-
MachineLearningServicesRunStatusChangedEventName = "Microsoft.MachineLearningServices.RunStatusChanged"
70+
KeyVaultSecretNewVersionCreatedEventName = (
71+
"Microsoft.KeyVault.SecretNewVersionCreated"
72+
)
73+
MachineLearningServicesDatasetDriftDetectedEventName = (
74+
"Microsoft.MachineLearningServices.DatasetDriftDetected"
75+
)
76+
MachineLearningServicesModelDeployedEventName = (
77+
"Microsoft.MachineLearningServices.ModelDeployed"
78+
)
79+
MachineLearningServicesModelRegisteredEventName = (
80+
"Microsoft.MachineLearningServices.ModelRegistered"
81+
)
82+
MachineLearningServicesRunCompletedEventName = (
83+
"Microsoft.MachineLearningServices.RunCompleted"
84+
)
85+
MachineLearningServicesRunStatusChangedEventName = (
86+
"Microsoft.MachineLearningServices.RunStatusChanged"
87+
)
5288
MapsGeofenceEnteredEventName = "Microsoft.Maps.GeofenceEntered"
5389
MapsGeofenceExitedEventName = "Microsoft.Maps.GeofenceExited"
5490
MapsGeofenceResultEventName = "Microsoft.Maps.GeofenceResult"
@@ -67,15 +103,31 @@ class SystemEventNames(str, Enum):
67103
MediaJobProcessingEventName = "Microsoft.Media.JobProcessing"
68104
MediaJobScheduledEventName = "Microsoft.Media.JobScheduled"
69105
MediaJobStateChangeEventName = "Microsoft.Media.JobStateChange"
70-
MediaLiveEventConnectionRejectedEventName = "Microsoft.Media.LiveEventConnectionRejected"
71-
MediaLiveEventEncoderConnectedEventName = "Microsoft.Media.LiveEventEncoderConnected"
72-
MediaLiveEventEncoderDisconnectedEventName = "Microsoft.Media.LiveEventEncoderDisconnected"
73-
MediaLiveEventIncomingDataChunkDroppedEventName = "Microsoft.Media.LiveEventIncomingDataChunkDropped"
74-
MediaLiveEventIncomingStreamReceivedEventName = "Microsoft.Media.LiveEventIncomingStreamReceived"
75-
MediaLiveEventIncomingStreamsOutOfSyncEventName = "Microsoft.Media.LiveEventIncomingStreamsOutOfSync"
76-
MediaLiveEventIncomingVideoStreamsOutOfSyncEventName = "Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync"
106+
MediaLiveEventConnectionRejectedEventName = (
107+
"Microsoft.Media.LiveEventConnectionRejected"
108+
)
109+
MediaLiveEventEncoderConnectedEventName = (
110+
"Microsoft.Media.LiveEventEncoderConnected"
111+
)
112+
MediaLiveEventEncoderDisconnectedEventName = (
113+
"Microsoft.Media.LiveEventEncoderDisconnected"
114+
)
115+
MediaLiveEventIncomingDataChunkDroppedEventName = (
116+
"Microsoft.Media.LiveEventIncomingDataChunkDropped"
117+
)
118+
MediaLiveEventIncomingStreamReceivedEventName = (
119+
"Microsoft.Media.LiveEventIncomingStreamReceived"
120+
)
121+
MediaLiveEventIncomingStreamsOutOfSyncEventName = (
122+
"Microsoft.Media.LiveEventIncomingStreamsOutOfSync"
123+
)
124+
MediaLiveEventIncomingVideoStreamsOutOfSyncEventName = (
125+
"Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync"
126+
)
77127
MediaLiveEventIngestHeartbeatEventName = "Microsoft.Media.LiveEventIngestHeartbeat"
78-
MediaLiveEventTrackDiscontinuityDetectedEventName = "Microsoft.Media.LiveEventTrackDiscontinuityDetected"
128+
MediaLiveEventTrackDiscontinuityDetectedEventName = (
129+
"Microsoft.Media.LiveEventTrackDiscontinuityDetected"
130+
)
79131
ResourceActionCancelEventName = "Microsoft.Resources.ResourceActionCancel"
80132
ResourceActionFailureEventName = "Microsoft.Resources.ResourceActionFailure"
81133
ResourceActionSuccessEventName = "Microsoft.Resources.ResourceActionSuccess"
@@ -85,17 +137,21 @@ class SystemEventNames(str, Enum):
85137
ResourceWriteCancelEventName = "Microsoft.Resources.ResourceWriteCancel"
86138
ResourceWriteFailureEventName = "Microsoft.Resources.ResourceWriteFailure"
87139
ResourceWriteSuccessEventName = "Microsoft.Resources.ResourceWriteSuccess"
88-
ServiceBusActiveMessagesAvailableWithNoListenersEventName = \
89-
"Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners"
90-
ServiceBusDeadletterMessagesAvailableWithNoListenerEventName = \
91-
"Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener"
140+
ServiceBusActiveMessagesAvailableWithNoListenersEventName = (
141+
"Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners"
142+
)
143+
ServiceBusDeadletterMessagesAvailableWithNoListenerEventName = (
144+
"Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener"
145+
)
92146
StorageBlobCreatedEventName = "Microsoft.Storage.BlobCreated"
93147
StorageBlobDeletedEventName = "Microsoft.Storage.BlobDeleted"
94148
StorageBlobRenamedEventName = "Microsoft.Storage.BlobRenamed"
95149
StorageDirectoryCreatedEventName = "Microsoft.Storage.DirectoryCreated"
96150
StorageDirectoryDeletedEventName = "Microsoft.Storage.DirectoryDeleted"
97151
StorageDirectoryRenamedEventName = "Microsoft.Storage.DirectoryRenamed"
98-
StorageLifecyclePolicyCompletedEventName = "Microsoft.Storage.LifecyclePolicyCompleted"
152+
StorageLifecyclePolicyCompletedEventName = (
153+
"Microsoft.Storage.LifecyclePolicyCompleted"
154+
)
99155
WebAppServicePlanUpdatedEventName = "Microsoft.Web.AppServicePlanUpdated"
100156
WebAppUpdatedEventName = "Microsoft.Web.AppUpdated"
101157
WebBackupOperationCompletedEventName = "Microsoft.Web.BackupOperationCompleted"
@@ -107,5 +163,7 @@ class SystemEventNames(str, Enum):
107163
WebSlotSwapCompletedEventName = "Microsoft.Web.SlotSwapCompleted"
108164
WebSlotSwapFailedEventName = "Microsoft.Web.SlotSwapFailed"
109165
WebSlotSwapStartedEventName = "Microsoft.Web.SlotSwapStarted"
110-
WebSlotSwapWithPreviewCancelledEventName = "Microsoft.Web.SlotSwapWithPreviewCancelled"
166+
WebSlotSwapWithPreviewCancelledEventName = (
167+
"Microsoft.Web.SlotSwapWithPreviewCancelled"
168+
)
111169
WebSlotSwapWithPreviewStartedEventName = "Microsoft.Web.SlotSwapWithPreviewStarted"

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_helpers.py

+51-36
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@
77
import hmac
88
import base64
99
import six
10+
1011
try:
1112
from urllib.parse import quote
1213
except ImportError:
13-
from urllib2 import quote # type: ignore
14+
from urllib2 import quote # type: ignore
1415

1516
from azure.core.pipeline.policies import AzureKeyCredentialPolicy
1617
from azure.core.credentials import AzureKeyCredential, AzureSasCredential
@@ -20,102 +21,116 @@
2021
if TYPE_CHECKING:
2122
from datetime import datetime
2223

24+
2325
def generate_sas(endpoint, shared_access_key, expiration_date_utc, **kwargs):
2426
# type: (str, str, datetime, Any) -> str
25-
""" Helper method to generate shared access signature given hostname, key, and expiration date.
26-
:param str endpoint: The topic endpoint to send the events to.
27-
Similar to <YOUR-TOPIC-NAME>.<YOUR-REGION-NAME>-1.eventgrid.azure.net
28-
:param str shared_access_key: The shared access key to be used for generating the token
29-
:param datetime.datetime expiration_date_utc: The expiration datetime in UTC for the signature.
30-
:keyword str api_version: The API Version to include in the signature.
31-
If not provided, the default API version will be used.
32-
:rtype: str
33-
34-
.. admonition:: Example:
35-
36-
.. literalinclude:: ../samples/sync_samples/sample_generate_sas.py
37-
:start-after: [START generate_sas]
38-
:end-before: [END generate_sas]
39-
:language: python
40-
:dedent: 0
41-
:caption: Generate a shared access signature.
27+
"""Helper method to generate shared access signature given hostname, key, and expiration date.
28+
:param str endpoint: The topic endpoint to send the events to.
29+
Similar to <YOUR-TOPIC-NAME>.<YOUR-REGION-NAME>-1.eventgrid.azure.net
30+
:param str shared_access_key: The shared access key to be used for generating the token
31+
:param datetime.datetime expiration_date_utc: The expiration datetime in UTC for the signature.
32+
:keyword str api_version: The API Version to include in the signature.
33+
If not provided, the default API version will be used.
34+
:rtype: str
35+
36+
.. admonition:: Example:
37+
38+
.. literalinclude:: ../samples/sync_samples/sample_generate_sas.py
39+
:start-after: [START generate_sas]
40+
:end-before: [END generate_sas]
41+
:language: python
42+
:dedent: 0
43+
:caption: Generate a shared access signature.
4244
"""
4345

4446
full_endpoint = _get_full_endpoint(endpoint)
4547

4648
full_endpoint = "{}?apiVersion={}".format(
47-
full_endpoint,
48-
kwargs.get('api_version', None) or constants.DEFAULT_API_VERSION
49+
full_endpoint, kwargs.get("api_version", None) or constants.DEFAULT_API_VERSION
4950
)
5051
encoded_resource = quote(full_endpoint, safe=constants.SAFE_ENCODE)
5152
encoded_expiration_utc = quote(str(expiration_date_utc), safe=constants.SAFE_ENCODE)
5253

5354
unsigned_sas = "r={}&e={}".format(encoded_resource, encoded_expiration_utc)
54-
signature = quote(_generate_hmac(shared_access_key, unsigned_sas), safe=constants.SAFE_ENCODE)
55+
signature = quote(
56+
_generate_hmac(shared_access_key, unsigned_sas), safe=constants.SAFE_ENCODE
57+
)
5558
signed_sas = "{}&s={}".format(unsigned_sas, signature)
5659
return signed_sas
5760

61+
5862
def _get_endpoint_only_fqdn(endpoint):
59-
if endpoint.startswith('http://'):
63+
if endpoint.startswith("http://"):
6064
raise ValueError("HTTP is not supported. Only HTTPS is supported.")
61-
if endpoint.startswith('https://'):
65+
if endpoint.startswith("https://"):
6266
endpoint = endpoint.replace("https://", "")
6367
if endpoint.endswith("/api/events"):
6468
endpoint = endpoint.replace("/api/events", "")
6569

6670
return endpoint
6771

72+
6873
def _get_full_endpoint(endpoint):
69-
if endpoint.startswith('http://'):
74+
if endpoint.startswith("http://"):
7075
raise ValueError("HTTP is not supported. Only HTTPS is supported.")
71-
if not endpoint.startswith('https://'):
76+
if not endpoint.startswith("https://"):
7277
endpoint = "https://{}".format(endpoint)
7378
if not endpoint.endswith("/api/events"):
7479
endpoint = "{}/api/events".format(endpoint)
7580

7681
return endpoint
7782

83+
7884
def _generate_hmac(key, message):
7985
decoded_key = base64.b64decode(key)
80-
bytes_message = message.encode('ascii')
86+
bytes_message = message.encode("ascii")
8187
hmac_new = hmac.new(decoded_key, bytes_message, hashlib.sha256).digest()
8288

8389
return base64.b64encode(hmac_new)
8490

91+
8592
def _get_authentication_policy(credential):
8693
if credential is None:
8794
raise ValueError("Parameter 'self._credential' must not be None.")
8895
if isinstance(credential, AzureKeyCredential):
89-
return AzureKeyCredentialPolicy(credential=credential, name=constants.EVENTGRID_KEY_HEADER)
96+
return AzureKeyCredentialPolicy(
97+
credential=credential, name=constants.EVENTGRID_KEY_HEADER
98+
)
9099
if isinstance(credential, AzureSasCredential):
91100
return EventGridSasCredentialPolicy(
92-
credential=credential,
93-
name=constants.EVENTGRID_TOKEN_HEADER
101+
credential=credential, name=constants.EVENTGRID_TOKEN_HEADER
94102
)
95-
raise ValueError("The provided credential should be an instance of AzureSasCredential or AzureKeyCredential")
103+
raise ValueError(
104+
"The provided credential should be an instance of AzureSasCredential or AzureKeyCredential"
105+
)
106+
96107

97108
def _is_cloud_event(event):
98109
# type: (Any) -> bool
99-
required = ('id', 'source', 'specversion', 'type')
110+
required = ("id", "source", "specversion", "type")
100111
try:
101-
return all([_ in event for _ in required]) and event['specversion'] == "1.0"
112+
return all([_ in event for _ in required]) and event["specversion"] == "1.0"
102113
except TypeError:
103114
return False
104115

116+
105117
def _is_eventgrid_event(event):
106118
# type: (Any) -> bool
107-
required = ('subject', 'eventType', 'data', 'dataVersion', 'id', 'eventTime')
119+
required = ("subject", "eventType", "data", "dataVersion", "id", "eventTime")
108120
try:
109121
return all([prop in event for prop in required])
110122
except TypeError:
111123
return False
112124

125+
113126
def _eventgrid_data_typecheck(event):
114127
try:
115-
data = event.get('data')
128+
data = event.get("data")
116129
except AttributeError:
117130
data = event.data
118131

119132
if isinstance(data, six.binary_type):
120-
raise TypeError("Data in EventGridEvent cannot be bytes. Please refer to"\
121-
"https://docs.microsoft.com/en-us/azure/event-grid/event-schema")
133+
raise TypeError(
134+
"Data in EventGridEvent cannot be bytes. Please refer to"
135+
"https://docs.microsoft.com/en-us/azure/event-grid/event-schema"
136+
)

0 commit comments

Comments
 (0)