def test_eg_event_repr(self):
        event = EventGridEvent(subject="sample2",
                               data="eventgridevent2",
                               event_type="Sample.EventGrid.Event",
                               data_version="2.0")

        assert "EventGridEvent(subject=sample2" in event.__repr__()
Ejemplo n.º 2
0
 def test_send_event_grid_event_data_as_list(self, variables,
                                             eventgrid_topic_endpoint):
     client = self.create_eg_publisher_client(eventgrid_topic_endpoint)
     eg_event1 = EventGridEvent(subject="sample",
                                data=u"eventgridevent",
                                event_type="Sample.EventGrid.Event",
                                data_version="2.0")
     eg_event2 = EventGridEvent(subject="sample2",
                                data=u"eventgridevent2",
                                event_type="Sample.EventGrid.Event",
                                data_version="2.0")
     client.send([eg_event1, eg_event2])
Ejemplo n.º 3
0
 async def test_send_event_grid_event_data_as_list(
         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)
     eg_event1 = EventGridEvent(subject="sample",
                                data="eventgridevent",
                                event_type="Sample.EventGrid.Event",
                                data_version="2.0")
     eg_event2 = EventGridEvent(subject="sample2",
                                data="eventgridevent2",
                                event_type="Sample.EventGrid.Event",
                                data_version="2.0")
     await client.send([eg_event1, eg_event2])
Ejemplo n.º 4
0
 def publish(self, topic, message=''):
    try:
         print(f'event_grid.publish({topic}, {message})')
         event = EventGridEvent(data=message, subject=topic, event_type="mobil-e-hub", data_version="1.0")
         self.client.send(event)
    except Error as err:
         print(err)
async def publish():
    credential = AzureKeyCredential(domain_key)
    client = EventGridPublisherClient(domain_hostname, credential)

    await client.send([
        EventGridEvent(topic="MyCustomDomainTopic1",
                       event_type="Contoso.Items.ItemReceived",
                       data={"itemSku": "Contoso Item SKU #1"},
                       subject="Door1",
                       data_version="2.0"),
        EventGridEvent(topic="MyCustomDomainTopic2",
                       event_type="Contoso.Items.ItemReceived",
                       data={"itemSku": "Contoso Item SKU #2"},
                       subject="Door1",
                       data_version="2.0")
    ])
Ejemplo n.º 6
0
 def test_event_grid_event_raises_on_no_data(self):
     with pytest.raises(TypeError):
         eg_event = EventGridEvent(
                 subject="sample",
                 event_type="Sample.EventGrid.Event",
                 data_version="2.0"
                 )
Ejemplo n.º 7
0
 def test_send_token_credential(self, variables, eventgrid_topic_endpoint):
     credential = self.get_credential(EventGridPublisherClient)
     client = EventGridPublisherClient(eventgrid_topic_endpoint, credential)
     eg_event = EventGridEvent(subject="sample",
                               data={"sample": "eventgridevent"},
                               event_type="Sample.EventGrid.Event",
                               data_version="2.0")
     client.send(eg_event)
Ejemplo n.º 8
0
 def test_send_event_grid_event_data_dict(self, variables,
                                          eventgrid_topic_endpoint):
     client = self.create_eg_publisher_client(eventgrid_topic_endpoint)
     eg_event = EventGridEvent(subject="sample",
                               data={"sample": "eventgridevent"},
                               event_type="Sample.EventGrid.Event",
                               data_version="2.0")
     client.send(eg_event)
 def test_send_event_grid_event_data_str(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)
     eg_event = EventGridEvent(
             subject="sample", 
             data=u"eventgridevent",
             event_type="Sample.EventGrid.Event",
             data_version="2.0"
             )
     client.send(eg_event)
async def publish():
    credential = AzureKeyCredential(topic_key)
    client = EventGridPublisherClient(endpoint, credential)

    await client.send([
        EventGridEvent(event_type="Contoso.Items.ItemReceived",
                       data={"itemSku": "Contoso Item SKU #1"},
                       subject="Door1",
                       data_version="2.0")
    ])
