__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. # Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. #
  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. #
  7. # http:#www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import functools
  15. import json
  16. import logging
  17. import os
  18. import re
  19. from copy import deepcopy
  20. import junit_xml
  21. from tiny_test_fw import TinyFW, Utility
  22. from .DebugUtils import CustomProcess, GDBBackend, OCDBackend # noqa: export DebugUtils for users
  23. from .IDFApp import UT, ComponentUTApp, Example, IDFApp, LoadableElfTestApp, TestApp # noqa: export all Apps for users
  24. from .IDFDUT import (ESP32C3DUT, ESP32DUT, ESP32QEMUDUT, ESP32S2DUT, ESP32S3DUT, # noqa: export DUTs for users
  25. ESP8266DUT, IDFDUT)
  26. from .unity_test_parser import TestFormat, TestResults
  27. # pass TARGET_DUT_CLS_DICT to Env.py to avoid circular dependency issue.
  28. TARGET_DUT_CLS_DICT = {
  29. 'ESP32': ESP32DUT,
  30. 'ESP32S2': ESP32S2DUT,
  31. 'ESP32S3': ESP32S3DUT,
  32. 'ESP32C3': ESP32C3DUT,
  33. }
  34. try:
  35. string_type = basestring # type: ignore
  36. except NameError:
  37. string_type = str
  38. def upper_list_or_str(text):
  39. """
  40. Return the uppercase of list of string or string. Return itself for other
  41. data types
  42. :param text: list or string, other instance will be returned immediately
  43. :return: uppercase of list of string
  44. """
  45. if isinstance(text, string_type):
  46. return [text.upper()]
  47. elif isinstance(text, list):
  48. return [item.upper() for item in text]
  49. else:
  50. return text
  51. def local_test_check(decorator_target):
  52. # Try to get the sdkconfig.json to read the IDF_TARGET value.
  53. # If not set, will set to ESP32.
  54. # For CI jobs, this is a fake procedure, the true target and dut will be
  55. # overwritten by the job config YAML file.
  56. idf_target = 'ESP32' # default if sdkconfig not found or not readable
  57. if os.getenv('CI_JOB_ID'): # Only auto-detect target when running locally
  58. return idf_target
  59. decorator_target = upper_list_or_str(decorator_target)
  60. expected_json_path = os.path.join('build', 'config', 'sdkconfig.json')
  61. if os.path.exists(expected_json_path):
  62. sdkconfig = json.load(open(expected_json_path))
  63. try:
  64. idf_target = sdkconfig['IDF_TARGET'].upper()
  65. except KeyError:
  66. logging.debug('IDF_TARGET not in {}. IDF_TARGET set to esp32'.format(os.path.abspath(expected_json_path)))
  67. else:
  68. logging.debug('IDF_TARGET: {}'.format(idf_target))
  69. else:
  70. logging.debug('{} not found. IDF_TARGET set to esp32'.format(os.path.abspath(expected_json_path)))
  71. if isinstance(decorator_target, list):
  72. if idf_target not in decorator_target:
  73. raise ValueError('IDF_TARGET set to {}, not in decorator target value'.format(idf_target))
  74. else:
  75. if idf_target != decorator_target:
  76. raise ValueError('IDF_TARGET set to {}, not equal to decorator target value'.format(idf_target))
  77. return idf_target
  78. def get_dut_class(target, dut_class_dict, erase_nvs=None):
  79. if target not in dut_class_dict:
  80. raise Exception('target can only be {%s} (case insensitive)' % ', '.join(dut_class_dict.keys()))
  81. dut = dut_class_dict[target.upper()]
  82. if erase_nvs:
  83. dut.ERASE_NVS = 'erase_nvs'
  84. return dut
  85. def ci_target_check(func):
  86. @functools.wraps(func)
  87. def wrapper(**kwargs):
  88. target = upper_list_or_str(kwargs.get('target', []))
  89. ci_target = upper_list_or_str(kwargs.get('ci_target', []))
  90. if not set(ci_target).issubset(set(target)):
  91. raise ValueError('ci_target must be a subset of target')
  92. return func(**kwargs)
  93. return wrapper
  94. def test_func_generator(func, app, target, ci_target, module, execution_time, level, erase_nvs, **kwargs):
  95. target = upper_list_or_str(target)
  96. test_target = local_test_check(target)
  97. if 'additional_duts' in kwargs:
  98. dut_classes = deepcopy(TARGET_DUT_CLS_DICT)
  99. dut_classes.update(kwargs['additional_duts'])
  100. else:
  101. dut_classes = TARGET_DUT_CLS_DICT
  102. dut = get_dut_class(test_target, dut_classes, erase_nvs)
  103. original_method = TinyFW.test_method(
  104. app=app, dut=dut, target=target, ci_target=upper_list_or_str(ci_target),
  105. module=module, execution_time=execution_time, level=level, erase_nvs=erase_nvs,
  106. dut_dict=dut_classes, **kwargs
  107. )
  108. test_func = original_method(func)
  109. return test_func
  110. @ci_target_check
  111. def idf_example_test(app=Example, target='ESP32', ci_target=None, module='examples', execution_time=1,
  112. level='example', erase_nvs=True, config_name=None, **kwargs):
  113. """
  114. decorator for testing idf examples (with default values for some keyword args).
  115. :param app: test application class
  116. :param target: target supported, string or list
  117. :param ci_target: target auto run in CI, if None than all target will be tested, None, string or list
  118. :param module: module, string
  119. :param execution_time: execution time in minutes, int
  120. :param level: test level, could be used to filter test cases, string
  121. :param erase_nvs: if need to erase_nvs in DUT.start_app()
  122. :param config_name: if specified, name of the app configuration
  123. :param kwargs: other keyword args
  124. :return: test method
  125. """
  126. def test(func):
  127. return test_func_generator(func, app, target, ci_target, module, execution_time, level, erase_nvs, **kwargs)
  128. return test
  129. @ci_target_check
  130. def idf_unit_test(app=UT, target='ESP32', ci_target=None, module='unit-test', execution_time=1,
  131. level='unit', erase_nvs=True, **kwargs):
  132. """
  133. decorator for testing idf unit tests (with default values for some keyword args).
  134. :param app: test application class
  135. :param target: target supported, string or list
  136. :param ci_target: target auto run in CI, if None than all target will be tested, None, string or list
  137. :param module: module, string
  138. :param execution_time: execution time in minutes, int
  139. :param level: test level, could be used to filter test cases, string
  140. :param erase_nvs: if need to erase_nvs in DUT.start_app()
  141. :param kwargs: other keyword args
  142. :return: test method
  143. """
  144. def test(func):
  145. return test_func_generator(func, app, target, ci_target, module, execution_time, level, erase_nvs, **kwargs)
  146. return test
  147. @ci_target_check
  148. def idf_custom_test(app=TestApp, target='ESP32', ci_target=None, module='misc', execution_time=1,
  149. level='integration', erase_nvs=True, config_name=None, **kwargs):
  150. """
  151. decorator for idf custom tests (with default values for some keyword args).
  152. :param app: test application class
  153. :param target: target supported, string or list
  154. :param ci_target: target auto run in CI, if None than all target will be tested, None, string or list
  155. :param module: module, string
  156. :param execution_time: execution time in minutes, int
  157. :param level: test level, could be used to filter test cases, string
  158. :param erase_nvs: if need to erase_nvs in DUT.start_app()
  159. :param config_name: if specified, name of the app configuration
  160. :param kwargs: other keyword args
  161. :return: test method
  162. """
  163. def test(func):
  164. return test_func_generator(func, app, target, ci_target, module, execution_time, level, erase_nvs, **kwargs)
  165. return test
  166. @ci_target_check
  167. def idf_component_unit_test(app=ComponentUTApp, target='ESP32', ci_target=None, module='misc', execution_time=1,
  168. level='integration', erase_nvs=True, config_name=None, **kwargs):
  169. """
  170. decorator for idf custom tests (with default values for some keyword args).
  171. :param app: test application class
  172. :param target: target supported, string or list
  173. :param ci_target: target auto run in CI, if None than all target will be tested, None, string or list
  174. :param module: module, string
  175. :param execution_time: execution time in minutes, int
  176. :param level: test level, could be used to filter test cases, string
  177. :param erase_nvs: if need to erase_nvs in DUT.start_app()
  178. :param config_name: if specified, name of the app configuration
  179. :param kwargs: other keyword args
  180. :return: test method
  181. """
  182. def test(func):
  183. return test_func_generator(func, app, target, ci_target, module, execution_time, level, erase_nvs, **kwargs)
  184. return test
  185. class ComponentUTResult:
  186. """
  187. Function Class, parse component unit test results
  188. """
  189. @staticmethod
  190. def parse_result(stdout):
  191. try:
  192. results = TestResults(stdout, TestFormat.UNITY_FIXTURE_VERBOSE)
  193. except (ValueError, TypeError) as e:
  194. raise ValueError('Error occurs when parsing the component unit test stdout to JUnit report: ' + str(e))
  195. group_name = results.tests()[0].group()
  196. with open(os.path.join(os.getenv('LOG_PATH', ''), '{}_XUNIT_RESULT.xml'.format(group_name)), 'w') as fw:
  197. junit_xml.to_xml_report_file(fw, [results.to_junit()])
  198. if results.num_failed():
  199. # raise exception if any case fails
  200. err_msg = 'Failed Cases:\n'
  201. for test_case in results.test_iter():
  202. if test_case.result() == 'FAIL':
  203. err_msg += '\t{}: {}'.format(test_case.name(), test_case.message())
  204. raise AssertionError(err_msg)
  205. def log_performance(item, value):
  206. """
  207. do print performance with pre-defined format to console
  208. :param item: performance item name
  209. :param value: performance value
  210. """
  211. performance_msg = '[Performance][{}]: {}'.format(item, value)
  212. Utility.console_log(performance_msg, 'orange')
  213. # update to junit test report
  214. current_junit_case = TinyFW.JunitReport.get_current_test_case()
  215. current_junit_case.stdout += performance_msg + '\r\n'
  216. def check_performance(item, value, target):
  217. """
  218. check if idf performance meet pass standard
  219. :param item: performance item name
  220. :param value: performance item value
  221. :param target: target chip
  222. :raise: AssertionError: if check fails
  223. """
  224. def _find_perf_item(path):
  225. with open(path, 'r') as f:
  226. data = f.read()
  227. match = re.search(r'#define\s+IDF_PERFORMANCE_(MIN|MAX)_{}\s+([\d.]+)'.format(item.upper()), data)
  228. return match.group(1), float(match.group(2))
  229. def _check_perf(op, standard_value):
  230. if op == 'MAX':
  231. ret = value <= standard_value
  232. else:
  233. ret = value >= standard_value
  234. if not ret:
  235. raise AssertionError("[Performance] {} value is {}, doesn't meet pass standard {}"
  236. .format(item, value, standard_value))
  237. path_prefix = os.path.join(IDFApp.get_sdk_path(), 'components', 'idf_test', 'include')
  238. performance_files = (os.path.join(path_prefix, target, 'idf_performance_target.h'),
  239. os.path.join(path_prefix, 'idf_performance.h'))
  240. for performance_file in performance_files:
  241. try:
  242. op, standard = _find_perf_item(performance_file)
  243. except (IOError, AttributeError):
  244. # performance file doesn't exist or match is not found in it
  245. continue
  246. _check_perf(op, standard)
  247. # if no exception was thrown then the performance is met and no need to continue
  248. break
  249. else:
  250. raise AssertionError('Failed to get performance standard for {}'.format(item))
  251. MINIMUM_FREE_HEAP_SIZE_RE = re.compile(r'Minimum free heap size: (\d+) bytes')
  252. def print_heap_size(app_name, config_name, target, minimum_free_heap_size):
  253. """
  254. Do not change the print output in case you really need to.
  255. The result is parsed by ci-dashboard project
  256. """
  257. print('------ heap size info ------\n'
  258. '[app_name] {}\n'
  259. '[config_name] {}\n'
  260. '[target] {}\n'
  261. '[minimum_free_heap_size] {} Bytes\n'
  262. '------ heap size end ------'.format(app_name,
  263. '' if not config_name else config_name,
  264. target,
  265. minimum_free_heap_size))