progress.py 11.3 KB
Newer Older
1 2 3 4 5 6 7
# Copyright 2018 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import json
import os
import sys
8
import time
9 10

from . import base
11
from ..local import junit_output
12 13 14 15 16 17 18 19 20 21 22 23 24


def print_failure_header(test):
  if test.output_proc.negative:
    negative_marker = '[negative] '
  else:
    negative_marker = ''
  print "=== %(label)s %(negative)s===" % {
    'label': test,
    'negative': negative_marker,
  }


25 26 27 28 29 30 31 32 33
class TestsCounter(base.TestProcObserver):
  def __init__(self):
    super(TestsCounter, self).__init__()
    self.total = 0

  def _on_next_test(self, test):
    self.total += 1


34
class ResultsTracker(base.TestProcObserver):
35
  def __init__(self):
36
    super(ResultsTracker, self).__init__()
37 38
    self._requirement = base.DROP_OUTPUT

39 40 41 42 43 44 45 46
    self.failed = 0
    self.remaining = 0
    self.total = 0

  def _on_next_test(self, test):
    self.total += 1
    self.remaining += 1

47
  def _on_result_for(self, test, result):
48 49 50 51 52 53 54 55 56 57 58 59 60
    self.remaining -= 1
    if result.has_unexpected_output:
      self.failed += 1


class ProgressIndicator(base.TestProcObserver):
  def finished(self):
    pass


class SimpleProgressIndicator(ProgressIndicator):
  def __init__(self):
    super(SimpleProgressIndicator, self).__init__()
61
    self._requirement = base.DROP_PASS_OUTPUT
62 63 64 65 66 67 68

    self._failed = []
    self._total = 0

  def _on_next_test(self, test):
    self._total += 1

69 70
  def _on_result_for(self, test, result):
    # TODO(majeski): Support for dummy/grouped results
71
    if result.has_unexpected_output:
72
      self._failed.append((test, result))
73 74 75 76

  def finished(self):
    crashed = 0
    print
77
    for test, result in self._failed:
78
      print_failure_header(test)
79
      if result.output.stderr:
80
        print "--- stderr ---"
81 82
        print result.output.stderr.strip()
      if result.output.stdout:
83
        print "--- stdout ---"
84 85 86 87
        print result.output.stdout.strip()
      print "Command: %s" % result.cmd.to_string()
      if result.output.HasCrashed():
        print "exit code: %d" % result.output.exit_code
88 89
        print "--- CRASHED ---"
        crashed += 1
90
      if result.output.HasTimedOut():
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
        print "--- TIMEOUT ---"
    if len(self._failed) == 0:
      print "==="
      print "=== All tests succeeded"
      print "==="
    else:
      print
      print "==="
      print "=== %i tests failed" % len(self._failed)
      if crashed > 0:
        print "=== %i tests CRASHED" % crashed
      print "==="


class VerboseProgressIndicator(SimpleProgressIndicator):
106 107 108 109 110 111 112 113 114
  def __init__(self):
    super(VerboseProgressIndicator, self).__init__()
    self._last_printed_time = time.time()

  def _print(self, text):
    print text
    sys.stdout.flush()
    self._last_printed_time = time.time()

115 116 117
  def _on_result_for(self, test, result):
    super(VerboseProgressIndicator, self)._on_result_for(test, result)
    # TODO(majeski): Support for dummy/grouped results
118 119 120 121 122 123 124
    if result.has_unexpected_output:
      if result.output.HasCrashed():
        outcome = 'CRASH'
      else:
        outcome = 'FAIL'
    else:
      outcome = 'pass'
125
    self._print('Done running %s: %s' % (test, outcome))
126

127
  def _on_heartbeat(self):
128 129 130 131
    if time.time() - self._last_printed_time > 30:
      # Print something every 30 seconds to not get killed by an output
      # timeout.
      self._print('Still working...')
132 133 134 135 136 137 138


class DotsProgressIndicator(SimpleProgressIndicator):
  def __init__(self):
    super(DotsProgressIndicator, self).__init__()
    self._count = 0

