File: test_event_warnings_errors.py

package info (click to toggle)
python-openleadr-python 0.5.34%2Bdfsg.1-2
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,496 kB
  • sloc: python: 6,942; xml: 663; makefile: 32; sh: 18
file content (405 lines) | stat: -rw-r--r-- 19,583 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
from openleadr import OpenADRClient, OpenADRServer, enable_default_logging, utils, messaging
import pytest
from functools import partial
import asyncio
from datetime import datetime, timedelta, timezone
import logging

enable_default_logging()

async def on_create_party_registration(ven_name):
    return 'venid', 'regid'

async def on_event_accepted(ven_id, event_id, opt_type, future=None):
    if future and future.done() is False:
        future.set_result(opt_type)

async def good_on_event(event):
    return 'optIn'

async def faulty_on_event(event):
    return None

async def broken_on_event(event):
    raise KeyError("BOOM")

@pytest.mark.asyncio
async def test_client_no_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')
    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_no_event_handler',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{'dtstart': datetime.now(timezone.utc),
                                 'duration': timedelta(hours=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 ("You should implement your own on_event handler. This handler receives "
            "an Event dict and should return either 'optIn' or 'optOut' based on your "
            "choice. Will opt out of the event for now.") 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:])

@pytest.mark.asyncio
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(hours=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:])

@pytest.mark.asyncio
async def test_client_exception_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', 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',
                     event_id='test_client_exception_event_handler',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{'dtstart': datetime.now(timezone.utc),
                                 'duration': timedelta(hours=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'

    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.gather(*[t for t in asyncio.all_tasks()][1:])

@pytest.mark.asyncio
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(hours=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:])

@pytest.mark.asyncio
async def test_server_warning_conflicting_poll_methods(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_poll', print)
    server.add_event(ven_id='venid',
                     event_id='test_server_warning_conflicting_poll_methods',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{'dtstart': datetime.now(timezone.utc),
                                 'duration': timedelta(hours=1),
                                 'signal_payload': 1.1}],
                     target={'ven_id': 'venid'},
                     callback=on_event_accepted)
    assert ("You cannot use the add_event method after you assign your own on_poll "
            "handler. If you use your own on_poll handler, you are responsible for "
            "delivering events from that handler. If you want to use OpenLEADRs "
            "message queuing system, you should not assign an on_poll handler. "
            "Your Event will NOT be added.") in [record.msg for record in caplog.records]


@pytest.mark.asyncio
async def test_server_warning_naive_datetimes_in_event(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_event(ven_id='venid',
                     event_id='test_server_warning_naive_datetimes_in_event',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{'dtstart': datetime.now(),
                                 'duration': timedelta(hours=1),
                                 'signal_payload': 1.1}],
                     target={'ven_id': 'venid'},
                     callback=on_event_accepted)
    assert ("You supplied a naive datetime object to your interval's dtstart. "
            "This will be interpreted as a timestamp in your local timezone "
            "and then converted to UTC before sending. Please supply timezone-"
            "aware timestamps like datetime.datetime.new(timezone.utc) or "
            "datetime.datetime(..., tzinfo=datetime.timezone.utc)") in [record.msg for record in caplog.records]


def test_event_with_wrong_response_required(caplog):
    now = datetime.now(timezone.utc)
    event = {'active_period': {'dtstart': now, 'duration': timedelta(seconds=10)},
             'event_descriptor': {'event_id': 'event123',
                                  'modification_number': 1,
                                  'priority': 0,
                                  'event_status': 'far',
                                  'created_date_time': now},
             'event_signals': [{'signal_name': 'simple',
                                'signal_type': 'level',
                                'intervals': [{'dtstart': now,
                                               'duration': timedelta(seconds=10),
                                               'signal_payload': 1}]}],
             'targets': [{'ven_id': 'ven123'}],
             'response_required': 'blabla'}
    msg = messaging.create_message('oadrDistributeEvent', events=[event])
    assert ("The response_required property in an Event should be "
            "'never' or 'always', not blabla. Changing to 'always'.") in caplog.messages
    message_type, message_payload= messaging.parse_message(msg)
    assert message_payload['events'][0]['response_required'] == 'always'


def test_event_missing_created_date_time(caplog):
    now = datetime.now(timezone.utc)
    event = {'active_period': {'dtstart': now, 'duration': timedelta(seconds=10)},
             'event_descriptor': {'event_id': 'event123',
                                  'modification_number': 1,
                                  'priority': 0,
                                  'event_status': 'far'},
             'event_signals': [{'signal_name': 'simple',
                                'signal_type': 'level',
                                'intervals': [{'dtstart': now,
                                               'duration': timedelta(seconds=10),
                                               'signal_payload': 1}]}],
             'targets': [{'ven_id': 'ven123'}],
             'response_required': 'always'}
    msg = messaging.create_message('oadrDistributeEvent', events=[event])
    assert ("Your event descriptor did not contain a created_date_time. "
            "This will be automatically added.") in caplog.messages


def test_event_incongruent_targets(caplog):
    now = datetime.now(timezone.utc)
    event = {'active_period': {'dtstart': now, 'duration': timedelta(seconds=10)},
             'event_descriptor': {'event_id': 'event123',
                                  'modification_number': 1,
                                  'priority': 0,
                                  'event_status': 'far',
                                  'created_date_time': now},
             'event_signals': [{'signal_name': 'simple',
                                'signal_type': 'level',
                                'intervals': [{'dtstart': now,
                                               'duration': timedelta(seconds=10),
                                               'signal_payload': 1}]}],
             'targets': [{'ven_id': 'ven123'}],
             'targets_by_type': {'ven_id': ['ven456']},
             'response_required': 'always'}
    with pytest.raises(ValueError) as err:
        msg = messaging.create_message('oadrDistributeEvent', events=[event])
    assert str(err.value) == ("You assigned both 'targets' and 'targets_by_type' in your event, "
                "but the two were not consistent with each other. "
                f"You supplied 'targets' = {event['targets']} and "
                f"'targets_by_type' = {event['targets_by_type']}")


def test_event_only_targets_by_type(caplog):
    now = datetime.now(timezone.utc)
    event = {'active_period': {'dtstart': now, 'duration': timedelta(seconds=10)},
             'event_descriptor': {'event_id': 'event123',
                                  'modification_number': 1,
                                  'priority': 0,
                                  'event_status': 'far',
                                  'created_date_time': now},
             'event_signals': [{'signal_name': 'simple',
                                'signal_type': 'level',
                                'intervals': [{'dtstart': now,
                                               'duration': timedelta(seconds=10),
                                               'signal_payload': 1}]}],
             'targets_by_type': {'ven_id': ['ven456']},
             'response_required': 'always'}
    msg = messaging.create_message('oadrDistributeEvent', events=[event])
    message_type, message_payload = messaging.parse_message(msg)
    assert message_payload['events'][0]['targets'] == [{'ven_id': 'ven456'}]

@pytest.mark.asyncio
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(hours=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(2)
    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:])

