__init__.py 13 KB

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