139 140
  def _on_result_for(self, test, result):
    # TODO(majeski): Support for dummy/grouped results
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    self._count += 1
    if self._count > 1 and self._count % 50 == 1:
      sys.stdout.write('\n')
    if result.has_unexpected_output:
      if result.output.HasCrashed():
        sys.stdout.write('C')
        sys.stdout.flush()
      elif result.output.HasTimedOut():
        sys.stdout.write('T')
        sys.stdout.flush()
      else:
        sys.stdout.write('F')
        sys.stdout.flush()
    else:
      sys.stdout.write('.')
      sys.stdout.flush()


class CompactProgressIndicator(ProgressIndicator):
  def __init__(self, templates):
    super(CompactProgressIndicator, self).__init__()
162 163
    self._requirement = base.DROP_PASS_OUTPUT

164 165 166 167 168 169 170 171 172 173 174
    self._templates = templates
    self._last_status_length = 0
    self._start_time = time.time()

    self._total = 0
    self._passed = 0
    self._failed = 0

  def _on_next_test(self, test):
    self._total += 1

175 176
  def _on_result_for(self, test, result):
    # TODO(majeski): Support for dummy/grouped results
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    if result.has_unexpected_output:
      self._failed += 1
    else:
      self._passed += 1

    self._print_progress(str(test))
    if result.has_unexpected_output:
      output = result.output
      stdout = output.stdout.strip()
      stderr = output.stderr.strip()

      self._clear_line(self._last_status_length)
      print_failure_header(test)
      if len(stdout):
        print self._templates['stdout'] % stdout
      if len(stderr):
        print self._templates['stderr'] % stderr
194
      print "Command: %s" % result.cmd
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
      if output.HasCrashed():
        print "exit code: %d" % output.exit_code
        print "--- CRASHED ---"
      if output.HasTimedOut():
        print "--- TIMEOUT ---"

  def finished(self):
    self._print_progress('Done')
    print

  def _print_progress(self, name):
    self._clear_line(self._last_status_length)
    elapsed = time.time() - self._start_time
    if not self._total:
      progress = 0
    else:
      progress = (self._passed + self._failed) * 100 // self._total
    status = self._templates['status_line'] % {
      'passed': self._passed,
      'progress': progress,
      'failed': self._failed,
      'test': name,
      'mins': int(elapsed) / 60,
      'secs': int(elapsed) % 60
    }
    status = self._truncate(status, 78)
    self._last_status_length = len(status)
    print status,
    sys.stdout.flush()

  def _truncate(self, string, length):
    if length and len(string) > (length - 3):
      return string[:(length - 3)] + "..."
    else:
      return string

  def _clear_line(self, last_length):
    raise NotImplementedError()


class ColorProgressIndicator(CompactProgressIndicator):
  def __init__(self):
    templates = {
      'status_line': ("[%(mins)02i:%(secs)02i|"
                      "\033[34m%%%(progress) 4d\033[0m|"
                      "\033[32m+%(passed) 4d\033[0m|"
                      "\033[31m-%(failed) 4d\033[0m]: %(test)s"),
      'stdout': "\033[1m%s\033[0m",
      'stderr': "\033[31m%s\033[0m",
    }
    super(ColorProgressIndicator, self).__init__(templates)

  def _clear_line(self, last_length):
    print "\033[1K\r",


class MonochromeProgressIndicator(CompactProgressIndicator):
  def __init__(self):
    templates = {
      'status_line': ("[%(mins)02i:%(secs)02i|%%%(progress) 4d|"
                      "+%(passed) 4d|-%(failed) 4d]: %(test)s"),
      'stdout': '%s',
      'stderr': '%s',
    }
    super(MonochromeProgressIndicator, self).__init__(templates)

  def _clear_line(self, last_length):
    print ("\r" + (" " * last_length) + "\r"),


class JUnitTestProgressIndicator(ProgressIndicator):
  def __init__(self, junitout, junittestsuite):
    super(JUnitTestProgressIndicator, self).__init__()
268 269
    self._requirement = base.DROP_PASS_STDOUT

270 271 272 273 274 275
    self.outputter = junit_output.JUnitTestOutput(junittestsuite)
    if junitout:
      self.outfile = open(junitout, "w")
    else:
      self.outfile = sys.stdout

276 277
  def _on_result_for(self, test, result):
    # TODO(majeski): Support for dummy/grouped results
