Skip to content

Commit 1de0641

Browse files
Merge pull request #55 from Mbed-TLS/dev/gilles-peskine-arm/analyze_outcome-split-framework
Framework: Split check_test_cases.py and outcome_analysis.py
2 parents 33ac133 + 6759e80 commit 1de0641

File tree

3 files changed

+647
-0
lines changed

3 files changed

+647
-0
lines changed

scripts/check_test_cases.py

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#!/usr/bin/env python3
2+
3+
"""Sanity checks for test data."""
4+
5+
# Copyright The Mbed TLS Contributors
6+
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
7+
8+
import argparse
9+
import re
10+
import sys
11+
12+
from mbedtls_framework import collect_test_cases
13+
14+
15+
class DescriptionChecker(collect_test_cases.TestDescriptionExplorer):
16+
"""Check all test case descriptions.
17+
18+
* Check that each description is valid (length, allowed character set, etc.).
19+
* Check that there is no duplicated description inside of one test suite.
20+
"""
21+
22+
def __init__(self, results):
23+
self.results = results
24+
25+
def new_per_file_state(self):
26+
"""Dictionary mapping descriptions to their line number."""
27+
return {}
28+
29+
def process_test_case(self, per_file_state,
30+
file_name, line_number, description):
31+
"""Check test case descriptions for errors."""
32+
results = self.results
33+
seen = per_file_state
34+
if description in seen:
35+
results.error(file_name, line_number,
36+
'Duplicate description (also line {})',
37+
seen[description])
38+
return
39+
if re.search(br'[\t;]', description):
40+
results.error(file_name, line_number,
41+
'Forbidden character \'{}\' in description',
42+
re.search(br'[\t;]', description).group(0).decode('ascii'))
43+
if re.search(br'[^ -~]', description):
44+
results.error(file_name, line_number,
45+
'Non-ASCII character in description')
46+
if len(description) > 66:
47+
results.warning(file_name, line_number,
48+
'Test description too long ({} > 66)',
49+
len(description))
50+
seen[description] = line_number
51+
52+
def main():
53+
parser = argparse.ArgumentParser(description=__doc__)
54+
parser.add_argument('--list-all',
55+
action='store_true',
56+
help='List all test cases, without doing checks')
57+
parser.add_argument('--quiet', '-q',
58+
action='store_true',
59+
help='Hide warnings')
60+
parser.add_argument('--verbose', '-v',
61+
action='store_false', dest='quiet',
62+
help='Show warnings (default: on; undoes --quiet)')
63+
options = parser.parse_args()
64+
if options.list_all:
65+
descriptions = collect_test_cases.collect_available_test_cases()
66+
sys.stdout.write('\n'.join(descriptions + ['']))
67+
return
68+
results = collect_test_cases.Results(options)
69+
checker = DescriptionChecker(results)
70+
try:
71+
checker.walk_all()
72+
except collect_test_cases.ScriptOutputError as e:
73+
results.error(e.script_name, e.idx,
74+
'"{}" should be listed as "<suite_name>;<description>"',
75+
e.line)
76+
if (results.warnings or results.errors) and not options.quiet:
77+
sys.stderr.write('{}: {} errors, {} warnings\n'
78+
.format(sys.argv[0], results.errors, results.warnings))
79+
sys.exit(1 if results.errors else 0)
80+
81+
if __name__ == '__main__':
82+
main()
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
"""Discover all the test cases (unit tests and SSL tests)."""
2+
3+
# Copyright The Mbed TLS Contributors
4+
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
5+
6+
import glob
7+
import os
8+
import re
9+
import subprocess
10+
import sys
11+
12+
from . import build_tree
13+
14+
15+
class ScriptOutputError(ValueError):
16+
"""A kind of ValueError that indicates we found
17+
the script doesn't list test cases in an expected
18+
pattern.
19+
"""
20+
21+
@property
22+
def script_name(self):
23+
return super().args[0]
24+
25+
@property
26+
def idx(self):
27+
return super().args[1]
28+
29+
@property
30+
def line(self):
31+
return super().args[2]
32+
33+
class Results:
34+
"""Store file and line information about errors or warnings in test suites."""
35+
36+
def __init__(self, options):
37+
self.errors = 0
38+
self.warnings = 0
39+
self.ignore_warnings = options.quiet
40+
41+
def error(self, file_name, line_number, fmt, *args):
42+
sys.stderr.write(('{}:{}:ERROR:' + fmt + '\n').
43+
format(file_name, line_number, *args))
44+
self.errors += 1
45+
46+
def warning(self, file_name, line_number, fmt, *args):
47+
if not self.ignore_warnings:
48+
sys.stderr.write(('{}:{}:Warning:' + fmt + '\n')
49+
.format(file_name, line_number, *args))
50+
self.warnings += 1
51+
52+
class TestDescriptionExplorer:
53+
"""An iterator over test cases with descriptions.
54+
55+
The test cases that have descriptions are:
56+
* Individual unit tests (entries in a .data file) in test suites.
57+
* Individual test cases in ssl-opt.sh.
58+
59+
This is an abstract class. To use it, derive a class that implements
60+
the process_test_case method, and call walk_all().
61+
"""
62+
63+
def process_test_case(self, per_file_state,
64+
file_name, line_number, description):
65+
"""Process a test case.
66+
67+
per_file_state: an object created by new_per_file_state() at the beginning
68+
of each file.
69+
file_name: a relative path to the file containing the test case.
70+
line_number: the line number in the given file.
71+
description: the test case description as a byte string.
72+
"""
73+
raise NotImplementedError
74+
75+
def new_per_file_state(self):
76+
"""Return a new per-file state object.
77+
78+
The default per-file state object is None. Child classes that require per-file
79+
state may override this method.
80+
"""
81+
#pylint: disable=no-self-use
82+
return None
83+
84+
def walk_test_suite(self, data_file_name):
85+
"""Iterate over the test cases in the given unit test data file."""
86+
in_paragraph = False
87+
descriptions = self.new_per_file_state() # pylint: disable=assignment-from-none
88+
with open(data_file_name, 'rb') as data_file:
89+
for line_number, line in enumerate(data_file, 1):
90+
line = line.rstrip(b'\r\n')
91+
if not line:
92+
in_paragraph = False
93+
continue
94+
if line.startswith(b'#'):
95+
continue
96+
if not in_paragraph:
97+
# This is a test case description line.
98+
self.process_test_case(descriptions,
99+
data_file_name, line_number, line)
100+
in_paragraph = True
101+
102+
def collect_from_script(self, script_name):
103+
"""Collect the test cases in a script by calling its listing test cases
104+
option"""
105+
descriptions = self.new_per_file_state() # pylint: disable=assignment-from-none
106+
listed = subprocess.check_output(['sh', script_name, '--list-test-cases'])
107+
# Assume test file is responsible for printing identical format of
108+
# test case description between --list-test-cases and its OUTCOME.CSV
109+
#
110+
# idx indicates the number of test case since there is no line number
111+
# in the script for each test case.
112+
for idx, line in enumerate(listed.splitlines()):
113+
# We are expecting the script to list the test cases in
114+
# `<suite_name>;<description>` pattern.
115+
script_outputs = line.split(b';', 1)
116+
if len(script_outputs) == 2:
117+
suite_name, description = script_outputs
118+
else:
119+
raise ScriptOutputError(script_name, idx, line.decode("utf-8"))
120+
121+
self.process_test_case(descriptions,
122+
suite_name.decode('utf-8'),
123+
idx,
124+
description.rstrip())
125+
126+
@staticmethod
127+
def collect_test_directories():
128+
"""Get the relative path for the TLS and Crypto test directories."""
129+
mbedtls_root = build_tree.guess_mbedtls_root()
130+
directories = [os.path.join(mbedtls_root, 'tests'),
131+
os.path.join(mbedtls_root, 'tf-psa-crypto', 'tests')]
132+
directories = [os.path.relpath(p) for p in directories]
133+
return directories
134+
135+
def walk_all(self):
136+
"""Iterate over all named test cases."""
137+
test_directories = self.collect_test_directories()
138+
for directory in test_directories:
139+
for data_file_name in glob.glob(os.path.join(directory, 'suites',
140+
'*.data')):
141+
self.walk_test_suite(data_file_name)
142+
143+
for sh_file in ['ssl-opt.sh', 'compat.sh']:
144+
sh_file = os.path.join(directory, sh_file)
145+
if os.path.isfile(sh_file):
146+
self.collect_from_script(sh_file)
147+
148+
class TestDescriptions(TestDescriptionExplorer):
149+
"""Collect the available test cases."""
150+
151+
def __init__(self):
152+
super().__init__()
153+
self.descriptions = set()
154+
155+
def process_test_case(self, _per_file_state,
156+
file_name, _line_number, description):
157+
"""Record an available test case."""
158+
base_name = re.sub(r'\.[^.]*$', '', re.sub(r'.*/', '', file_name))
159+
key = ';'.join([base_name, description.decode('utf-8')])
160+
self.descriptions.add(key)
161+
162+
def collect_available_test_cases():
163+
"""Collect the available test cases."""
164+
explorer = TestDescriptions()
165+
explorer.walk_all()
166+
return sorted(explorer.descriptions)

0 commit comments

Comments
 (0)