IDFAssignTest.py 13 KB

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