test: make autotest runner python 2/3 compliant
[dpdk.git] / test / test / autotest_runner.py
1 # SPDX-License-Identifier: BSD-3-Clause
2 # Copyright(c) 2010-2014 Intel Corporation
3
4 # The main logic behind running autotests in parallel
5
6 from __future__ import print_function
7 import StringIO
8 import csv
9 import multiprocessing
10 import pexpect
11 import re
12 import subprocess
13 import sys
14 import time
15
16 # wait for prompt
17
18
19 def wait_prompt(child):
20     try:
21         child.sendline()
22         result = child.expect(["RTE>>", pexpect.TIMEOUT, pexpect.EOF],
23                               timeout=120)
24     except:
25         return False
26     if result == 0:
27         return True
28     else:
29         return False
30
31 # run a test group
32 # each result tuple in results list consists of:
33 #   result value (0 or -1)
34 #   result string
35 #   test name
36 #   total test run time (double)
37 #   raw test log
38 #   test report (if not available, should be None)
39 #
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).
43
44
45 def run_test_group(cmdline, target, test_group):
46     results = []
47     child = None
48     start_time = time.time()
49     startuplog = None
50
51     # run test app
52     try:
53         # prepare logging of init
54         startuplog = StringIO.StringIO()
55
56         print("\n%s %s\n" % ("=" * 20, test_group["Prefix"]), file=startuplog)
57         print("\ncmdline=%s" % cmdline, file=startuplog)
58
59         child = pexpect.spawn(cmdline, logfile=startuplog)
60
61         # wait for target to boot
62         if not wait_prompt(child):
63             child.close()
64
65             results.append((-1,
66                             "Fail [No prompt]",
67                             "Start %s" % test_group["Prefix"],
68                             time.time() - start_time,
69                             startuplog.getvalue(),
70                             None))
71
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))
76             # exit test
77             return results
78
79     except:
80         results.append((-1,
81                         "Fail [Can't run]",
82                         "Start %s" % test_group["Prefix"],
83                         time.time() - start_time,
84                         startuplog.getvalue(),
85                         None))
86
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))
91         # exit test
92         return results
93
94     # startup was successful
95     results.append((0, "Success", "Start %s" % test_group["Prefix"],
96                     time.time() - start_time, startuplog.getvalue(), None))
97
98     # parse the binary for available test commands
99     binary = cmdline.split()[0]
100     stripped = 'not stripped' not in subprocess.check_output(['file', binary])
101     if not stripped:
102         symbols = subprocess.check_output(['nm', binary]).decode('utf-8')
103         avail_cmds = re.findall('test_register_(\w+)', symbols)
104
105     # run all tests in test group
106     for test in test_group["Tests"]:
107
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
113
114         result = ()
115
116         # make a note when the test started
117         start_time = time.time()
118
119         try:
120             # print test name to log buffer
121             print("\n%s %s\n" % ("-" * 20, test["Name"]), file=logfile)
122
123             # run test function associated with the test
124             if stripped or test["Command"] in avail_cmds:
125                 result = test["Func"](child, test["Command"])
126             else:
127                 result = (0, "Skipped [Not Available]")
128
129             # make a note when the test was finished
130             end_time = time.time()
131
132             log = logfile.getvalue()
133
134             # append test data to the result tuple
135             result += (test["Name"], end_time - start_time, log)
136
137             # call report function, if any defined, and supply it with
138             # target and complete log for test run
139             if test["Report"]:
140                 report = test["Report"](target, log)
141
142                 # append report to results tuple
143                 result += (report,)
144             else:
145                 # report is None
146                 result += (None,)
147         except:
148             # make a note when the test crashed
149             end_time = time.time()
150
151             # mark test as failed
152             result = (-1, "Fail [Crash]", test["Name"],
153                       end_time - start_time, logfile.getvalue(), None)
154         finally:
155             # append the results to the results list
156             results.append(result)
157
158     # regardless of whether test has crashed, try quitting it
159     try:
160         child.sendline("quit")
161         child.close()
162     # if the test crashed, just do nothing instead
163     except:
164         # nop
165         pass
166
167     # return test results
168     return results
169
170
171 # class representing an instance of autotests run
172 class AutotestRunner:
173     cmdline = ""
174     parallel_test_groups = []
175     non_parallel_test_groups = []
176     logfile = None
177     csvwriter = None
178     target = ""
179     start = None
180     n_tests = 0
181     fails = 0
182     log_buffers = []
183     blacklist = []
184     whitelist = []
185
186     def __init__(self, cmdline, target, blacklist, whitelist):
187         self.cmdline = cmdline
188         self.target = target
189         self.blacklist = blacklist
190         self.whitelist = whitelist
191
192         # log file filename
193         logfile = "%s.log" % target
194         csvfile = "%s.csv" % target
195
196         self.logfile = open(logfile, "w")
197         csvfile = open(csvfile, "w")
198         self.csvwriter = csv.writer(csvfile)
199
200         # prepare results table
201         self.csvwriter.writerow(["test_name", "test_result", "result_str"])
202
203     # set up cmdline string
204     def __get_cmdline(self, test):
205         cmdline = self.cmdline
206
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"]
211         else:
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(","))))
215
216         # set group prefix for autotest group
217         # otherwise they won't run in parallel
218         cmdline += " --file-prefix=%s" % test["Prefix"]
219
220         return cmdline
221
222     def add_parallel_test_group(self, test_group):
223         self.parallel_test_groups.append(test_group)
224
225     def add_non_parallel_test_group(self, test_group):
226         self.non_parallel_test_groups.append(test_group)
227
228     def __process_results(self, results):
229         # this iterates over individual test results
230         for i, result in enumerate(results):
231
232             # increase total number of tests that were run
233             # do not include "start" test
234             if i > 0:
235                 self.n_tests += 1
236
237             # unpack result tuple
238             test_result, result_str, test_name, \
239                 test_time, log, report = result
240
241             # get total run time
242             cur_time = time.time()
243             total_time = int(cur_time - self.start)
244
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)
249
250             # don't print out total time every line, it's the same anyway
251             if i == len(results) - 1:
252                 print(result +
253                       "[%02dm %02ds]" % (total_time / 60, total_time % 60))
254             else:
255                 print(result)
256
257             # if test failed and it wasn't a "start" test
258             if test_result < 0 and not i == 0:
259                 self.fails += 1
260
261             # collect logs
262             self.log_buffers.append(log)
263
264             # create report if it exists
265             if report:
266                 try:
267                     f = open("%s_%s_report.rst" %
268                              (self.target, test_name), "w")
269                 except IOError:
270                     print("Report for %s could not be created!" % test_name)
271                 else:
272                     with f:
273                         f.write(report)
274
275             # write test result to CSV file
276             if i != 0:
277                 self.csvwriter.writerow([test_name, test_result, result_str])
278
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 = []
283
284         # filter out tests from parallel test groups
285         for i, test_group in enumerate(test_groups):
286
287             # iterate over a copy so that we could safely delete individual
288             # tests
289             for test in test_group["Tests"][:]:
290                 test_id = test["Command"]
291
292                 # dump tests are specified in full e.g. "Dump_mempool"
293                 if "_autotest" in test_id:
294                     test_id = test_id[:-len("_autotest")]
295
296                 # filter out blacklisted/whitelisted tests
297                 if self.blacklist and test_id in self.blacklist:
298                     test_group["Tests"].remove(test)
299                     continue
300                 if self.whitelist and test_id not in self.whitelist:
301                     test_group["Tests"].remove(test)
302                     continue
303
304             # modify or remove original group
305             if len(test_group["Tests"]) > 0:
306                 test_groups[i] = test_group
307             else:
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)
312
313         # remove test groups that need to be removed
314         for i in groups_to_remove:
315             del test_groups[i]
316
317         return test_groups
318
319     # iterate over test groups and run tests associated with them
320     def run_all_tests(self):
321         # filter groups
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)
326
327         # create a pool of worker threads
328         pool = multiprocessing.Pool(processes=1)
329
330         results = []
331
332         # whatever happens, try to save as much logs as possible
333         try:
334
335             # create table header
336             print("")
337             print("Test name".ljust(30) + "Test result".ljust(29) +
338                   "Test".center(9) + "Total".center(9))
339             print("=" * 80)
340
341             # make a note of tests start time
342             self.start = time.time()
343
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),
348                                            self.target,
349                                            test_group])
350                 results.append(result)
351
352             # iterate while we have group execution results to get
353             while len(results) > 0:
354
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[:]:
358
359                     # if the thread hasn't finished yet, continue
360                     if not group_result.ready():
361                         continue
362
363                     res = group_result.get()
364
365                     self.__process_results(res)
366
367                     # remove result from results list once we're done with it
368                     results.remove(group_result)
369
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)
374
375                 self.__process_results(group_result)
376
377             # get total run time
378             cur_time = time.time()
379             total_time = int(cur_time - self.start)
380
381             # print out summary
382             print("=" * 80)
383             print("Total run time: %02dm %02ds" % (total_time / 60,
384                                                    total_time % 60))
385             if self.fails != 0:
386                 print("Number of failed tests: %s" % str(self.fails))
387
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)
394         except:
395             print("Exception occurred")
396             print(sys.exc_info())
397             self.fails = 1
398
399         # drop logs from all executions to a logfile
400         for buf in self.log_buffers:
401             self.logfile.write(buf.replace("\r", ""))
402
403         return self.fails