test_schema.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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 pyopenadr.utils import generate_id, indent_xml
  13. from pyopenadr.messaging import create_message
  14. from pyopenadr import enums
  15. from lxml import etree
  16. import os
  17. from datetime import datetime, timedelta, timezone
  18. from termcolor import colored
  19. import jinja2
  20. from pprint import pprint
  21. DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
  22. SCHEMA_LOCATION = os.path.join('schema', 'oadr_20b.xsd')
  23. schema_root = etree.parse(SCHEMA_LOCATION)
  24. schema = etree.XMLSchema(schema_root)
  25. parser = etree.XMLParser(schema=schema)
  26. def create_dummy_event(ven_id):
  27. """
  28. Creates a dummy event
  29. """
  30. now = datetime.now(timezone.utc)
  31. event_id = generate_id()
  32. active_period = {"dtstart": now + timedelta(minutes=1),
  33. "duration": timedelta(minutes=9)}
  34. event_descriptor = {"event_id": event_id,
  35. "modification_number": 1,
  36. "modification_date_time": now,
  37. "priority": 1,
  38. "market_context": "http://MarketContext1",
  39. "created_date_time": now,
  40. "event_status": "near",
  41. "test_event": "false",
  42. "vtn_comment": "This is an event"}
  43. event_signals = [{"intervals": [{"duration": timedelta(minutes=1), "uid": 1, "signal_payload": 8},
  44. {"duration": timedelta(minutes=1), "uid": 2, "signal_payload": 10},
  45. {"duration": timedelta(minutes=1), "uid": 3, "signal_payload": 12},
  46. {"duration": timedelta(minutes=1), "uid": 4, "signal_payload": 14},
  47. {"duration": timedelta(minutes=1), "uid": 5, "signal_payload": 16},
  48. {"duration": timedelta(minutes=1), "uid": 6, "signal_payload": 18},
  49. {"duration": timedelta(minutes=1), "uid": 7, "signal_payload": 20},
  50. {"duration": timedelta(minutes=1), "uid": 8, "signal_payload": 10},
  51. {"duration": timedelta(minutes=1), "uid": 9, "signal_payload": 20}],
  52. "signal_name": "LOAD_CONTROL",
  53. #"signal_name": "simple",
  54. #"signal_type": "level",
  55. "signal_type": "x-loadControlCapacity",
  56. "signal_id": generate_id(),
  57. "current_value": 9.99}]
  58. event_targets = [{"ven_id": 'VEN001'}, {"ven_id": 'VEN002'}]
  59. event = {'active_period': active_period,
  60. 'event_descriptor': event_descriptor,
  61. 'event_signals': event_signals,
  62. 'targets': event_targets,
  63. 'response_required': 'always'}
  64. return event
  65. def test_message(msg_type, **payload):
  66. try:
  67. with open(os.path.join('example_messages', f'{msg_type}.xml'), 'w') as file:
  68. message = create_message(msg_type, **payload)
  69. print(indent_xml(message),file=file)
  70. # print(type, file=file)
  71. # print("="*len(type), file=file)
  72. # print("", file=file)
  73. # print("OpenADR payload:", file=file)
  74. # print("..code-block:xml", file=file)
  75. # print("", file=file)
  76. # print(indent_xml(message), file=file)
  77. # print("", file=file)
  78. # print("pyOpenADR representation:", file=file)
  79. # print("..code-block:python3", file=file)
  80. # print("", file=file)
  81. # pprint(payload, stream=file)
  82. etree.fromstring(message.encode('utf-8'), parser)
  83. print(colored(f"pass: {msg_type} OK", "green"))
  84. except etree.XMLSyntaxError as err:
  85. print(colored(f"fail: {msg_type} failed validation: {err}", "red"))
  86. print(message)
  87. except jinja2.exceptions.UndefinedError as err:
  88. print(colored(f"fail: {msg_type} failed message construction: {err}", "yellow"))
  89. test_message('oadrCanceledOpt', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, opt_id=generate_id())
  90. test_message('oadrCanceledPartyRegistration', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, registration_id=generate_id(), ven_id='123ABC')
  91. test_message('oadrCanceledReport', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}])
  92. test_message('oadrCanceledReport', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}], ven_id='123ABC')
  93. test_message('oadrCancelOpt', request_id=generate_id(), ven_id='123ABC', opt_id=generate_id())
  94. test_message('oadrCancelPartyRegistration', request_id=generate_id(), ven_id='123ABC', registration_id=generate_id())
  95. test_message('oadrCancelReport', request_id=generate_id(), ven_id='123ABC', report_request_id=generate_id(), report_to_follow=True)
  96. test_message('oadrCreatedEvent', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  97. event_responses=[{'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. {'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(), 'event_id': generate_id(), 'modification_number': 1, 'opt_type': 'optIn'}],
  100. ven_id='123ABC')
  101. test_message('oadrCreatedReport', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}], ven_id='123ABC')
  102. test_message('oadrCreatedEvent', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  103. event_responses=[{'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(),
  104. 'event_id': generate_id(),
  105. 'modification_number': 1,
  106. 'opt_type': 'optIn'},
  107. {'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(),
  108. 'event_id': generate_id(),
  109. 'modification_number': 1,
  110. 'opt_type': 'optOut'}],
  111. ven_id='123ABC')
  112. test_message('oadrCreatedPartyRegistration', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  113. registration_id=generate_id(),
  114. ven_id='123ABC',
  115. profiles=[{'profile_name': '2.0b',
  116. 'transports': [{'transport_name': 'simpleHttp'}]}],
  117. vtn_id='VTN123')
  118. test_message('oadrCreatedReport', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}])
  119. test_message('oadrCreateOpt', opt_id=generate_id(),
  120. opt_type='optIn',
  121. opt_reason='participating',
  122. created_date_time=datetime.now(timezone.utc),
  123. request_id=generate_id(),
  124. event_id=generate_id(),
  125. modification_number=1,
  126. targets=[{'ven_id': '123ABC'}],
  127. ven_id='VEN123')
  128. test_message('oadrCreatePartyRegistration', 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. test_message('oadrCreateReport', 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. 'tolerance': {'tolerate': {'startafter': timedelta(seconds=300)}}},
  137. 'report_specifier_id': '9c8bdc00e7',
  138. 'specifier_payload': {'r_id': 'd6e2e07485',
  139. 'reading_type': 'Direct Read'}}}])
  140. test_message('oadrDistributeEvent', request_id=generate_id(), response={'request_id': 123, 'response_code': 200, 'response_description': 'OK'}, events=[create_dummy_event(ven_id='123ABC')], vtn_id='VTN123')
  141. test_message('oadrPoll', ven_id='123ABC')
  142. test_message('oadrQueryRegistration', request_id=generate_id())
  143. test_message('oadrRegisteredReport', 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. 'tolerance': {'tolerate': {'startafter': timedelta(minutes=5)}},
  151. 'notification': timedelta(minutes=30),
  152. 'ramp_up': timedelta(minutes=15),
  153. 'recovery': timedelta(minutes=5)},
  154. 'specifier_payload': {'r_id': generate_id(),
  155. 'reading_type': 'Direct Read'}}},
  156. {'report_request_id': generate_id(),
  157. 'report_specifier': {'report_specifier_id': generate_id(),
  158. 'granularity': timedelta(minutes=15),
  159. 'report_back_duration': timedelta(minutes=15),
  160. 'report_interval': {'dtstart': datetime.now(timezone.utc),
  161. 'duration': timedelta(hours=2),
  162. 'tolerance': {'tolerate': {'startafter': timedelta(minutes=5)}},
  163. 'notification': timedelta(minutes=30),
  164. 'ramp_up': timedelta(minutes=15),
  165. 'recovery': timedelta(minutes=5)},
  166. 'specifier_payload': {'r_id': generate_id(),
  167. 'reading_type': 'Direct Read'}}}])
  168. test_message('oadrRequestEvent', request_id=generate_id(), ven_id='123ABC')
  169. test_message('oadrRequestReregistration', ven_id='123ABC')
  170. test_message('oadrRegisterReport', request_id=generate_id(), reports=[{'report_id': generate_id(),
  171. 'report_descriptions': [{
  172. 'r_id': generate_id(),
  173. 'report_subjects': {'ven_id': '123ABC'},
  174. 'report_data_sources': {'ven_id': '123ABC'},
  175. 'report_type': 'reading',
  176. 'reading_type': 'Direct Read',
  177. 'market_context': 'http://localhost',
  178. 'sampling_rate': {'min_period': timedelta(minutes=1), 'max_period': timedelta(minutes=1), 'on_change': True}}],
  179. 'report_request_id': generate_id(),
  180. 'report_specifier_id': generate_id(),
  181. 'report_name': 'HISTORY_USAGE',
  182. 'created_date_time': datetime.now(timezone.utc)}],
  183. ven_id='123ABC',
  184. report_request_id=generate_id())
  185. test_message('oadrRegisterReport', **{'request_id': '8a4f859883', 'reports': [{'duration': timedelta(seconds=7200), 'report_descriptions': [{'r_id': 'resource1_status', 'report_data_sources': [{'resource_id': 'resource1'}], 'report_type': 'x-resourceStatus', 'reading_type': 'x-notApplicable', 'market_context': 'http://MarketContext1', 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}], 'report_request_id': '0', 'report_specifier_id': '789ed6cd4e_telemetry_status', 'report_name': 'METADATA_TELEMETRY_STATUS', 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)}, {'duration': timedelta(seconds=7200), 'report_descriptions': [{'r_id': 'resource1_energy', 'report_data_sources': [{'resource_id': 'resource1'}], 'report_type': 'usage', 'energy_real': {'item_description': 'RealEnergy', 'item_units': 'Wh', 'si_scale_code': 'n'}, 'reading_type': 'Direct Read', 'market_context': 'http://MarketContext1', 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}, {'r_id': 'resource1_power', 'report_data_sources': [{'resource_id': 'resource1'}], 'report_type': 'usage', 'power_real': {'item_description': 'RealPower', 'item_units': 'W', 'si_scale_code': 'n', 'power_attributes': {'hertz': 60, 'voltage': 110, 'ac': False}}, 'reading_type': 'Direct Read', 'market_context': 'http://MarketContext1', 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}], 'report_request_id': '0', 'report_specifier_id': '789ed6cd4e_telemetry_usage', 'report_name': 'METADATA_TELEMETRY_USAGE', 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)}, {'duration': timedelta(seconds=7200), 'report_descriptions': [{'r_id': 'resource1_energy', 'report_data_sources': [{'resource_id': 'resource1'}], 'report_type': 'usage', 'energy_real': {'item_description': 'RealEnergy', 'item_units': 'Wh', 'si_scale_code': 'n'}, 'reading_type': 'Direct Read', 'market_context': 'http://MarketContext1', 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}, {'r_id': 'resource1_power', 'report_data_sources': [{'resource_id': 'resource1'}], 'report_type': 'usage', 'power_real': {'item_description': 'RealPower', 'item_units': 'W', 'si_scale_code': 'n', 'power_attributes': {'hertz': 60, 'voltage': 110, 'ac': False}}, 'reading_type': 'Direct Read', 'market_context': 'http://MarketContext1', 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}], 'report_request_id': '0', 'report_specifier_id': '789ed6cd4e_history_usage', 'report_name': 'METADATA_HISTORY_USAGE', 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)}], 'ven_id': 's3cc244ee6'})
  186. test_message('oadrResponse', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, ven_id='123ABC')
  187. test_message('oadrResponse', response={'response_code': 200, 'response_description': 'OK', 'request_id': None}, ven_id='123ABC')
  188. test_message('oadrUpdatedReport', 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'})
  189. test_message('oadrUpdateReport', request_id=generate_id(), reports=[{'report_id': generate_id(),
  190. 'report_name': enums.REPORT_NAME.values[0],
  191. 'created_date_time': datetime.now(timezone.utc),
  192. 'report_request_id': generate_id(),
  193. 'report_specifier_id': generate_id(),
  194. 'report_descriptions': [{'r_id': generate_id(),
  195. 'report_subjects': [{'ven_id': '123ABC'}, {'ven_id': 'DEF456'}],
  196. 'report_data_sources': [{'ven_id': '123ABC'}],
  197. 'report_type': enums.REPORT_TYPE.values[0],
  198. 'reading_type': enums.READING_TYPE.values[0],
  199. 'market_context': 'http://localhost',
  200. 'sampling_rate': {'min_period': timedelta(minutes=1),
  201. 'max_period': timedelta(minutes=2),
  202. 'on_change': False}}]}], ven_id='123ABC')
  203. # for report_name in enums.REPORT_NAME.values:
  204. # for reading_type in enums.READING_TYPE.values:
  205. # for report_type in enums.REPORT_TYPE.values:
  206. # test_message('oadrUpdateReport', request_id=generate_id(), reports=[{'report_id': generate_id(),
  207. # 'report_name': report_name,
  208. # 'created_date_time': datetime.now(timezone.utc),
  209. # 'report_request_id': generate_id(),
  210. # 'report_specifier_id': generate_id(),
  211. # 'report_descriptions': [{'r_id': generate_id(),
  212. # 'report_subjects': [{'ven_id': '123ABC'}, {'ven_id': 'DEF456'}],
  213. # 'report_data_sources': [{'ven_id': '123ABC'}],
  214. # 'report_type': report_type,
  215. # 'reading_type': reading_type,
  216. # 'market_context': 'http://localhost',
  217. # 'sampling_rate': {'min_period': timedelta(minutes=1),
  218. # 'max_period': timedelta(minutes=2),
  219. # 'on_change': False}}]}], ven_id='123ABC')