def test_cloud_event_serialization_extension_string(self, **kwargs): data = "cloudevent" cloud_event = CloudEvent( source="http://samplesource.dev", data=data, type="Sample.Cloud.Event", extensions={'e1':1, 'e2':2} ) cloud_event.subject = "subject" # to test explicit setting of prop internal = _cloud_event_to_generated(cloud_event) assert internal.additional_properties is not None assert 'e1' in internal.additional_properties json = internal.serialize() expected = { 'source':'http://samplesource.dev', 'data': data, 'type':'Sample.Cloud.Event', 'reason_code':204, 'e1':1, 'e2':2 } self._assert_cloud_event_serialized(expected, json) if sys.version_info > (3, 5): assert expected['data'] == json['data'] else: encoded = base64.b64encode(data).decode('utf-8') expected['data_base64'] = encoded assert expected['data_base64'] == json['data_base64'] assert 'data' not in json
def test_cloud_event_constructor_NULL_data(): event = CloudEvent(source='Azure.Core.Sample', type='SampleType', data=NULL) assert event.data == NULL assert event.data is NULL
def test_send_cloud_event_fails_on_providing_data_and_b64(self): with pytest.raises(ValueError, match="Unexpected keyword arguments data_base64.*"): cloud_event = CloudEvent(source="http://samplesource.dev", data_base64=b'cloudevent', data="random data", type="Sample.Cloud.Event")
def test_send_cloud_event_data_as_list( self, variables, 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") client.send([cloud_event])
def test_cloud_event_repr(): event = CloudEvent(source='Azure.Core.Sample', type='SampleType', data='cloudevent') assert repr(event).startswith( "CloudEvent(source=Azure.Core.Sample, type=SampleType, specversion=1.0," )
def test_extensions_upper_case_value_error(): with pytest.raises(ValueError): event = CloudEvent( source='sample', type='type', data='data', extensions={"lowercase123": "accepted", "NOTlower123": "not allowed"} )
def test_cloud_event_constructor_none_data(): event = CloudEvent( source='Azure.Core.Sample', type='SampleType', data=None ) assert event.data == None
def test_cloud_event_constructor_blank_data(): event = CloudEvent(source='Azure.Core.Sample', type='SampleType', data='') assert event.specversion == '1.0' assert event.time.__class__ == datetime.datetime assert event.id is not None assert event.source == 'Azure.Core.Sample' assert event.data == ''
async def test_send_cloud_event_data_none(self, variables, 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" ) await client.send(cloud_event)
def test_extensions_not_alphanumeric_value_error(): with pytest.raises(ValueError): event = CloudEvent( source='sample', type='type', data='data', extensions={"lowercase123": "accepted", "not@lph@nu^^3ic": "not allowed"} )
def test_cloud_event_constructor_unexpected_keyword(): with pytest.raises(ValueError) as e: event = CloudEvent(source='Azure.Core.Sample', type='SampleType', data='cloudevent', unexpected_keyword="not allowed", another_bad_kwarg="not allowed either") assert "unexpected_keyword" in e assert "another_bad_kwarg" in e
async def test_send_cloud_event_data_none(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) cloud_event = CloudEvent( source = "http://samplesource.dev", data = None, type="Sample.Cloud.Event" ) await client.send(cloud_event)
async def test_send_and_close_async_session(self, variables, 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( source = "http://samplesource.dev", data = "cloudevent", type="Sample.Cloud.Event" ) await client.send(cloud_event)
def test_cloud_event_constructor_missing_data(): event = CloudEvent( source='Azure.Core.Sample', type='SampleType', ) assert event.data == None assert event.datacontenttype == None assert event.dataschema == None assert event.subject == None
async def test_send_and_close_async_session(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) async with client: # this throws if client can't close cloud_event = CloudEvent( source = "http://samplesource.dev", data = "cloudevent", type="Sample.Cloud.Event" ) await client.send(cloud_event)
async def publish(): credential = AzureKeyCredential(topic_key) client = EventGridPublisherClient(endpoint, credential) await client.send([ CloudEvent(type="Contoso.Items.ItemReceived", source="/contoso/items", data={"itemSku": "Contoso Item SKU #1"}, subject="Door1") ])
async def test_send_cloud_event_data_NULL(self, variables, 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" ) def callback(request): req = json.loads(request.http_request.body) assert req[0].get("data") is None await client.send(cloud_event, raw_request_hook=callback)
async def test_send_cloud_event_data_NULL(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) cloud_event = CloudEvent( source = "http://samplesource.dev", data = NULL, type="Sample.Cloud.Event" ) def callback(request): req = json.loads(request.http_request.body) assert req[0].get("data") is None await client.send(cloud_event, raw_request_hook=callback)
def test_send_cloud_event_data_base64_using_data( self, variables, eventgrid_cloud_event_topic_endpoint): client = self.create_eg_publisher_client( eventgrid_cloud_event_topic_endpoint) cloud_event = CloudEvent(source="http://samplesource.dev", data=b'cloudevent', type="Sample.Cloud.Event") def callback(request): req = json.loads(request.http_request.body) assert req[0].get("data_base64") is not None assert req[0].get("data") is None client.send(cloud_event, raw_response_hook=callback)
def test_send_cloud_event_data_with_extensions( self, variables, 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", extensions={ 'reasoncode': 204, 'extension': 'hello' }) client.send([cloud_event]) internal = _cloud_event_to_generated(cloud_event).serialize() assert 'reasoncode' in internal assert 'extension' in internal assert internal['reasoncode'] == 204
async def test_send_cloud_event_data_with_extensions(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) cloud_event = CloudEvent( source = "http://samplesource.dev", data = "cloudevent", type="Sample.Cloud.Event", extensions={ 'reasoncode':204, 'extension':'hello' } ) await client.send([cloud_event]) internal = _cloud_event_to_generated(cloud_event).serialize() assert 'reasoncode' in internal assert 'extension' in internal assert internal['reasoncode'] == 204
def publish_event(): # publish events for _ in range(3): 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 data_dict = {"team": sample_members} event = CloudEvent(type="Azure.Sdk.Sample", source="https://egsample.dev/sampleevent", data={"team": sample_members}) event_list.append(event) # publish list of events client.send(event_list) print("Batch of size {} published".format(len(event_list))) time.sleep(randint(1, 5))
def publish_event(): # publish events for _ in range(3): event_list = [] # list of events to publish services = ["EventGrid", "ServiceBus", "EventHubs", "Storage"] # possible values for data field # 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 event = CloudEvent(type="Azure.Sdk.Demo", source=domain_name, data={"team": sample_members}) event_list.append(event) # publish list of events client.send(event_list) print("Batch of size {} published".format(len(event_list))) time.sleep(randint(1, 5))
""" FILE: sample_publish_events_using_cloud_events_1.0_schema.py DESCRIPTION: These samples demonstrate creating a list of CloudEvents and sending then as a list. USAGE: python sample_publish_events_using_cloud_events_1.0_schema.py Set the environment variables with your own values before running the sample: 1) CLOUD_ACCESS_KEY - The access key of your eventgrid account. 2) CLOUD_TOPIC_HOSTNAME - The topic hostname. Typically it exists in the format "<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net". """ # [START publish_cloud_event_to_topic] import os from azure.eventgrid import EventGridPublisherClient from azure.core.credentials import AzureKeyCredential from azure.core.messaging import CloudEvent topic_key = os.environ["CLOUD_ACCESS_KEY"] endpoint = os.environ["CLOUD_TOPIC_HOSTNAME"] credential = AzureKeyCredential(topic_key) client = EventGridPublisherClient(endpoint, credential) client.send([ CloudEvent(type="Contoso.Items.ItemReceived", source="/contoso/items", data={"itemSku": "Contoso Item SKU #1"}, subject="Door1") ]) # [END publish_cloud_event_to_topic]
FILE: sample_consume_custom_payload.py DESCRIPTION: These samples demonstrate consuming a raw json with a list of jsons and deserializing them into typed objects of CloudEvents. USAGE: python sample_consume_custom_payload.py """ from azure.core.messaging import CloudEvent import json # all types of CloudEvents below produce same DeserializedEvent cloud_custom_dict = """[{ "id":"de0fd76c-4ef4-4dfb-ab3a-8f24a307e033", "source":"https://egtest.dev/cloudcustomevent", "data":{ "team": "event grid squad" }, "type":"Azure.Sdk.Sample", "time":"2020-08-07T02:06:08.11969Z", "specversion":"1.0" }]""" deserialized_dict_events = [ CloudEvent(**msg) for msg in json.loads(cloud_custom_dict) ] for event in deserialized_dict_events: print(event.data) print(type(event))
# Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import ConsoleSpanExporter from opentelemetry.sdk.trace.export import SimpleSpanProcessor # Simple console exporter exporter = ConsoleSpanExporter() trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) trace.get_tracer_provider().add_span_processor(SimpleSpanProcessor(exporter)) # Example with Eventgrid SDKs import os from azure.core.messaging import CloudEvent from azure.eventgrid import EventGridPublisherClient from azure.core.credentials import AzureKeyCredential hostname = os.environ['CLOUD_TOPIC_HOSTNAME'] key = AzureKeyCredential(os.environ['CLOUD_ACCESS_KEY']) cloud_event = CloudEvent(source='demo', type='sdk.demo', data={'test': 'hello'}, extensions={'test': 'maybe'}) with tracer.start_as_current_span(name="MyApplication"): client = EventGridPublisherClient(hostname, key) client.send(cloud_event)