IDFAssignTest.py 14 KB

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