__init__.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. 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.warning('IDF_TARGET not in {}. IDF_TARGET set to esp32'.format(os.path.abspath(expected_json_path)))
  62. else:
  63. logging.info('IDF_TARGET: {}'.format(idf_target))
  64. else:
  65. logging.warning('{} 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. raise ValueError('IDF_TARGET set to {}, not in decorator target value'.format(idf_target))
  69. else:
  70. if idf_target != decorator_target:
  71. raise ValueError('IDF_TARGET set to {}, not equal to decorator target value'.format(idf_target))
  72. return idf_target
  73. def get_dut_class(target, erase_nvs=None):
  74. if target not in TARGET_DUT_CLS_DICT:
  75. raise Exception('target can only be {%s} (case insensitive)' % ', '.join(TARGET_DUT_CLS_DICT.keys()))
  76. dut = TARGET_DUT_CLS_DICT[target.upper()]
  77. if erase_nvs:
  78. dut.ERASE_NVS = 'erase_nvs'
  79. return dut
  80. def ci_target_check(func):
  81. @functools.wraps(func)
  82. def wrapper(**kwargs):
  83. target = upper_list_or_str(kwargs.get('target', []))
  84. ci_target = upper_list_or_str(kwargs.get('ci_target', []))
  85. if not set(ci_target).issubset(set(target)):
  86. raise ValueError('ci_target must be a subset of target')
  87. return func(**kwargs)
  88. return wrapper
  89. @ci_target_check
  90. def idf_example_test(app=Example, target="ESP32", ci_target=None, module="examples", execution_time=1,
  91. level="example", erase_nvs=True, config_name=None, **kwargs):
  92. """
  93. decorator for testing idf examples (with default values for some keyword args).
  94. :param app: test application class
  95. :param target: target supported, string or list
  96. :param ci_target: target auto run in CI, if None than all target will be tested, None, string or list
  97. :param module: module, string
  98. :param execution_time: execution time in minutes, int
  99. :param level: test level, could be used to filter test cases, string
  100. :param erase_nvs: if need to erase_nvs in DUT.start_app()
  101. :param config_name: if specified, name of the app configuration
  102. :param kwargs: other keyword args
  103. :return: test method
  104. """
  105. def test(func):
  106. test_target = local_test_check(target)
  107. dut = get_dut_class(test_target, erase_nvs)
  108. original_method = TinyFW.test_method(
  109. app=app, dut=dut, target=upper_list_or_str(target), ci_target=upper_list_or_str(ci_target),
  110. module=module, execution_time=execution_time, level=level, erase_nvs=erase_nvs,
  111. dut_dict=TARGET_DUT_CLS_DICT, **kwargs
  112. )
  113. test_func = original_method(func)
  114. test_func.case_info["ID"] = format_case_id(target, test_func.case_info["name"])
  115. return test_func
  116. return test
  117. @ci_target_check
  118. def idf_unit_test(app=UT, target="ESP32", ci_target=None, module="unit-test", execution_time=1,
  119. level="unit", erase_nvs=True, **kwargs):
  120. """
  121. decorator for testing idf unit tests (with default values for some keyword args).
  122. :param app: test application class
  123. :param target: target supported, string or list
  124. :param ci_target: target auto run in CI, if None than all target will be tested, None, string or list
  125. :param module: module, string
  126. :param execution_time: execution time in minutes, int
  127. :param level: test level, could be used to filter test cases, string
  128. :param erase_nvs: if need to erase_nvs in DUT.start_app()
  129. :param kwargs: other keyword args
  130. :return: test method
  131. """
  132. def test(func):
  133. test_target = local_test_check(target)
  134. dut = get_dut_class(test_target, erase_nvs)
  135. original_method = TinyFW.test_method(
  136. app=app, dut=dut, target=upper_list_or_str(target), ci_target=upper_list_or_str(ci_target),
  137. module=module, execution_time=execution_time, level=level, erase_nvs=erase_nvs,
  138. dut_dict=TARGET_DUT_CLS_DICT, **kwargs
  139. )
  140. test_func = original_method(func)
  141. test_func.case_info["ID"] = format_case_id(target, test_func.case_info["name"])
  142. return test_func
  143. return test
  144. @ci_target_check
  145. def idf_custom_test(app=TestApp, target="ESP32", ci_target=None, module="misc", execution_time=1,
  146. level="integration", erase_nvs=True, config_name=None, group="test-apps", **kwargs):
  147. """
  148. decorator for idf custom tests (with default values for some keyword args).
  149. :param app: test application class
  150. :param target: target supported, string or list
  151. :param ci_target: target auto run in CI, if None than all target will be tested, None, string or list
  152. :param module: module, string
  153. :param execution_time: execution time in minutes, int
  154. :param level: test level, could be used to filter test cases, string
  155. :param erase_nvs: if need to erase_nvs in DUT.start_app()
  156. :param config_name: if specified, name of the app configuration
  157. :param group: identifier to group custom tests (unused for now, defaults to "test-apps")
  158. :param kwargs: other keyword args
  159. :return: test method
  160. """
  161. def test(func):
  162. test_target = local_test_check(target)
  163. dut = get_dut_class(test_target, erase_nvs)
  164. if 'dut' in kwargs: # panic_test() will inject dut, resolve conflicts here
  165. dut = kwargs['dut']
  166. del kwargs['dut']
  167. original_method = TinyFW.test_method(
  168. app=app, dut=dut, target=upper_list_or_str(target), ci_target=upper_list_or_str(ci_target),
  169. module=module, execution_time=execution_time, level=level, erase_nvs=erase_nvs,
  170. dut_dict=TARGET_DUT_CLS_DICT, **kwargs
  171. )
  172. test_func = original_method(func)
  173. test_func.case_info["ID"] = format_case_id(target, test_func.case_info["name"])
  174. return test_func
  175. return test
  176. def log_performance(item, value):
  177. """
  178. do print performance with pre-defined format to console
  179. :param item: performance item name
  180. :param value: performance value
  181. """
  182. performance_msg = "[Performance][{}]: {}".format(item, value)
  183. Utility.console_log(performance_msg, "orange")
  184. # update to junit test report
  185. current_junit_case = TinyFW.JunitReport.get_current_test_case()
  186. current_junit_case.stdout += performance_msg + "\r\n"
  187. def check_performance(item, value, target):
  188. """
  189. check if idf performance meet pass standard
  190. :param item: performance item name
  191. :param value: performance item value
  192. :param target: target chip
  193. :raise: AssertionError: if check fails
  194. """
  195. def _find_perf_item(path):
  196. with open(path, 'r') as f:
  197. data = f.read()
  198. match = re.search(r'#define\s+IDF_PERFORMANCE_(MIN|MAX)_{}\s+([\d.]+)'.format(item.upper()), data)
  199. return match.group(1), float(match.group(2))
  200. def _check_perf(op, standard_value):
  201. if op == 'MAX':
  202. ret = value <= standard_value
  203. else:
  204. ret = value >= standard_value
  205. if not ret:
  206. raise AssertionError("[Performance] {} value is {}, doesn't meet pass standard {}"
  207. .format(item, value, standard_value))
  208. path_prefix = os.path.join(IDFApp.get_sdk_path(), 'components', 'idf_test', 'include')
  209. performance_files = (os.path.join(path_prefix, target, 'idf_performance_target.h'),
  210. os.path.join(path_prefix, 'idf_performance.h'))
  211. for performance_file in performance_files:
  212. try:
  213. op, value = _find_perf_item(performance_file)
  214. except (IOError, AttributeError):
  215. # performance file doesn't exist or match is not found in it
  216. continue
  217. _check_perf(op, value)
  218. # if no exception was thrown then the performance is met and no need to continue
  219. break