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 "avf" in suite_id:
119 # Not supported by AVF driver.
120 # https://git.fd.io/vpp/tree/src/plugins/avf/README.md
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 "soak" in suite_id:
128 # Soak test take too long, do not risk other than tc01.
129 if kwargs["phy_cores"] != 1:
131 if kwargs["frame_size"] not in min_frame_size_values:
134 file_out.write(testcase.generate(num=num, **kwargs))
135 # We bump tc number in any case, so that future enables/disables
136 # do not affect the numbering of other test cases.
139 def add_testcases(testcase, iface, suite_id, file_out, tc_kwargs_list):
140 """Add testcases to file.
142 :param testcase: Testcase class.
143 :param iface: Interface.
144 :param suite_id: Suite ID.
145 :param file_out: File to write testcases to.
146 :param tc_kwargs_list: Key-value pairs used to construct testcases.
147 :type testcase: Testcase
151 :type tc_kwargs_list: dict
154 for tc_kwargs in tc_kwargs_list:
156 testcase, iface, suite_id, file_out, num, **tc_kwargs)
158 def replace_defensively(
159 whole, to_replace, replace_with, how_many, msg, in_filename):
160 """Replace substrings while checking the number of occurences.
162 Return edited copy of the text (so original string is not affected).
164 :param whole: The text to perform replacements on.
165 :param to_replace: Substring occurences of which to replace.
166 :param replace_with: Substring to replace occurences with.
167 :param how_many: Number of occurences to expect.
168 :param msg: Error message to raise.
169 :param in_filename: File name in which the error occured.
171 :type to_replace: str
172 :type replace_with: str
175 :type in_filename: str
176 :return: The whole text after replacements are done.
178 :raise ValueError: If number of occurences does not match.
180 found = whole.count(to_replace)
181 if found != how_many:
182 raise ValueError(in_filename + ": " + msg)
183 return whole.replace(to_replace, replace_with)
185 def write_files(in_filename, in_prolog, kwargs_list):
186 """Using given filename and prolog, write all generated suites.
188 :param in_filename: Template filename to derive real filenames from.
189 :param in_prolog: Template content to derive real content from.
190 :param kwargs_list: List of kwargs for add_testcase.
191 :type in_filename: str
193 :type kwargs_list: list of dict
195 for suite_type in Constants.PERF_TYPE_TO_KEYWORD.keys():
196 tmp_filename = replace_defensively(
197 in_filename, "ndrpdr", suite_type, 1,
198 "File name should contain suite type once.", in_filename)
199 tmp_prolog = replace_defensively(
200 in_prolog, "ndrpdr".upper(), suite_type.upper(), 1,
201 "Suite type should appear once in uppercase (as tag).",
203 tmp_prolog = replace_defensively(
205 "Find NDR and PDR intervals using optimized search",
206 Constants.PERF_TYPE_TO_KEYWORD[suite_type], 1,
207 "Main search keyword should appear once in suite.",
209 tmp_prolog = replace_defensively(
211 Constants.PERF_TYPE_TO_SUITE_DOC_VER["ndrpdr"],
212 Constants.PERF_TYPE_TO_SUITE_DOC_VER[suite_type],
213 1, "Exact suite type doc not found.", in_filename)
214 tmp_prolog = replace_defensively(
216 Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER["ndrpdr"],
217 Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER[suite_type],
218 1, "Exact template type doc not found.", in_filename)
219 _, suite_id = get_iface_and_suite_id(tmp_filename)
220 testcase = self.testcase_class(suite_id)
221 for nic_name in Constants.NIC_NAME_TO_CODE.keys():
222 out_filename = replace_defensively(
223 tmp_filename, "10ge2p1x710",
224 Constants.NIC_NAME_TO_CODE[nic_name], 1,
225 "File name should contain NIC code once.", in_filename)
226 out_prolog = replace_defensively(
227 tmp_prolog, "Intel-X710", nic_name, 2,
228 "NIC name should appear twice (tag and variable).",
230 if out_prolog.count("HW_") == 2:
231 # TODO CSIT-1481: Crypto HW should be read
232 # from topology file instead.
233 if nic_name in Constants.NIC_NAME_TO_CRYPTO_HW.keys():
234 out_prolog = replace_defensively(
235 out_prolog, "HW_DH895xcc",
236 Constants.NIC_NAME_TO_CRYPTO_HW[nic_name], 1,
237 "HW crypto name should appear.", in_filename)
238 iface, suite_id = get_iface_and_suite_id(out_filename)
239 with open(out_filename, "w") as file_out:
240 file_out.write(out_prolog)
242 testcase, iface, suite_id, file_out, kwargs_list)
245 eprint("Regenerator starts at {cwd}".format(cwd=getcwd()))
246 min_frame_size = protocol_to_min_frame_size[protocol]
247 kwargs_list = tc_kwargs_list if tc_kwargs_list else [
248 {"frame_size": min_frame_size, "phy_cores": 1},
249 {"frame_size": min_frame_size, "phy_cores": 2},
250 {"frame_size": min_frame_size, "phy_cores": 4},
251 {"frame_size": 1518, "phy_cores": 1},
252 {"frame_size": 1518, "phy_cores": 2},
253 {"frame_size": 1518, "phy_cores": 4},
254 {"frame_size": 9000, "phy_cores": 1},
255 {"frame_size": 9000, "phy_cores": 2},
256 {"frame_size": 9000, "phy_cores": 4},
257 {"frame_size": "IMIX_v4_1", "phy_cores": 1},
258 {"frame_size": "IMIX_v4_1", "phy_cores": 2},
259 {"frame_size": "IMIX_v4_1", "phy_cores": 4}
261 for in_filename in glob(pattern):
263 eprint("Regenerating in_filename:", in_filename)
264 if not in_filename.endswith("ndrpdr.robot"):
265 eprint("Error in {fil}: non-primary suite type encountered."
266 .format(fil=in_filename))
268 iface, _ = get_iface_and_suite_id(in_filename)
269 if not iface.endswith("10ge2p1x710"):
270 eprint("Error in {fil}: non-primary NIC encountered."
271 .format(fil=in_filename))
273 with open(in_filename, "r") as file_in:
275 file_in.read().partition("*** Test Cases ***")[:-1])
276 write_files(in_filename, in_prolog, kwargs_list)
278 eprint("Regenerator ends.")
279 eprint() # To make autogen check output more readable.