IDFAssignTest.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. """
  2. Command line tool to assign tests to CI test jobs.
  3. """
  4. import argparse
  5. import errno
  6. import json
  7. import os
  8. import re
  9. import yaml
  10. try:
  11. from yaml import CLoader as Loader
  12. except ImportError:
  13. from yaml import Loader as Loader
  14. import gitlab_api
  15. from tiny_test_fw.Utility import CIAssignTest
  16. try:
  17. from idf_py_actions.constants import SUPPORTED_TARGETS, PREVIEW_TARGETS
  18. except ImportError:
  19. SUPPORTED_TARGETS = []
  20. PREVIEW_TARGETS = []
  21. IDF_PATH_FROM_ENV = os.getenv('IDF_PATH')
  22. class IDFCaseGroup(CIAssignTest.Group):
  23. LOCAL_BUILD_DIR = None
  24. BUILD_JOB_NAMES = None
  25. @classmethod
  26. def get_artifact_index_file(cls):
  27. assert cls.LOCAL_BUILD_DIR
  28. if IDF_PATH_FROM_ENV:
  29. artifact_index_file = os.path.join(IDF_PATH_FROM_ENV, cls.LOCAL_BUILD_DIR, 'artifact_index.json')
  30. else:
  31. artifact_index_file = 'artifact_index.json'
  32. return artifact_index_file
  33. class IDFAssignTest(CIAssignTest.AssignTest):
  34. def __init__(self, test_case_path, ci_config_file, case_group=IDFCaseGroup):
  35. super(IDFAssignTest, self).__init__(test_case_path, ci_config_file, case_group)
  36. def format_build_log_path(self, parallel_num):
  37. return '{}/list_job_{}.json'.format(self.case_group.LOCAL_BUILD_DIR, parallel_num)
  38. def create_artifact_index_file(self, project_id=None, pipeline_id=None):
  39. if project_id is None:
  40. project_id = os.getenv('CI_PROJECT_ID')
  41. if pipeline_id is None:
  42. pipeline_id = os.getenv('CI_PIPELINE_ID')
  43. gitlab_inst = gitlab_api.Gitlab(project_id)
  44. artifact_index_list = []
  45. for build_job_name in self.case_group.BUILD_JOB_NAMES:
  46. job_info_list = gitlab_inst.find_job_id(build_job_name, pipeline_id=pipeline_id)
  47. for job_info in job_info_list:
  48. parallel_num = job_info['parallel_num'] or 1 # Could be None if "parallel_num" not defined for the job
  49. raw_data = gitlab_inst.download_artifact(job_info['id'],
  50. [self.format_build_log_path(parallel_num)])[0]
  51. build_info_list = [json.loads(line) for line in raw_data.decode().splitlines()]
  52. for build_info in build_info_list:
  53. build_info['ci_job_id'] = job_info['id']
  54. artifact_index_list.append(build_info)
  55. artifact_index_file = self.case_group.get_artifact_index_file()
  56. try:
  57. os.makedirs(os.path.dirname(artifact_index_file))
  58. except OSError as e:
  59. if e.errno != errno.EEXIST:
  60. raise e
  61. with open(artifact_index_file, 'w') as f:
  62. json.dump(artifact_index_list, f)
  63. class ExampleGroup(IDFCaseGroup):
  64. SORT_KEYS = CI_JOB_MATCH_KEYS = ['env_tag', 'target']
  65. LOCAL_BUILD_DIR = 'build_examples'
  66. BUILD_JOB_NAMES = ['build_examples_cmake_{}'.format(target) for target in SUPPORTED_TARGETS]
  67. class TestAppsGroup(ExampleGroup):
  68. LOCAL_BUILD_DIR = 'build_test_apps'
  69. BUILD_JOB_NAMES = ['build_test_apps_{}'.format(target) for target in SUPPORTED_TARGETS]
  70. class ComponentUTGroup(TestAppsGroup):
  71. LOCAL_BUILD_DIR = 'build_component_ut'
  72. BUILD_JOB_NAMES = ['build_component_ut_{}'.format(target) for target in SUPPORTED_TARGETS]
  73. class UnitTestGroup(IDFCaseGroup):
  74. SORT_KEYS = ['test environment', 'tags', 'chip_target']
  75. CI_JOB_MATCH_KEYS = ['test environment']
  76. LOCAL_BUILD_DIR = 'tools/unit-test-app/builds'
  77. BUILD_JOB_NAMES = ['build_esp_idf_tests_cmake_{}'.format(target) for target in SUPPORTED_TARGETS]
  78. MAX_CASE = 50
  79. ATTR_CONVERT_TABLE = {
  80. 'execution_time': 'execution time'
  81. }
  82. DUT_CLS_NAME = {
  83. 'esp32': 'ESP32DUT',
  84. 'esp32s2': 'ESP32S2DUT',
  85. 'esp8266': 'ESP8266DUT',
  86. }
  87. def __init__(self, case):
  88. super(UnitTestGroup, self).__init__(case)
  89. for tag in self._get_case_attr(case, 'tags'):
  90. self.ci_job_match_keys.add(tag)
  91. @staticmethod
  92. def _get_case_attr(case, attr):
  93. if attr in UnitTestGroup.ATTR_CONVERT_TABLE:
  94. attr = UnitTestGroup.ATTR_CONVERT_TABLE[attr]
  95. return case[attr]
  96. def add_extra_case(self, case):
  97. """ If current group contains all tags required by case, then add succeed """
  98. added = False
  99. if self.accept_new_case():
  100. for key in self.filters:
  101. if self._get_case_attr(case, key) != self.filters[key]:
  102. if key == 'tags':
  103. if set(self._get_case_attr(case, key)).issubset(set(self.filters[key])):
  104. continue
  105. break
  106. else:
  107. self.case_list.append(case)
  108. added = True
  109. return added
  110. def _create_extra_data(self, test_cases, test_function):
  111. """
  112. For unit test case, we need to copy some attributes of test cases into config file.
  113. So unit test function knows how to run the case.
  114. """
  115. case_data = []
  116. for case in test_cases:
  117. one_case_data = {
  118. 'config': self._get_case_attr(case, 'config'),
  119. 'name': self._get_case_attr(case, 'summary'),
  120. 'reset': self._get_case_attr(case, 'reset'),
  121. 'timeout': self._get_case_attr(case, 'timeout'),
  122. }
  123. if test_function in ['run_multiple_devices_cases', 'run_multiple_stage_cases']:
  124. try:
  125. one_case_data['child case num'] = self._get_case_attr(case, 'child case num')
  126. except KeyError as e:
  127. print('multiple devices/stages cases must contains at least two test functions')
  128. print('case name: {}'.format(one_case_data['name']))
  129. raise e
  130. case_data.append(one_case_data)
  131. return case_data
  132. def _divide_case_by_test_function(self):
  133. """
  134. divide cases of current test group by test function they need to use
  135. :return: dict of list of cases for each test functions
  136. """
  137. case_by_test_function = {
  138. 'run_multiple_devices_cases': [],
  139. 'run_multiple_stage_cases': [],
  140. 'run_unit_test_cases': [],
  141. }
  142. for case in self.case_list:
  143. if case['multi_device'] == 'Yes':
  144. case_by_test_function['run_multiple_devices_cases'].append(case)
  145. elif case['multi_stage'] == 'Yes':
  146. case_by_test_function['run_multiple_stage_cases'].append(case)
  147. else:
  148. case_by_test_function['run_unit_test_cases'].append(case)
  149. return case_by_test_function
  150. def output(self):
  151. """
  152. output data for job configs
  153. :return: {"Filter": case filter, "CaseConfig": list of case configs for cases in this group}
  154. """
  155. target = self._get_case_attr(self.case_list[0], 'chip_target')
  156. if target:
  157. overwrite = {
  158. 'dut': {
  159. 'package': 'ttfw_idf',
  160. 'class': self.DUT_CLS_NAME[target],
  161. }
  162. }
  163. else:
  164. overwrite = dict()
  165. case_by_test_function = self._divide_case_by_test_function()
  166. output_data = {
  167. # we don't need filter for test function, as UT uses a few test functions for all cases
  168. 'CaseConfig': [
  169. {
  170. 'name': test_function,
  171. 'extra_data': self._create_extra_data(test_cases, test_function),
  172. 'overwrite': overwrite,
  173. } for test_function, test_cases in case_by_test_function.items() if test_cases
  174. ],
  175. }
  176. return output_data
  177. class ExampleAssignTest(IDFAssignTest):
  178. CI_TEST_JOB_PATTERN = re.compile(r'^example_test_.+')
  179. def __init__(self, test_case_path, ci_config_file):
  180. super(ExampleAssignTest, self).__init__(test_case_path, ci_config_file, case_group=ExampleGroup)
  181. class TestAppsAssignTest(IDFAssignTest):
  182. CI_TEST_JOB_PATTERN = re.compile(r'^test_app_test_.+')
  183. def __init__(self, test_case_path, ci_config_file):
  184. super(TestAppsAssignTest, self).__init__(test_case_path, ci_config_file, case_group=TestAppsGroup)
  185. class ComponentUTAssignTest(IDFAssignTest):
  186. CI_TEST_JOB_PATTERN = re.compile(r'^component_ut_test_.+')
  187. def __init__(self, test_case_path, ci_config_file):
  188. super(ComponentUTAssignTest, self).__init__(test_case_path, ci_config_file, case_group=ComponentUTGroup)
  189. class UnitTestAssignTest(IDFAssignTest):
  190. CI_TEST_JOB_PATTERN = re.compile(r'^UT_.+')
  191. def __init__(self, test_case_path, ci_config_file):
  192. super(UnitTestAssignTest, self).__init__(test_case_path, ci_config_file, case_group=UnitTestGroup)
  193. def search_cases(self, case_filter=None):
  194. """
  195. For unit test case, we don't search for test functions.
  196. The unit test cases is stored in a yaml file which is created in job build-idf-test.
  197. """
  198. def find_by_suffix(suffix, path):
  199. res = []
  200. for root, _, files in os.walk(path):
  201. for file in files:
  202. if file.endswith(suffix):
  203. res.append(os.path.join(root, file))
  204. return res
  205. def get_test_cases_from_yml(yml_file):
  206. try:
  207. with open(yml_file) as fr:
  208. raw_data = yaml.load(fr, Loader=Loader)
  209. test_cases = raw_data['test cases']
  210. except (IOError, KeyError):
  211. return []
  212. else:
  213. return test_cases
  214. test_cases = []
  215. for path in self.test_case_paths:
  216. if os.path.isdir(path):
  217. for yml_file in find_by_suffix('.yml', path):
  218. test_cases.extend(get_test_cases_from_yml(yml_file))
  219. elif os.path.isfile(path) and path.endswith('.yml'):
  220. test_cases.extend(get_test_cases_from_yml(path))
  221. else:
  222. print('Test case path is invalid. Should only happen when use @bot to skip unit test.')
  223. # filter keys are lower case. Do map lower case keys with original keys.
  224. try:
  225. key_mapping = {x.lower(): x for x in test_cases[0].keys()}
  226. except IndexError:
  227. key_mapping = dict()
  228. if case_filter:
  229. for key in case_filter:
  230. filtered_cases = []
  231. for case in test_cases:
  232. try:
  233. mapped_key = key_mapping[key]
  234. # bot converts string to lower case
  235. if isinstance(case[mapped_key], str):
  236. _value = case[mapped_key].lower()
  237. else:
  238. _value = case[mapped_key]
  239. if _value in case_filter[key]:
  240. filtered_cases.append(case)
  241. except KeyError:
  242. # case don't have this key, regard as filter success
  243. filtered_cases.append(case)
  244. test_cases = filtered_cases
  245. # sort cases with configs and test functions
  246. # in later stage cases with similar attributes are more likely to be assigned to the same job
  247. # it will reduce the count of flash DUT operations
  248. test_cases.sort(key=lambda x: x['config'] + x['multi_stage'] + x['multi_device'])
  249. return test_cases
  250. if __name__ == '__main__':
  251. parser = argparse.ArgumentParser()
  252. parser.add_argument('case_group', choices=['example_test', 'custom_test', 'unit_test', 'component_ut'])
  253. parser.add_argument('test_case_paths', nargs='+', help='test case folder or file')
  254. parser.add_argument('-c', '--config', help='gitlab ci config file')
  255. parser.add_argument('-o', '--output', help='output path of config files')
  256. parser.add_argument('--pipeline_id', '-p', type=int, default=None, help='pipeline_id')
  257. parser.add_argument('--test-case-file-pattern', help='file name pattern used to find Python test case files')
  258. args = parser.parse_args()
  259. SUPPORTED_TARGETS.extend(PREVIEW_TARGETS)
  260. test_case_paths = [os.path.join(IDF_PATH_FROM_ENV, path) if not os.path.isabs(path) else path for path in args.test_case_paths]
  261. args_list = [test_case_paths, args.config]
  262. if args.case_group == 'example_test':
  263. assigner = ExampleAssignTest(*args_list)
  264. elif args.case_group == 'custom_test':
  265. assigner = TestAppsAssignTest(*args_list)
  266. elif args.case_group == 'unit_test':
  267. assigner = UnitTestAssignTest(*args_list)
  268. elif args.case_group == 'component_ut':
  269. assigner = ComponentUTAssignTest(*args_list)
  270. else:
  271. raise SystemExit(1) # which is impossible
  272. if args.test_case_file_pattern:
  273. assigner.CI_TEST_JOB_PATTERN = re.compile(r'{}'.format(args.test_case_file_pattern))
  274. assigner.assign_cases()
  275. assigner.output_configs(args.output)
  276. assigner.create_artifact_index_file()