1 # SPDX-License-Identifier: BSD-3-Clause
2 # Copyright(c) 2010-2014 Intel Corporation
4 # The main logic behind running autotests in parallel
6 from __future__ import print_function
19 def wait_prompt(child):
22 result = child.expect(["RTE>>", pexpect.TIMEOUT, pexpect.EOF],
32 # each result tuple in results list consists of:
33 # result value (0 or -1)
36 # total test run time (double)
38 # test report (if not available, should be None)
40 # this function needs to be outside AutotestRunner class
41 # because otherwise Pool won't work (or rather it will require
42 # quite a bit of effort to make it work).
45 def run_test_group(cmdline, target, test_group):
48 start_time = time.time()
53 # prepare logging of init
54 startuplog = StringIO.StringIO()
56 print("\n%s %s\n" % ("=" * 20, test_group["Prefix"]), file=startuplog)
57 print("\ncmdline=%s" % cmdline, file=startuplog)
59 child = pexpect.spawn(cmdline, logfile=startuplog)
61 # wait for target to boot
62 if not wait_prompt(child):
67 "Start %s" % test_group["Prefix"],
68 time.time() - start_time,
69 startuplog.getvalue(),
72 # mark all tests as failed
73 for test in test_group["Tests"]:
74 results.append((-1, "Fail [No prompt]", test["Name"],
75 time.time() - start_time, "", None))
82 "Start %s" % test_group["Prefix"],
83 time.time() - start_time,
84 startuplog.getvalue(),
87 # mark all tests as failed
88 for t in test_group["Tests"]:
89 results.append((-1, "Fail [Can't run]", t["Name"],
90 time.time() - start_time, "", None))
94 # startup was successful
95 results.append((0, "Success", "Start %s" % test_group["Prefix"],
96 time.time() - start_time, startuplog.getvalue(), None))
98 # parse the binary for available test commands
99 binary = cmdline.split()[0]
100 stripped = 'not stripped' not in subprocess.check_output(['file', binary])
102 symbols = subprocess.check_output(['nm', binary]).decode('utf-8')
103 avail_cmds = re.findall('test_register_(\w+)', symbols)
105 # run all tests in test group
106 for test in test_group["Tests"]:
108 # create log buffer for each test
109 # in multiprocessing environment, the logging would be
110 # interleaved and will create a mess, hence the buffering
111 logfile = StringIO.StringIO()
112 child.logfile = logfile
116 # make a note when the test started
117 start_time = time.time()
120 # print test name to log buffer
121 print("\n%s %s\n" % ("-" * 20, test["Name"]), file=logfile)
123 # run test function associated with the test
124 if stripped or test["Command"] in avail_cmds:
125 result = test["Func"](child, test["Command"])
127 result = (0, "Skipped [Not Available]")
129 # make a note when the test was finished
130 end_time = time.time()
132 log = logfile.getvalue()
134 # append test data to the result tuple
135 result += (test["Name"], end_time - start_time, log)
137 # call report function, if any defined, and supply it with
138 # target and complete log for test run
140 report = test["Report"](target, log)
142 # append report to results tuple
148 # make a note when the test crashed
149 end_time = time.time()
151 # mark test as failed
152 result = (-1, "Fail [Crash]", test["Name"],
153 end_time - start_time, logfile.getvalue(), None)
155 # append the results to the results list
156 results.append(result)
158 # regardless of whether test has crashed, try quitting it
160 child.sendline("quit")
162 # if the test crashed, just do nothing instead
167 # return test results
171 # class representing an instance of autotests run
172 class AutotestRunner:
174 parallel_test_groups = []
175 non_parallel_test_groups = []
186 def __init__(self, cmdline, target, blacklist, whitelist):
187 self.cmdline = cmdline
189 self.blacklist = blacklist
190 self.whitelist = whitelist
193 logfile = "%s.log" % target
194 csvfile = "%s.csv" % target
196 self.logfile = open(logfile, "w")
197 csvfile = open(csvfile, "w")
198 self.csvwriter = csv.writer(csvfile)
200 # prepare results table
201 self.csvwriter.writerow(["test_name", "test_result", "result_str"])
203 # set up cmdline string
204 def __get_cmdline(self, test):
205 cmdline = self.cmdline
207 # append memory limitations for each test
208 # otherwise tests won't run in parallel
209 if "i686" not in self.target:
210 cmdline += " --socket-mem=%s" % test["Memory"]
212 # affinitize startup so that tests don't fail on i686
213 cmdline = "taskset 1 " + cmdline
214 cmdline += " -m " + str(sum(map(int, test["Memory"].split(","))))
216 # set group prefix for autotest group
217 # otherwise they won't run in parallel
218 cmdline += " --file-prefix=%s" % test["Prefix"]
222 def add_parallel_test_group(self, test_group):
223 self.parallel_test_groups.append(test_group)
225 def add_non_parallel_test_group(self, test_group):
226 self.non_parallel_test_groups.append(test_group)
228 def __process_results(self, results):
229 # this iterates over individual test results
230 for i, result in enumerate(results):
232 # increase total number of tests that were run
233 # do not include "start" test
237 # unpack result tuple
238 test_result, result_str, test_name, \
239 test_time, log, report = result
242 cur_time = time.time()
243 total_time = int(cur_time - self.start)
245 # print results, test run time and total time since start
246 result = ("%s:" % test_name).ljust(30)
247 result += result_str.ljust(29)
248 result += "[%02dm %02ds]" % (test_time / 60, test_time % 60)
250 # don't print out total time every line, it's the same anyway
251 if i == len(results) - 1:
253 "[%02dm %02ds]" % (total_time / 60, total_time % 60))
257 # if test failed and it wasn't a "start" test
258 if test_result < 0 and not i == 0:
262 self.log_buffers.append(log)
264 # create report if it exists
267 f = open("%s_%s_report.rst" %
268 (self.target, test_name), "w")
270 print("Report for %s could not be created!" % test_name)
275 # write test result to CSV file
277 self.csvwriter.writerow([test_name, test_result, result_str])
279 # this function iterates over test groups and removes each
280 # test that is not in whitelist/blacklist
281 def __filter_groups(self, test_groups):
282 groups_to_remove = []
284 # filter out tests from parallel test groups
285 for i, test_group in enumerate(test_groups):
287 # iterate over a copy so that we could safely delete individual
289 for test in test_group["Tests"][:]:
290 test_id = test["Command"]
292 # dump tests are specified in full e.g. "Dump_mempool"
293 if "_autotest" in test_id:
294 test_id = test_id[:-len("_autotest")]
296 # filter out blacklisted/whitelisted tests
297 if self.blacklist and test_id in self.blacklist:
298 test_group["Tests"].remove(test)
300 if self.whitelist and test_id not in self.whitelist:
301 test_group["Tests"].remove(test)
304 # modify or remove original group
305 if len(test_group["Tests"]) > 0:
306 test_groups[i] = test_group
308 # remember which groups should be deleted
309 # put the numbers backwards so that we start
310 # deleting from the end, not from the beginning
311 groups_to_remove.insert(0, i)
313 # remove test groups that need to be removed
314 for i in groups_to_remove:
319 # iterate over test groups and run tests associated with them
320 def run_all_tests(self):
322 self.parallel_test_groups = \
323 self.__filter_groups(self.parallel_test_groups)
324 self.non_parallel_test_groups = \
325 self.__filter_groups(self.non_parallel_test_groups)
327 # create a pool of worker threads
328 pool = multiprocessing.Pool(processes=1)
332 # whatever happens, try to save as much logs as possible
335 # create table header
337 print("Test name".ljust(30) + "Test result".ljust(29) +
338 "Test".center(9) + "Total".center(9))
341 # make a note of tests start time
342 self.start = time.time()
344 # assign worker threads to run test groups
345 for test_group in self.parallel_test_groups:
346 result = pool.apply_async(run_test_group,
347 [self.__get_cmdline(test_group),
350 results.append(result)
352 # iterate while we have group execution results to get
353 while len(results) > 0:
355 # iterate over a copy to be able to safely delete results
356 # this iterates over a list of group results
357 for group_result in results[:]:
359 # if the thread hasn't finished yet, continue
360 if not group_result.ready():
363 res = group_result.get()
365 self.__process_results(res)
367 # remove result from results list once we're done with it
368 results.remove(group_result)
370 # run non_parallel tests. they are run one by one, synchronously
371 for test_group in self.non_parallel_test_groups:
372 group_result = run_test_group(
373 self.__get_cmdline(test_group), self.target, test_group)
375 self.__process_results(group_result)
378 cur_time = time.time()
379 total_time = int(cur_time - self.start)
383 print("Total run time: %02dm %02ds" % (total_time / 60,
386 print("Number of failed tests: %s" % str(self.fails))
388 # write summary to logfile
389 self.logfile.write("Summary\n")
390 self.logfile.write("Target: ".ljust(15) + "%s\n" % self.target)
391 self.logfile.write("Tests: ".ljust(15) + "%i\n" % self.n_tests)
392 self.logfile.write("Failed tests: ".ljust(
393 15) + "%i\n" % self.fails)
395 print("Exception occurred")
396 print(sys.exc_info())
399 # drop logs from all executions to a logfile
400 for buf in self.log_buffers:
401 self.logfile.write(buf.replace("\r", ""))