blob: 2dddf7a16ac5a41ec0a925784c35197a7dfda564 [file] [log] [blame]
Gilles Peskineba94b582019-09-16 19:18:40 +02001#!/usr/bin/env python3
2
3"""Sanity checks for test data.
Gilles Peskinebbb36642020-07-03 00:30:12 +02004
5This program contains a class for traversing test cases that can be used
6independently of the checks.
Gilles Peskineba94b582019-09-16 19:18:40 +02007"""
8
Bence Szépkúti1e148272020-08-07 13:07:28 +02009# Copyright The Mbed TLS Contributors
Gilles Peskineba94b582019-09-16 19:18:40 +020010# SPDX-License-Identifier: Apache-2.0
11#
12# Licensed under the Apache License, Version 2.0 (the "License"); you may
13# not use this file except in compliance with the License.
14# You may obtain a copy of the License at
15#
16# http://www.apache.org/licenses/LICENSE-2.0
17#
18# Unless required by applicable law or agreed to in writing, software
19# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
20# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21# See the License for the specific language governing permissions and
22# limitations under the License.
Gilles Peskineba94b582019-09-16 19:18:40 +020023
Gilles Peskine1fb7aea2019-12-02 14:26:04 +010024import argparse
Gilles Peskineba94b582019-09-16 19:18:40 +020025import glob
26import os
27import re
Yanray Wang23546932023-02-24 14:53:29 +080028import subprocess
Gilles Peskineba94b582019-09-16 19:18:40 +020029import sys
Tomás González754f8cd2023-08-17 15:11:10 +010030
Gilles Peskineba94b582019-09-16 19:18:40 +020031
32class Results:
Darryl Green18220612019-12-17 15:03:59 +000033 """Store file and line information about errors or warnings in test suites."""
Gilles Peskine1fb7aea2019-12-02 14:26:04 +010034
35 def __init__(self, options):
Gilles Peskineba94b582019-09-16 19:18:40 +020036 self.errors = 0
37 self.warnings = 0
Gilles Peskine1fb7aea2019-12-02 14:26:04 +010038 self.ignore_warnings = options.quiet
Gilles Peskineba94b582019-09-16 19:18:40 +020039
40 def error(self, file_name, line_number, fmt, *args):
41 sys.stderr.write(('{}:{}:ERROR:' + fmt + '\n').
42 format(file_name, line_number, *args))
43 self.errors += 1
44
45 def warning(self, file_name, line_number, fmt, *args):
Gilles Peskine1fb7aea2019-12-02 14:26:04 +010046 if not self.ignore_warnings:
47 sys.stderr.write(('{}:{}:Warning:' + fmt + '\n')
48 .format(file_name, line_number, *args))
49 self.warnings += 1
Gilles Peskineba94b582019-09-16 19:18:40 +020050
Gilles Peskine78c45db2020-06-25 16:34:11 +020051class TestDescriptionExplorer:
52 """An iterator over test cases with descriptions.
Gilles Peskined34e9e42020-06-25 16:16:25 +020053
Gilles Peskine78c45db2020-06-25 16:34:11 +020054The test cases that have descriptions are:
55* Individual unit tests (entries in a .data file) in test suites.
56* Individual test cases in ssl-opt.sh.
57
58This is an abstract class. To use it, derive a class that implements
59the process_test_case method, and call walk_all().
Gilles Peskined34e9e42020-06-25 16:16:25 +020060"""
Gilles Peskineba94b582019-09-16 19:18:40 +020061
Gilles Peskine78c45db2020-06-25 16:34:11 +020062 def process_test_case(self, per_file_state,
63 file_name, line_number, description):
64 """Process a test case.
Gilles Peskined34e9e42020-06-25 16:16:25 +020065
Gilles Peskinebbb36642020-07-03 00:30:12 +020066per_file_state: an object created by new_per_file_state() at the beginning
67 of each file.
Gilles Peskine78c45db2020-06-25 16:34:11 +020068file_name: a relative path to the file containing the test case.
69line_number: the line number in the given file.
70description: the test case description as a byte string.
Gilles Peskined34e9e42020-06-25 16:16:25 +020071"""
Gilles Peskine78c45db2020-06-25 16:34:11 +020072 raise NotImplementedError
Gilles Peskined34e9e42020-06-25 16:16:25 +020073
Gilles Peskinebbb36642020-07-03 00:30:12 +020074 def new_per_file_state(self):
Gilles Peskine78c45db2020-06-25 16:34:11 +020075 """Return a new per-file state object.
Gilles Peskined34e9e42020-06-25 16:16:25 +020076
Gilles Peskine78c45db2020-06-25 16:34:11 +020077The default per-file state object is None. Child classes that require per-file
78state may override this method.
Gilles Peskined34e9e42020-06-25 16:16:25 +020079"""
Gilles Peskine78c45db2020-06-25 16:34:11 +020080 #pylint: disable=no-self-use
81 return None
82
83 def walk_test_suite(self, data_file_name):
84 """Iterate over the test cases in the given unit test data file."""
85 in_paragraph = False
Gilles Peskinebbb36642020-07-03 00:30:12 +020086 descriptions = self.new_per_file_state() # pylint: disable=assignment-from-none
Gilles Peskine78c45db2020-06-25 16:34:11 +020087 with open(data_file_name, 'rb') as data_file:
88 for line_number, line in enumerate(data_file, 1):
89 line = line.rstrip(b'\r\n')
90 if not line:
91 in_paragraph = False
92 continue
93 if line.startswith(b'#'):
94 continue
95 if not in_paragraph:
96 # This is a test case description line.
97 self.process_test_case(descriptions,
98 data_file_name, line_number, line)
99 in_paragraph = True
100
Tomás González4a86da22023-09-01 17:41:16 +0100101 def collect_from_script(self, file_name):
102 """Collect the test cases in a script by calling its listing test cases
103option"""
Gilles Peskinebbb36642020-07-03 00:30:12 +0200104 descriptions = self.new_per_file_state() # pylint: disable=assignment-from-none
Tomás González4a86da22023-09-01 17:41:16 +0100105 listed = subprocess.check_output(['sh', file_name, '--list-test-cases'])
106 # Assume test file is responsible for printing identical format of
107 # test case description between --list-test-cases and its OUTCOME.CSV
Tomás González970b39f2023-08-17 17:07:53 +0100108 listed = set(map(lambda x: x.rstrip(), listed.splitlines()))
Yanray Wang63f0abe2023-08-30 18:31:35 +0800109 # idx indicates the number of test case since there is no line number
110 # in `compat.sh` for each test case.
Tomás González4a86da22023-09-01 17:41:16 +0100111 for idx, description in enumerate(listed):
112 self.process_test_case(descriptions, file_name, idx, description)
Yanray Wang23546932023-02-24 14:53:29 +0800113
Gilles Peskine6f6ff332020-06-25 16:40:10 +0200114 @staticmethod
115 def collect_test_directories():
116 """Get the relative path for the TLS and Crypto test directories."""
117 if os.path.isdir('tests'):
118 tests_dir = 'tests'
119 elif os.path.isdir('suites'):
120 tests_dir = '.'
121 elif os.path.isdir('../suites'):
122 tests_dir = '..'
123 directories = [tests_dir]
124 return directories
125
Gilles Peskine78c45db2020-06-25 16:34:11 +0200126 def walk_all(self):
127 """Iterate over all named test cases."""
Gilles Peskine6f6ff332020-06-25 16:40:10 +0200128 test_directories = self.collect_test_directories()
Gilles Peskine78c45db2020-06-25 16:34:11 +0200129 for directory in test_directories:
130 for data_file_name in glob.glob(os.path.join(directory, 'suites',
131 '*.data')):
132 self.walk_test_suite(data_file_name)
Tomás González4a86da22023-09-01 17:41:16 +0100133
134 for sh_file in ['ssl-opt.sh', 'compat.sh']:
135 sh_file = os.path.join(directory, sh_file)
136 if os.path.exists(sh_file):
137 self.collect_from_script(sh_file)
Gilles Peskine78c45db2020-06-25 16:34:11 +0200138
Gilles Peskine686c2922022-01-07 15:58:38 +0100139class TestDescriptions(TestDescriptionExplorer):
140 """Collect the available test cases."""
141
142 def __init__(self):
143 super().__init__()
144 self.descriptions = set()
145
146 def process_test_case(self, _per_file_state,
147 file_name, _line_number, description):
148 """Record an available test case."""
149 base_name = re.sub(r'\.[^.]*$', '', re.sub(r'.*/', '', file_name))
150 key = ';'.join([base_name, description.decode('utf-8')])
151 self.descriptions.add(key)
152
153def collect_available_test_cases():
154 """Collect the available test cases."""
155 explorer = TestDescriptions()
156 explorer.walk_all()
157 return sorted(explorer.descriptions)
158
Gilles Peskine78c45db2020-06-25 16:34:11 +0200159class DescriptionChecker(TestDescriptionExplorer):
160 """Check all test case descriptions.
161
162* Check that each description is valid (length, allowed character set, etc.).
163* Check that there is no duplicated description inside of one test suite.
164"""
165
166 def __init__(self, results):
167 self.results = results
168
Gilles Peskinebbb36642020-07-03 00:30:12 +0200169 def new_per_file_state(self):
Gilles Peskine6f6ff332020-06-25 16:40:10 +0200170 """Dictionary mapping descriptions to their line number."""
Gilles Peskine78c45db2020-06-25 16:34:11 +0200171 return {}
172
173 def process_test_case(self, per_file_state,
174 file_name, line_number, description):
Gilles Peskine6f6ff332020-06-25 16:40:10 +0200175 """Check test case descriptions for errors."""
176 results = self.results
177 seen = per_file_state
178 if description in seen:
179 results.error(file_name, line_number,
180 'Duplicate description (also line {})',
181 seen[description])
182 return
183 if re.search(br'[\t;]', description):
184 results.error(file_name, line_number,
185 'Forbidden character \'{}\' in description',
186 re.search(br'[\t;]', description).group(0).decode('ascii'))
187 if re.search(br'[^ -~]', description):
188 results.error(file_name, line_number,
189 'Non-ASCII character in description')
190 if len(description) > 66:
191 results.warning(file_name, line_number,
192 'Test description too long ({} > 66)',
193 len(description))
194 seen[description] = line_number
Gilles Peskineba94b582019-09-16 19:18:40 +0200195
196def main():
Gilles Peskine1fb7aea2019-12-02 14:26:04 +0100197 parser = argparse.ArgumentParser(description=__doc__)
Gilles Peskine7e091052022-01-07 15:58:55 +0100198 parser.add_argument('--list-all',
199 action='store_true',
200 help='List all test cases, without doing checks')
Gilles Peskine1fb7aea2019-12-02 14:26:04 +0100201 parser.add_argument('--quiet', '-q',
202 action='store_true',
203 help='Hide warnings')
204 parser.add_argument('--verbose', '-v',
205 action='store_false', dest='quiet',
206 help='Show warnings (default: on; undoes --quiet)')
207 options = parser.parse_args()
Gilles Peskine7e091052022-01-07 15:58:55 +0100208 if options.list_all:
209 descriptions = collect_available_test_cases()
210 sys.stdout.write('\n'.join(descriptions + ['']))
211 return
Gilles Peskine1fb7aea2019-12-02 14:26:04 +0100212 results = Results(options)
Gilles Peskine78c45db2020-06-25 16:34:11 +0200213 checker = DescriptionChecker(results)
214 checker.walk_all()
Gilles Peskine1fb7aea2019-12-02 14:26:04 +0100215 if (results.warnings or results.errors) and not options.quiet:
Gilles Peskineba94b582019-09-16 19:18:40 +0200216 sys.stderr.write('{}: {} errors, {} warnings\n'
217 .format(sys.argv[0], results.errors, results.warnings))
218 sys.exit(1 if results.errors else 0)
219
220if __name__ == '__main__':
221 main()