CIAssignTest.py 9.1 KB

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