CIAssignTest.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 os
  36. import re
  37. import json
  38. import yaml
  39. from Utility import (CaseConfig, SearchCases, GitlabCIJob, console_log)
  40. class Group(object):
  41. MAX_EXECUTION_TIME = 30
  42. MAX_CASE = 15
  43. SORT_KEYS = ["env_tag"]
  44. # Matching CI job rules could be different from the way we want to group test cases.
  45. # For example, when assign unit test cases, different test cases need to use different test functions.
  46. # We need to put them into different groups.
  47. # But these groups can be assigned to jobs with same tags, as they use the same test environment.
  48. CI_JOB_MATCH_KEYS = SORT_KEYS
  49. def __init__(self, case):
  50. self.execution_time = 0
  51. self.case_list = [case]
  52. self.filters = dict(zip(self.SORT_KEYS, [self._get_case_attr(case, x) for x in self.SORT_KEYS]))
  53. # we use ci_job_match_keys to match CI job tags. It's a set of required tags.
  54. self.ci_job_match_keys = set([self._get_case_attr(case, x) for x in self.CI_JOB_MATCH_KEYS])
  55. @staticmethod
  56. def _get_case_attr(case, attr):
  57. # we might use different type for case (dict or test_func)
  58. # this method will do get attribute form cases
  59. return case.case_info[attr]
  60. def accept_new_case(self):
  61. """
  62. check if allowed to add any case to this group
  63. :return: True or False
  64. """
  65. max_time = (sum([self._get_case_attr(x, "execution_time") for x in self.case_list])
  66. < self.MAX_EXECUTION_TIME)
  67. max_case = (len(self.case_list) < self.MAX_CASE)
  68. return max_time and max_case
  69. def add_case(self, case):
  70. """
  71. add case to current group
  72. :param case: test case
  73. :return: True if add succeed, else False
  74. """
  75. added = False
  76. if self.accept_new_case():
  77. for key in self.filters:
  78. if self._get_case_attr(case, key) != self.filters[key]:
  79. break
  80. else:
  81. self.case_list.append(case)
  82. added = True
  83. return added
  84. def output(self):
  85. """
  86. output data for job configs
  87. :return: {"Filter": case filter, "CaseConfig": list of case configs for cases in this group}
  88. """
  89. output_data = {
  90. "Filter": self.filters,
  91. "CaseConfig": [{"name": self._get_case_attr(x, "name")} for x in self.case_list],
  92. }
  93. return output_data
  94. class AssignTest(object):
  95. """
  96. Auto assign tests to CI jobs.
  97. :param test_case_path: path of test case file(s)
  98. :param ci_config_file: path of ``.gitlab-ci.yml``
  99. """
  100. # subclass need to rewrite CI test job pattern, to filter all test jobs
  101. CI_TEST_JOB_PATTERN = re.compile(r"^test_.+")
  102. # by default we only run function in CI, as other tests could take long time
  103. DEFAULT_FILTER = {
  104. "category": "function",
  105. "ignore": False,
  106. }
  107. def __init__(self, test_case_path, ci_config_file, case_group=Group):
  108. self.test_case_path = test_case_path
  109. self.test_cases = []
  110. self.jobs = self._parse_gitlab_ci_config(ci_config_file)
  111. self.case_group = case_group
  112. @staticmethod
  113. def _handle_parallel_attribute(job_name, job):
  114. jobs_out = []
  115. try:
  116. for i in range(job["parallel"]):
  117. jobs_out.append(GitlabCIJob.Job(job, job_name + "_{}".format(i + 1)))
  118. except KeyError:
  119. # Gitlab don't allow to set parallel to 1.
  120. # to make test job name same ($CI_JOB_NAME_$CI_NODE_INDEX),
  121. # we append "_" to jobs don't have parallel attribute
  122. jobs_out.append(GitlabCIJob.Job(job, job_name + "_"))
  123. return jobs_out
  124. def _parse_gitlab_ci_config(self, ci_config_file):
  125. with open(ci_config_file, "r") as f:
  126. ci_config = yaml.load(f, Loader=yaml.Loader)
  127. job_list = list()
  128. for job_name in ci_config:
  129. if self.CI_TEST_JOB_PATTERN.search(job_name) is not None:
  130. job_list.extend(self._handle_parallel_attribute(job_name, ci_config[job_name]))
  131. job_list.sort(key=lambda x: x["name"])
  132. return job_list
  133. def _search_cases(self, test_case_path, case_filter=None):
  134. """
  135. :param test_case_path: path contains test case folder
  136. :param case_filter: filter for test cases. the filter to use is default filter updated with case_filter param.
  137. :return: filtered test case list
  138. """
  139. _case_filter = self.DEFAULT_FILTER.copy()
  140. if case_filter:
  141. _case_filter.update(case_filter)
  142. test_methods = SearchCases.Search.search_test_cases(test_case_path)
  143. return CaseConfig.filter_test_cases(test_methods, _case_filter)
  144. def _group_cases(self):
  145. """
  146. separate all cases into groups according group rules. each group will be executed by one CI job.
  147. :return: test case groups.
  148. """
  149. groups = []
  150. for case in self.test_cases:
  151. for group in groups:
  152. # add to current group
  153. if group.add_case(case):
  154. break
  155. else:
  156. # create new group
  157. groups.append(self.case_group(case))
  158. return groups
  159. @staticmethod
  160. def _apply_bot_filter():
  161. """
  162. we support customize CI test with bot.
  163. here we process from and return the filter which ``_search_cases`` accepts.
  164. :return: filter for search test cases
  165. """
  166. bot_filter = os.getenv("BOT_CASE_FILTER")
  167. if bot_filter:
  168. bot_filter = json.loads(bot_filter)
  169. else:
  170. bot_filter = dict()
  171. return bot_filter
  172. def _apply_bot_test_count(self):
  173. """
  174. Bot could also pass test count.
  175. If filtered cases need to be tested for several times, then we do duplicate them here.
  176. """
  177. test_count = os.getenv("BOT_TEST_COUNT")
  178. if test_count:
  179. test_count = int(test_count)
  180. self.test_cases *= test_count
  181. def assign_cases(self):
  182. """
  183. separate test cases to groups and assign test cases to CI jobs.
  184. :raise AssertError: if failed to assign any case to CI job.
  185. :return: None
  186. """
  187. failed_to_assign = []
  188. case_filter = self._apply_bot_filter()
  189. self.test_cases = self._search_cases(self.test_case_path, case_filter)
  190. self._apply_bot_test_count()
  191. test_groups = self._group_cases()
  192. for group in test_groups:
  193. for job in self.jobs:
  194. if job.match_group(group):
  195. job.assign_group(group)
  196. break
  197. else:
  198. failed_to_assign.append(group)
  199. if failed_to_assign:
  200. console_log("Too many test cases vs jobs to run. Please add the following jobs to .gitlab-ci.yml with specific tags:", "R")
  201. for group in failed_to_assign:
  202. console_log("* Add job with: " + ",".join(group.ci_job_match_keys), "R")
  203. raise RuntimeError("Failed to assign test case to CI jobs")
  204. def output_configs(self, output_path):
  205. """
  206. :param output_path: path to output config files for each CI job
  207. :return: None
  208. """
  209. if not os.path.exists(output_path):
  210. os.makedirs(output_path)
  211. for job in self.jobs:
  212. job.output_config(output_path)