__init__.py 12 KB

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