CaseConfig.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. Processing case config files.
  16. This is mainly designed for CI, we need to auto create and assign test jobs.
  17. Template Config File::
  18. TestConfig:
  19. app:
  20. path: Users/Test/TinyTestFW/IDF/IDFApp.py
  21. class: Example
  22. dut:
  23. path:
  24. class:
  25. config_file: /somewhere/config_file_for_runner
  26. test_name: CI_test_job_1
  27. Filter:
  28. chip: ESP32
  29. env_tag: default
  30. CaseConfig:
  31. - name: test_examples_protocol_https_request
  32. # optional
  33. extra_data: some extra data passed to case with kwarg extra_data
  34. overwrite: # overwrite test configs
  35. app:
  36. path: Users/Test/TinyTestFW/IDF/IDFApp.py
  37. class: Example
  38. - name: xxx
  39. """
  40. # TODO: add a function to use suitable import lib for python2 and python3
  41. import imp
  42. import yaml
  43. import TestCase
  44. def _convert_to_lower_case(item):
  45. """
  46. bot filter is always lower case string.
  47. this function will convert to all string to lower case.
  48. """
  49. if isinstance(item, (tuple, list)):
  50. output = [_convert_to_lower_case(v) for v in item]
  51. elif isinstance(item, str):
  52. output = item.lower()
  53. else:
  54. output = item
  55. return output
  56. def _filter_one_case(test_method, case_filter):
  57. """ Apply filter for one case (the filter logic is the same as described in ``filter_test_cases``) """
  58. filter_result = True
  59. for key in case_filter:
  60. if key in test_method.case_info:
  61. # the filter key is both in case and filter
  62. # we need to check if they match
  63. filter_item = _convert_to_lower_case(case_filter[key])
  64. accepted_item = _convert_to_lower_case(test_method.case_info[key])
  65. if isinstance(filter_item, (tuple, list)) \
  66. and isinstance(accepted_item, (tuple, list)):
  67. # both list/tuple, check if they have common item
  68. filter_result = True if set(filter_item) & set(accepted_item) else False
  69. elif isinstance(filter_item, (tuple, list)):
  70. # filter item list/tuple, check if case accepted value in filter item list/tuple
  71. filter_result = True if accepted_item in filter_item else False
  72. elif isinstance(accepted_item, (tuple, list)):
  73. # accepted item list/tuple, check if case filter value is in accept item list/tuple
  74. filter_result = True if filter_item in accepted_item else False
  75. else:
  76. # both string/int, just do string compare
  77. filter_result = (filter_item == accepted_item)
  78. else:
  79. # key in filter only, which means the case supports all values for this filter key, match succeed
  80. pass
  81. if not filter_result:
  82. # match failed
  83. break
  84. return filter_result
  85. def filter_test_cases(test_methods, case_filter):
  86. """
  87. filter test case. filter logic:
  88. 1. if filter key both in case attribute and filter:
  89. * if both value is string/int, then directly compare
  90. * if one is list/tuple, the other one is string/int, then check if string/int is in list/tuple
  91. * if both are list/tuple, then check if they have common item
  92. 2. if only case attribute or filter have the key, filter succeed
  93. 3. will do case insensitive compare for string
  94. for example, the following are match succeed scenarios
  95. (the rule is symmetric, result is same if exchange values for user filter and case attribute):
  96. * user case filter is ``chip: ["esp32", "esp32c"]``, case doesn't have ``chip`` attribute
  97. * user case filter is ``chip: ["esp32", "esp32c"]``, case attribute is ``chip: "esp32"``
  98. * user case filter is ``chip: "esp32"``, case attribute is ``chip: "esp32"``
  99. :param test_methods: a list of test methods functions
  100. :param case_filter: case filter
  101. :return: filtered test methods
  102. """
  103. filtered_test_methods = []
  104. for test_method in test_methods:
  105. if _filter_one_case(test_method, case_filter):
  106. filtered_test_methods.append(test_method)
  107. return filtered_test_methods
  108. class Parser(object):
  109. DEFAULT_CONFIG = {
  110. "TestConfig": dict(),
  111. "Filter": dict(),
  112. "CaseConfig": [{"extra_data": None}],
  113. }
  114. @classmethod
  115. def parse_config_file(cls, config_file):
  116. """
  117. parse from config file and then update to default config.
  118. :param config_file: config file path
  119. :return: configs
  120. """
  121. configs = cls.DEFAULT_CONFIG.copy()
  122. if config_file:
  123. with open(config_file, "r") as f:
  124. configs.update(yaml.load(f))
  125. return configs
  126. @classmethod
  127. def handle_overwrite_args(cls, overwrite):
  128. """
  129. handle overwrite configs. import module from path and then get the required class.
  130. :param overwrite: overwrite args
  131. :return: dict of (original key: class)
  132. """
  133. output = dict()
  134. for key in overwrite:
  135. _path = overwrite[key]["path"]
  136. # TODO: add a function to use suitable import lib for python2 and python3
  137. _module = imp.load_source(str(hash(_path)), overwrite[key]["path"])
  138. output[key] = _module.__getattribute__(overwrite[key]["class"])
  139. return output
  140. @classmethod
  141. def apply_config(cls, test_methods, config_file):
  142. """
  143. apply config for test methods
  144. :param test_methods: a list of test methods functions
  145. :param config_file: case filter file
  146. :return: filtered cases
  147. """
  148. configs = cls.parse_config_file(config_file)
  149. test_case_list = []
  150. for _config in configs["CaseConfig"]:
  151. _filter = configs["Filter"].copy()
  152. _filter.update(_config)
  153. _overwrite = cls.handle_overwrite_args(_filter.pop("overwrite", dict()))
  154. _extra_data = _filter.pop("extra_data", None)
  155. for test_method in test_methods:
  156. if _filter_one_case(test_method, _filter):
  157. test_case_list.append(TestCase.TestCase(test_method, _extra_data, **_overwrite))
  158. return test_case_list
  159. class Generator(object):
  160. """ Case config file generator """
  161. def __init__(self):
  162. self.default_config = {
  163. "TestConfig": dict(),
  164. "Filter": dict(),
  165. }
  166. def set_default_configs(self, test_config, case_filter):
  167. """
  168. :param test_config: "TestConfig" value
  169. :param case_filter: "Filter" value
  170. :return: None
  171. """
  172. self.default_config = {"TestConfig": test_config, "Filter": case_filter}
  173. def generate_config(self, case_configs, output_file):
  174. """
  175. :param case_configs: "CaseConfig" value
  176. :param output_file: output file path
  177. :return: None
  178. """
  179. config = self.default_config.copy()
  180. config.update({"CaseConfig": case_configs})
  181. with open(output_file, "w") as f:
  182. yaml.dump(config, f)