__init__.py 11 KB

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