Ejemplo n.º 11
0
 def test_send_event_grid_event_data_bytes(self, variables,
                                           eventgrid_topic_endpoint):
     client = self.create_eg_publisher_client(eventgrid_topic_endpoint)
     eg_event = EventGridEvent(subject="sample",
                               data=b"eventgridevent",
                               event_type="Sample.EventGrid.Event",
                               data_version="2.0")
     with pytest.raises(TypeError,
                        match="Data in EventGridEvent cannot be bytes*"):
         client.send(eg_event)
 async def test_send_token_credential(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint):
     credential = self.get_credential(EventGridPublisherClient)
     client = EventGridPublisherClient(eventgrid_topic_endpoint, credential)
     eg_event = EventGridEvent(
             subject="sample", 
             data={"sample": "eventgridevent"}, 
             event_type="Sample.EventGrid.Event",
             data_version="2.0"
             )
     await client.send(eg_event)
Ejemplo n.º 13
0
 def test_send_event_grid_event_fails_without_full_url(
         self, variables, 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)
     eg_event = EventGridEvent(subject="sample",
                               data={"sample": "eventgridevent"},
                               event_type="Sample.EventGrid.Event",
                               data_version="2.0")
     with pytest.raises(ValueError):
         client.send(eg_event)
Ejemplo n.º 14
0
 def test_raise_on_bad_resource(self, variables, eventgrid_topic_key):
     akc_credential = AzureKeyCredential(eventgrid_topic_key)
     client = EventGridPublisherClient(
         "https://bad-resource.westus-1.eventgrid.azure.net/api/events",
         akc_credential)
     eg_event = EventGridEvent(subject="sample",
                               data={"sample": "eventgridevent"},
                               event_type="Sample.EventGrid.Event",
                               data_version="2.0")
     with pytest.raises(HttpResponseError):
         client.send(eg_event)
 async def test_send_event_grid_event_data_bytes(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)
     eg_event = EventGridEvent(
             subject="sample", 
             data=b"eventgridevent", 
             event_type="Sample.EventGrid.Event",
             data_version="2.0"
             )
     with pytest.raises(TypeError, match="Data in EventGridEvent cannot be bytes*"):
         await client.send(eg_event)
Ejemplo n.º 16
0
 async def test_send_signature_credential(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint):
     expiration_date_utc = dt.datetime.now(UTC()) + timedelta(hours=1)
     signature = generate_shared_access_signature(eventgrid_topic_endpoint, eventgrid_topic_primary_key, expiration_date_utc)
     credential = EventGridSharedAccessSignatureCredential(signature)
     client = EventGridPublisherClient(eventgrid_topic_endpoint, credential)
     eg_event = EventGridEvent(
             subject="sample", 
             data={"sample": "eventgridevent"}, 
             event_type="Sample.EventGrid.Event",
             data_version="2.0"
             )
     await client.send(eg_event)
Ejemplo n.º 17
0
 def test_raise_on_auth_error(self, variables, eventgrid_topic_endpoint):
     akc_credential = AzureKeyCredential("bad credential")
     client = EventGridPublisherClient(eventgrid_topic_endpoint,
                                       akc_credential)
     eg_event = EventGridEvent(subject="sample",
                               data={"sample": "eventgridevent"},
                               event_type="Sample.EventGrid.Event",
                               data_version="2.0")
     with pytest.raises(
             ClientAuthenticationError,
             match="The request authorization key is not authorized for*"):
         client.send(eg_event)
Ejemplo n.º 18
0
 def test_send_signature_credential(self, variables, 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)
     credential = AzureSasCredential(signature)
     client = EventGridPublisherClient(eventgrid_topic_endpoint, credential)
     eg_event = EventGridEvent(subject="sample",
                               data={"sample": "eventgridevent"},
                               event_type="Sample.EventGrid.Event",
                               data_version="2.0")
     client.send(eg_event)
 async def test_raise_on_bad_resource(self, resource_group, eventgrid_topic,
                                      eventgrid_topic_primary_key,
                                      eventgrid_topic_endpoint):
     akc_credential = AzureKeyCredential(eventgrid_topic_primary_key)
     client = EventGridPublisherClient(
         "https://bad-resource.westus-1.eventgrid.azure.net/api/events",
         akc_credential)
     eg_event = EventGridEvent(subject="sample",
                               data={"sample": "eventgridevent"},
                               event_type="Sample.EventGrid.Event",
                               data_version="2.0")
     with pytest.raises(ServiceRequestError):
         await client.send(eg_event)
Ejemplo n.º 20
0
def main(event: func.EventGridEvent):
    logging.info(sys.version)
    logging.info(event)
    result = json.dumps({
        'id': event.id,
        'data': event.get_json(),
        'topic': event.topic,
        'subject': event.subject,
        'event_type': event.event_type
    })
    logging.info(result)
    deserialized_event = EventGridEvent.from_dict(json.loads(result))
    ## can only be EventGridEvent
    print("model: {}".format(event.model))
