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 # run all tests in test group
99 for test in test_group["Tests"]:
101 # create log buffer for each test
102 # in multiprocessing environment, the logging would be
103 # interleaved and will create a mess, hence the buffering
104 logfile = StringIO.StringIO()
105 child.logfile = logfile
109 # make a note when the test started
110 start_time = time.time()
113 # print test name to log buffer
114 print("\n%s %s\n" % ("-" * 20, test["Name"]), file=logfile)
116 # run test function associated with the test
117 result = test["Func"](child, test["Command"])
119 # make a note when the test was finished
120 end_time = time.time()
122 log = logfile.getvalue()
124 # append test data to the result tuple
125 result += (test["Name"], end_time - start_time, log)
127 # call report function, if any defined, and supply it with
128 # target and complete log for test run
130 report = test["Report"](target, log)
132 # append report to results tuple
138 # make a note when the test crashed
139 end_time = time.time()
141 # mark test as failed
142 result = (-1, "Fail [Crash]", test["Name"],
143 end_time - start_time, logfile.getvalue(), None)
145 # append the results to the results list
146 results.append(result)
148 # regardless of whether test has crashed, try quitting it
150 child.sendline("quit")
152 # if the test crashed, just do nothing instead
157 # return test results
161 # class representing an instance of autotests run
162 class AutotestRunner:
164 parallel_test_groups = []
165 non_parallel_test_groups = []
176 def __init__(self, cmdline, target, blacklist, whitelist):
177 self.cmdline = cmdline
179 self.binary = cmdline.split()[0]
180 self.blacklist = blacklist
181 self.whitelist = whitelist
185 logfile = "%s.log" % target
186 csvfile = "%s.csv" % target
188 self.logfile = open(logfile, "w")
189 csvfile = open(csvfile, "w")
190 self.csvwriter = csv.writer(csvfile)
192 # prepare results table
193 self.csvwriter.writerow(["test_name", "test_result", "result_str"])
195 # set up cmdline string
196 def __get_cmdline(self, test):
197 cmdline = self.cmdline
199 # append memory limitations for each test
200 # otherwise tests won't run in parallel
201 if "i686" not in self.target:
202 cmdline += " --socket-mem=%s" % test["Memory"]
204 # affinitize startup so that tests don't fail on i686
205 cmdline = "taskset 1 " + cmdline
206 cmdline += " -m " + str(sum(map(int, test["Memory"].split(","))))
208 # set group prefix for autotest group
209 # otherwise they won't run in parallel
210 cmdline += " --file-prefix=%s" % test["Prefix"]
214 def add_parallel_test_group(self, test_group):
215 self.parallel_test_groups.append(test_group)
217 def add_non_parallel_test_group(self, test_group):
218 self.non_parallel_test_groups.append(test_group)
220 def __process_results(self, results):
221 # this iterates over individual test results
222 for i, result in enumerate(results):
224 # increase total number of tests that were run
225 # do not include "start" test
229 # unpack result tuple
230 test_result, result_str, test_name, \
231 test_time, log, report = result
234 cur_time = time.time()
235 total_time = int(cur_time - self.start)
237 # print results, test run time and total time since start
238 result = ("%s:" % test_name).ljust(30)
239 result += result_str.ljust(29)
240 result += "[%02dm %02ds]" % (test_time / 60, test_time % 60)
242 # don't print out total time every line, it's the same anyway
243 if i == len(results) - 1:
245 "[%02dm %02ds]" % (total_time / 60, total_time % 60))
249 # if test failed and it wasn't a "start" test
250 if test_result < 0 and not i == 0:
254 self.log_buffers.append(log)
256 # create report if it exists
259 f = open("%s_%s_report.rst" %
260 (self.target, test_name), "w")
262 print("Report for %s could not be created!" % test_name)
267 # write test result to CSV file
269 self.csvwriter.writerow([test_name, test_result, result_str])
271 # this function checks individual test and decides if this test should be in
272 # the group by comparing it against whitelist/blacklist. it also checks if
273 # the test is compiled into the binary, and marks it as skipped if necessary
274 def __filter_test(self, test):
275 test_cmd = test["Command"]
278 # dump tests are specified in full e.g. "Dump_mempool"
279 if "_autotest" in test_id:
280 test_id = test_id[:-len("_autotest")]
282 # filter out blacklisted/whitelisted tests
283 if self.blacklist and test_id in self.blacklist:
285 if self.whitelist and test_id not in self.whitelist:
288 # if test wasn't compiled in, remove it as well
290 # parse the binary for available test commands
291 stripped = 'not stripped' not in \
292 subprocess.check_output(['file', self.binary])
294 symbols = subprocess.check_output(['nm',
295 self.binary]).decode('utf-8')
296 avail_cmds = re.findall('test_register_(\w+)', symbols)
298 if test_cmd not in avail_cmds:
300 result = 0, "Skipped [Not compiled]", test_id, 0, "", None
301 self.skipped.append(tuple(result))
306 def __filter_group(self, group):
307 group["Tests"] = list(filter(self.__filter_test, group["Tests"]))
308 return len(group["Tests"]) > 0
310 # iterate over test groups and run tests associated with them
311 def run_all_tests(self):
313 # for each test group, check all tests against the filter, then remove
314 # all groups that don't have any tests
315 self.parallel_test_groups = list(
316 filter(self.__filter_group,
317 self.parallel_test_groups)
319 self.non_parallel_test_groups = list(
320 filter(self.__filter_group,
321 self.non_parallel_test_groups)
324 # create a pool of worker threads
325 pool = multiprocessing.Pool(processes=1)
329 # whatever happens, try to save as much logs as possible
332 # create table header
334 print("Test name".ljust(30) + "Test result".ljust(29) +
335 "Test".center(9) + "Total".center(9))
338 # print out skipped autotests if there were any
339 if len(self.skipped):
340 print("Skipped autotests:")
342 # print out any skipped tests
343 for result in self.skipped:
344 # unpack result tuple
345 test_result, result_str, test_name, _, _, _ = result
346 self.csvwriter.writerow([test_name, test_result,
349 t = ("%s:" % test_name).ljust(30)
350 t += result_str.ljust(29)
355 # make a note of tests start time
356 self.start = time.time()
358 print("Parallel autotests:")
359 # assign worker threads to run test groups
360 for test_group in self.parallel_test_groups:
361 result = pool.apply_async(run_test_group,
362 [self.__get_cmdline(test_group),
365 results.append(result)
367 # iterate while we have group execution results to get
368 while len(results) > 0:
370 # iterate over a copy to be able to safely delete results
371 # this iterates over a list of group results
372 for group_result in results[:]:
374 # if the thread hasn't finished yet, continue
375 if not group_result.ready():
378 res = group_result.get()
380 self.__process_results(res)
382 # remove result from results list once we're done with it
383 results.remove(group_result)
385 print("Non-parallel autotests:")
386 # run non_parallel tests. they are run one by one, synchronously
387 for test_group in self.non_parallel_test_groups:
388 group_result = run_test_group(
389 self.__get_cmdline(test_group), self.target, test_group)
391 self.__process_results(group_result)
394 cur_time = time.time()
395 total_time = int(cur_time - self.start)
399 print("Total run time: %02dm %02ds" % (total_time / 60,
402 print("Number of failed tests: %s" % str(self.fails))
404 # write summary to logfile
405 self.logfile.write("Summary\n")
406 self.logfile.write("Target: ".ljust(15) + "%s\n" % self.target)
407 self.logfile.write("Tests: ".ljust(15) + "%i\n" % self.n_tests)
408 self.logfile.write("Failed tests: ".ljust(
409 15) + "%i\n" % self.fails)
411 print("Exception occurred")
412 print(sys.exc_info())
415 # drop logs from all executions to a logfile
416 for buf in self.log_buffers:
417 self.logfile.write(buf.replace("\r", ""))