"""Every named test must have run and passed. Usage: required-tests-check.py [--status STATUS_FILE] NAMES_FILE EVENTS_FILE... NAMES_FILE holds one top-level test name per line (# starts a comment). A name whose comment says `nongating=#N` (an open issue) is non-gating: it runs and is reported like every other, but its failure does not fail the run; its line says NON-GATING and names the issue, and a failure-process exit after it is its own, not the binary's. A non-gating test that never ran still fails: a test that is not run is not reported. EVENTS_FILE is `go test -json` (or `go tool test2json`) output. A named test that skipped, failed, never started or never ended is a failure: a test that cannot start proves nothing, so it is not allowed to read as a pass. A name listed twice, or a test that passed in one stream and failed in another, is a failure too. A package-level failure event fails the run. STATUS_FILE (run-named-tests.sh) holds one line per named test, NAME and the exit status of the process that ran it. With it, a named test passes only if it also has exactly one line and that status is 0: a test that reports PASS and then fails, panics or hangs on its way out is not a pass. Prints one line per named test with its outcome and elapsed seconds, then the total. For every named test that did not pass, its own reported lines (the test's file:line messages with the last lines of each one's continuation, not the harness's log dumps) and its last lines follow the table, so a run's log carries its own reasons. Exit 0: every named test passed. 1: at least one did not. 2: usage or an unreadable input. """ import json import re import sys OWN = 12 # a failed test's own file:line messages shown (the last ones) TAIL = 5 # and its last output lines OWN_LINE = re.compile(r'^ [^ \t]+\.go:\d+: ') # the test's own t.Log/t.Error lines # Not reasons: the harness's cleanup headers (" log:", "---- log # tail ----") and the echo of a command that succeeded ("...: exit 0"). NOISE = re.compile(r' log:\s*$|---- .* ----\s*$|: exit 0\s*$') CONT = 20 # the last continuation lines shown of each own message CONT_LINE = re.compile(r'^ ') # a message's next line, as go test indents it def own_messages(text): """The test's own messages, each its file:line line and the last CONT of the continuation lines after it (a reason, such as a process's log tail, is often on those). A harness header's lines are not kept, nor its dump.""" msgs, cur = [], None for line in text: if OWN_LINE.match(line): cur = None if not NOISE.search(line): cur = [line, []] msgs.append(cur) elif cur is not None and CONT_LINE.match(line): cur[1].append(line) else: cur = None return [[head] + cont[-CONT:] for head, cont in msgs] NONGATING = re.compile(r'\bnongating=(#\d+)') def names_of(path): """The named tests, in order, and the non-gating ones with their issue.""" names, seen, nongating = [], set(), {} with open(path, encoding='utf-8') as f: for n, raw in enumerate(f, 1): line, _, comment = raw.partition('#') line = line.strip() if not line: continue m = NONGATING.search('#' + comment) if m: nongating[line] = m.group(1) elif 'nongating' in comment: raise ValueError('%s:%d: %r: nongating needs an issue, nongating=#N' % (path, n, raw.strip())) if not line.startswith('Test') or '/' in line or ' ' in line: raise ValueError('%s:%d: %r is not a top-level test name' % (path, n, line)) if line in seen: raise ValueError('%s:%d: %s is listed twice' % (path, n, line)) seen.add(line) names.append(line) if not names: raise ValueError('%s: no test names' % path) return names, nongating def statuses_of(path): """Test name -> list of exit statuses.""" out = {} with open(path, encoding='utf-8') as f: for n, raw in enumerate(f, 1): parts = raw.split() if not parts: continue if len(parts) != 2 or not parts[1].lstrip('-').isdigit(): raise ValueError('%s:%d: %r is not NAME EXIT_STATUS' % (path, n, raw.strip())) out.setdefault(parts[0], []).append(int(parts[1])) return out def outcomes(paths): """Test name -> list of (action, elapsed) for its terminal events, the names that started (action run), the package-level failure events (each with the test last started in its stream before it, or None), and each test's output.""" ends, started, pkg_fail, output = {}, set(), [], {} for path in paths: last = None with open(path, encoding='utf-8', errors='replace') as f: for raw in f: raw = raw.strip() if not raw.startswith('{'): continue # build output or a panic line between events try: ev = json.loads(raw) except ValueError: continue test = ev.get('Test') if not test: if ev.get('Action') == 'fail': pkg_fail.append(last) # the binary failed outside any test (or after one) continue # other package events; a subtest's name never matches a top-level one action = ev.get('Action') if action == 'output': output.setdefault(test.split('/')[0], []).append(ev.get('Output', '')) continue if action == 'run': started.add(test) if '/' not in test: last = test elif action in ('pass', 'fail', 'skip'): ends.setdefault(test, []).append((action, ev.get('Elapsed'))) return ends, started, pkg_fail, output def main(argv): args = argv[1:] status_file = None if args[:1] == ['--status']: if len(args) < 2: print(__doc__.strip().splitlines()[2], file=sys.stderr) return 2 status_file, args = args[1], args[2:] if len(args) < 2: print(__doc__.strip().splitlines()[2], file=sys.stderr) return 2 try: names, nongating = names_of(args[0]) ends, started, pkg_fail, output = outcomes(args[1:]) statuses = statuses_of(status_file) if status_file else None except (OSError, ValueError) as e: print('required-tests: %s' % e, file=sys.stderr) return 2 # A package-level failure right after a non-gating test is that test's # (each named test runs in its own process); any other fails the run. pkg_own = {} for after in pkg_fail: if after in nongating: pkg_own[after] = pkg_own.get(after, 0) + 1 pkg_fail = [a for a in pkg_fail if a not in nongating] bad, total, failed, ng_failed = 0, 0.0, [], 0 for name in names: got = ends.get(name, []) actions = {a for a, _ in got} secs = sum(e for _, e in got if isinstance(e, (int, float))) total += secs rcs = statuses.get(name, []) if statuses is not None else [0] if actions == {'pass'} and len(got) == 1 and rcs == [0] and not pkg_own.get(name): print('PASS %-70s %7.1fs' % (name, secs)) continue failed.append(name) issue = nongating.get(name) ran_at_all = bool(got) or name in started if issue and ran_at_all: ng_failed += 1 else: bad += 1 if actions == {'pass'} and len(got) == 1: why = ('NO EXIT STATUS' if not rcs else 'PASSED, THEN EXIT %s' % ','.join(str(r) for r in rcs)) elif not got: why = 'STARTED, NEVER ENDED' if name in started else 'NEVER RAN' elif len(got) > 1: why = 'RAN %d TIMES (%s)' % (len(got), ', '.join(a for a, _ in got)) else: why = got[0][0].upper() if pkg_own.get(name): why += ', THEN THE PROCESS FAILED' if issue and ran_at_all: print('%-8s %-70s %7.1fs' % ('FAIL', name, secs) + ' ' + why + ' NON-GATING (%s): reported, does not fail the run' % issue) else: print('%-8s %-70s %7.1fs' % ('FAIL', name, secs) + ' ' + why) for name in failed: text = ''.join(output.get(name, [])).splitlines() own = own_messages(text)[-OWN:] print('---- %s: its own messages (%d), then its last %d lines' % (name, len(own), min(TAIL, len(text)))) for line in [l for m in own for l in m] + [' ...'] + text[-TAIL:]: print(' ' + line[:300]) if pkg_fail: print('FAIL the test binary reported %d package-level failure(s)' % len(pkg_fail)) print('required-tests: %d named, %d not passed, %.1fs in named tests' % (len(names), bad, total)) if nongating: print('required-tests: %d non-gating (%s), %d of them failed' % (len(nongating), ', '.join('%s %s' % (n, nongating[n]) for n in names if n in nongating), ng_failed)) return 1 if bad or pkg_fail else 0 if __name__ == '__main__': sys.exit(main(sys.argv))