Ejemplo n.º 21
0
    def test_raise_on_large_payload(self, variables, 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"))
        with open(path) as json_file:
            data = json.load(json_file)
        eg_event = EventGridEvent(subject="sample",
                                  data=data,
                                  event_type="Sample.EventGrid.Event",
                                  data_version="2.0")
        with pytest.raises(HttpResponseError) as err:
            client.send(eg_event)
        assert "The maximum size (1536000) has been exceeded." in err.value.message
Ejemplo n.º 22
0
def test_from_json_sb():
    obj = MockServiceBusReceivedMessage(
        body=MockBody(),
        message_id='3f6c5441-5be5-4f33-80c3-3ffeb6a090ce',
        content_type='application/cloudevents+json; charset=utf-8',
        time_to_live=datetime.timedelta(days=14),
        delivery_count=13,
        enqueued_sequence_number=0,
        enqueued_time_utc=datetime.datetime(2021, 7, 22, 22, 27, 41, 236000),
        expires_at_utc=datetime.datetime(2021, 8, 5, 22, 27, 41, 236000),
        sequence_number=11219,
        lock_token='233146e3-d5a6-45eb-826f-691d82fb8b13')
    event = EventGridEvent.from_json(obj)

    assert event.id == "f208feff-099b-4bda-a341-4afd0fa02fef"
    assert event.data == "ServiceBus"
Ejemplo n.º 23
0
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, 3)):
            sample_members = sample(services, k=randint(
                1, 4))  # select random subset of team members
            event = EventGridEvent(subject="Door1",
                                   data={"team": sample_members},
                                   event_type="Azure.Sdk.Demo",
                                   data_version="2.0")
            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))
    async def test_raise_on_large_payload(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)

        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(subject="sample",
                                  data=data,
                                  event_type="Sample.EventGrid.Event",
                                  data_version="2.0")
        with pytest.raises(HttpResponseError) as err:
            await client.send(eg_event)
        assert "The maximum size (1536000) has been exceeded." in err.value.message
Ejemplo n.º 25
0
def main():
    # Read configuration information
    config_dict = loadcfg()
    cfg_event_grid_topic_key = config_dict['eventgridtopickey']
    cfg_event_grid_topic_endpoint = config_dict['eventgridtopicendpoint']

    event = EventGridEvent(data={
        "make": "Audi",
        "model": "Q5"
    },
                           subject="myapp/vehicles/cars",
                           event_type="recordInserted",
                           data_version="1.0")

    credential = AzureKeyCredential(cfg_event_grid_topic_key)
    print('Sending event to Event Grid Topic ...')
    client = EventGridPublisherClient(cfg_event_grid_topic_endpoint,
                                      credential)
    # Send event
    client.send(event)
    print('Sent')
Ejemplo n.º 26
0
def test_from_json_storage():
    eg_storage_dict = """{
        "id":"a0517898-9fa4-4e70-b4a3-afda1dd68672",
        "subject":"/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.Storage/storageAccounts/{storage-account}",
        "data":{
            "api":"PutBlockList",
            "client_request_id":"6d79dbfb-0e37-4fc4-981f-442c9ca65760",
            "request_id":"831e1650-001e-001b-66ab-eeb76e000000",
            "e_tag":"0x8D4BCC2E4835CD0",
            "content_type":"application/octet-stream",
            "content_length":524288,
            "blob_type":"BlockBlob",
            "url":"https://oc2d2817345i60006.blob.core.windows.net/oc2d2817345i200097container/oc2d2817345i20002296blob",
            "sequencer":"00000000000004420000000000028963",
            "storage_diagnostics":{"batchId":"b68529f3-68cd-4744-baa4-3c0498ec19f0"}
        },
        "event_type":"Microsoft.Storage.BlobCreated",
        "event_time":"2021-02-18T20:18:10.581147898Z",
        "data_version":"1.0"
    }"""
    obj = MockQueueMessage(content=eg_storage_dict)
    event = EventGridEvent.from_json(obj)
    assert event.data == {
        "api": "PutBlockList",
        "client_request_id": "6d79dbfb-0e37-4fc4-981f-442c9ca65760",
        "request_id": "831e1650-001e-001b-66ab-eeb76e000000",
        "e_tag": "0x8D4BCC2E4835CD0",
        "content_type": "application/octet-stream",
        "content_length": 524288,
        "blob_type": "BlockBlob",
        "url":
        "https://oc2d2817345i60006.blob.core.windows.net/oc2d2817345i200097container/oc2d2817345i20002296blob",
        "sequencer": "00000000000004420000000000028963",
        "storage_diagnostics": {
            "batchId": "b68529f3-68cd-4744-baa4-3c0498ec19f0"
        }
    }
