async def test_client_event_cleanup(): now = datetime.datetime.now(datetime.timezone.utc) server = OpenADRServer(vtn_id='myvtn') server.add_handler('on_create_party_registration', on_create_party_registration) loop = asyncio.get_event_loop() event_1_callback_future = loop.create_future() event_2_callback_future = loop.create_future() server.add_event(ven_id='ven123', signal_name='simple', signal_type='level', intervals=[ objects.Interval( dtstart=now, duration=datetime.timedelta(seconds=1), signal_payload=1) ], callback=event_1_callback_future) await server.run() client = OpenADRClient( ven_name='ven123', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b') client.add_handler('on_event', on_event_opt_in) await client.run() await asyncio.sleep(0.5) assert len(client.received_events) == 1 await asyncio.sleep(0.5) await client._event_cleanup() assert len(client.received_events) == 0 await server.stop() await client.stop()
async def test_cancel_event(): async def opt_in_to_event(event, future=None): if future: future.set_result(True) return 'optIn' async def on_update_event(event, future=None): if future: future.set_result(event) return 'optIn' now = datetime.datetime.now(datetime.timezone.utc) server = OpenADRServer(vtn_id='myvtn', requested_poll_freq=datetime.timedelta(seconds=1)) server.add_handler('on_create_party_registration', on_create_party_registration) loop = asyncio.get_event_loop() event_1_callback_future = loop.create_future() event_id = server.add_event( ven_id='ven123', signal_name='simple', signal_type='level', intervals=[ objects.Interval(dtstart=now, duration=datetime.timedelta(seconds=60), signal_payload=1) ], callback=event_1_callback_future, response_required='always') await server.run() client = OpenADRClient( ven_name='ven123', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b') client.add_handler('on_event', opt_in_to_event) cancel_future = loop.create_future() client.add_handler('on_update_event', partial(on_update_event, future=cancel_future)) await client.run() await event_1_callback_future server.cancel_event('ven123', event_id) result = await cancel_future assert utils.getmember(result, 'event_descriptor.event_status') == 'cancelled' response_type, response_payload = await client.request_event() assert response_type == 'oadrResponse' await client._event_cleanup() assert len(client.responded_events) == 0 assert len(client.received_events) == 0 await server.stop() await client.stop()
async def test_raw_event(): now = datetime.datetime.now(datetime.timezone.utc) server = OpenADRServer(vtn_id='myvtn') server.add_handler('on_create_party_registration', on_create_party_registration) event = objects.Event( event_descriptor=objects.EventDescriptor( event_id='event001', modification_number=0, event_status='far', market_context='http://marketcontext01'), event_signals=[ objects.EventSignal( signal_id='signal001', signal_type='level', signal_name='simple', intervals=[ objects.Interval(dtstart=now, duration=datetime.timedelta(minutes=10), signal_payload=1) ]), objects.EventSignal( signal_id='signal002', signal_type='price', signal_name='ELECTRICITY_PRICE', intervals=[ objects.Interval(dtstart=now, duration=datetime.timedelta(minutes=10), signal_payload=1) ]) ], targets=[objects.Target(ven_id='ven123')]) loop = asyncio.get_event_loop() event_callback_future = loop.create_future() server.add_raw_event(ven_id='ven123', event=event, callback=partial(event_callback, future=event_callback_future)) on_event_future = loop.create_future() client = OpenADRClient( ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b') client.add_handler('on_event', partial(on_event_opt_in, future=on_event_future)) await server.run_async() await client.run() event = await on_event_future assert len(event['event_signals']) == 2 result = await event_callback_future assert result == 'optIn' await client.stop() await server.stop()
async def test_client_exception_event_handler(caplog): caplog.set_level(logging.WARNING) enable_default_logging() logger = logging.getLogger('openleadr') logger.setLevel(logging.DEBUG) client = OpenADRClient( ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b') client.add_handler('on_event', broken_on_event) server = OpenADRServer(vtn_id='myvtn', requested_poll_freq=timedelta(seconds=1)) server.add_handler('on_create_party_registration', on_create_party_registration) print("Running server") await server.run_async() await asyncio.sleep(0.1) print("Running client") await client.run() event_confirm_future = asyncio.get_event_loop().create_future() print("Adding event") server.add_event(ven_id='venid', signal_name='simple', signal_type='level', intervals=[{ 'dtstart': datetime.now(), 'duration': timedelta(seconds=10), 'signal_payload': 1.1 }], target={'ven_id': 'venid'}, callback=partial(on_event_accepted, future=event_confirm_future)) print("Waiting for a response to the event") result = await event_confirm_future assert result == 'optOut' err = KeyError("BOOM") assert ( "Your on_event handler encountered an error. Will Opt Out of the event. " f"The error was {err.__class__.__name__}: {str(err)}") in [ rec.message for rec in caplog.records ] await client.stop() await server.stop() await asyncio.sleep(0)
async def test_client_good_event_handler(caplog): caplog.set_level(logging.WARNING) logger = logging.getLogger('openleadr') logger.setLevel(logging.DEBUG) client = OpenADRClient( ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b') client.add_handler('on_event', good_on_event) server = OpenADRServer(vtn_id='myvtn', requested_poll_freq=timedelta(seconds=1)) server.add_handler('on_create_party_registration', on_create_party_registration) caplog.clear() print("Running server") await server.run_async() # await asyncio.sleep(0.1) print("Running client") await client.run() event_confirm_future = asyncio.get_event_loop().create_future() print("Adding event") server.add_event(ven_id='venid', event_id='test_client_good_event_handler', signal_name='simple', signal_type='level', intervals=[{ 'dtstart': datetime.now(timezone.utc), 'duration': timedelta(seconds=1), 'signal_payload': 1.1 }], target={'ven_id': 'venid'}, callback=partial(on_event_accepted, future=event_confirm_future)) print("Waiting for a response to the event") result = await event_confirm_future assert result == 'optIn' print("-" * 80) print("THE CAPLOG RECORDS ARE:") print(caplog.records) print("-" * 80) assert len(caplog.records) == 0 await client.stop() await server.stop() await asyncio.gather(*[t for t in asyncio.all_tasks()][1:])
async def test_client_faulty_event_handler(caplog): caplog.set_level(logging.WARNING) logger = logging.getLogger('openleadr') logger.setLevel(logging.DEBUG) client = OpenADRClient( ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b') client.add_handler('on_event', faulty_on_event) server = OpenADRServer(vtn_id='myvtn', requested_poll_freq=timedelta(seconds=1)) server.add_handler('on_create_party_registration', on_create_party_registration) print("Running server") await server.run_async() # await asyncio.sleep(0.1) print("Running client") await client.run() event_confirm_future = asyncio.get_event_loop().create_future() print("Adding event") server.add_event(ven_id='venid', event_id='test_client_faulty_event_handler', signal_name='simple', signal_type='level', intervals=[{ 'dtstart': datetime.now(timezone.utc), 'duration': timedelta(seconds=1), 'signal_payload': 1.1 }], target={'ven_id': 'venid'}, callback=partial(on_event_accepted, future=event_confirm_future)) print("Waiting for a response to the event") result = await event_confirm_future assert result == 'optOut' assert ( "Your on_event or on_update_event handler must return 'optIn' or 'optOut'; " f"you supplied {None}. Please fix your on_event handler.") in [ rec.message for rec in caplog.records ] await client.stop() await server.stop() await asyncio.gather(*[t for t in asyncio.all_tasks()][1:])
async def test_client_warning_no_update_event_handler(caplog): caplog.set_level(logging.WARNING) logger = logging.getLogger('openleadr') logger.setLevel(logging.DEBUG) server = OpenADRServer(vtn_id='myvtn', requested_poll_freq=timedelta(seconds=1)) server.add_handler('on_create_party_registration', on_create_party_registration) event_accepted_future = asyncio.get_event_loop().create_future() server.add_event(ven_id='venid', event_id='test_client_warning_no_update_event_handler', signal_name='simple', signal_type='level', intervals=[{ 'dtstart': datetime.now(timezone.utc), 'duration': timedelta(seconds=1), 'signal_payload': 1.1 }], target={'ven_id': 'venid'}, callback=event_accepted_future) client = OpenADRClient( ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b') client.add_handler('on_event', good_on_event) print("Starting server") await server.run() await client.run() print("Waiting for first event to be accepted...") await event_accepted_future # Manually update the event server.events['venid'][0].event_descriptor.modification_number = 1 server.events_updated['venid'] = True await asyncio.sleep(1) assert ( "An Event was updated, but you don't have an on_updated_event handler configured. " "You should implement your own on_update_event handler. This handler receives " "an Event dict and should return either 'optIn' or 'optOut' based on your " "choice. Will re-use the previous opt status for this event_id for now" ) in [record.msg for record in caplog.records] await client.stop() await server.stop() await asyncio.gather(*[t for t in asyncio.all_tasks()][1:])
async def test_internal_message_queue(): loop = asyncio.get_event_loop() client = OpenADRClient( ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b') client.add_handler('on_event', on_event) server = OpenADRServer(vtn_id='myvtn', requested_poll_freq=datetime.timedelta(seconds=1)) server.add_handler('on_create_party_registration', on_create_party_registration) event_callback_future = loop.create_future() server.add_event(ven_id='ven123', signal_name='simple', signal_type='level', intervals=[{ 'dtstart': datetime.datetime.now(datetime.timezone.utc), 'duration': datetime.timedelta(seconds=3), 'signal_payload': 1 }], callback=partial(event_callback, future=event_callback_future)) await server.run_async() #await asyncio.sleep(1) await client.run() #await asyncio.sleep(1) status = await event_callback_future assert status == 'optIn' message_type, message_payload = await asyncio.wait_for(client.poll(), 0.5) assert message_type == 'oadrResponse' message_type, message_payload = await asyncio.wait_for(client.poll(), 0.5) assert message_type == 'oadrResponse' #await asyncio.sleep(1) # Wait for the event to be completed await client.stop() await server.stop()
async def test_event_external_polling_function(): async def opt_in_to_event(event, future=None): if future: future.set_result(True) return 'optIn' async def on_update_event(event, future=None): if future: future.set_result(event) return 'optIn' async def on_poll(ven_id, future=None): if future and not future.done(): future.set_result(True) return objects.Event( event_descriptor=objects.EventDescriptor( event_id='event001', modification_number=0, event_status='far', market_context='http://marketcontext01'), event_signals=[ objects.EventSignal( signal_id='signal001', signal_type='level', signal_name='simple', intervals=[ objects.Interval( dtstart=now, duration=datetime.timedelta(minutes=10), signal_payload=1) ]), objects.EventSignal( signal_id='signal002', signal_type='price', signal_name='ELECTRICITY_PRICE', intervals=[ objects.Interval( dtstart=now, duration=datetime.timedelta(minutes=10), signal_payload=1) ]) ], targets=[objects.Target(ven_id=ven_id)]) else: print("Returning None") return None loop = asyncio.get_event_loop() now = datetime.datetime.now(datetime.timezone.utc) server = OpenADRServer(vtn_id='myvtn', requested_poll_freq=datetime.timedelta(seconds=1)) server.add_handler('on_create_party_registration', on_create_party_registration) poll_fut = loop.create_future() server.add_handler('on_poll', partial(on_poll, future=poll_fut)) await server.run() client = OpenADRClient( ven_name='ven123', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b') fut = loop.create_future() client.add_handler('on_event', partial(opt_in_to_event, future=fut)) await client.run() await fut assert len(client.responded_events) == 1 assert len(client.received_events) == 1 await server.stop() await client.stop()
def test_wrong_handler_supplied(caplog): client = OpenADRClient(ven_name='myven', vtn_url='http://localhost') client.add_handler('non_existant', print) assert ("'handler' must be either on_event or on_update_event") in [ rec.message for rec in caplog.records ]