def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') connection_str = "Endpoint=sb://{}/;SharedAccessKeyName={};SharedAccessKey={};EntityPath={}".format( os.environ['EVENT_HUB_HOSTNAME'], os.environ['EVENT_HUB_SAS_POLICY'], os.environ['EVENT_HUB_SAS_KEY'], os.environ['EVENT_HUB_NAME']) client = EventHubClient.from_connection_string(connection_str) req_body = req.get_json() req_payload = json.dumps(req_body) client = EventHubClient.from_connection_string(connection_str) sender = client.add_sender(partition="0") try: client.run() logging.info('Send Alert with this payload: %s', req_payload) event_data = EventData(req_payload) sender.send(event_data) logging.info('Sent payload to Event Hub!') except: raise finally: client.stop() return func.HttpResponse(f"Hello {req_body}!")
def test_example_eventhub_sync_sender_ops(live_eventhub_config, connection_str): import os # [START create_eventhub_client_sender_instance] from azure.eventhub import EventHubClient client = EventHubClient.from_connection_string(connection_str) sender = client.add_sender(partition="0") # [END create_eventhub_client_sender_instance] # [START eventhub_client_sender_open] client = EventHubClient.from_connection_string(connection_str) sender = client.add_sender(partition="0") try: # Open the Sender using the supplied conneciton. sender.open() # Start sending except: raise finally: # Close down the send handler. sender.close() # [END eventhub_client_sender_open] # [START eventhub_client_sender_close] client = EventHubClient.from_connection_string(connection_str) sender = client.add_sender(partition="0") try: # Open the Sender using the supplied conneciton. sender.open() # Start sending except: raise finally: # Close down the send handler. sender.close()
def test_send_with_partition_key(connstr_receivers): connection_str, receivers = connstr_receivers client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender() try: client.run() data_val = 0 for partition in [b"a", b"b", b"c", b"d", b"e", b"f"]: partition_key = b"test_partition_" + partition for i in range(50): data = EventData(str(data_val)) data.partition_key = partition_key data_val += 1 sender.send(data) except: raise finally: client.stop() found_partition_keys = {} for index, partition in enumerate(receivers): received = partition.receive(timeout=5) for message in received: try: existing = found_partition_keys[message.partition_key] assert existing == index except KeyError: found_partition_keys[message.partition_key] = index
def test_long_running_send(connection_str): if sys.platform.startswith('darwin'): import pytest pytest.skip("Skipping on OSX") parser = argparse.ArgumentParser() parser.add_argument("--duration", help="Duration in seconds of the test", type=int, default=30) parser.add_argument("--payload", help="payload size", type=int, default=512) parser.add_argument("--batch", help="Number of events to send and wait", type=int, default=1) parser.add_argument("--conn-str", help="EventHub connection string", default=connection_str) parser.add_argument("--eventhub", help="Name of EventHub") parser.add_argument("--address", help="Address URI to the EventHub entity") parser.add_argument("--sas-policy", help="Name of the shared access policy to authenticate with") parser.add_argument("--sas-key", help="Shared access key") args, _ = parser.parse_known_args() if args.conn_str: client = EventHubClient.from_connection_string( args.conn_str, eventhub=args.eventhub) elif args.address: client = EventHubClient( args.address, username=args.sas_policy, password=args.sas_key) else: try: import pytest pytest.skip("Must specify either '--conn-str' or '--address'") except ImportError: raise ValueError("Must specify either '--conn-str' or '--address'") try: main(client, args) except KeyboardInterrupt: pass
def test_send_with_invalid_hostname(invalid_hostname, connstr_receivers): _, receivers = connstr_receivers client = EventHubClient.from_connection_string(invalid_hostname, debug=False) sender = client.add_sender() with pytest.raises(EventHubError): client.run()
def test_non_existing_entity_receiver(connection_str): client = EventHubClient.from_connection_string(connection_str, eventhub="nemo", debug=False) receiver = client.add_receiver("$default", "0") with pytest.raises(EventHubError): client.run()
def test_receive_with_custom_datetime_sync(connstr_senders): connection_str, senders = connstr_senders client = EventHubClient.from_connection_string(connection_str, debug=False) for i in range(5): senders[0].send(EventData(b"Message before timestamp")) time.sleep(60) now = datetime.datetime.utcnow() offset = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute) for i in range(5): senders[0].send(EventData(b"Message after timestamp")) receiver = client.add_receiver("$default", "0", offset=Offset(offset)) try: client.run() all_received = [] received = receiver.receive(timeout=1) while received: all_received.extend(received) received = receiver.receive(timeout=1) assert len(all_received) == 5 for received_event in all_received: assert received_event.body_as_str() == "Message after timestamp" assert received_event.enqueued_time > offset except: raise finally: client.stop()
def __init__(self): # This test requires a previusly created Event Hub. # In this example the name is "myeventhub", but it could be change below connectionString = os.environ["EVENT_HUBS_CONNECTION_STRING"] eventHubName = "myeventhub" self.client = EventHubClient.from_connection_string( connectionString, eventHubName)
def build_sender_client(): print(CONNECTION_STRING) client = EventHubClient.from_connection_string(CONNECTION_STRING, EVENT_HUB_TOPIC) sender = client.add_sender(EVENT_HUB_PARTITION) client.run() return client, sender
def getEvents(lastOffset): try: client = EventHubClient.from_connection_string(cfg.connection_str) EVENT_POSITION = EventPosition(lastOffset) #for a vanilla eventhub replace "custom" consumer_group by "$default" consumer = client.create_consumer(consumer_group="custom", partition_id=PARTITION, event_position=EVENT_POSITION, prefetch=100000) total=0 last_offset = -1 with consumer: batched_events = consumer.receive(max_batch_size=100000) for event_data in batched_events: last_offset = event_data.offset last_sn = event_data.sequence_number total += 1 print("Partition {}, Received {}, sn={} offset={}".format( PARTITION, total, last_sn, last_offset)) print (event_data) getEvents(last_offset) client.stop() except: print('got all events for now') finally: print('got all events for now') client.stop()
def test_receive_with_offset_sync(connstr_senders): connection_str, senders = connstr_senders client = EventHubClient.from_connection_string(connection_str, debug=False) partitions = client.get_eventhub_info() assert partitions["partition_ids"] == ["0", "1"] receiver = client.add_receiver("$default", "0", offset=Offset('@latest')) try: client.run() more_partitions = client.get_eventhub_info() assert more_partitions["partition_ids"] == ["0", "1"] received = receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Data")) received = receiver.receive(timeout=5) assert len(received) == 1 offset = received[0].offset assert list(received[0].body) == [b'Data'] assert received[0].body_as_str() == "Data" offset_receiver = client.add_receiver("$default", "0", offset=offset) client.run() received = offset_receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Message after offset")) received = offset_receiver.receive(timeout=5) assert len(received) == 1 except: raise finally: client.stop()
def test_non_existing_entity_sender(connection_str): client = EventHubClient.from_connection_string(connection_str, eventhub="nemo", debug=False) sender = client.add_sender(partition="1") with pytest.raises(EventHubError): client.run()
def create_eventhub_client_from_iothub_connection_string(live_eventhub_config): # [START create_eventhub_client_iot_connstr] import os from azure.eventhub import EventHubClient iot_connection_str = os.environ['IOTHUB_CONNECTION_STR'] client = EventHubClient.from_connection_string(iot_connection_str)
def test_receive_with_custom_datetime_sync(connstr_senders): connection_str, senders = connstr_senders client = EventHubClient.from_connection_string(connection_str, network_tracing=False) for i in range(5): senders[0].send(EventData(b"Message before timestamp")) time.sleep(65) now = datetime.datetime.utcnow() offset = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute) for i in range(5): senders[0].send(EventData(b"Message after timestamp")) receiver = client.create_consumer(consumer_group="$default", partition_id="0", event_position=EventPosition(offset)) with receiver: all_received = [] received = receiver.receive(timeout=1) while received: all_received.extend(received) received = receiver.receive(timeout=1) assert len(all_received) == 5 for received_event in all_received: assert received_event.body_as_str() == "Message after timestamp" assert received_event.enqueued_time > offset
def test_send_with_create_event_batch_sync(connstr_receivers): connection_str, receivers = connstr_receivers client = EventHubClient.from_connection_string( connection_str, transport_type=TransportType.AmqpOverWebsocket, network_tracing=False) sender = client.create_producer() event_data_batch = sender.create_batch(max_size=100000, partition_key="0") while True: try: event_data_batch.try_add(EventData('A single event data')) except ValueError: break sender.send(event_data_batch) event_data_batch = sender.create_batch(max_size=100000) while True: try: event_data_batch.try_add(EventData('A single event data')) except ValueError: break sender.send(event_data_batch) sender.close()
def test_receive_over_websocket_sync(connstr_senders): connection_str, senders = connstr_senders client = EventHubClient.from_connection_string( connection_str, transport_type=TransportType.AmqpOverWebsocket, network_tracing=False) receiver = client.create_consumer(consumer_group="$default", partition_id="0", event_position=EventPosition('@latest'), prefetch=500) event_list = [] for i in range(20): event_list.append(EventData("Event Number {}".format(i))) with receiver: received = receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(event_list) time.sleep(1) received = receiver.receive(max_batch_size=50, timeout=5) assert len(received) == 20
def test_receive_with_sequence_no(connstr_senders): connection_str, senders = connstr_senders client = EventHubClient.from_connection_string(connection_str, network_tracing=False) receiver = client.create_consumer(consumer_group="$default", partition_id="0", event_position=EventPosition('@latest')) with receiver: received = receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Data")) time.sleep(1) received = receiver.receive(timeout=5) assert len(received) == 1 offset = received[0].sequence_number offset_receiver = client.create_consumer(consumer_group="$default", partition_id="0", event_position=EventPosition( offset, False)) with offset_receiver: received = offset_receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Message next in sequence")) time.sleep(1) received = offset_receiver.receive(timeout=5) assert len(received) == 1
def test_receive_with_offset_sync(connstr_senders): connection_str, senders = connstr_senders client = EventHubClient.from_connection_string(connection_str, network_tracing=False) partitions = client.get_properties() assert partitions["partition_ids"] == ["0", "1"] receiver = client.create_consumer(consumer_group="$default", partition_id="0", event_position=EventPosition('@latest')) with receiver: more_partitions = client.get_properties() assert more_partitions["partition_ids"] == ["0", "1"] received = receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Data")) received = receiver.receive(timeout=5) assert len(received) == 1 offset = received[0].offset assert list(received[0].body) == [b'Data'] assert received[0].body_as_str() == "Data" offset_receiver = client.create_consumer(consumer_group="$default", partition_id="0", event_position=EventPosition( offset, inclusive=False)) with offset_receiver: received = offset_receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Message after offset")) received = offset_receiver.receive(timeout=5) assert len(received) == 1
def test_receive_with_inclusive_offset(connstr_senders): connection_str, senders = connstr_senders client = EventHubClient.from_connection_string(connection_str, network_tracing=False) receiver = client.create_consumer(consumer_group="$default", partition_id="0", event_position=EventPosition('@latest')) with receiver: received = receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Data")) time.sleep(1) received = receiver.receive(timeout=5) assert len(received) == 1 offset = received[0].offset assert list(received[0].body) == [b'Data'] assert received[0].body_as_str() == "Data" offset_receiver = client.create_consumer(consumer_group="$default", partition_id="0", event_position=EventPosition( offset, inclusive=True)) with offset_receiver: received = offset_receiver.receive(timeout=5) assert len(received) == 1
def __init__(self): connection_string = "Endpoint=sb://{}/;SharedAccessKeyName={};SharedAccessKey={};EntityPath={}".format( Settings.eh.hostname, Settings.eh.sas_policy, Settings.eh.sas_key, Settings.eh.event_hub_name) self.client = EventHubClient.from_connection_string(connection_string) self.sender = self.client.add_sender(partition="0") self.client.run()
def test_send_with_partition_key(connection_str, receivers): client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender() try: client.run() data_val = 0 for partition in [b"a", b"b", b"c", b"d", b"e", b"f"]: partition_key = b"test_partition_" + partition for i in range(50): data = EventData(str(data_val)) data.partition_key = partition_key data_val += 1 sender.send(data) except: raise finally: client.stop() found_partition_keys = {} for index, partition in enumerate(receivers): received = partition.receive(timeout=5) for message in received: try: existing = found_partition_keys[message.partition_key] assert existing == index except KeyError: found_partition_keys[message.partition_key] = index
def test_receive_with_invalid_key_sync(invalid_key): client = EventHubClient.from_connection_string(invalid_key, network_tracing=False) receiver = client.create_consumer(consumer_group="$default", partition_id="0", event_position=EventPosition("-1")) with pytest.raises(AuthenticationError): receiver.receive(timeout=10) receiver.close()
def test_send_batch_sync(connstr_receivers): connection_str, receivers = connstr_receivers def batched(): for i in range(10): yield "Event number {}".format(i) client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender() try: client.run() sender.send(EventData(batch=batched())) except: raise finally: client.stop() time.sleep(1) received = [] for r in receivers: received.extend(r.receive(timeout=3)) assert len(received) == 10 for index, message in enumerate(received): assert list( message.body)[0] == "Event number {}".format(index).encode('utf-8')
def start_event_generation_sync_impl(cancellation_token): random.seed(int(time.time())) # use ticks as seed client = EventHubClient.from_connection_string(conn_str=EVENTHUB_CONNECTION_STRING, eventhub=EVENTHUB_NAME) sender = client.add_sender() client.run() while cancellation_token.is_set(): try: # Simulate sending data from 100 weather sensors devices_data = [] for i in range(0, 100): scale_factor = random.randrange(0,25) windturbine_measure = generate_turbine_measure("Python_Turbine_" + str(i), scale_factor) ev_data = serialize_windturbine_to_eventdata(windturbine_measure) devices_data.append(ev_data) sender.send(EventData(batch=[event for event in devices_data])) logger.info("100 events sent!") print(".", end='', flush=True) except Exception as e: logger.error(e) client.stop()
def send_data(): EVENTHUBCONNECTIONSTRING = "<EventHubConnectionString>" EVENTHUBNAME = "<EventHubName>" telemetry_message = { "deviceid": "<Your device Id>", "timestamp": datetime.datetime.utcnow().isoformat(), "version": "1", "sensors": [{ "id": "<Your sensor Id>", "sensordata": [{ "timestamp": datetime.datetime.utcnow().isoformat(), "Temperature": random.randint(150, 170) }] }] } write_client = EventHubClient.from_connection_string( EVENTHUBCONNECTIONSTRING, eventhub=EVENTHUBNAME, debug=True) sender = write_client.add_sender(partition="0") write_client.run() print("Sending telemetry: " + json.dumps(telemetry_message)) sender.send(EventData(json.dumps(telemetry_message))) write_client.stop()
def test_send_batch_with_app_prop_sync(connstr_receivers): connection_str, receivers = connstr_receivers app_prop_key = "raw_prop" app_prop_value = "raw_value" app_prop = {app_prop_key: app_prop_value} def batched(): for i in range(10): ed = EventData("Event number {}".format(i)) ed.application_properties = app_prop yield ed for i in range(10, 20): ed = EventData("Event number {}".format(i)) ed.application_properties = app_prop yield ed client = EventHubClient.from_connection_string(connection_str, network_tracing=False) sender = client.create_producer() with sender: sender.send(batched()) time.sleep(1) received = [] for r in receivers: received.extend(r.receive(timeout=3)) assert len(received) == 20 for index, message in enumerate(received): assert list(message.body)[0] == "Event number {}".format(index).encode('utf-8') assert (app_prop_key.encode('utf-8') in message.application_properties) \ and (dict(message.application_properties)[app_prop_key.encode('utf-8')] == app_prop_value.encode('utf-8'))
def test_receive_with_sequence_no(connstr_senders): connection_str, senders = connstr_senders client = EventHubClient.from_connection_string(connection_str, debug=False) receiver = client.add_receiver("$default", "0", offset=Offset('@latest')) try: client.run() received = receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Data")) time.sleep(1) received = receiver.receive(timeout=5) assert len(received) == 1 offset = received[0].sequence_number offset_receiver = client.add_receiver("$default", "0", offset=Offset(offset)) client.run() received = offset_receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Message next in sequence")) time.sleep(1) received = offset_receiver.receive(timeout=5) assert len(received) == 1 except: raise finally: client.stop()
def test_send_with_forced_conn_close_sync(connstr_receivers, sleep): pytest.skip("This test is similar to the above one") connection_str, receivers = connstr_receivers client = EventHubClient.from_connection_string(connection_str, network_tracing=False) sender = client.create_producer() with sender: sender.send(EventData(b"A single event")) sender._handler._connection._conn.destroy() if sleep: time.sleep(300) else: sender._handler._connection._conn.destroy() sender.send(EventData(b"A single event")) sender.send(EventData(b"A single event")) if sleep: time.sleep(300) else: sender._handler._connection._conn.destroy() sender.send(EventData(b"A single event")) sender.send(EventData(b"A single event")) received = [] for r in receivers: if not sleep: r._handler._connection._conn.destroy() received.extend(r.receive(timeout=1)) assert len(received) == 5 assert list(received[0].body)[0] == b"A single event"
def test_receive_with_datetime(connection_str, senders): client = EventHubClient.from_connection_string(connection_str, debug=False) partitions = client.get_eventhub_info() assert partitions["partition_ids"] == ["0", "1"] receiver = client.add_receiver("$default", "0", offset=Offset('@latest')) try: client.run() more_partitions = client.get_eventhub_info() assert more_partitions["partition_ids"] == ["0", "1"] received = receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Data")) received = receiver.receive(timeout=5) assert len(received) == 1 offset = received[0].enqueued_time offset_receiver = client.add_receiver("$default", "0", offset=Offset(offset)) client.run() received = offset_receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Message after timestamp")) received = offset_receiver.receive(timeout=5) assert len(received) == 1 except: raise finally: client.stop()
def test_receive_with_inclusive_offset(connstr_senders): connection_str, senders = connstr_senders client = EventHubClient.from_connection_string(connection_str, debug=False) receiver = client.add_receiver("$default", "0", offset=Offset('@latest')) try: client.run() received = receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Data")) time.sleep(1) received = receiver.receive(timeout=5) assert len(received) == 1 offset = received[0].offset assert list(received[0].body) == [b'Data'] assert received[0].body_as_str() == "Data" offset_receiver = client.add_receiver("$default", "0", offset=Offset(offset.value, inclusive=True)) client.run() received = offset_receiver.receive(timeout=5) assert len(received) == 1 except: raise finally: client.stop()
def test_create_batch_with_none_sync(connection_str): client = EventHubClient.from_connection_string(connection_str, network_tracing=False) sender = client.create_producer() batch_event_data = sender.create_batch(max_size=300, partition_key="key") with pytest.raises(ValueError): batch_event_data.try_add(EventData(None)) sender.close()
def test_create_batch_with_too_large_size_sync(connection_str): client = EventHubClient.from_connection_string(connection_str, network_tracing=False) sender = client.create_producer() with pytest.raises(ValueError): batch_event_data = sender.create_batch(max_size=5 * 1024 * 1024, partition_key="key") sender.close()
def test_send_with_invalid_policy(invalid_policy, connstr_receivers): _, receivers = connstr_receivers client = EventHubClient.from_connection_string(invalid_policy, network_tracing=False) sender = client.create_producer() with pytest.raises(AuthenticationError): sender.send(EventData("test data")) sender.close()
def test_send_to_invalid_partitions(connection_str): partitions = ["XYZ", "-1", "1000", "-" ] for p in partitions: client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender(partition=p) try: with pytest.raises(EventHubError): client.run() finally: client.stop()
def test_send_partition_key_with_partition_sync(connection_str): client = EventHubClient.from_connection_string(connection_str, debug=True) sender = client.add_sender(partition="1") try: client.run() data = EventData(b"Data") data.partition_key = b"PKey" with pytest.raises(ValueError): sender.send(data) finally: client.stop()
def test_send_null_body(connection_str): partitions = ["XYZ", "-1", "1000", "-" ] client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender() try: client.run() with pytest.raises(ValueError): data = EventData(None) sender.send(data) finally: client.stop()
def test_receive_from_invalid_partitions_sync(connection_str): partitions = ["XYZ", "-1", "1000", "-" ] for p in partitions: client = EventHubClient.from_connection_string(connection_str, debug=True) receiver = client.add_receiver("$default", p) try: with pytest.raises(EventHubError): client.run() receiver.receive(timeout=10) finally: client.stop()
def test_message_body_types(connstr_senders): connection_str, senders = connstr_senders client = EventHubClient.from_connection_string(connection_str, debug=False) receiver = client.add_receiver("$default", "0", offset=Offset('@latest')) try: client.run() received = receiver.receive(timeout=5) assert len(received) == 0 senders[0].send(EventData(b"Bytes Data")) time.sleep(1) received = receiver.receive(timeout=5) assert len(received) == 1 assert list(received[0].body) == [b'Bytes Data'] assert received[0].body_as_str() == "Bytes Data" with pytest.raises(TypeError): received[0].body_as_json() senders[0].send(EventData("Str Data")) time.sleep(1) received = receiver.receive(timeout=5) assert len(received) == 1 assert list(received[0].body) == [b'Str Data'] assert received[0].body_as_str() == "Str Data" with pytest.raises(TypeError): received[0].body_as_json() senders[0].send(EventData(b'{"test_value": "JSON bytes data", "key1": true, "key2": 42}')) time.sleep(1) received = receiver.receive(timeout=5) assert len(received) == 1 assert list(received[0].body) == [b'{"test_value": "JSON bytes data", "key1": true, "key2": 42}'] assert received[0].body_as_str() == '{"test_value": "JSON bytes data", "key1": true, "key2": 42}' assert received[0].body_as_json() == {"test_value": "JSON bytes data", "key1": True, "key2": 42} senders[0].send(EventData('{"test_value": "JSON str data", "key1": true, "key2": 42}')) time.sleep(1) received = receiver.receive(timeout=5) assert len(received) == 1 assert list(received[0].body) == [b'{"test_value": "JSON str data", "key1": true, "key2": 42}'] assert received[0].body_as_str() == '{"test_value": "JSON str data", "key1": true, "key2": 42}' assert received[0].body_as_json() == {"test_value": "JSON str data", "key1": True, "key2": 42} senders[0].send(EventData(42)) time.sleep(1) received = receiver.receive(timeout=5) assert len(received) == 1 assert received[0].body_as_str() == "42" assert received[0].body == 42 except: raise finally: client.stop()
def test_send_too_large_message(connection_str): if sys.platform.startswith('darwin'): pytest.skip("Skipping on OSX - open issue regarding message size") client = EventHubClient.from_connection_string(connection_str, debug=True) sender = client.add_sender() try: client.run() data = EventData(b"A" * 300000) with pytest.raises(EventHubError): sender.send(data) finally: client.stop()
def connstr_senders(connection_str): client = EventHubClient.from_connection_string(connection_str, debug=True) eh_hub_info = client.get_eventhub_info() partitions = eh_hub_info["partition_ids"] senders = [] for p in partitions: senders.append(client.add_sender(partition=p)) client.run() yield connection_str, senders client.stop()
def test_example_eventhub_sync_receiver_ops(live_eventhub_config, connection_str): import os # [START create_eventhub_client_receiver_instance] from azure.eventhub import EventHubClient, Offset client = EventHubClient.from_connection_string(connection_str) receiver = client.add_receiver(consumer_group="$default", partition="0", offset=Offset('@latest')) # [END create_eventhub_client_receiver_instance] # [START eventhub_client_receiver_open] client = EventHubClient.from_connection_string(connection_str) receiver = client.add_receiver(consumer_group="$default", partition="0", offset=Offset('@latest')) try: # Open the Receiver using the supplied conneciton. receiver.open() # Start receiving except: raise finally: # Close down the receive handler. receiver.close() # [END eventhub_client_receiver_open] # [START eventhub_client_receiver_close] client = EventHubClient.from_connection_string(connection_str) receiver = client.add_receiver(consumer_group="$default", partition="0", offset=Offset('@latest')) try: # Open the Receiver using the supplied conneciton. receiver.open() # Start receiving except: raise finally: # Close down the receive handler. receiver.close() # [END eventhub_client_receiver_close]
def test_send_partition(connstr_receivers): connection_str, receivers = connstr_receivers client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender(partition="1") try: client.run() sender.send(EventData(b"Data")) except: raise finally: client.stop() partition_0 = receivers[0].receive(timeout=2) assert len(partition_0) == 0 partition_1 = receivers[1].receive(timeout=2) assert len(partition_1) == 1
def test_send_non_ascii(connstr_receivers): connection_str, receivers = connstr_receivers client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender(partition="0") try: client.run() sender.send(EventData(u"é,è,à,ù,â,ê,î,ô,û")) sender.send(EventData(json.dumps({"foo": u"漢字"}))) except: raise finally: client.stop() partition_0 = receivers[0].receive(timeout=2) assert len(partition_0) == 2 assert partition_0[0].body_as_str() == u"é,è,à,ù,â,ê,î,ô,û" assert partition_0[1].body_as_json() == {"foo": u"漢字"}
def connstr_receivers(connection_str): client = EventHubClient.from_connection_string(connection_str, debug=False) eh_hub_info = client.get_eventhub_info() partitions = eh_hub_info["partition_ids"] recv_offset = Offset("@latest") receivers = [] for p in partitions: receivers.append(client.add_receiver("$default", p, prefetch=500, offset=Offset("@latest"))) client.run() for r in receivers: r.receive(timeout=1) yield connection_str, receivers client.stop()
def test_long_running_receive(connection_str): parser = argparse.ArgumentParser() parser.add_argument("--duration", help="Duration in seconds of the test", type=int, default=30) parser.add_argument("--consumer", help="Consumer group name", default="$default") parser.add_argument("--partitions", help="Comma seperated partition IDs") parser.add_argument("--offset", help="Starting offset", default="-1") parser.add_argument("--conn-str", help="EventHub connection string", default=connection_str) parser.add_argument("--eventhub", help="Name of EventHub") parser.add_argument("--address", help="Address URI to the EventHub entity") parser.add_argument("--sas-policy", help="Name of the shared access policy to authenticate with") parser.add_argument("--sas-key", help="Shared access key") args, _ = parser.parse_known_args() if args.conn_str: client = EventHubClient.from_connection_string( args.conn_str, eventhub=args.eventhub, debug=False) elif args.address: client = EventHubClient( args.address, username=args.sas_policy, password=args.sas_key) else: try: import pytest pytest.skip("Must specify either '--conn-str' or '--address'") except ImportError: raise ValueError("Must specify either '--conn-str' or '--address'") try: if not args.partitions: partitions = get_partitions(client) else: partitions = args.partitions.split(",") pumps = {} for pid in partitions: pumps[pid] = client.add_receiver( consumer_group=args.consumer, partition=pid, offset=Offset(args.offset), prefetch=50) client.run() pump(pumps, args.duration) finally: client.stop()
def test_send_multiple_clients(connstr_receivers): connection_str, receivers = connstr_receivers client = EventHubClient.from_connection_string(connection_str, debug=False) sender_0 = client.add_sender(partition="0") sender_1 = client.add_sender(partition="1") try: client.run() sender_0.send(EventData(b"Message 0")) sender_1.send(EventData(b"Message 1")) except: raise finally: client.stop() partition_0 = receivers[0].receive(timeout=2) assert len(partition_0) == 1 partition_1 = receivers[1].receive(timeout=2) assert len(partition_1) == 1
def test_send_single_event(connstr_receivers): connection_str, receivers = connstr_receivers client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender() try: client.run() sender.send(EventData(b"A single event")) except: raise finally: client.stop() received = [] for r in receivers: received.extend(r.receive(timeout=1)) assert len(received) == 1 assert list(received[0].body)[0] == b"A single event"
def test_send_array_sync(connstr_receivers): connection_str, receivers = connstr_receivers client = EventHubClient.from_connection_string(connection_str, debug=True) sender = client.add_sender() try: client.run() sender.send(EventData([b"A", b"B", b"C"])) except: raise finally: client.stop() received = [] for r in receivers: received.extend(r.receive(timeout=1)) assert len(received) == 1 assert list(received[0].body) == [b"A", b"B", b"C"]
def test_send_with_long_interval_sync(connstr_receivers): connection_str, receivers = connstr_receivers client = EventHubClient.from_connection_string(connection_str, debug=True) sender = client.add_sender() try: client.run() sender.send(EventData(b"A single event")) for _ in range(2): time.sleep(300) sender.send(EventData(b"A single event")) finally: client.stop() received = [] for r in receivers: received.extend(r.receive(timeout=1)) assert len(received) == 3 assert list(received[0].body)[0] == b"A single event"
def test_send_and_receive_large_body_size(connstr_receivers): if sys.platform.startswith('darwin'): pytest.skip("Skipping on OSX - open issue regarding message size") connection_str, receivers = connstr_receivers client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender() try: client.run() payload = 250 * 1024 sender.send(EventData("A" * payload)) except: raise finally: client.stop() received = [] for r in receivers: received.extend(r.receive(timeout=4)) assert len(received) == 1 assert len(list(received[0].body)[0]) == payload
def test_send_partition_batch(connstr_receivers): connection_str, receivers = connstr_receivers def batched(): for i in range(10): yield "Event number {}".format(i) client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender(partition="1") try: client.run() sender.send(EventData(batch=batched())) time.sleep(1) except: raise finally: client.stop() partition_0 = receivers[0].receive(timeout=2) assert len(partition_0) == 0 partition_1 = receivers[1].receive(timeout=2) assert len(partition_1) == 10
def test_send_with_forced_conn_close_sync(connstr_receivers): connection_str, receivers = connstr_receivers client = EventHubClient.from_connection_string(connection_str, debug=True) sender = client.add_sender() try: client.run() sender.send(EventData(b"A single event")) sender._handler._message_sender.destroy() time.sleep(300) sender.send(EventData(b"A single event")) sender.send(EventData(b"A single event")) sender._handler._message_sender.destroy() time.sleep(300) sender.send(EventData(b"A single event")) sender.send(EventData(b"A single event")) finally: client.stop() received = [] for r in receivers: received.extend(r.receive(timeout=1)) assert len(received) == 5 assert list(received[0].body)[0] == b"A single event"
def test_example_eventhub_transfer(connection_str): import os from azure.eventhub import EventHubClient, EventData client = EventHubClient.from_connection_string(connection_str) sender = client.add_sender() try: client.run() # [START eventhub_client_transfer] logger = logging.getLogger("azure.eventhub") def callback(outcome, condition): logger.info("Message sent. Outcome: {}, Condition: {}".format( outcome, condition)) event_data = EventData(b"A single event") sender.transfer(event_data, callback=callback) sender.wait() # [END eventhub_client_transfer] except: raise finally: client.stop()
def test_send_batch_with_app_prop_sync(connstr_receivers): pytest.skip("Waiting on uAMQP release") connection_str, receivers = connstr_receivers def batched(): for i in range(10): yield "Event number {}".format(i) for i in range(10, 20): yield EventData("Event number {}".format(i)) client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender() try: client.run() app_prop_key = "raw_prop" app_prop_value = "raw_value" batch_app_prop = {app_prop_key:app_prop_value} batch_event = EventData(batch=batched()) batch_event.application_properties = batch_app_prop sender.send(batch_event) except: raise finally: client.stop() time.sleep(1) received = [] for r in receivers: received.extend(r.receive(timeout=3)) assert len(received) == 20 for index, message in enumerate(received): assert list(message.body)[0] == "Event number {}".format(index).encode('utf-8') assert (app_prop_key.encode('utf-8') in message.application_properties) \ and (dict(message.application_properties)[app_prop_key.encode('utf-8')] == app_prop_value.encode('utf-8'))
def test_send_batch_sync(connstr_receivers): connection_str, receivers = connstr_receivers def batched(): for i in range(10): yield "Event number {}".format(i) client = EventHubClient.from_connection_string(connection_str, debug=False) sender = client.add_sender() try: client.run() sender.send(EventData(batch=batched())) except: raise finally: client.stop() time.sleep(1) received = [] for r in receivers: received.extend(r.receive(timeout=3)) assert len(received) == 10 for index, message in enumerate(received): assert list(message.body)[0] == "Event number {}".format(index).encode('utf-8')
def test_send_with_invalid_policy(invalid_policy, connstr_receivers): _, receivers = connstr_receivers client = EventHubClient.from_connection_string(invalid_policy, debug=False) sender = client.add_sender() with pytest.raises(EventHubError): client.run()
def test_receive_with_invalid_policy_sync(invalid_policy): client = EventHubClient.from_connection_string(invalid_policy, debug=True) receiver = client.add_receiver("$default", "0") with pytest.raises(EventHubError): client.run()
def test_example_eventhub_sync_send_and_receive(live_eventhub_config): # [START create_eventhub_client_connstr] import os from azure.eventhub import EventHubClient connection_str = "Endpoint=sb://{}/;SharedAccessKeyName={};SharedAccessKey={};EntityPath={}".format( os.environ['EVENT_HUB_HOSTNAME'], os.environ['EVENT_HUB_SAS_POLICY'], os.environ['EVENT_HUB_SAS_KEY'], os.environ['EVENT_HUB_NAME']) client = EventHubClient.from_connection_string(connection_str) # [END create_eventhub_client_connstr] from azure.eventhub import EventData, Offset # [START create_eventhub_client_sender] client = EventHubClient.from_connection_string(connection_str) # Add a sender to the client object. sender = client.add_sender(partition="0") # [END create_eventhub_client_sender] # [START create_eventhub_client_receiver] client = EventHubClient.from_connection_string(connection_str) # Add a receiver to the client object. receiver = client.add_receiver(consumer_group="$default", partition="0", offset=Offset('@latest')) # [END create_eventhub_client_receiver] # [START create_eventhub_client_epoch_receiver] client = EventHubClient.from_connection_string(connection_str) # Add a receiver to the client object with an epoch value. epoch_receiver = client.add_epoch_receiver(consumer_group="$default", partition="0", epoch=42) # [END create_eventhub_client_epoch_receiver] # [START eventhub_client_run] client = EventHubClient.from_connection_string(connection_str) # Add Senders/Receivers try: client.run() # Start sending and receiving except: raise finally: client.stop() # [END eventhub_client_run] client = EventHubClient.from_connection_string(connection_str) sender = client.add_sender(partition="0") receiver = client.add_receiver(consumer_group="$default", partition="0", offset=Offset('@latest')) try: # Opens the connection and starts running all Sender/Receiver clients. client.run() # Start sending and receiving # [START create_event_data] event_data = EventData("String data") event_data = EventData(b"Bytes data") event_data = EventData([b"A", b"B", b"C"]) def batched(): for i in range(10): yield "Batch data, Event number {}".format(i) event_data = EventData(batch=batched()) # [END create_event_data] # [START eventhub_client_sync_send] event_data = EventData(b"A single event") sender.send(event_data) # [END eventhub_client_sync_send] time.sleep(1) # [START eventhub_client_sync_receive] logger = logging.getLogger("azure.eventhub") received = receiver.receive(timeout=5, max_batch_size=1) for event_data in received: logger.info("Message received:{}".format(event_data.body_as_str())) # [END eventhub_client_sync_receive] assert len(received) == 1 assert received[0].body_as_str() == "A single event" assert list(received[-1].body)[0] == b"A single event" except: raise finally: client.stop() # [START eventhub_client_stop] client = EventHubClient.from_connection_string(connection_str) # Add Senders/Receivers try: client.run() # Start sending and receiving except: raise finally: client.stop()