blob: 2414f3a4b541a6ddea1441e52a3520f219ffcff6 [file] [log] [blame]
Werner Lewisfbb75e32022-08-24 11:30:03 +01001#!/usr/bin/env python3
2"""Common test generation classes and main function.
3
4These are used both by generate_psa_tests.py and generate_bignum_tests.py.
5"""
6
7# Copyright The Mbed TLS Contributors
8# SPDX-License-Identifier: Apache-2.0
9#
10# Licensed under the Apache License, Version 2.0 (the "License"); you may
11# not use this file except in compliance with the License.
12# You may obtain a copy of the License at
13#
14# http://www.apache.org/licenses/LICENSE-2.0
15#
16# Unless required by applicable law or agreed to in writing, software
17# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19# See the License for the specific language governing permissions and
20# limitations under the License.
21
22import argparse
23import os
24import posixpath
25import re
26from typing import Callable, Dict, Iterable, List, Type, TypeVar
27
28from mbedtls_dev import build_tree
29from mbedtls_dev import test_case
30
31T = TypeVar('T') #pylint: disable=invalid-name
32
33
34class BaseTarget:
35 """Base target for test case generation.
36
37 Attributes:
38 count: Counter for test class.
39 desc: Short description of test case.
40 func: Function which the class generates tests for.
41 gen_file: File to write generated tests to.
42 title: Description of the test function/purpose.
43 """
44 count = 0
45 desc = ""
46 func = ""
47 gen_file = ""
48 title = ""
49
50 def __init__(self) -> None:
51 type(self).count += 1
52
53 @property
54 def args(self) -> List[str]:
55 """Create list of arguments for test case."""
56 return []
57
58 @property
59 def description(self) -> str:
60 """Create a numbered test description."""
61 return "{} #{} {}".format(self.title, self.count, self.desc)
62
63 def create_test_case(self) -> test_case.TestCase:
64 """Generate test case from the current object."""
65 tc = test_case.TestCase()
66 tc.set_description(self.description)
67 tc.set_function(self.func)
68 tc.set_arguments(self.args)
69
70 return tc
71
72 @classmethod
73 def generate_tests(cls):
74 """Generate test cases for the target subclasses."""
75 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
76 yield from subclass.generate_tests()
77
78
79class TestGenerator:
80 """Generate test data."""
81 def __init__(self, options) -> None:
82 self.test_suite_directory = self.get_option(options, 'directory',
83 'tests/suites')
84
85 @staticmethod
86 def get_option(options, name: str, default: T) -> T:
87 value = getattr(options, name, None)
88 return default if value is None else value
89
90 def filename_for(self, basename: str) -> str:
91 """The location of the data file with the specified base name."""
92 return posixpath.join(self.test_suite_directory, basename + '.data')
93
94 def write_test_data_file(self, basename: str,
95 test_cases: Iterable[test_case.TestCase]) -> None:
96 """Write the test cases to a .data file.
97
98 The output file is ``basename + '.data'`` in the test suite directory.
99 """
100 filename = self.filename_for(basename)
101 test_case.write_data_file(filename, test_cases)
102
103 # Note that targets whose names contain 'test_format' have their content
104 # validated by `abi_check.py`.
105 TARGETS = {} # type: Dict[str, Callable[..., test_case.TestCase]]
106
107 def generate_target(self, name: str, *target_args) -> None:
108 """Generate cases and write to data file for a target.
109
110 For target callables which require arguments, override this function
111 and pass these arguments using super() (see PSATestGenerator).
112 """
113 test_cases = self.TARGETS[name](*target_args)
114 self.write_test_data_file(name, test_cases)
115
116def main(args, generator_class: Type[TestGenerator] = TestGenerator):
117 """Command line entry point."""
118 parser = argparse.ArgumentParser(description=__doc__)
119 parser.add_argument('--list', action='store_true',
120 help='List available targets and exit')
121 parser.add_argument('--list-for-cmake', action='store_true',
122 help='Print \';\'-separated list of available targets and exit')
123 parser.add_argument('--directory', metavar='DIR',
124 help='Output directory (default: tests/suites)')
125 parser.add_argument('targets', nargs='*', metavar='TARGET',
126 help='Target file to generate (default: all; "-": none)')
127 options = parser.parse_args(args)
128 build_tree.chdir_to_root()
129 generator = generator_class(options)
130 if options.list:
131 for name in sorted(generator.TARGETS):
132 print(generator.filename_for(name))
133 return
134 # List in a cmake list format (i.e. ';'-separated)
135 if options.list_for_cmake:
136 print(';'.join(generator.filename_for(name)
137 for name in sorted(generator.TARGETS)), end='')
138 return
139 if options.targets:
140 # Allow "-" as a special case so you can run
141 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
142 # ``$targets`` is empty or not.
143 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
144 for target in options.targets
145 if target != '-']
146 else:
147 options.targets = sorted(generator.TARGETS)
148 for target in options.targets:
149 generator.generate_target(target)