278 279 280 281 282 283 284 285 286
    fail_text = ""
    output = result.output
    if result.has_unexpected_output:
      stdout = output.stdout.strip()
      if len(stdout):
        fail_text += "stdout:\n%s\n" % stdout
      stderr = output.stderr.strip()
      if len(stderr):
        fail_text += "stderr:\n%s\n" % stderr
287
      fail_text += "Command: %s" % result.cmd.to_string()
288 289 290 291 292 293
      if output.HasCrashed():
        fail_text += "exit code: %d\n--- CRASHED ---" % output.exit_code
      if output.HasTimedOut():
        fail_text += "--- TIMEOUT ---"
    self.outputter.HasRunTest(
        test_name=str(test),
294
        test_cmd=result.cmd.to_string(relative=True),
295 296 297 298 299 300 301 302
        test_duration=output.duration,
        test_failure=fail_text)

  def finished(self):
    self.outputter.FinishAndWrite(self.outfile)
    if self.outfile != sys.stdout:
      self.outfile.close()

303 304

class JsonTestProgressIndicator(ProgressIndicator):
305
  def __init__(self, json_test_results, arch, mode):
306
    super(JsonTestProgressIndicator, self).__init__()
307 308 309 310 311 312
    # We want to drop stdout/err for all passed tests on the first try, but we
    # need to get outputs for all runs after the first one. To accommodate that,
    # reruns are set to keep the result no matter what requirement says, i.e.
    # keep_output set to True in the RerunProc.
    self._requirement = base.DROP_PASS_STDOUT

313 314 315 316 317 318
    self.json_test_results = json_test_results
    self.arch = arch
    self.mode = mode
    self.results = []
    self.tests = []

319
  def _on_result_for(self, test, result):
320 321 322 323 324 325 326 327 328 329
    if result.is_rerun:
      self.process_results(test, result.results)
    else:
      self.process_results(test, [result])

  def process_results(self, test, results):
    for run, result in enumerate(results):
      # TODO(majeski): Support for dummy/grouped results
      output = result.output
      # Buffer all tests for sorting the durations in the end.
330 331
      # TODO(machenbach): Running average + buffer only slowest 20 tests.
      self.tests.append((test, output.duration, result.cmd))
332 333 334 335 336 337 338 339 340

      # Omit tests that run as expected on the first try.
      # Everything that happens after the first run is included in the output
      # even if it flakily passes.
      if not result.has_unexpected_output and run == 0:
        continue

      self.results.append({
        "name": str(test),
341 342
        "flags": result.cmd.args,
        "command": result.cmd.to_string(relative=True),
343 344 345 346 347 348 349
        "run": run + 1,
        "stdout": output.stdout,
        "stderr": output.stderr,
        "exit_code": output.exit_code,
        "result": test.output_proc.get_outcome(output),
        "expected": test.expected_outcomes,
        "duration": output.duration,
350
        "random_seed": test.random_seed,
351 352 353
        "target_name": test.get_shell(),
        "variant": test.variant,
      })
354 355 356 357 358 359 360 361 362 363 364 365

  def finished(self):
    complete_results = []
    if os.path.exists(self.json_test_results):
      with open(self.json_test_results, "r") as f:
        # Buildbot might start out with an empty file.
        complete_results = json.loads(f.read() or "[]")

    duration_mean = None
    if self.tests:
      # Get duration mean.
      duration_mean = (
366
          sum(duration for (_, duration, cmd) in self.tests) /
367 368 369
          float(len(self.tests)))

    # Sort tests by duration.
370
    self.tests.sort(key=lambda (_, duration, cmd): duration, reverse=True)
371 372 373
    slowest_tests = [
      {
        "name": str(test),
374 375
        "flags": cmd.args,
        "command": cmd.to_string(relative=True),
376 377
        "duration": duration,
        "marked_slow": test.is_slow,
378
      } for (test, duration, cmd) in self.tests[:20]
379 380 381 382 383 384 385 386 387 388 389 390 391
    ]

    complete_results.append({
      "arch": self.arch,
      "mode": self.mode,
      "results": self.results,
      "slowest_tests": slowest_tests,
      "duration_mean": duration_mean,
      "test_total": len(self.tests),
    })

    with open(self.json_test_results, "w") as f:
      f.write(json.dumps(complete_results))