CIAssignTest.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. """
  15. Common logic to assign test cases to CI jobs.
  16. Some background knowledge about Gitlab CI and use flow in esp-idf:
  17. * Gitlab CI jobs are static in ``.gitlab-ci.yml``. We can't dynamically create test jobs
  18. * For test job running on DUT, we use ``tags`` to select runners with different test environment
  19. * We have ``assign_test`` stage, will collect cases, and then assign them to correct test jobs
  20. * ``assign_test`` will fail if failed to assign any cases
  21. * with ``assign_test``, we can:
  22. * dynamically filter test case we want to test
  23. * alert user if they forget to add CI jobs and guide how to add test jobs
  24. * the last step of ``assign_test`` is to output config files, then test jobs will run these cases
  25. The Basic logic to assign test cases is as follow:
  26. 1. do search all the cases
  27. 2. do filter case (if filter is specified by @bot)
  28. 3. put cases to different groups according to rule of ``Group``
  29. * try to put them in existed groups
  30. * if failed then create a new group and add this case
  31. 4. parse and filter the test jobs from CI config file
  32. 5. try to assign all groups to jobs according to tags
  33. 6. output config files for jobs
  34. """
  35. import json
  36. import os
  37. import re
  38. import yaml
  39. try:
  40. from yaml import CLoader as Loader
  41. except ImportError:
  42. from yaml import Loader as Loader
  43. from . import CaseConfig, GitlabCIJob, SearchCases, console_log
  44. class Group(object):
  45. MAX_EXECUTION_TIME = 30
  46. MAX_CASE = 15
  47. SORT_KEYS = ['env_tag']
  48. # Matching CI job rules could be different from the way we want to group test cases.
  49. # For example, when assign unit test cases, different test cases need to use different test functions.
  50. # We need to put them into different groups.
  51. # But these groups can be assigned to jobs with same tags, as they use the same test environment.
  52. CI_JOB_MATCH_KEYS = SORT_KEYS
  53. def __init__(self, case):
  54. self.execution_time = 0
  55. self.case_list = [case]
  56. self.filters = dict(zip(self.SORT_KEYS, [self._get_case_attr(case, x) for x in self.SORT_KEYS]))
  57. # we use ci_job_match_keys to match CI job tags. It's a set of required tags.
  58. self.ci_job_match_keys = self._get_match_keys(case)
  59. @staticmethod
  60. def _get_case_attr(case, attr):
  61. # we might use different type for case (dict or test_func)
  62. # this method will do get attribute form cases
  63. return case.case_info[attr]
  64. def _get_match_keys(self, case):
  65. keys = []
  66. for attr in self.CI_JOB_MATCH_KEYS:
  67. val = self._get_case_attr(case, attr)
  68. if isinstance(val, list):
  69. keys.extend(val)
  70. else:
  71. keys.append(val)
  72. return set(keys)
  73. def accept_new_case(self):
  74. """
  75. check if allowed to add any case to this group
  76. :return: True or False
  77. """
  78. max_time = (sum([self._get_case_attr(x, 'execution_time') for x in self.case_list])
  79. < self.MAX_EXECUTION_TIME)
  80. max_case = (len(self.case_list) < self.MAX_CASE)
  81. return max_time and max_case
  82. def add_case(self, case):
  83. """
  84. add case to current group
  85. :param case: test case
  86. :return: True if add succeed, else False
  87. """
  88. added = False
  89. if self.accept_new_case():
  90. for key in self.filters:
  91. if self._get_case_attr(case, key) != self.filters[key]:
  92. break
  93. else:
  94. self.case_list.append(case)
  95. added = True
  96. return added
  97. def add_extra_case(self, case):
  98. """
  99. By default (``add_case`` method), cases will only be added when have equal values of all filters with group.
  100. But in some cases, we also want to add cases which are not best fit.
  101. For example, one group has can run cases require (A, B). It can also accept cases require (A, ) and (B, ).
  102. When assign failed by best fit, we will use this method to try if we can assign all failed cases.
  103. If subclass want to retry, they need to overwrite this method.
  104. Logic can be applied to handle such scenario could be different for different cases.
  105. :return: True if accepted else False
  106. """
  107. pass
  108. def output(self):
  109. """
  110. output data for job configs
  111. :return: {"Filter": case filter, "CaseConfig": list of case configs for cases in this group}
  112. """
  113. output_data = {
  114. 'Filter': self.filters,
  115. 'CaseConfig': [{'name': self._get_case_attr(x, 'name')} for x in self.case_list],
  116. }
  117. return output_data
  118. class AssignTest(object):
  119. """
  120. Auto assign tests to CI jobs.
  121. :param test_case_paths: path of test case file(s)
  122. :param ci_config_file: path of ``.gitlab-ci.yml``
  123. """
  124. # subclass need to rewrite CI test job pattern, to filter all test jobs
  125. CI_TEST_JOB_PATTERN = re.compile(r'^test_.+')
  126. # by default we only run function in CI, as other tests could take long time
  127. DEFAULT_FILTER = {
  128. 'category': 'function',
  129. 'ignore': False,
  130. 'supported_in_ci': True,
  131. }
  132. def __init__(self, test_case_paths, ci_config_file, case_group=Group):
  133. self.test_case_paths = test_case_paths
  134. self.test_case_file_pattern = None
  135. self.test_cases = []
  136. self.jobs = self._parse_gitlab_ci_config(ci_config_file)
  137. self.case_group = case_group
  138. @staticmethod
  139. def _handle_parallel_attribute(job_name, job):
  140. jobs_out = []
  141. try:
  142. for i in range(job['parallel']):
  143. jobs_out.append(GitlabCIJob.Job(job, job_name + '_{}'.format(i + 1)))
  144. except KeyError:
  145. # Gitlab don't allow to set parallel to 1.
  146. # to make test job name same ($CI_JOB_NAME_$CI_NODE_INDEX),
  147. # we append "_" to jobs don't have parallel attribute
  148. jobs_out.append(GitlabCIJob.Job(job, job_name + '_'))
  149. return jobs_out
  150. def _parse_gitlab_ci_config(self, ci_config_file):
  151. with open(ci_config_file, 'r') as f:
  152. ci_config = yaml.load(f, Loader=Loader)
  153. job_list = list()
  154. for job_name in ci_config:
  155. if self.CI_TEST_JOB_PATTERN.search(job_name) is not None:
  156. job_list.extend(self._handle_parallel_attribute(job_name, ci_config[job_name]))
  157. job_list.sort(key=lambda x: x['name'])
  158. return job_list
  159. def search_cases(self, case_filter=None):
  160. """
  161. :param case_filter: filter for test cases. the filter to use is default filter updated with case_filter param.
  162. :return: filtered test case list
  163. """
  164. _case_filter = self.DEFAULT_FILTER.copy()
  165. if case_filter:
  166. _case_filter.update(case_filter)
  167. test_methods = SearchCases.Search.search_test_cases(self.test_case_paths, self.test_case_file_pattern)
  168. return CaseConfig.filter_test_cases(test_methods, _case_filter)
  169. def _group_cases(self):
  170. """
  171. separate all cases into groups according group rules. each group will be executed by one CI job.
  172. :return: test case groups.
  173. """
  174. groups = []
  175. for case in self.test_cases:
  176. for group in groups:
  177. # add to current group
  178. if group.add_case(case):
  179. break
  180. else:
  181. # create new group
  182. groups.append(self.case_group(case))
  183. return groups
  184. def _assign_failed_cases(self, assigned_groups, failed_groups):
  185. """ try to assign failed cases to already assigned test groups """
  186. still_failed_groups = []
  187. failed_cases = []
  188. for group in failed_groups:
  189. failed_cases.extend(group.case_list)
  190. for case in failed_cases:
  191. # first try to assign to already assigned groups
  192. for group in assigned_groups:
  193. if group.add_extra_case(case):
  194. break
  195. else:
  196. # if failed, group the failed cases
  197. for group in still_failed_groups:
  198. if group.add_case(case):
  199. break
  200. else:
  201. still_failed_groups.append(self.case_group(case))
  202. return still_failed_groups
  203. @staticmethod
  204. def _apply_bot_filter():
  205. """
  206. we support customize CI test with bot.
  207. here we process from and return the filter which ``_search_cases`` accepts.
  208. :return: filter for search test cases
  209. """
  210. res = dict()
  211. for bot_filter in [os.getenv('BOT_CASE_FILTER'), os.getenv('BOT_TARGET_FILTER')]:
  212. if bot_filter:
  213. res.update(json.loads(bot_filter))
  214. return res
  215. def _apply_bot_test_count(self):
  216. """
  217. Bot could also pass test count.
  218. If filtered cases need to be tested for several times, then we do duplicate them here.
  219. """
  220. test_count = os.getenv('BOT_TEST_COUNT')
  221. if test_count:
  222. test_count = int(test_count)
  223. self.test_cases *= test_count
  224. @staticmethod
  225. def _count_groups_by_keys(test_groups):
  226. """
  227. Count the number of test groups by job match keys.
  228. It's an important information to update CI config file.
  229. """
  230. group_count = dict()
  231. for group in test_groups:
  232. key = ','.join(group.ci_job_match_keys)
  233. try:
  234. group_count[key] += 1
  235. except KeyError:
  236. group_count[key] = 1
  237. return group_count
  238. def assign_cases(self):
  239. """
  240. separate test cases to groups and assign test cases to CI jobs.
  241. :raise AssertError: if failed to assign any case to CI job.
  242. :return: None
  243. """
  244. failed_to_assign = []
  245. assigned_groups = []
  246. case_filter = self._apply_bot_filter()
  247. self.test_cases = self.search_cases(case_filter)
  248. self._apply_bot_test_count()
  249. test_groups = self._group_cases()
  250. for group in test_groups:
  251. for job in self.jobs:
  252. if job.match_group(group):
  253. job.assign_group(group)
  254. assigned_groups.append(group)
  255. break
  256. else:
  257. failed_to_assign.append(group)
  258. if failed_to_assign:
  259. failed_to_assign = self._assign_failed_cases(assigned_groups, failed_to_assign)
  260. # print debug info
  261. # total requirement of current pipeline
  262. required_group_count = self._count_groups_by_keys(test_groups)
  263. console_log('Required job count by tags:')
  264. for tags in required_group_count:
  265. console_log('\t{}: {}'.format(tags, required_group_count[tags]))
  266. # number of unused jobs
  267. not_used_jobs = [job for job in self.jobs if 'case group' not in job]
  268. if not_used_jobs:
  269. console_log('{} jobs not used. Please check if you define too much jobs'.format(len(not_used_jobs)), 'O')
  270. for job in not_used_jobs:
  271. console_log('\t{}'.format(job['name']), 'O')
  272. # failures
  273. if failed_to_assign:
  274. console_log('Too many test cases vs jobs to run. '
  275. 'Please increase parallel count in tools/ci/config/target-test.yml '
  276. 'for jobs with specific tags:', 'R')
  277. failed_group_count = self._count_groups_by_keys(failed_to_assign)
  278. for tags in failed_group_count:
  279. console_log('\t{}: {}'.format(tags, failed_group_count[tags]), 'R')
  280. raise RuntimeError('Failed to assign test case to CI jobs')
  281. def output_configs(self, output_path):
  282. """
  283. :param output_path: path to output config files for each CI job
  284. :return: None
  285. """
  286. if not os.path.exists(output_path):
  287. os.makedirs(output_path)
  288. for job in self.jobs:
  289. job.output_config(output_path)