1 # Copyright (c) 2019 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
14 """Module defining utilities for test directory regeneration."""
16 from __future__ import print_function
22 from .DefaultTestcase import DefaultTestcase
23 from resources.libraries.python.Constants import Constants
26 # Copied from https://stackoverflow.com/a/14981125
27 def eprint(*args, **kwargs):
28 """Print to stderr."""
29 print(*args, file=sys.stderr, **kwargs)
32 class Regenerator(object):
33 """Class containing file generating methods."""
35 def __init__(self, testcase_class=DefaultTestcase, quiet=True):
36 """Initialize Testcase class to use.
38 TODO: See the type doc for testcase_class?
39 It implies the design is wrong. Fix it.
40 Easiest: Hardcode Regenerator to use DefaultTestcase only.
42 :param testcase_class: Subclass of DefaultTestcase for generation.
43 Default: DefaultTestcase
44 :param quiet: Reduce log prints (to stderr) when True (default).
45 :type testcase_class: subclass of DefaultTestcase accepting suite_id
48 self.testcase_class = testcase_class
51 def regenerate_glob(self, pattern, protocol="ip4", tc_kwargs_list=None):
52 """Regenerate files matching glob pattern based on arguments.
54 In the current working directory, find all files matching
55 the glob pattern. Use testcase template (from init) to regenerate
56 test cases, autonumbering them, taking arguments from list.
57 If the list is None, use default list, which depends on ip6 usage.
59 Log-like prints are emited to sys.stderr.
61 :param pattern: Glob pattern to select files. Example: *-ndrpdr.robot
62 :param is_ip6: Flag determining minimal frame size. Default: False
63 :param tc_kwargs_list: Arguments defining the testcases. Default: None
64 When None, default list is used.
65 List item is a dict, argument names are keys.
66 The initialized testcase_class should accept those, and "num".
67 DefaultTestcase accepts "frame_size" and "phy_cores".
70 :type tc_kwargs_list: list of tuple or None
73 protocol_to_min_frame_size = {
76 "ethip4vxlan": 114, # What is the real minimum for latency stream?
79 min_frame_size_values = protocol_to_min_frame_size.values()
81 def get_iface_and_suite_id(filename):
82 """Get interface and suite ID.
84 :param filename: Suite file.
86 :returns: Interface ID, Suite ID.
89 dash_split = filename.split("-", 1)
90 if len(dash_split[0]) <= 4:
91 # It was something like "2n1l", we need one more split.
92 dash_split = dash_split[1].split("-", 1)
93 return dash_split[0], dash_split[1].split(".", 1)[0]
95 def add_testcase(testcase, iface, suite_id, file_out, num, **kwargs):
96 """Add testcase to file.
98 :param testcase: Testcase class.
99 :param iface: Interface.
100 :param suite_id: Suite ID.
101 :param file_out: File to write testcases to.
102 :param num: Testcase number.
103 :param kwargs: Key-value pairs used to construct testcase.
104 :type testcase: Testcase
110 :returns: Next testcase number.
113 # TODO: Is there a better way to disable some combinations?
115 if kwargs["frame_size"] == 9000:
116 if "vic1227" in iface:
117 # Not supported in HW.
119 if "vic1385" in iface:
120 # Not supported in HW.
122 if "-16vm2t-" in suite_id or "-16dcr2t-" in suite_id:
123 if kwargs["phy_cores"] > 3:
124 # CSIT lab only has 28 (physical) core processors,
125 # so these test would fail when attempting to assign cores.
127 if "-24vm1t-" in suite_id or "-24dcr1t-" in suite_id:
128 if kwargs["phy_cores"] > 3:
129 # CSIT lab only has 28 (physical) core processors,
130 # so these test would fail when attempting to assign cores.
132 if "soak" in suite_id:
133 # Soak test take too long, do not risk other than tc01.
134 if kwargs["phy_cores"] != 1:
136 if kwargs["frame_size"] not in min_frame_size_values:
139 file_out.write(testcase.generate(num=num, **kwargs))
140 # We bump tc number in any case, so that future enables/disables
141 # do not affect the numbering of other test cases.
144 def add_testcases(testcase, iface, suite_id, file_out, tc_kwargs_list):
145 """Add testcases to file.
147 :param testcase: Testcase class.
148 :param iface: Interface.
149 :param suite_id: Suite ID.
150 :param file_out: File to write testcases to.
151 :param tc_kwargs_list: Key-value pairs used to construct testcases.
152 :type testcase: Testcase
156 :type tc_kwargs_list: dict
159 for tc_kwargs in tc_kwargs_list:
161 testcase, iface, suite_id, file_out, num, **tc_kwargs)
163 def replace_defensively(
164 whole, to_replace, replace_with, how_many, msg, in_filename):
165 """Replace substrings while checking the number of occurences.
167 Return edited copy of the text (so original string is not affected).
169 :param whole: The text to perform replacements on.
170 :param to_replace: Substring occurences of which to replace.
171 :param replace_with: Substring to replace occurences with.
172 :param how_many: Number of occurences to expect.
173 :param msg: Error message to raise.
174 :param in_filename: File name in which the error occured.
176 :type to_replace: str
177 :type replace_with: str
180 :type in_filename: str
181 :return: The whole text after replacements are done.
183 :raise ValueError: If number of occurences does not match.
185 found = whole.count(to_replace)
186 if found != how_many:
187 raise ValueError(in_filename + ": " + msg)
188 return whole.replace(to_replace, replace_with)
190 def write_files(in_filename, in_prolog, kwargs_list):
191 """Using given filename and prolog, write all generated suites.
193 :param in_filename: Template filename to derive real filenames from.
194 :param in_prolog: Template content to derive real content from.
195 :param kwargs_list: List of kwargs for add_testcase.
196 :type in_filename: str
198 :type kwargs_list: list of dict
200 for suite_type in Constants.PERF_TYPE_TO_KEYWORD.keys():
201 tmp_filename = replace_defensively(
202 in_filename, "ndrpdr", suite_type, 1,
203 "File name should contain suite type once.", in_filename)
204 tmp_prolog = replace_defensively(
205 in_prolog, "ndrpdr".upper(), suite_type.upper(), 1,
206 "Suite type should appear once in uppercase (as tag).",
208 tmp_prolog = replace_defensively(
210 "Find NDR and PDR intervals using optimized search",
211 Constants.PERF_TYPE_TO_KEYWORD[suite_type], 1,
212 "Main search keyword should appear once in suite.",
214 tmp_prolog = replace_defensively(
216 Constants.PERF_TYPE_TO_SUITE_DOC_VER["ndrpdr"],
217 Constants.PERF_TYPE_TO_SUITE_DOC_VER[suite_type],
218 1, "Exact suite type doc not found.", in_filename)
219 tmp_prolog = replace_defensively(
221 Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER["ndrpdr"],
222 Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER[suite_type],
223 1, "Exact template type doc not found.", in_filename)
224 _, suite_id = get_iface_and_suite_id(tmp_filename)
225 testcase = self.testcase_class(suite_id)
226 for nic_name in Constants.NIC_NAME_TO_CODE.keys():
227 out_filename = replace_defensively(
228 tmp_filename, "10ge2p1x710",
229 Constants.NIC_NAME_TO_CODE[nic_name], 1,
230 "File name should contain NIC code once.", in_filename)
231 out_prolog = replace_defensively(
232 tmp_prolog, "Intel-X710", nic_name, 2,
233 "NIC name should appear twice (tag and variable).",
235 if out_prolog.count("HW_") == 2:
236 # TODO CSIT-1481: Crypto HW should be read
237 # from topology file instead.
238 if nic_name in Constants.NIC_NAME_TO_CRYPTO_HW.keys():
239 out_prolog = replace_defensively(
240 out_prolog, "HW_DH895xcc",
241 Constants.NIC_NAME_TO_CRYPTO_HW[nic_name], 1,
242 "HW crypto name should appear.", in_filename)
243 iface, suite_id = get_iface_and_suite_id(out_filename)
244 with open(out_filename, "w") as file_out:
245 file_out.write(out_prolog)
247 testcase, iface, suite_id, file_out, kwargs_list)
250 eprint("Regenerator starts at {cwd}".format(cwd=getcwd()))
251 min_frame_size = protocol_to_min_frame_size[protocol]
252 kwargs_list = tc_kwargs_list if tc_kwargs_list else [
253 {"frame_size": min_frame_size, "phy_cores": 1},
254 {"frame_size": min_frame_size, "phy_cores": 2},
255 {"frame_size": min_frame_size, "phy_cores": 4},
256 {"frame_size": 1518, "phy_cores": 1},
257 {"frame_size": 1518, "phy_cores": 2},
258 {"frame_size": 1518, "phy_cores": 4},
259 {"frame_size": 9000, "phy_cores": 1},
260 {"frame_size": 9000, "phy_cores": 2},
261 {"frame_size": 9000, "phy_cores": 4},
262 {"frame_size": "IMIX_v4_1", "phy_cores": 1},
263 {"frame_size": "IMIX_v4_1", "phy_cores": 2},
264 {"frame_size": "IMIX_v4_1", "phy_cores": 4}
266 for in_filename in glob(pattern):
268 eprint("Regenerating in_filename:", in_filename)
269 if not in_filename.endswith("ndrpdr.robot"):
270 eprint("Error in {fil}: non-primary suite type encountered."
271 .format(fil=in_filename))
273 iface, _ = get_iface_and_suite_id(in_filename)
274 if not iface.endswith("10ge2p1x710"):
275 eprint("Error in {fil}: non-primary NIC encountered."
276 .format(fil=in_filename))
278 with open(in_filename, "r") as file_in:
280 file_in.read().partition("*** Test Cases ***")[:-1])
281 write_files(in_filename, in_prolog, kwargs_list)
283 eprint("Regenerator ends.")
284 eprint() # To make autogen check output more readable.