@pytest.mark.asyncio
async def test_server_add_event_with_wrong_callback_signature(caplog):
    def dummy_callback(some_param):
        pass
    caplog.set_level(logging.WARNING)
    logger = logging.getLogger('openleadr')
    logger.setLevel(logging.DEBUG)
    server = OpenADRServer(vtn_id='myvtn', requested_poll_freq=timedelta(seconds=1))
    with pytest.raises(ValueError) as err:
        server.add_event(ven_id='venid',
                         event_id='test_server_add_event_with_wrong_callback_signature',
                         signal_name='simple',
                         signal_type='level',
                         intervals=[{'dtstart': datetime.now(timezone.utc),
                                     'duration': timedelta(hours=1),
                                     'signal_payload': 1.1}],
                         target={'ven_id': 'venid'},
                         callback=dummy_callback)

@pytest.mark.asyncio
async def test_server_add_event_with_no_callback(caplog):
    def dummy_callback(some_param):
        pass
    caplog.set_level(logging.WARNING)
    logger = logging.getLogger('openleadr')
    logger.setLevel(logging.DEBUG)
    server = OpenADRServer(vtn_id='myvtn')
    server.add_event(ven_id='venid',
                     event_id='test_server_add_event_with_no_callback',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{'dtstart': datetime.now(timezone.utc),
                                 'duration': timedelta(hours=1),
                                 'signal_payload': 1.1}],
                     target={'ven_id': 'venid'})
    assert ("You did not provide a 'callback', which means you won't know if the "
            "VEN will opt in or opt out of your event. You should consider adding "
            "a callback for this.") in caplog.messages

@pytest.mark.asyncio
async def test_server_add_event_with_no_callback_response_never_required(caplog):
    caplog.set_level(logging.WARNING)
    logger = logging.getLogger('openleadr')
    logger.setLevel(logging.DEBUG)
    server = OpenADRServer(vtn_id='myvtn')
    server.add_event(ven_id='venid',
                     event_id='test_server_add_event_with_no_callback_response_never_required',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{'dtstart': datetime.now(timezone.utc),
                                 'duration': timedelta(hours=1),
                                 'signal_payload': 1.1}],
                     target={'ven_id': 'venid'},
                     response_required='never')
    await server.run()
    await server.stop()
    assert ("You did not provide a 'callback', which means you won't know if the "
            "VEN will opt in or opt out of your event. You should consider adding "
            "a callback for this.") not in caplog.messages