__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 OCDBackend, GDBBackend, CustomProcess # noqa: export DebugUtils for users
  23. from .IDFApp import IDFApp, Example, LoadableElfTestApp, UT, TestApp, ComponentUTApp # noqa: export all Apps for users
  24. from .IDFDUT import IDFDUT, ESP32DUT, ESP32S2DUT, ESP32C3DUT, ESP8266DUT, ESP32QEMUDUT # noqa: export DUTs for users
  25. from .unity_test_parser import TestResults, TestFormat
  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. def format_case_id(target, case_name):
  33. return "{}.{}".format(target, case_name)
  34. try:
  35. string_type = basestring
  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. test_func.case_info["ID"] = format_case_id(target, test_func.case_info["name"])
  110. return test_func
  111. @ci_target_check
  112. def idf_example_test(app=Example, target="ESP32", ci_target=None, module="examples", execution_time=1,
  113. level="example", erase_nvs=True, config_name=None, **kwargs):
  114. """
  115. decorator for testing idf examples (with default values for some keyword args).
  116. :param app: test application class
  117. :param target: target supported, string or list
  118. :param ci_target: target auto run in CI, if None than all target will be tested, None, string or list
  119. :param module: module, string
  120. :param execution_time: execution time in minutes, int
  121. :param level: test level, could be used to filter test cases, string
  122. :param erase_nvs: if need to erase_nvs in DUT.start_app()
  123. :param config_name: if specified, name of the app configuration
  124. :param kwargs: other keyword args
  125. :return: test method
  126. """
  127. def test(func):
  128. return test_func_generator(func, app, target, ci_target, module, execution_time, level, erase_nvs, **kwargs)
  129. return test
  130. @ci_target_check
  131. def idf_unit_test(app=UT, target="ESP32", ci_target=None, module="unit-test", execution_time=1,
  132. level="unit", erase_nvs=True, **kwargs):
  133. """
  134. decorator for testing idf unit tests (with default values for some keyword args).
  135. :param app: test application class
  136. :param target: target supported, string or list
  137. :param ci_target: target auto run in CI, if None than all target will be tested, None, string or list
  138. :param module: module, string
  139. :param execution_time: execution time in minutes, int
  140. :param level: test level, could be used to filter test cases, string
  141. :param erase_nvs: if need to erase_nvs in DUT.start_app()
  142. :param kwargs: other keyword args
  143. :return: test method
  144. """
  145. def test(func):
  146. return test_func_generator(func, app, target, ci_target, module, execution_time, level, erase_nvs, **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, **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, **kwargs)
  166. return test
  167. @ci_target_check
  168. def idf_component_unit_test(app=ComponentUTApp, target="ESP32", ci_target=None, module="misc", execution_time=1,
  169. level="integration", erase_nvs=True, config_name=None, **kwargs):
  170. """
  171. decorator for idf custom tests (with default values for some keyword args).
  172. :param app: test application class
  173. :param target: target supported, string or list
  174. :param ci_target: target auto run in CI, if None than all target will be tested, None, string or list
  175. :param module: module, string
  176. :param execution_time: execution time in minutes, int
  177. :param level: test level, could be used to filter test cases, string
  178. :param erase_nvs: if need to erase_nvs in DUT.start_app()
  179. :param config_name: if specified, name of the app configuration
  180. :param kwargs: other keyword args
  181. :return: test method
  182. """
  183. def test(func):
  184. return test_func_generator(func, app, target, ci_target, module, execution_time, level, erase_nvs, **kwargs)
  185. return test
  186. class ComponentUTResult:
  187. """
  188. Function Class, parse component unit test results
  189. """
  190. @staticmethod
  191. def parse_result(stdout):
  192. try:
  193. results = TestResults(stdout, TestFormat.UNITY_FIXTURE_VERBOSE)
  194. except (ValueError, TypeError) as e:
  195. raise ValueError('Error occurs when parsing the component unit test stdout to JUnit report: ' + str(e))
  196. group_name = results.tests()[0].group()
  197. with open(os.path.join(os.getenv('LOG_PATH', ''), '{}_XUNIT_RESULT.xml'.format(group_name)), 'w') as fw:
  198. junit_xml.to_xml_report_file(fw, [results.to_junit()])
  199. if results.num_failed():
  200. # raise exception if any case fails
  201. err_msg = 'Failed Cases:\n'
  202. for test_case in results.test_iter():
  203. if test_case.result() == 'FAIL':
  204. err_msg += '\t{}: {}'.format(test_case.name(), test_case.message())
  205. raise AssertionError(err_msg)
  206. def log_performance(item, value):
  207. """
  208. do print performance with pre-defined format to console
  209. :param item: performance item name
  210. :param value: performance value
  211. """
  212. performance_msg = "[Performance][{}]: {}".format(item, value)
  213. Utility.console_log(performance_msg, "orange")
  214. # update to junit test report
  215. current_junit_case = TinyFW.JunitReport.get_current_test_case()
  216. current_junit_case.stdout += performance_msg + "\r\n"
  217. def check_performance(item, value, target):
  218. """
  219. check if idf performance meet pass standard
  220. :param item: performance item name
  221. :param value: performance item value
  222. :param target: target chip
  223. :raise: AssertionError: if check fails
  224. """
  225. def _find_perf_item(path):
  226. with open(path, 'r') as f:
  227. data = f.read()
  228. match = re.search(r'#define\s+IDF_PERFORMANCE_(MIN|MAX)_{}\s+([\d.]+)'.format(item.upper()), data)
  229. return match.group(1), float(match.group(2))
  230. def _check_perf(op, standard_value):
  231. if op == 'MAX':
  232. ret = value <= standard_value
  233. else:
  234. ret = value >= standard_value
  235. if not ret:
  236. raise AssertionError("[Performance] {} value is {}, doesn't meet pass standard {}"
  237. .format(item, value, standard_value))
  238. path_prefix = os.path.join(IDFApp.get_sdk_path(), 'components', 'idf_test', 'include')
  239. performance_files = (os.path.join(path_prefix, target, 'idf_performance_target.h'),
  240. os.path.join(path_prefix, 'idf_performance.h'))
  241. for performance_file in performance_files:
  242. try:
  243. op, standard = _find_perf_item(performance_file)
  244. except (IOError, AttributeError):
  245. # performance file doesn't exist or match is not found in it
  246. continue
  247. _check_perf(op, standard)
  248. # if no exception was thrown then the performance is met and no need to continue
  249. break
  250. else:
  251. raise AssertionError("Failed to get performance standard for {}".format(item))
  252. MINIMUM_FREE_HEAP_SIZE_RE = re.compile(r'Minimum free heap size: (\d+) bytes')
  253. def print_heap_size(app_name, config_name, target, minimum_free_heap_size):
  254. """
  255. Do not change the print output in case you really need to.
  256. The result is parsed by ci-dashboard project
  257. """
  258. print('------ heap size info ------\n'
  259. '[app_name] {}\n'
  260. '[config_name] {}\n'
  261. '[target] {}\n'
  262. '[minimum_free_heap_size] {} Bytes\n'
  263. '------ heap size end ------'.format(app_name,
  264. '' if not config_name else config_name,
  265. target,
  266. minimum_free_heap_size))