test_message_conversion.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. # SPDX-License-Identifier: Apache-2.0
  2. # Copyright 2020 Contributors to OpenLEADR
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. from openleadr.utils import generate_id, group_targets_by_type
  13. from openleadr.messaging import create_message, parse_message, validate_xml_schema
  14. from openleadr import enums
  15. from pprint import pprint
  16. from termcolor import colored
  17. from datetime import datetime, timezone, timedelta
  18. import pytest
  19. from dataclasses import asdict
  20. DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
  21. def create_dummy_event(ven_id):
  22. """
  23. Creates a dummy event
  24. """
  25. now = datetime.now(timezone.utc)
  26. event_id = generate_id()
  27. active_period = {"dtstart": (now + timedelta(minutes=1)),
  28. "duration": timedelta(minutes=9)}
  29. event_descriptor = {"event_id": event_id,
  30. "modification_number": 1,
  31. "modification_date_time": now,
  32. "priority": 1,
  33. "market_context": "http://MarketContext1",
  34. "created_date_time": now,
  35. "event_status": "near",
  36. "test_event": False,
  37. "vtn_comment": "This is an event"}
  38. event_signals = [{"intervals": [{"duration": timedelta(minutes=1), "uid": 0, "signal_payload": 8.0},
  39. {"duration": timedelta(minutes=1), "uid": 1, "signal_payload": 10.0},
  40. {"duration": timedelta(minutes=1), "uid": 2, "signal_payload": 12.0},
  41. {"duration": timedelta(minutes=1), "uid": 3, "signal_payload": 14.0},
  42. {"duration": timedelta(minutes=1), "uid": 4, "signal_payload": 16.0},
  43. {"duration": timedelta(minutes=1), "uid": 5, "signal_payload": 18.0},
  44. {"duration": timedelta(minutes=1), "uid": 6, "signal_payload": 20.0},
  45. {"duration": timedelta(minutes=1), "uid": 7, "signal_payload": 10.0},
  46. {"duration": timedelta(minutes=1), "uid": 8, "signal_payload": 20.0}],
  47. "signal_name": "LOAD_CONTROL",
  48. "signal_type": "x-loadControlCapacity",
  49. "signal_id": generate_id(),
  50. "measurement": {"name": "voltage",
  51. "description": "Voltage",
  52. "unit": "V",
  53. "scale": "none"},
  54. "current_value": 0.0}]
  55. event_targets = [{"ven_id": 'VEN001'}, {"ven_id": 'VEN002'}]
  56. event = {'active_period': active_period,
  57. 'event_descriptor': event_descriptor,
  58. 'event_signals': event_signals,
  59. 'targets': event_targets,
  60. 'targets_by_type': group_targets_by_type(event_targets),
  61. 'response_required': 'always'}
  62. return event
  63. reports = [{'report_id': generate_id(),
  64. 'duration': timedelta(seconds=3600),
  65. 'report_descriptions': [{'r_id': generate_id(),
  66. 'report_subject': {'resource_id': 'resource001'},
  67. 'report_data_source': {'resource_id': 'resource001'},
  68. 'report_type': 'usage',
  69. 'measurement': asdict(measurement),
  70. 'reading_type': 'Direct Read',
  71. 'market_context': 'http://MarketContext1',
  72. 'sampling_rate': {'min_period': timedelta(seconds=10), 'max_period': timedelta(seconds=30), 'on_change': False}} for measurement in enums.MEASUREMENTS.values],
  73. 'report_specifier_id': generate_id(),
  74. 'report_name': 'METADATA_HISTORY_USAGE',
  75. 'report_request_id': None,
  76. 'created_date_time': datetime.now(timezone.utc)}]
  77. for report in reports:
  78. for rd in report['report_descriptions']:
  79. rd['measurement'].pop('acceptable_units')
  80. rd['measurement'].pop('ns')
  81. if rd['measurement']['power_attributes'] is None:
  82. rd['measurement'].pop('power_attributes')
  83. if rd['measurement']['scale'] is None:
  84. rd['measurement'].pop('scale')
  85. if rd['measurement']['pulse_factor'] is None:
  86. rd['measurement'].pop('pulse_factor')
  87. testcases = [
  88. ('oadrCanceledOpt', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, opt_id=generate_id())),
  89. ('oadrCanceledPartyRegistration', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, registration_id=generate_id(), ven_id='123ABC')),
  90. ('oadrCanceledReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}])),
  91. ('oadrCanceledReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}], ven_id='123ABC')),
  92. ('oadrCancelOpt', dict(request_id=generate_id(), ven_id='123ABC', opt_id=generate_id())),
  93. ('oadrCancelPartyRegistration', dict(request_id=generate_id(), ven_id='123ABC', registration_id=generate_id())),
  94. ('oadrCancelReport', dict(request_id=generate_id(), ven_id='123ABC', report_request_id=generate_id(), report_to_follow=True)),
  95. ('oadrCreatedEvent', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  96. event_responses=[{'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(), 'event_id': generate_id(), 'modification_number': 1, 'opt_type': 'optIn'},
  97. {'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(), 'event_id': generate_id(), 'modification_number': 1, 'opt_type': 'optIn'},
  98. {'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(), 'event_id': generate_id(), 'modification_number': 1, 'opt_type': 'optIn'}],
  99. ven_id='123ABC')),
  100. ('oadrCreatedReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}], ven_id='123ABC')),
  101. ('oadrCreatedEvent', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  102. event_responses=[{'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(),
  103. 'event_id': generate_id(),
  104. 'modification_number': 1,
  105. 'opt_type': 'optIn'},
  106. {'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(),
  107. 'event_id': generate_id(),
  108. 'modification_number': 1,
  109. 'opt_type': 'optOut'}],
  110. ven_id='123ABC')),
  111. ('oadrCreatedPartyRegistration', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  112. registration_id=generate_id(),
  113. ven_id='123ABC',
  114. profiles=[{'profile_name': '2.0b',
  115. 'transports': [{'transport_name': 'simpleHttp'}]}],
  116. vtn_id='VTN123')),
  117. ('oadrCreatedReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}])),
  118. ('oadrCreateOpt', dict(opt_id=generate_id(),
  119. opt_type='optIn',
  120. opt_reason='participating',
  121. created_date_time=datetime.now(timezone.utc),
  122. request_id=generate_id(),
  123. event_id=generate_id(),
  124. modification_number=1,
  125. targets=[{'ven_id': '123ABC'}],
  126. targets_by_type=group_targets_by_type([{'ven_id': '123ABC'}]),
  127. ven_id='VEN123')),
  128. ('oadrCreatePartyRegistration', dict(request_id=generate_id(), ven_id='123ABC', profile_name='2.0b', transport_name='simpleHttp', transport_address='http://localhost', report_only=False, xml_signature=False, ven_name='test', http_pull_model=True)),
  129. ('oadrCreateReport', dict(request_id=generate_id(),
  130. ven_id='123ABC',
  131. report_requests=[{'report_request_id': 'd2b7bade5f',
  132. 'report_specifier': {'granularity': timedelta(seconds=900),
  133. 'report_back_duration': timedelta(seconds=900),
  134. 'report_interval': {'dtstart': datetime(2019, 11, 19, 11, 0, 18, 672768, tzinfo=timezone.utc),
  135. 'duration': timedelta(seconds=7200)},
  136. 'report_specifier_id': '9c8bdc00e7',
  137. 'specifier_payloads': [{'r_id': 'd6e2e07485',
  138. 'reading_type': 'Direct Read'}]}}])),
  139. ('oadrDistributeEvent', dict(request_id=generate_id(), response={'request_id': 123, 'response_code': 200, 'response_description': 'OK'}, events=[create_dummy_event(ven_id='123ABC')], vtn_id='VTN123')),
  140. ('oadrDistributeEvent', dict(request_id=generate_id(), response={'request_id': 123, 'response_code': 200, 'response_description': 'OK'}, events=[create_dummy_event(ven_id='123ABC'), create_dummy_event(ven_id='123ABC')], vtn_id='VTN123')),
  141. ('oadrPoll', dict(ven_id='123ABC')),
  142. ('oadrQueryRegistration', dict(request_id=generate_id())),
  143. ('oadrRegisteredReport', dict(ven_id='VEN123', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  144. report_requests=[{'report_request_id': generate_id(),
  145. 'report_specifier': {'report_specifier_id': generate_id(),
  146. 'granularity': timedelta(minutes=15),
  147. 'report_back_duration': timedelta(minutes=15),
  148. 'report_interval': {'dtstart': datetime.now(timezone.utc),
  149. 'duration': timedelta(hours=2)},
  150. 'specifier_payloads': [{'r_id': generate_id(),
  151. 'reading_type': 'Direct Read'}]}},
  152. {'report_request_id': generate_id(),
  153. 'report_specifier': {'report_specifier_id': generate_id(),
  154. 'granularity': timedelta(minutes=15),
  155. 'report_back_duration': timedelta(minutes=15),
  156. 'report_interval': {'dtstart': datetime.now(timezone.utc),
  157. 'duration': timedelta(hours=2)},
  158. 'specifier_payloads': [{'r_id': generate_id(),
  159. 'reading_type': 'Direct Read'}]}}])),
  160. ('oadrRequestEvent', dict(request_id=generate_id(), ven_id='123ABC')),
  161. ('oadrRequestReregistration', dict(ven_id='123ABC')),
  162. ('oadrRegisterReport', dict(request_id=generate_id(), reports=[{'report_id': generate_id(),
  163. 'report_descriptions': [{
  164. 'r_id': generate_id(),
  165. 'report_subject': {'resource_id': '123ABC'},
  166. 'report_data_source': {'resource_id': '123ABC'},
  167. 'report_type': 'reading',
  168. 'reading_type': 'Direct Read',
  169. 'market_context': 'http://localhost',
  170. 'sampling_rate': {'min_period': timedelta(minutes=1), 'max_period': timedelta(minutes=1), 'on_change': True}}],
  171. 'report_request_id': generate_id(),
  172. 'report_specifier_id': generate_id(),
  173. 'report_name': 'HISTORY_USAGE',
  174. 'created_date_time': datetime.now(timezone.utc)}],
  175. ven_id='123ABC',
  176. report_request_id=generate_id())),
  177. ('oadrRegisterReport', {'request_id': '8a4f859883', 'reports': [{'report_id': generate_id(),
  178. 'duration': timedelta(seconds=7200),
  179. 'report_descriptions': [{'r_id': generate_id(),
  180. 'report_data_source': {'resource_id': 'resource1'},
  181. 'report_type': 'x-resourceStatus',
  182. 'reading_type': 'x-notApplicable',
  183. 'market_context': 'http://MarketContext1',
  184. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}],
  185. 'report_request_id': generate_id(),
  186. 'report_specifier_id': '789ed6cd4e_telemetry_status',
  187. 'report_name': 'METADATA_TELEMETRY_STATUS',
  188. 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)},
  189. {'report_id': generate_id(),
  190. 'duration': timedelta(seconds=7200),
  191. 'report_descriptions': [{'r_id': 'resource1_energy',
  192. 'report_data_source': {'resource_id': 'resource1'},
  193. 'report_type': 'usage',
  194. 'measurement': {'name': 'energyReal',
  195. 'description': 'RealEnergy',
  196. 'ns': 'power',
  197. 'unit': 'Wh',
  198. 'scale': 'n'},
  199. 'reading_type': 'Direct Read',
  200. 'market_context': 'http://MarketContext1',
  201. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}},
  202. {'r_id': 'resource1_power',
  203. 'report_data_source': {'resource_id': 'resource1'},
  204. 'report_type': 'usage',
  205. 'measurement': {'name': 'powerReal',
  206. 'description': 'RealPower',
  207. 'ns': 'power',
  208. 'unit': 'W',
  209. 'scale': 'n',
  210. 'power_attributes': {'hertz': 50, 'voltage': 230, 'ac': True}},
  211. 'reading_type': 'Direct Read',
  212. 'market_context': 'http://MarketContext1',
  213. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}],
  214. 'report_request_id': generate_id(),
  215. 'report_specifier_id': '789ed6cd4e_telemetry_usage',
  216. 'report_name': 'METADATA_TELEMETRY_USAGE',
  217. 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)},
  218. {'report_id': generate_id(),
  219. 'duration': timedelta(seconds=7200),
  220. 'report_descriptions': [{'r_id': 'resource1_energy',
  221. 'report_data_source': {'resource_id': 'resource1'},
  222. 'report_type': 'usage',
  223. 'measurement': {'name': 'energyReal',
  224. 'description': 'RealEnergy',
  225. 'ns': 'power',
  226. 'unit': 'Wh',
  227. 'scale': 'n'},
  228. 'reading_type': 'Direct Read',
  229. 'market_context': 'http://MarketContext1',
  230. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}},
  231. {'r_id': 'resource1_power',
  232. 'report_data_source': {'resource_id': 'resource1'},
  233. 'report_type': 'usage',
  234. 'measurement': {'name': 'powerReal',
  235. 'description': 'RealPower',
  236. 'ns': 'power',
  237. 'unit': 'W',
  238. 'scale': 'n',
  239. 'power_attributes': {'hertz': 50, 'voltage': 230, 'ac': True}},
  240. 'reading_type': 'Direct Read',
  241. 'market_context': 'http://MarketContext1',
  242. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}],
  243. 'report_request_id': generate_id(),
  244. 'report_specifier_id': '789ed6cd4e_history_usage',
  245. 'report_name': 'METADATA_HISTORY_USAGE',
  246. 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)}], 'ven_id': 's3cc244ee6'}),
  247. ('oadrRegisterReport', {'ven_id': 'ven123', 'request_id': generate_id(), 'reports': reports}),
  248. ('oadrResponse', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, ven_id='123ABC')),
  249. ('oadrResponse', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': None}, ven_id='123ABC')),
  250. ('oadrUpdatedReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, ven_id='123ABC', cancel_report={'request_id': generate_id(), 'report_request_id': [generate_id(), generate_id(), generate_id()], 'report_to_follow': False, 'ven_id': '123ABC'})),
  251. ('oadrUpdateReport', dict(request_id=generate_id(), reports=[{'report_id': generate_id(),
  252. 'report_name': enums.REPORT_NAME.values[0],
  253. 'created_date_time': datetime.now(timezone.utc),
  254. 'report_request_id': generate_id(),
  255. 'report_specifier_id': generate_id(),
  256. 'report_descriptions': [{'r_id': generate_id(),
  257. 'report_subject': {'resource_id': '123ABC'},
  258. 'report_data_source': {'resource_id': '123ABC'},
  259. 'report_type': enums.REPORT_TYPE.values[0],
  260. 'reading_type': enums.READING_TYPE.values[0],
  261. 'market_context': 'http://localhost',
  262. 'sampling_rate': {'min_period': timedelta(minutes=1),
  263. 'max_period': timedelta(minutes=2),
  264. 'on_change': False}}
  265. ]}], ven_id='123ABC'))
  266. ]
  267. @pytest.mark.parametrize('message_type,data', testcases)
  268. def test_message(message_type, data):
  269. message = create_message(message_type, **data)
  270. parsed = parse_message(message)[1]
  271. if message_type == 'oadrRegisterReport':
  272. for report in data['reports']:
  273. for rd in report['report_descriptions']:
  274. if 'measurement' in rd:
  275. rd['measurement'].pop('ns')
  276. if message_type == 'oadrDistributeEvent':
  277. for event in data['events']:
  278. for signal in event['event_signals']:
  279. if 'measurement' in signal:
  280. signal['measurement'].pop('ns')
  281. assert parsed == data