CaseConfig.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. # filter keys are lower case. Do map lower case keys with original keys.
  60. key_mapping = {x.lower(): x for x in test_method.case_info.keys()}
  61. for orig_key in case_filter:
  62. key = key_mapping[orig_key]
  63. if key in test_method.case_info:
  64. # the filter key is both in case and filter
  65. # we need to check if they match
  66. filter_item = _convert_to_lower_case(case_filter[orig_key])
  67. accepted_item = _convert_to_lower_case(test_method.case_info[key])
  68. if isinstance(filter_item, (tuple, list)) \
  69. and isinstance(accepted_item, (tuple, list)):
  70. # both list/tuple, check if they have common item
  71. filter_result = True if set(filter_item) & set(accepted_item) else False
  72. elif isinstance(filter_item, (tuple, list)):
  73. # filter item list/tuple, check if case accepted value in filter item list/tuple
  74. filter_result = True if accepted_item in filter_item else False
  75. elif isinstance(accepted_item, (tuple, list)):
  76. # accepted item list/tuple, check if case filter value is in accept item list/tuple
  77. filter_result = True if filter_item in accepted_item else False
  78. else:
  79. # both string/int, just do string compare
  80. filter_result = (filter_item == accepted_item)
  81. else:
  82. # key in filter only, which means the case supports all values for this filter key, match succeed
  83. pass
  84. if not filter_result:
  85. # match failed
  86. break
  87. return filter_result
  88. def filter_test_cases(test_methods, case_filter):
  89. """
  90. filter test case. filter logic:
  91. 1. if filter key both in case attribute and filter:
  92. * if both value is string/int, then directly compare
  93. * if one is list/tuple, the other one is string/int, then check if string/int is in list/tuple
  94. * if both are list/tuple, then check if they have common item
  95. 2. if only case attribute or filter have the key, filter succeed
  96. 3. will do case insensitive compare for string
  97. for example, the following are match succeed scenarios
  98. (the rule is symmetric, result is same if exchange values for user filter and case attribute):
  99. * user case filter is ``chip: ["esp32", "esp32c"]``, case doesn't have ``chip`` attribute
  100. * user case filter is ``chip: ["esp32", "esp32c"]``, case attribute is ``chip: "esp32"``
  101. * user case filter is ``chip: "esp32"``, case attribute is ``chip: "esp32"``
  102. :param test_methods: a list of test methods functions
  103. :param case_filter: case filter
  104. :return: filtered test methods
  105. """
  106. filtered_test_methods = []
  107. for test_method in test_methods:
  108. if _filter_one_case(test_method, case_filter):
  109. filtered_test_methods.append(test_method)
  110. return filtered_test_methods
  111. class Parser(object):
  112. DEFAULT_CONFIG = {
  113. "TestConfig": dict(),
  114. "Filter": dict(),
  115. "CaseConfig": [{"extra_data": None}],
  116. }
  117. @classmethod
  118. def parse_config_file(cls, config_file):
  119. """
  120. parse from config file and then update to default config.
  121. :param config_file: config file path
  122. :return: configs
  123. """
  124. configs = cls.DEFAULT_CONFIG.copy()
  125. if config_file:
  126. with open(config_file, "r") as f:
  127. configs.update(yaml.load(f))
  128. return configs
  129. @classmethod
  130. def handle_overwrite_args(cls, overwrite):
  131. """
  132. handle overwrite configs. import module from path and then get the required class.
  133. :param overwrite: overwrite args
  134. :return: dict of (original key: class)
  135. """
  136. output = dict()
  137. for key in overwrite:
  138. _path = overwrite[key]["path"]
  139. # TODO: add a function to use suitable import lib for python2 and python3
  140. _module = imp.load_source(str(hash(_path)), overwrite[key]["path"])
  141. output[key] = _module.__getattribute__(overwrite[key]["class"])
  142. return output
  143. @classmethod
  144. def apply_config(cls, test_methods, config_file):
  145. """
  146. apply config for test methods
  147. :param test_methods: a list of test methods functions
  148. :param config_file: case filter file
  149. :return: filtered cases
  150. """
  151. configs = cls.parse_config_file(config_file)
  152. test_case_list = []
  153. for _config in configs["CaseConfig"]:
  154. _filter = configs["Filter"].copy()
  155. _filter.update(_config)
  156. _overwrite = cls.handle_overwrite_args(_filter.pop("overwrite", dict()))
  157. _extra_data = _filter.pop("extra_data", None)
  158. for test_method in test_methods:
  159. if _filter_one_case(test_method, _filter):
  160. test_case_list.append(TestCase.TestCase(test_method, _extra_data, **_overwrite))
  161. return test_case_list
  162. class Generator(object):
  163. """ Case config file generator """
  164. def __init__(self):
  165. self.default_config = {
  166. "TestConfig": dict(),
  167. "Filter": dict(),
  168. }
  169. def set_default_configs(self, test_config, case_filter):
  170. """
  171. :param test_config: "TestConfig" value
  172. :param case_filter: "Filter" value
  173. :return: None
  174. """
  175. self.default_config = {"TestConfig": test_config, "Filter": case_filter}
  176. def generate_config(self, case_configs, output_file):
  177. """
  178. :param case_configs: "CaseConfig" value
  179. :param output_file: output file path
  180. :return: None
  181. """
  182. config = self.default_config.copy()
  183. config.update({"CaseConfig": case_configs})
  184. with open(output_file, "w") as f:
  185. yaml.dump(config, f)