CIAssignTest.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. }
  106. def __init__(self, test_case_path, ci_config_file, case_group=Group):
  107. self.test_case_path = test_case_path
  108. self.test_cases = []
  109. self.jobs = self._parse_gitlab_ci_config(ci_config_file)
  110. self.case_group = case_group
  111. def _parse_gitlab_ci_config(self, ci_config_file):
  112. with open(ci_config_file, "r") as f:
  113. ci_config = yaml.load(f)
  114. job_list = list()
  115. for job_name in ci_config:
  116. if self.CI_TEST_JOB_PATTERN.search(job_name) is not None:
  117. job_list.append(GitlabCIJob.Job(ci_config[job_name], job_name))
  118. return job_list
  119. def _search_cases(self, test_case_path, case_filter=None):
  120. """
  121. :param test_case_path: path contains test case folder
  122. :param case_filter: filter for test cases. the filter to use is default filter updated with case_filter param.
  123. :return: filtered test case list
  124. """
  125. _case_filter = self.DEFAULT_FILTER.copy()
  126. if case_filter:
  127. _case_filter.update(case_filter)
  128. test_methods = SearchCases.Search.search_test_cases(test_case_path)
  129. return CaseConfig.filter_test_cases(test_methods, _case_filter)
  130. def _group_cases(self):
  131. """
  132. separate all cases into groups according group rules. each group will be executed by one CI job.
  133. :return: test case groups.
  134. """
  135. groups = []
  136. for case in self.test_cases:
  137. for group in groups:
  138. # add to current group
  139. if group.add_case(case):
  140. break
  141. else:
  142. # create new group
  143. groups.append(self.case_group(case))
  144. return groups
  145. @staticmethod
  146. def _apply_bot_filter():
  147. """
  148. we support customize CI test with bot.
  149. here we process from and return the filter which ``_search_cases`` accepts.
  150. :return: filter for search test cases
  151. """
  152. bot_filter = os.getenv("BOT_CASE_FILTER")
  153. if bot_filter:
  154. bot_filter = json.loads(bot_filter)
  155. else:
  156. bot_filter = dict()
  157. return bot_filter
  158. def assign_cases(self):
  159. """
  160. separate test cases to groups and assign test cases to CI jobs.
  161. :raise AssertError: if failed to assign any case to CI job.
  162. :return: None
  163. """
  164. failed_to_assign = []
  165. case_filter = self._apply_bot_filter()
  166. self.test_cases = self._search_cases(self.test_case_path, case_filter)
  167. test_groups = self._group_cases()
  168. for group in test_groups:
  169. for job in self.jobs:
  170. if job.match_group(group):
  171. job.assign_group(group)
  172. break
  173. else:
  174. failed_to_assign.append(group)
  175. if failed_to_assign:
  176. console_log("Please add the following jobs to .gitlab-ci.yml with specific tags:", "R")
  177. for group in failed_to_assign:
  178. console_log("* Add job with: " + ",".join(group.ci_job_match_keys), "R")
  179. raise RuntimeError("Failed to assign test case to CI jobs")
  180. def output_configs(self, output_path):
  181. """
  182. :param output_path: path to output config files for each CI job
  183. :return: None
  184. """
  185. if not os.path.exists(output_path):
  186. os.makedirs(output_path)
  187. for job in self.jobs:
  188. job.output_config(output_path)