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