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