CIAssignUnitTest.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. """
  2. Command line tool to assign unit tests to CI test jobs.
  3. """
  4. import re
  5. import argparse
  6. import yaml
  7. try:
  8. from yaml import CLoader as Loader
  9. except ImportError:
  10. from yaml import Loader as Loader
  11. from tiny_test_fw.Utility import CIAssignTest
  12. class Group(CIAssignTest.Group):
  13. SORT_KEYS = ["test environment", "tags", "chip_target"]
  14. MAX_CASE = 50
  15. ATTR_CONVERT_TABLE = {
  16. "execution_time": "execution time"
  17. }
  18. CI_JOB_MATCH_KEYS = ["test environment"]
  19. DUT_CLS_NAME = {
  20. "esp32": "ESP32DUT",
  21. "esp32s2": "ESP32S2DUT",
  22. "esp8266": "ESP8266DUT",
  23. }
  24. def __init__(self, case):
  25. super(Group, self).__init__(case)
  26. for tag in self._get_case_attr(case, "tags"):
  27. self.ci_job_match_keys.add(tag)
  28. @staticmethod
  29. def _get_case_attr(case, attr):
  30. if attr in Group.ATTR_CONVERT_TABLE:
  31. attr = Group.ATTR_CONVERT_TABLE[attr]
  32. return case[attr]
  33. def add_extra_case(self, case):
  34. """ If current group contains all tags required by case, then add succeed """
  35. added = False
  36. if self.accept_new_case():
  37. for key in self.filters:
  38. if self._get_case_attr(case, key) != self.filters[key]:
  39. if key == "tags":
  40. if self._get_case_attr(case, key).issubset(self.filters[key]):
  41. continue
  42. break
  43. else:
  44. self.case_list.append(case)
  45. added = True
  46. return added
  47. def _create_extra_data(self, test_cases, test_function):
  48. """
  49. For unit test case, we need to copy some attributes of test cases into config file.
  50. So unit test function knows how to run the case.
  51. """
  52. case_data = []
  53. for case in test_cases:
  54. one_case_data = {
  55. "config": self._get_case_attr(case, "config"),
  56. "name": self._get_case_attr(case, "summary"),
  57. "reset": self._get_case_attr(case, "reset"),
  58. "timeout": self._get_case_attr(case, "timeout"),
  59. }
  60. if test_function in ["run_multiple_devices_cases", "run_multiple_stage_cases"]:
  61. try:
  62. one_case_data["child case num"] = self._get_case_attr(case, "child case num")
  63. except KeyError as e:
  64. print("multiple devices/stages cases must contains at least two test functions")
  65. print("case name: {}".format(one_case_data["name"]))
  66. raise e
  67. case_data.append(one_case_data)
  68. return case_data
  69. def _divide_case_by_test_function(self):
  70. """
  71. divide cases of current test group by test function they need to use
  72. :return: dict of list of cases for each test functions
  73. """
  74. case_by_test_function = {
  75. "run_multiple_devices_cases": [],
  76. "run_multiple_stage_cases": [],
  77. "run_unit_test_cases": [],
  78. }
  79. for case in self.case_list:
  80. if case["multi_device"] == "Yes":
  81. case_by_test_function["run_multiple_devices_cases"].append(case)
  82. elif case["multi_stage"] == "Yes":
  83. case_by_test_function["run_multiple_stage_cases"].append(case)
  84. else:
  85. case_by_test_function["run_unit_test_cases"].append(case)
  86. return case_by_test_function
  87. def output(self):
  88. """
  89. output data for job configs
  90. :return: {"Filter": case filter, "CaseConfig": list of case configs for cases in this group}
  91. """
  92. target = self._get_case_attr(self.case_list[0], "chip_target")
  93. if target:
  94. overwrite = {
  95. "dut": {
  96. "package": "ttfw_idf",
  97. "class": self.DUT_CLS_NAME[target],
  98. }
  99. }
  100. else:
  101. overwrite = dict()
  102. case_by_test_function = self._divide_case_by_test_function()
  103. output_data = {
  104. # we don't need filter for test function, as UT uses a few test functions for all cases
  105. "CaseConfig": [
  106. {
  107. "name": test_function,
  108. "extra_data": self._create_extra_data(test_cases, test_function),
  109. "overwrite": overwrite,
  110. } for test_function, test_cases in case_by_test_function.iteritems() if test_cases
  111. ],
  112. }
  113. return output_data
  114. class UnitTestAssignTest(CIAssignTest.AssignTest):
  115. CI_TEST_JOB_PATTERN = re.compile(r"^UT_.+")
  116. def __init__(self, test_case_path, ci_config_file):
  117. CIAssignTest.AssignTest.__init__(self, test_case_path, ci_config_file, case_group=Group)
  118. def _search_cases(self, test_case_path, case_filter=None, test_case_file_pattern=None):
  119. """
  120. For unit test case, we don't search for test functions.
  121. The unit test cases is stored in a yaml file which is created in job build-idf-test.
  122. """
  123. try:
  124. with open(test_case_path, "r") as f:
  125. raw_data = yaml.load(f, Loader=Loader)
  126. test_cases = raw_data["test cases"]
  127. for case in test_cases:
  128. case["tags"] = set(case["tags"])
  129. except IOError:
  130. print("Test case path is invalid. Should only happen when use @bot to skip unit test.")
  131. test_cases = []
  132. # filter keys are lower case. Do map lower case keys with original keys.
  133. try:
  134. key_mapping = {x.lower(): x for x in test_cases[0].keys()}
  135. except IndexError:
  136. key_mapping = dict()
  137. if case_filter:
  138. for key in case_filter:
  139. filtered_cases = []
  140. for case in test_cases:
  141. try:
  142. mapped_key = key_mapping[key]
  143. # bot converts string to lower case
  144. if isinstance(case[mapped_key], str):
  145. _value = case[mapped_key].lower()
  146. else:
  147. _value = case[mapped_key]
  148. if _value in case_filter[key]:
  149. filtered_cases.append(case)
  150. except KeyError:
  151. # case don't have this key, regard as filter success
  152. filtered_cases.append(case)
  153. test_cases = filtered_cases
  154. # sort cases with configs and test functions
  155. # in later stage cases with similar attributes are more likely to be assigned to the same job
  156. # it will reduce the count of flash DUT operations
  157. test_cases.sort(key=lambda x: x["config"] + x["multi_stage"] + x["multi_device"])
  158. return test_cases
  159. if __name__ == '__main__':
  160. parser = argparse.ArgumentParser()
  161. parser.add_argument("test_case",
  162. help="test case folder or file")
  163. parser.add_argument("ci_config_file",
  164. help="gitlab ci config file")
  165. parser.add_argument("output_path",
  166. help="output path of config files")
  167. args = parser.parse_args()
  168. assign_test = UnitTestAssignTest(args.test_case, args.ci_config_file)
  169. assign_test.assign_cases()
  170. assign_test.output_configs(args.output_path)