blob: 4f381bd6bc50f64b604f12fe33bce8fc2b6e7e16 [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ález45d49592023-08-11 15:22:04 +010054def analyze_coverage(results, outcomes, allow_list, full_coverage):
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:
Tomás González45d49592023-08-11 15:22:04 +010060 if full_coverage:
61 results.error('Test case not executed: {}', key)
62 else:
63 results.warning('Test case not executed: {}', key)
Tomás González2fdd5032023-08-23 16:43:26 +010064 elif hits != 0 and key in allow_list:
65 # Test Case should be removed from the allow list.
66 results.warning('Allow listed test case was executed: {}', key)
Gilles Peskine8d3c70a2020-06-25 18:37:43 +020067
Tomás González45d49592023-08-11 15:22:04 +010068def analyze_outcomes(outcomes, args):
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020069 """Run all analyses on the given outcome collection."""
70 results = Results()
Tomás González45d49592023-08-11 15:22:04 +010071 analyze_coverage(results, outcomes, args['allow_list'],
72 args['full_coverage'])
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020073 return results
74
75def read_outcome_file(outcome_file):
76 """Parse an outcome file and return an outcome collection.
77
78An outcome collection is a dictionary mapping keys to TestCaseOutcomes objects.
79The keys are the test suite name and the test case description, separated
80by a semicolon.
81"""
82 outcomes = {}
83 with open(outcome_file, 'r', encoding='utf-8') as input_file:
84 for line in input_file:
85 (platform, config, suite, case, result, _cause) = line.split(';')
86 key = ';'.join([suite, case])
87 setup = ';'.join([platform, config])
88 if key not in outcomes:
89 outcomes[key] = TestCaseOutcomes()
90 if result == 'PASS':
91 outcomes[key].successes.append(setup)
92 elif result == 'FAIL':
93 outcomes[key].failures.append(setup)
94 return outcomes
95
Tomás González2fdd5032023-08-23 16:43:26 +010096def do_analyze_coverage(outcome_file, args):
97 """Perform coverage analysis."""
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020098 outcomes = read_outcome_file(outcome_file)
Tomás González2fdd5032023-08-23 16:43:26 +010099 Results.log("\n*** Analyze coverage ***\n")
Tomás González45d49592023-08-11 15:22:04 +0100100 results = analyze_outcomes(outcomes, args)
Tomás González2fdd5032023-08-23 16:43:26 +0100101 return results.error_count == 0
102
103# List of tasks with a function that can handle this task and additional arguments if required
104TASKS = {
105 'analyze_coverage': {
106 'test_function': do_analyze_coverage,
107 'args': {
Tomás Gonzálezc8957332023-08-14 15:43:46 +0100108 'allow_list': [
109 # Algorithm not supported yet
110 'test_suite_psa_crypto_metadata;Asymmetric signature: pure EdDSA',
111 # Algorithm not supported yet
112 'test_suite_psa_crypto_metadata;Cipher: XTS',
113 ],
Tomás González45d49592023-08-11 15:22:04 +0100114 'full_coverage': False,
Tomás González2fdd5032023-08-23 16:43:26 +0100115 }
116 },
117}
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200118
119def main():
120 try:
121 parser = argparse.ArgumentParser(description=__doc__)
122 parser.add_argument('outcomes', metavar='OUTCOMES.CSV',
123 help='Outcome file to analyze')
Tomás González2fdd5032023-08-23 16:43:26 +0100124 parser.add_argument('task', default='all', nargs='?',
125 help='Analysis to be done. By default, run all tasks. '
126 'With one or more TASK, run only those. '
127 'TASK can be the name of a single task or '
128 'comma/space-separated list of tasks. ')
129 parser.add_argument('--list', action='store_true',
130 help='List all available tasks and exit.')
Tomás González45d49592023-08-11 15:22:04 +0100131 parser.add_argument('--require-full-coverage', action='store_true',
132 dest='full_coverage', help="Require all available "
133 "test cases to be executed and issue an error "
134 "otherwise. This flag is ignored if 'task' is "
135 "neither 'all' nor 'analyze_coverage'")
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200136 options = parser.parse_args()
Tomás González2fdd5032023-08-23 16:43:26 +0100137
138 if options.list:
139 for task in TASKS:
140 Results.log(task)
141 sys.exit(0)
142
143 result = True
144
145 if options.task == 'all':
146 tasks = TASKS.keys()
147 else:
148 tasks = re.split(r'[, ]+', options.task)
149
150 for task in tasks:
151 if task not in TASKS:
152 Results.log('Error: invalid task: {}'.format(task))
153 sys.exit(1)
154
Tomás González45d49592023-08-11 15:22:04 +0100155 TASKS['analyze_coverage']['args']['full_coverage'] = \
156 options.full_coverage
157
Tomás González2fdd5032023-08-23 16:43:26 +0100158 for task in TASKS:
159 if task in tasks:
160 if not TASKS[task]['test_function'](options.outcomes, TASKS[task]['args']):
161 result = False
162
163 if result is False:
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200164 sys.exit(1)
Tomás González2fdd5032023-08-23 16:43:26 +0100165 Results.log("SUCCESS :-)")
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200166 except Exception: # pylint: disable=broad-except
167 # Print the backtrace and exit explicitly with our chosen status.
168 traceback.print_exc()
169 sys.exit(120)
170
171if __name__ == '__main__':
172 main()