Ejemplo n.º 27
0
    def __init__(self, arguments):
        super().__init__(arguments)

        # auth configuration
        topic_key = self.get_from_env("EG_ACCESS_KEY")
        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.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"]
                    },
                    subject="Door1",
                    data_version="2.0"))
    These samples demonstrate creating a list of EventGrid Events and sending them as a list to a topic in a domain.
USAGE:
    python sample_publish_eg_events_to_a_domain.py
    Set the environment variables with your own values before running the sample:
    1) EG_ACCESS_KEY - The access key of your eventgrid account.
    2) EG_TOPIC_HOSTNAME - The topic hostname. Typically it exists in the format
    "https://<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net/api/events".
"""
import os
from azure.eventgrid import EventGridPublisherClient, EventGridEvent
from azure.core.credentials import AzureKeyCredential

domain_key = os.environ["EG_DOMAIN_ACCESS_KEY"]
domain_hostname = os.environ["EG_DOMAIN_TOPIC_HOSTNAME"]

credential = AzureKeyCredential(domain_key)
client = EventGridPublisherClient(domain_hostname, credential)

client.send([
    EventGridEvent(topic="MyCustomDomainTopic1",
                   event_type="Contoso.Items.ItemReceived",
                   data={"itemSku": "Contoso Item SKU #1"},
                   subject="Door1",
                   data_version="2.0"),
    EventGridEvent(topic="MyCustomDomainTopic2",
                   event_type="Contoso.Items.ItemReceived",
                   data={"itemSku": "Contoso Item SKU #2"},
                   subject="Door1",
                   data_version="2.0")
])
Ejemplo n.º 29
0
# license information.
# --------------------------------------------------------------------------
"""
FILE: sample_publish_events_to_a_topic_using_sas_credential.py
DESCRIPTION:
    These samples demonstrate sending an EventGrid Event using a shared access signature for authentication.
USAGE:
    python sample_publish_events_to_a_topic_using_sas_credential.py
    Set the environment variables with your own values before running the sample:
    1) EVENTGRID_SAS - The shared access signature to use Event Grid. This is typically given to you
    after creating it using the `generate_sas` method.
    2) EG_TOPIC_HOSTNAME - The topic hostname. Typically it exists in the format
    "https://<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net/api/events".
"""
import os
from azure.eventgrid import EventGridPublisherClient, EventGridEvent, generate_sas
from azure.core.credentials import AzureKeyCredential, AzureSasCredential

sas = os.environ["EVENTGRID_SAS"]
endpoint = os.environ["EG_TOPIC_HOSTNAME"]

credential = AzureSasCredential(sas)
client = EventGridPublisherClient(endpoint, credential)

client.send([
    EventGridEvent(event_type="Contoso.Items.ItemReceived",
                   data={"itemSku": "Contoso Item SKU #1"},
                   subject="Door1",
                   data_version="2.0")
])
client = EventGridPublisherClient(endpoint, credential)
# [END client_auth_with_key_cred_async]

# [START client_auth_with_sas_cred_async]
import os
from azure.eventgrid.aio import EventGridPublisherClient
from azure.core.credentials import AzureSasCredential

signature = os.environ["EVENTGRID_SAS"]
endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"]

credential = AzureSasCredential(signature)
client = EventGridPublisherClient(endpoint, credential)
# [END client_auth_with_sas_cred_async]

# [START client_auth_with_token_cred_async]
from azure.identity.aio import DefaultAzureCredential
from azure.eventgrid.aio import EventGridPublisherClient
from azure.eventgrid import EventGridEvent

event = EventGridEvent(
    data={"team": "azure-sdk"},
    subject="Door1",
    event_type="Azure.Sdk.Demo",
    data_version="2.0"
)

credential = DefaultAzureCredential()
endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"]
client = EventGridPublisherClient(endpoint, credential)
# [END client_auth_with_token_cred_async]