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 "vxlan+ip4": 114 # What is the real minimum for latency stream?
78 min_frame_size_values = protocol_to_min_frame_size.values()
80 def get_iface_and_suite_id(filename):
81 """Get interface and suite ID.
83 :param filename: Suite file.
85 :returns: Interface ID, Suite ID.
88 dash_split = filename.split("-", 1)
89 if len(dash_split[0]) <= 4:
90 # It was something like "2n1l", we need one more split.
91 dash_split = dash_split[1].split("-", 1)
92 return dash_split[0], dash_split[1].split(".", 1)[0]
94 def add_testcase(testcase, iface, suite_id, file_out, num, **kwargs):
95 """Add testcase to file.
97 :param testcase: Testcase class.
98 :param iface: Interface.
99 :param suite_id: Suite ID.
100 :param file_out: File to write testcases to.
101 :param num: Testcase number.
102 :param kwargs: Key-value pairs used to construct testcase.
103 :type testcase: Testcase
109 :returns: Next testcase number.
112 # TODO: Is there a better way to disable some combinations?
114 if kwargs["frame_size"] == 9000:
115 if "vic1227" in iface:
116 # Not supported in HW.
118 if "vic1385" in iface:
119 # Not supported in HW.
121 if "-16vm2t-" in suite_id or "-16dcr2t-" in suite_id:
122 if kwargs["phy_cores"] > 3:
123 # CSIT lab only has 28 (physical) core processors,
124 # so these test would fail when attempting to assign cores.
126 if "-24vm1t-" in suite_id or "-24dcr1t-" in suite_id:
127 if kwargs["phy_cores"] > 3:
128 # CSIT lab only has 28 (physical) core processors,
129 # so these test would fail when attempting to assign cores.
131 if "soak" in suite_id:
132 # Soak test take too long, do not risk other than tc01.
133 if kwargs["phy_cores"] != 1:
135 if kwargs["frame_size"] not in min_frame_size_values:
138 file_out.write(testcase.generate(num=num, **kwargs))
139 # We bump tc number in any case, so that future enables/disables
140 # do not affect the numbering of other test cases.
143 def add_testcases(testcase, iface, suite_id, file_out, tc_kwargs_list):
144 """Add testcases to file.
146 :param testcase: Testcase class.
147 :param iface: Interface.
148 :param suite_id: Suite ID.
149 :param file_out: File to write testcases to.
150 :param tc_kwargs_list: Key-value pairs used to construct testcases.
151 :type testcase: Testcase
155 :type tc_kwargs_list: dict
158 for tc_kwargs in tc_kwargs_list:
160 testcase, iface, suite_id, file_out, num, **tc_kwargs)
162 def replace_defensively(
163 whole, to_replace, replace_with, how_many, msg, in_filename):
164 """Replace substrings while checking the number of occurences.
166 Return edited copy of the text (so original string is not affected).
168 :param whole: The text to perform replacements on.
169 :param to_replace: Substring occurences of which to replace.
170 :param replace_with: Substring to replace occurences with.
171 :param how_many: Number of occurences to expect.
172 :param msg: Error message to raise.
173 :param in_filename: File name in which the error occured.
175 :type to_replace: str
176 :type replace_with: str
179 :type in_filename: str
180 :return: The whole text after replacements are done.
182 :raise ValueError: If number of occurences does not match.
184 found = whole.count(to_replace)
185 if found != how_many:
186 raise ValueError(in_filename + ": " + msg)
187 return whole.replace(to_replace, replace_with)
189 def write_files(in_filename, in_prolog, kwargs_list):
190 """Using given filename and prolog, write all generated suites.
192 :param in_filename: Template filename to derive real filenames from.
193 :param in_prolog: Template content to derive real content from.
194 :param kwargs_list: List of kwargs for add_testcase.
195 :type in_filename: str
197 :type kwargs_list: list of dict
199 for suite_type in Constants.PERF_TYPE_TO_KEYWORD.keys():
200 tmp_filename = replace_defensively(
201 in_filename, "ndrpdr", suite_type, 1,
202 "File name should contain suite type once.", in_filename)
203 tmp_prolog = replace_defensively(
204 in_prolog, "ndrpdr".upper(), suite_type.upper(), 1,
205 "Suite type should appear once in uppercase (as tag).",
207 tmp_prolog = replace_defensively(
209 "Find NDR and PDR intervals using optimized search",
210 Constants.PERF_TYPE_TO_KEYWORD[suite_type], 1,
211 "Main search keyword should appear once in suite.",
213 tmp_prolog = replace_defensively(
215 Constants.PERF_TYPE_TO_SUITE_DOC_VER["ndrpdr"],
216 Constants.PERF_TYPE_TO_SUITE_DOC_VER[suite_type],
217 1, "Exact suite type doc not found.", in_filename)
218 tmp_prolog = replace_defensively(
220 Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER["ndrpdr"],
221 Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER[suite_type],
222 1, "Exact template type doc not found.", in_filename)
223 _, suite_id = get_iface_and_suite_id(tmp_filename)
224 testcase = self.testcase_class(suite_id)
225 for nic_name in Constants.NIC_NAME_TO_CODE.keys():
226 out_filename = replace_defensively(
227 tmp_filename, "10ge2p1x710",
228 Constants.NIC_NAME_TO_CODE[nic_name], 1,
229 "File name should contain NIC code once.", in_filename)
230 out_prolog = replace_defensively(
231 tmp_prolog, "Intel-X710", nic_name, 2,
232 "NIC name should appear twice (tag and variable).",
234 if out_prolog.count("HW_") == 2:
235 # TODO CSIT-1481: Crypto HW should be read
236 # from topology file instead.
237 if nic_name in Constants.NIC_NAME_TO_CRYPTO_HW.keys():
238 out_prolog = replace_defensively(
239 out_prolog, "HW_DH895xcc",
240 Constants.NIC_NAME_TO_CRYPTO_HW[nic_name], 1,
241 "HW crypto name should appear.", in_filename)
242 iface, suite_id = get_iface_and_suite_id(out_filename)
243 with open(out_filename, "w") as file_out:
244 file_out.write(out_prolog)
246 testcase, iface, suite_id, file_out, kwargs_list)
249 eprint("Regenerator starts at {cwd}".format(cwd=getcwd()))
250 min_frame_size = protocol_to_min_frame_size[protocol]
251 kwargs_list = tc_kwargs_list if tc_kwargs_list else [
252 {"frame_size": min_frame_size, "phy_cores": 1},
253 {"frame_size": min_frame_size, "phy_cores": 2},
254 {"frame_size": min_frame_size, "phy_cores": 4},
255 {"frame_size": 1518, "phy_cores": 1},
256 {"frame_size": 1518, "phy_cores": 2},
257 {"frame_size": 1518, "phy_cores": 4},
258 {"frame_size": 9000, "phy_cores": 1},
259 {"frame_size": 9000, "phy_cores": 2},
260 {"frame_size": 9000, "phy_cores": 4},
261 {"frame_size": "IMIX_v4_1", "phy_cores": 1},
262 {"frame_size": "IMIX_v4_1", "phy_cores": 2},
263 {"frame_size": "IMIX_v4_1", "phy_cores": 4}
265 for in_filename in glob(pattern):
267 eprint("Regenerating in_filename:", in_filename)
268 if not in_filename.endswith("ndrpdr.robot"):
269 eprint("Error in {fil}: non-primary suite type encountered."
270 .format(fil=in_filename))
272 iface, _ = get_iface_and_suite_id(in_filename)
273 if not iface.endswith("10ge2p1x710"):
274 eprint("Error in {fil}: non-primary NIC encountered."
275 .format(fil=in_filename))
277 with open(in_filename, "r") as file_in:
279 file_in.read().partition("*** Test Cases ***")[:-1])
280 write_files(in_filename, in_prolog, kwargs_list)
282 eprint("Regenerator ends.")
283 eprint() # To make autogen check output more readable.