Allow a port to run tests with a custom device setup
[WebKit-https.git] / Tools / Scripts / webkitpy / layout_tests / views / printing.py
1 # Copyright (C) 2010, 2012 Google Inc. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or without
4 # modification, are permitted provided that the following conditions are
5 # met:
6 #
7 #     * Redistributions of source code must retain the above copyright
8 # notice, this list of conditions and the following disclaimer.
9 #     * Redistributions in binary form must reproduce the above
10 # copyright notice, this list of conditions and the following disclaimer
11 # in the documentation and/or other materials provided with the
12 # distribution.
13 #     * Neither the name of Google Inc. nor the names of its
14 # contributors may be used to endorse or promote products derived from
15 # this software without specific prior written permission.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 """Package that handles non-debug, non-file output for run-webkit-tests."""
30
31 import math
32 import optparse
33
34 from webkitpy.tool import grammar
35 from webkitpy.layout_tests.models import test_expectations
36 from webkitpy.layout_tests.models.test_expectations import TestExpectations, TestExpectationParser
37 from webkitpy.layout_tests.views.metered_stream import MeteredStream
38
39
40 NUM_SLOW_TESTS_TO_LOG = 10
41
42
43 def print_options():
44     return [
45         optparse.make_option('-q', '--quiet', action='store_true', default=False,
46                              help='run quietly (errors, warnings, and progress only)'),
47         optparse.make_option('-v', '--verbose', action='store_true', default=False,
48                              help='print a summarized result for every test (one line per test)'),
49         optparse.make_option('--details', action='store_true', default=False,
50                              help='print detailed results for every test'),
51         optparse.make_option('--debug-rwt-logging', action='store_true', default=False,
52                              help='print timestamps and debug information for run-webkit-tests itself'),
53     ]
54
55
56 class Printer(object):
57     """Class handling all non-debug-logging printing done by run-webkit-tests."""
58
59     def __init__(self, port, options, regular_output, logger=None):
60         self.num_started = 0
61         self.num_tests = 0
62         self._port = port
63         self._options = options
64         self._meter = MeteredStream(regular_output, options.debug_rwt_logging, logger=logger,
65                                     number_of_columns=self._port.host.platform.terminal_width())
66         self._running_tests = []
67         self._completed_tests = []
68
69     def cleanup(self):
70         self._meter.cleanup()
71
72     def __del__(self):
73         self.cleanup()
74
75     def print_config(self, results_directory):
76         self._print_default("Using port '%s'" % self._port.name())
77         self._print_default("Test configuration: %s" % self._port.test_configuration())
78         self._print_default("Placing test results in %s" % results_directory)
79
80         # FIXME: should these options be in printing_options?
81         if self._options.new_baseline:
82             self._print_default("Placing new baselines in %s" % self._port.baseline_path())
83
84         fs = self._port.host.filesystem
85         fallback_path = [fs.relpath(x, self._port.layout_tests_dir()).replace("../", "") for x in self._port.baseline_search_path()]
86         self._print_default("Baseline search path: %s -> generic" % " -> ".join(fallback_path))
87
88         self._print_default("Using %s build" % self._options.configuration)
89         if self._options.pixel_tests:
90             self._print_default("Pixel tests enabled")
91         else:
92             self._print_default("Pixel tests disabled")
93
94         self._print_default("Regular timeout: %s, slow test timeout: %s" %
95                   (self._options.time_out_ms, self._options.slow_time_out_ms))
96
97         self._print_default('Command line: ' + ' '.join(self._port.driver_cmd_line()))
98         self._print_default('')
99
100     def print_found(self, num_all_test_files, num_to_run, repeat_each, iterations):
101         found_str = 'Found %s; running %d' % (grammar.pluralize(num_all_test_files, "test"), num_to_run)
102         if repeat_each * iterations > 1:
103             found_str += ' (%s each: --repeat-each=%d --iterations=%d)' % (grammar.pluralize(repeat_each * iterations, "time"), repeat_each, iterations)
104         found_str += ', skipping %d' % (num_all_test_files - num_to_run)
105         self._print_default(found_str + '.')
106
107     def print_expected(self, run_results, tests_with_result_type_callback):
108         self._print_expected_results_of_type(run_results, test_expectations.PASS, "passes", tests_with_result_type_callback)
109         self._print_expected_results_of_type(run_results, test_expectations.FAIL, "failures", tests_with_result_type_callback)
110         self._print_expected_results_of_type(run_results, test_expectations.FLAKY, "flaky", tests_with_result_type_callback)
111         self._print_debug('')
112
113     def print_workers_and_shards(self, num_workers, num_shards):
114         driver_name = self._port.driver_name()
115
116         device_suffix = ' for device "{}"'.format(self._options.device_class) if self._options.device_class else ''
117         if num_workers == 1:
118             self._print_default('Running 1 {}{}.'.format(driver_name, device_suffix))
119             self._print_debug('({}).'.format(grammar.pluralize(num_shards, "shard")))
120         else:
121             self._print_default('Running {} in parallel{}.'.format(grammar.pluralize(num_workers, driver_name), device_suffix))
122             self._print_debug('({} shards).'.format(num_shards))
123         self._print_default('')
124
125     def _print_expected_results_of_type(self, run_results, result_type, result_type_str, tests_with_result_type_callback):
126         tests = tests_with_result_type_callback(result_type)
127         now = run_results.tests_by_timeline[test_expectations.NOW]
128         wontfix = run_results.tests_by_timeline[test_expectations.WONTFIX]
129
130         # We use a fancy format string in order to print the data out in a
131         # nicely-aligned table.
132         fmtstr = ("Expect: %%5d %%-8s (%%%dd now, %%%dd wontfix)"
133                   % (self._num_digits(now), self._num_digits(wontfix)))
134         self._print_debug(fmtstr % (len(tests), result_type_str, len(tests & now), len(tests & wontfix)))
135
136     def _num_digits(self, num):
137         ndigits = 1
138         if len(num):
139             ndigits = int(math.log10(len(num))) + 1
140         return ndigits
141
142     def print_results(self, run_time, run_results, summarized_results):
143         self._print_timing_statistics(run_time, run_results)
144         self._print_one_line_summary(run_results.total - run_results.expected_skips,
145                                      run_results.expected - run_results.expected_skips,
146                                      run_results.unexpected)
147
148     def _print_timing_statistics(self, total_time, run_results):
149         self._print_debug("Test timing:")
150         self._print_debug("  %6.2f total testing time" % total_time)
151         self._print_debug("")
152
153         self._print_worker_statistics(run_results, int(self._options.child_processes))
154         self._print_aggregate_test_statistics(run_results)
155         self._print_individual_test_times(run_results)
156         self._print_directory_timings(run_results)
157
158     def _print_worker_statistics(self, run_results, num_workers):
159         self._print_debug("Thread timing:")
160         stats = {}
161         cuml_time = 0
162         for result in run_results.results_by_name.values():
163             stats.setdefault(result.worker_name, {'num_tests': 0, 'total_time': 0})
164             stats[result.worker_name]['num_tests'] += 1
165             stats[result.worker_name]['total_time'] += result.total_run_time
166             cuml_time += result.total_run_time
167
168         for worker_name in stats:
169             self._print_debug("    %10s: %5d tests, %6.2f secs" % (worker_name, stats[worker_name]['num_tests'], stats[worker_name]['total_time']))
170         self._print_debug("   %6.2f cumulative, %6.2f optimal" % (cuml_time, cuml_time / num_workers))
171         self._print_debug("")
172
173     def _print_aggregate_test_statistics(self, run_results):
174         times_for_dump_render_tree = [result.test_run_time for result in run_results.results_by_name.values()]
175         self._print_statistics_for_test_timings("PER TEST TIME IN TESTSHELL (seconds):", times_for_dump_render_tree)
176
177     def _print_individual_test_times(self, run_results):
178         # Reverse-sort by the time spent in DumpRenderTree.
179
180         individual_test_timings = sorted(run_results.results_by_name.values(), key=lambda result: result.test_run_time, reverse=True)
181         num_printed = 0
182         slow_tests = []
183         timeout_or_crash_tests = []
184         unexpected_slow_tests = []
185         for test_tuple in individual_test_timings:
186             test_name = test_tuple.test_name
187             is_timeout_crash_or_slow = False
188             if test_name in run_results.slow_tests:
189                 is_timeout_crash_or_slow = True
190                 slow_tests.append(test_tuple)
191
192             if test_name in run_results.failures_by_name:
193                 result = run_results.results_by_name[test_name].type
194                 if (result == test_expectations.TIMEOUT or
195                     result == test_expectations.CRASH):
196                     is_timeout_crash_or_slow = True
197                     timeout_or_crash_tests.append(test_tuple)
198
199             if (not is_timeout_crash_or_slow and num_printed < NUM_SLOW_TESTS_TO_LOG):
200                 num_printed = num_printed + 1
201                 unexpected_slow_tests.append(test_tuple)
202
203         self._print_debug("")
204         self._print_test_list_timing("%s slowest tests that are not marked as SLOW and did not timeout/crash:" %
205             NUM_SLOW_TESTS_TO_LOG, unexpected_slow_tests)
206         self._print_debug("")
207         self._print_test_list_timing("Tests marked as SLOW:", slow_tests)
208         self._print_debug("")
209         self._print_test_list_timing("Tests that timed out or crashed:", timeout_or_crash_tests)
210         self._print_debug("")
211
212     def _print_test_list_timing(self, title, test_list):
213         self._print_debug(title)
214         for test_tuple in test_list:
215             test_run_time = round(test_tuple.test_run_time, 1)
216             self._print_debug("  %s took %s seconds" % (test_tuple.test_name, test_run_time))
217
218     def _print_directory_timings(self, run_results):
219         stats = {}
220         for result in run_results.results_by_name.values():
221             stats.setdefault(result.shard_name, {'num_tests': 0, 'total_time': 0})
222             stats[result.shard_name]['num_tests'] += 1
223             stats[result.shard_name]['total_time'] += result.total_run_time
224
225         timings = []
226         for directory in stats:
227             timings.append((directory, round(stats[directory]['total_time'], 1), stats[directory]['num_tests']))
228         timings.sort()
229
230         self._print_debug("Time to process slowest subdirectories:")
231         min_seconds_to_print = 10
232         for timing in timings:
233             if timing[0] > min_seconds_to_print:
234                 self._print_debug("  %s took %s seconds to run %s tests." % timing)
235         self._print_debug("")
236
237     def _print_statistics_for_test_timings(self, title, timings):
238         self._print_debug(title)
239         timings.sort()
240
241         num_tests = len(timings)
242         if not num_tests:
243             return
244         percentile90 = timings[int(.9 * num_tests)]
245         percentile99 = timings[int(.99 * num_tests)]
246
247         if num_tests % 2 == 1:
248             median = timings[((num_tests - 1) / 2) - 1]
249         else:
250             lower = timings[num_tests / 2 - 1]
251             upper = timings[num_tests / 2]
252             median = (float(lower + upper)) / 2
253
254         mean = sum(timings) / num_tests
255
256         for timing in timings:
257             sum_of_deviations = math.pow(timing - mean, 2)
258
259         std_deviation = math.sqrt(sum_of_deviations / num_tests)
260         self._print_debug("  Median:          %6.3f" % median)
261         self._print_debug("  Mean:            %6.3f" % mean)
262         self._print_debug("  90th percentile: %6.3f" % percentile90)
263         self._print_debug("  99th percentile: %6.3f" % percentile99)
264         self._print_debug("  Standard dev:    %6.3f" % std_deviation)
265         self._print_debug("")
266
267     def _print_one_line_summary(self, total, expected, unexpected):
268         incomplete = total - expected - unexpected
269         incomplete_str = ''
270         if incomplete:
271             self._print_default("")
272             incomplete_str = " (%d didn't run)" % incomplete
273
274         if self._options.verbose or self._options.debug_rwt_logging or unexpected:
275             self.writeln("")
276
277         summary = ''
278         if unexpected == 0:
279             if expected == total:
280                 if expected > 1:
281                     summary = "All %d tests ran as expected." % expected
282                 else:
283                     summary = "The test ran as expected."
284             else:
285                 summary = "%s ran as expected%s." % (grammar.pluralize(expected, "test"), incomplete_str)
286         else:
287             summary = "%s ran as expected, %d didn't%s:" % (grammar.pluralize(expected, "test"), unexpected, incomplete_str)
288
289         self._print_quiet(summary)
290         self._print_quiet("")
291
292     def _test_status_line(self, test_name, suffix, truncate=True):
293         format_string = '[%d/%d] %s%s'
294         status_line = format_string % (self.num_started, self.num_tests, test_name, suffix)
295         if truncate and len(status_line) > self._meter.number_of_columns():
296             overflow_columns = len(status_line) - self._meter.number_of_columns()
297             ellipsis = '...'
298             if len(test_name) < overflow_columns + len(ellipsis) + 2:
299                 # We don't have enough space even if we elide, just show the test filename.
300                 fs = self._port.host.filesystem
301                 test_name = fs.split(test_name)[1]
302             else:
303                 new_length = len(test_name) - overflow_columns - len(ellipsis)
304                 prefix = int(new_length / 2)
305                 test_name = test_name[:prefix] + ellipsis + test_name[-(new_length - prefix):]
306         return format_string % (self.num_started, self.num_tests, test_name, suffix)
307
308     def print_started_test(self, test_name):
309         self.num_started += 1
310         self._running_tests.append(test_name)
311         if len(self._running_tests) > 1:
312             suffix = ' (+%d)' % (len(self._running_tests) - 1)
313         else:
314             suffix = ''
315         if self._options.verbose:
316             write = self._meter.write_update
317         else:
318             write = self._meter.write_throttled_update
319         write(self._test_status_line(test_name, suffix))
320
321     def print_finished_test(self, result, expected, exp_str, got_str):
322         test_name = result.test_name
323
324         result_message = self._result_message(result.type, result.failures, expected, self._options.verbose)
325
326         if self._options.details:
327             self._print_test_trace(result, exp_str, got_str)
328         elif (self._options.verbose and not self._options.debug_rwt_logging) or not expected:
329             self.writeln(self._test_status_line(test_name, result_message, truncate=False))
330         elif self.num_started == self.num_tests:
331             self._meter.write_update('')
332         else:
333             if test_name == self._running_tests[0]:
334                 self._completed_tests.insert(0, [test_name, result_message])
335             else:
336                 self._completed_tests.append([test_name, result_message])
337
338             for test_name, result_message in self._completed_tests:
339                 self._meter.write_throttled_update(self._test_status_line(test_name, result_message, truncate=False))
340             self._completed_tests = []
341         self._running_tests.remove(test_name)
342
343     def _result_message(self, result_type, failures, expected, verbose):
344         exp_string = ' unexpectedly' if not expected else ''
345         if result_type == test_expectations.PASS:
346             return ' passed%s' % exp_string
347         else:
348             return ' failed%s (%s)' % (exp_string, ', '.join(failure.message() for failure in failures))
349
350     def _print_test_trace(self, result, exp_str, got_str):
351         test_name = result.test_name
352         self._print_default(self._test_status_line(test_name, ''))
353
354         for extension in ('.txt', '.png', '.wav', '.webarchive'):
355             self._print_baseline(test_name, extension)
356
357         self._print_default('  exp: %s' % exp_str)
358         self._print_default('  got: %s' % got_str)
359         self._print_default(' took: %-.3f' % result.test_run_time)
360         self._print_default('')
361
362     def _print_baseline(self, test_name, extension):
363         baseline = self._port.expected_filename(test_name, extension)
364         if self._port._filesystem.exists(baseline):
365             relpath = self._port.relative_test_filename(baseline)
366         else:
367             relpath = '<none>'
368         self._print_default('  %s: %s' % (extension[1:], relpath))
369
370     def _print_quiet(self, msg):
371         self.writeln(msg)
372
373     def _print_default(self, msg):
374         if not self._options.quiet:
375             self.writeln(msg)
376
377     def _print_debug(self, msg):
378         if self._options.debug_rwt_logging:
379             self.writeln(msg)
380
381     def write_update(self, msg):
382         self._meter.write_update(msg)
383
384     def writeln(self, msg):
385         self._meter.writeln(msg)
386
387     def flush(self):
388         self._meter.flush()