blob: 390cbbc72908874b6731adf868c71e40b38110e7 [file] [log] [blame]
Gilles Peskine15c2cbf2020-06-25 18:36:28 +02001#!/usr/bin/env python3
2
3"""Analyze the test outcomes from a full CI run.
4
5This script can also run on outcomes from a partial run, but the results are
6less likely to be useful.
7"""
8
9import argparse
10import sys
11import traceback
Tomás González2fdd5032023-08-23 16:43:26 +010012import re
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020013
Gilles Peskine8d3c70a2020-06-25 18:37:43 +020014import check_test_cases
15
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020016class Results:
17 """Process analysis results."""
18
19 def __init__(self):
20 self.error_count = 0
21 self.warning_count = 0
22
23 @staticmethod
24 def log(fmt, *args, **kwargs):
25 sys.stderr.write((fmt + '\n').format(*args, **kwargs))
26
27 def error(self, fmt, *args, **kwargs):
28 self.log('Error: ' + fmt, *args, **kwargs)
29 self.error_count += 1
30
31 def warning(self, fmt, *args, **kwargs):
32 self.log('Warning: ' + fmt, *args, **kwargs)
33 self.warning_count += 1
34
35class TestCaseOutcomes:
36 """The outcomes of one test case across many configurations."""
37 # pylint: disable=too-few-public-methods
38
39 def __init__(self):
Gilles Peskine3d863f22020-06-26 13:02:30 +020040 # Collect a list of witnesses of the test case succeeding or failing.
41 # Currently we don't do anything with witnesses except count them.
42 # The format of a witness is determined by the read_outcome_file
43 # function; it's the platform and configuration joined by ';'.
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020044 self.successes = []
45 self.failures = []
46
47 def hits(self):
48 """Return the number of times a test case has been run.
49
50 This includes passes and failures, but not skips.
51 """
52 return len(self.successes) + len(self.failures)
53
Tomás González2fdd5032023-08-23 16:43:26 +010054def analyze_coverage(results, outcomes, allow_list):
Gilles Peskine8d3c70a2020-06-25 18:37:43 +020055 """Check that all available test cases are executed at least once."""
Gilles Peskine0c2f8ee2022-01-07 15:58:38 +010056 available = check_test_cases.collect_available_test_cases()
Gilles Peskine8d3c70a2020-06-25 18:37:43 +020057 for key in available:
58 hits = outcomes[key].hits() if key in outcomes else 0
Tomás González2fdd5032023-08-23 16:43:26 +010059 if hits == 0 and key not in allow_list:
Gilles Peskine8d3c70a2020-06-25 18:37:43 +020060 # Make this a warning, not an error, as long as we haven't
61 # fixed this branch to have full coverage of test cases.
62 results.warning('Test case not executed: {}', key)
Tomás González2fdd5032023-08-23 16:43:26 +010063 elif hits != 0 and key in allow_list:
64 # Test Case should be removed from the allow list.
65 results.warning('Allow listed test case was executed: {}', key)
Gilles Peskine8d3c70a2020-06-25 18:37:43 +020066
Tomás González2fdd5032023-08-23 16:43:26 +010067def analyze_outcomes(outcomes, allow_list):
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020068 """Run all analyses on the given outcome collection."""
69 results = Results()
Tomás González2fdd5032023-08-23 16:43:26 +010070 analyze_coverage(results, outcomes, allow_list)
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020071 return results
72
73def read_outcome_file(outcome_file):
74 """Parse an outcome file and return an outcome collection.
75
76An outcome collection is a dictionary mapping keys to TestCaseOutcomes objects.
77The keys are the test suite name and the test case description, separated
78by a semicolon.
79"""
80 outcomes = {}
81 with open(outcome_file, 'r', encoding='utf-8') as input_file:
82 for line in input_file:
83 (platform, config, suite, case, result, _cause) = line.split(';')
84 key = ';'.join([suite, case])
85 setup = ';'.join([platform, config])
86 if key not in outcomes:
87 outcomes[key] = TestCaseOutcomes()
88 if result == 'PASS':
89 outcomes[key].successes.append(setup)
90 elif result == 'FAIL':
91 outcomes[key].failures.append(setup)
92 return outcomes
93
Tomás González2fdd5032023-08-23 16:43:26 +010094def do_analyze_coverage(outcome_file, args):
95 """Perform coverage analysis."""
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020096 outcomes = read_outcome_file(outcome_file)
Tomás González2fdd5032023-08-23 16:43:26 +010097 Results.log("\n*** Analyze coverage ***\n")
98 results = analyze_outcomes(outcomes, args['allow_list'])
99 return results.error_count == 0
100
101# List of tasks with a function that can handle this task and additional arguments if required
102TASKS = {
103 'analyze_coverage': {
104 'test_function': do_analyze_coverage,
105 'args': {
106 'allow_list': [],
107 }
108 },
109}
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200110
111def main():
112 try:
113 parser = argparse.ArgumentParser(description=__doc__)
114 parser.add_argument('outcomes', metavar='OUTCOMES.CSV',
115 help='Outcome file to analyze')
Tomás González2fdd5032023-08-23 16:43:26 +0100116 parser.add_argument('task', default='all', nargs='?',
117 help='Analysis to be done. By default, run all tasks. '
118 'With one or more TASK, run only those. '
119 'TASK can be the name of a single task or '
120 'comma/space-separated list of tasks. ')
121 parser.add_argument('--list', action='store_true',
122 help='List all available tasks and exit.')
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200123 options = parser.parse_args()
Tomás González2fdd5032023-08-23 16:43:26 +0100124
125 if options.list:
126 for task in TASKS:
127 Results.log(task)
128 sys.exit(0)
129
130 result = True
131
132 if options.task == 'all':
133 tasks = TASKS.keys()
134 else:
135 tasks = re.split(r'[, ]+', options.task)
136
137 for task in tasks:
138 if task not in TASKS:
139 Results.log('Error: invalid task: {}'.format(task))
140 sys.exit(1)
141
142 for task in TASKS:
143 if task in tasks:
144 if not TASKS[task]['test_function'](options.outcomes, TASKS[task]['args']):
145 result = False
146
147 if result is False:
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200148 sys.exit(1)
Tomás González2fdd5032023-08-23 16:43:26 +0100149 Results.log("SUCCESS :-)")
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200150 except Exception: # pylint: disable=broad-except
151 # Print the backtrace and exit explicitly with our chosen status.
152 traceback.print_exc()
153 sys.exit(120)
154
155if __name__ == '__main__':
156 main()