test_schema.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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_schemas():
  66. for message_type, content in testcases:
  67. _test_message(message_type, **content)
  68. def _test_message(msg_type, **payload):
  69. try:
  70. with open(os.path.join('example_messages', f'{msg_type}.xml'), 'w') as file:
  71. message = create_message(msg_type, **payload)
  72. print(indent_xml(message),file=file)
  73. # print(type, file=file)
  74. # print("="*len(type), file=file)
  75. # print("", file=file)
  76. # print("OpenADR payload:", file=file)
  77. # print("..code-block:xml", file=file)
  78. # print("", file=file)
  79. # print(indent_xml(message), file=file)
  80. # print("", file=file)
  81. # print("pyOpenADR representation:", file=file)
  82. # print("..code-block:python3", file=file)
  83. # print("", file=file)
  84. # pprint(payload, stream=file)
  85. etree.fromstring(message.encode('utf-8'), parser)
  86. print(colored(f"pass: {msg_type} OK", "green"))
  87. except etree.XMLSyntaxError as err:
  88. print(colored(f"fail: {msg_type} failed validation: {err}", "red"))
  89. print(message)
  90. except jinja2.exceptions.UndefinedError as err:
  91. print(colored(f"fail: {msg_type} failed message construction: {err}", "yellow"))
  92. testcases = [
  93. ('oadrCanceledOpt', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, opt_id=generate_id())),
  94. ('oadrCanceledPartyRegistration', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, registration_id=generate_id(), ven_id='123ABC')),
  95. ('oadrCanceledReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}])),
  96. ('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')),
  97. ('oadrCancelOpt', dict(request_id=generate_id(), ven_id='123ABC', opt_id=generate_id())),
  98. ('oadrCancelPartyRegistration', dict(request_id=generate_id(), ven_id='123ABC', registration_id=generate_id())),
  99. ('oadrCancelReport', dict(request_id=generate_id(), ven_id='123ABC', report_request_id=generate_id(), report_to_follow=True)),
  100. ('oadrCreatedEvent', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  101. event_responses=[{'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(), 'event_id': generate_id(), 'modification_number': 1, 'opt_type': 'optIn'},
  102. {'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(), 'event_id': generate_id(), 'modification_number': 1, 'opt_type': 'optIn'},
  103. {'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(), 'event_id': generate_id(), 'modification_number': 1, 'opt_type': 'optIn'}],
  104. ven_id='123ABC')),
  105. ('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')),
  106. ('oadrCreatedEvent', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  107. event_responses=[{'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(),
  108. 'event_id': generate_id(),
  109. 'modification_number': 1,
  110. 'opt_type': 'optIn'},
  111. {'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(),
  112. 'event_id': generate_id(),
  113. 'modification_number': 1,
  114. 'opt_type': 'optOut'}],
  115. ven_id='123ABC')),
  116. ('oadrCreatedPartyRegistration', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  117. registration_id=generate_id(),
  118. ven_id='123ABC',
  119. profiles=[{'profile_name': '2.0b',
  120. 'transports': [{'transport_name': 'simpleHttp'}]}],
  121. vtn_id='VTN123')),
  122. ('oadrCreatedReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}])),
  123. ('oadrCreateOpt', dict(opt_id=generate_id(),
  124. opt_type='optIn',
  125. opt_reason='participating',
  126. created_date_time=datetime.now(timezone.utc),
  127. request_id=generate_id(),
  128. event_id=generate_id(),
  129. modification_number=1,
  130. targets=[{'ven_id': '123ABC'}],
  131. ven_id='VEN123')),
  132. ('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)),
  133. ('oadrCreateReport', dict(request_id=generate_id(),
  134. ven_id='123ABC',
  135. report_requests=[{'report_request_id': 'd2b7bade5f',
  136. 'report_specifier': {'granularity': timedelta(seconds=900),
  137. 'report_back_duration': timedelta(seconds=900),
  138. 'report_interval': {'dtstart': datetime(2019, 11, 19, 11, 0, 18, 672768, tzinfo=timezone.utc),
  139. 'duration': timedelta(seconds=7200),
  140. 'tolerance': {'tolerate': {'startafter': timedelta(seconds=300)}}},
  141. 'report_specifier_id': '9c8bdc00e7',
  142. 'specifier_payload': {'r_id': 'd6e2e07485',
  143. 'reading_type': 'Direct Read'}}}])),
  144. ('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')),
  145. ('oadrPoll', dict(ven_id='123ABC')),
  146. ('oadrQueryRegistration', dict(request_id=generate_id())),
  147. ('oadrRegisteredReport', dict(ven_id='VEN123', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  148. report_requests=[{'report_request_id': generate_id(),
  149. 'report_specifier': {'report_specifier_id': generate_id(),
  150. 'granularity': timedelta(minutes=15),
  151. 'report_back_duration': timedelta(minutes=15),
  152. 'report_interval': {'dtstart': datetime.now(timezone.utc),
  153. 'duration': timedelta(hours=2),
  154. 'tolerance': {'tolerate': {'startafter': timedelta(minutes=5)}},
  155. 'notification': timedelta(minutes=30),
  156. 'ramp_up': timedelta(minutes=15),
  157. 'recovery': timedelta(minutes=5)},
  158. 'specifier_payload': {'r_id': generate_id(),
  159. 'reading_type': 'Direct Read'}}},
  160. {'report_request_id': generate_id(),
  161. 'report_specifier': {'report_specifier_id': generate_id(),
  162. 'granularity': timedelta(minutes=15),
  163. 'report_back_duration': timedelta(minutes=15),
  164. 'report_interval': {'dtstart': datetime.now(timezone.utc),
  165. 'duration': timedelta(hours=2),
  166. 'tolerance': {'tolerate': {'startafter': timedelta(minutes=5)}},
  167. 'notification': timedelta(minutes=30),
  168. 'ramp_up': timedelta(minutes=15),
  169. 'recovery': timedelta(minutes=5)},
  170. 'specifier_payload': {'r_id': generate_id(),
  171. 'reading_type': 'Direct Read'}}}])),
  172. ('oadrRequestEvent', dict(request_id=generate_id(), ven_id='123ABC')),
  173. ('oadrRequestReregistration', dict(ven_id='123ABC')),
  174. ('oadrRegisterReport', dict(request_id=generate_id(), reports=[{'report_id': generate_id(),
  175. 'report_descriptions': {
  176. generate_id(): {
  177. 'report_subjects': [{'ven_id': '123ABC'}],
  178. 'report_data_sources': [{'ven_id': '123ABC'}],
  179. 'report_type': 'reading',
  180. 'reading_type': 'Direct Read',
  181. 'market_context': 'http://localhost',
  182. 'sampling_rate': {'min_period': timedelta(minutes=1), 'max_period': timedelta(minutes=1), 'on_change': True}}},
  183. 'report_request_id': generate_id(),
  184. 'report_specifier_id': generate_id(),
  185. 'report_name': 'HISTORY_USAGE',
  186. 'created_date_time': datetime.now(timezone.utc)}],
  187. ven_id='123ABC',
  188. report_request_id=generate_id())),
  189. ('oadrRegisterReport', {'request_id': '8a4f859883', 'reports': [{'report_id': generate_id(),
  190. 'duration': timedelta(seconds=7200),
  191. 'report_descriptions': {'resource1_status': {
  192. 'report_data_sources': [{'resource_id': 'resource1'}],
  193. 'report_type': 'x-resourceStatus',
  194. 'reading_type': 'x-notApplicable',
  195. 'market_context': 'http://MarketContext1',
  196. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}},
  197. 'report_request_id': '0',
  198. 'report_specifier_id': '789ed6cd4e_telemetry_status',
  199. 'report_name': 'METADATA_TELEMETRY_STATUS',
  200. 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)},
  201. {'report_id': generate_id(),
  202. 'duration': timedelta(seconds=7200),
  203. 'report_descriptions': {'resource1_energy': {
  204. 'report_data_sources': [{'resource_id': 'resource1'}],
  205. 'report_type': 'usage',
  206. 'energy_real': {'item_description': 'RealEnergy',
  207. 'item_units': 'Wh',
  208. 'si_scale_code': 'n'},
  209. 'reading_type': 'Direct Read',
  210. 'market_context': 'http://MarketContext1',
  211. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}},
  212. 'resource1_power': {
  213. 'report_data_sources': [{'resource_id': 'resource1'}],
  214. 'report_type': 'usage',
  215. 'power_real': {'item_description': 'RealPower',
  216. 'item_units': 'W',
  217. 'si_scale_code': 'n',
  218. 'power_attributes': {'hertz': 60, 'voltage': 110, 'ac': False}},
  219. 'reading_type': 'Direct Read',
  220. 'market_context': 'http://MarketContext1',
  221. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}},
  222. 'report_request_id': '0',
  223. 'report_specifier_id': '789ed6cd4e_telemetry_usage',
  224. 'report_name': 'METADATA_TELEMETRY_USAGE',
  225. 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)},
  226. {'report_id': generate_id(),
  227. 'duration': timedelta(seconds=7200),
  228. 'report_descriptions': {'resource1_energy': {
  229. 'report_data_sources': [{'resource_id': 'resource1'}],
  230. 'report_type': 'usage',
  231. 'energy_real': {'item_description': 'RealEnergy',
  232. 'item_units': 'Wh',
  233. 'si_scale_code': 'n'},
  234. 'reading_type': 'Direct Read',
  235. 'market_context': 'http://MarketContext1',
  236. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}},
  237. 'resource1_power': {
  238. 'report_data_sources': [{'resource_id': 'resource1'}],
  239. 'report_type': 'usage',
  240. 'power_real': {'item_description': 'RealPower',
  241. 'item_units': 'W', 'si_scale_code': 'n',
  242. 'power_attributes': {'hertz': 60, 'voltage': 110, 'ac': False}},
  243. 'reading_type': 'Direct Read',
  244. 'market_context': 'http://MarketContext1',
  245. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}},
  246. 'report_request_id': '0',
  247. 'report_specifier_id': '789ed6cd4e_history_usage',
  248. 'report_name': 'METADATA_HISTORY_USAGE',
  249. 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)}], 'ven_id': 's3cc244ee6'}),
  250. ('oadrResponse', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, ven_id='123ABC')),
  251. ('oadrResponse', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': None}, ven_id='123ABC')),
  252. ('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'})),
  253. ('oadrUpdateReport', dict(request_id=generate_id(), reports=[{'report_id': generate_id(),
  254. 'report_name': enums.REPORT_NAME.values[0],
  255. 'created_date_time': datetime.now(timezone.utc),
  256. 'report_request_id': generate_id(),
  257. 'report_specifier_id': generate_id(),
  258. 'report_descriptions': {generate_id(): {'report_subjects': [{'ven_id': '123ABC'}, {'ven_id': 'DEF456'}],
  259. 'report_data_sources': [{'ven_id': '123ABC'}],
  260. 'report_type': enums.REPORT_TYPE.values[0],
  261. 'reading_type': enums.READING_TYPE.values[0],
  262. 'market_context': 'http://localhost',
  263. 'sampling_rate': {'min_period': timedelta(minutes=1),
  264. 'max_period': timedelta(minutes=2),
  265. 'on_change': False}}}}], ven_id='123ABC'))
  266. ]