blob: 11c085f6b8705a30f05a2f87f46072daefa964b5 [file] [log] [blame]
Werner Lewisfbb75e32022-08-24 11:30:03 +01001"""Common test generation classes and main function.
2
3These are used both by generate_psa_tests.py and generate_bignum_tests.py.
4"""
5
6# Copyright The Mbed TLS Contributors
7# SPDX-License-Identifier: Apache-2.0
8#
9# Licensed under the Apache License, Version 2.0 (the "License"); you may
10# not use this file except in compliance with the License.
11# You may obtain a copy of the License at
12#
13# http://www.apache.org/licenses/LICENSE-2.0
14#
15# Unless required by applicable law or agreed to in writing, software
16# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18# See the License for the specific language governing permissions and
19# limitations under the License.
20
21import argparse
22import os
23import posixpath
24import re
Werner Lewis169034a2022-08-23 16:07:37 +010025
Werner Lewis699e1262022-08-24 12:18:25 +010026from abc import ABCMeta, abstractmethod
Werner Lewis2b527a32022-08-24 12:42:00 +010027from typing import Callable, Dict, Iterable, Iterator, List, Type, TypeVar
Werner Lewisfbb75e32022-08-24 11:30:03 +010028
29from mbedtls_dev import build_tree
30from mbedtls_dev import test_case
31
32T = TypeVar('T') #pylint: disable=invalid-name
33
34
Werner Lewis699e1262022-08-24 12:18:25 +010035class BaseTarget(metaclass=ABCMeta):
Werner Lewisfbb75e32022-08-24 11:30:03 +010036 """Base target for test case generation.
37
38 Attributes:
Werner Lewis55e638c2022-08-23 14:21:53 +010039 count: Counter for test cases from this class.
40 case_description: Short description of the test case. This may be
41 automatically generated using the class, or manually set.
42 target_basename: Basename of file to write generated tests to. This
43 should be specified in a child class of BaseTarget.
44 test_function: Test function which the class generates cases for.
45 test_name: A common name or description of the test function. This can
46 be the function's name, or a short summary of its purpose.
Werner Lewisfbb75e32022-08-24 11:30:03 +010047 """
48 count = 0
Werner Lewis55e638c2022-08-23 14:21:53 +010049 case_description = ""
50 target_basename = ""
51 test_function = ""
52 test_name = ""
Werner Lewisfbb75e32022-08-24 11:30:03 +010053
Werner Lewiscfd47682022-08-24 17:04:07 +010054 def __new__(cls, *args, **kwargs):
Werner Lewisa195ce72022-08-24 18:09:10 +010055 # pylint: disable=unused-argument
Werner Lewiscfd47682022-08-24 17:04:07 +010056 cls.count += 1
57 return super().__new__(cls)
Werner Lewisfbb75e32022-08-24 11:30:03 +010058
Werner Lewis169034a2022-08-23 16:07:37 +010059 @abstractmethod
Werner Lewis55e638c2022-08-23 14:21:53 +010060 def arguments(self) -> List[str]:
Werner Lewis169034a2022-08-23 16:07:37 +010061 """Get the list of arguments for the test case.
62
63 Override this method to provide the list of arguments required for
64 generating the test_function.
65
66 Returns:
67 List of arguments required for the test function.
68 """
Werner Lewis6d654c62022-08-25 09:56:51 +010069 raise NotImplementedError
Werner Lewisfbb75e32022-08-24 11:30:03 +010070
Werner Lewisfbb75e32022-08-24 11:30:03 +010071 def description(self) -> str:
Werner Lewis169034a2022-08-23 16:07:37 +010072 """Create a test description.
73
74 Creates a description of the test case, including a name for the test
75 function, and describing the specific test case. This should inform a
76 reader of the purpose of the case. The case description may be
77 generated in the class, or provided manually as needed.
78
79 Returns:
80 Description for the test case.
81 """
Werner Lewisd03d2a32022-08-24 17:20:29 +010082 return "{} #{} {}".format(
83 self.test_name, self.count, self.case_description
84 ).strip()
Werner Lewisfbb75e32022-08-24 11:30:03 +010085
Werner Lewis169034a2022-08-23 16:07:37 +010086
Werner Lewisfbb75e32022-08-24 11:30:03 +010087 def create_test_case(self) -> test_case.TestCase:
Werner Lewis169034a2022-08-23 16:07:37 +010088 """Generate TestCase from the current object."""
Werner Lewisfbb75e32022-08-24 11:30:03 +010089 tc = test_case.TestCase()
Werner Lewis55e638c2022-08-23 14:21:53 +010090 tc.set_description(self.description())
91 tc.set_function(self.test_function)
92 tc.set_arguments(self.arguments())
Werner Lewisfbb75e32022-08-24 11:30:03 +010093
94 return tc
95
96 @classmethod
Werner Lewis2b527a32022-08-24 12:42:00 +010097 @abstractmethod
98 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
99 """Generate test cases for the test function.
Werner Lewis169034a2022-08-23 16:07:37 +0100100
Werner Lewis2b527a32022-08-24 12:42:00 +0100101 This will be called in classes where `test_function` is set.
102 Implementations should yield TestCase objects, by creating instances
103 of the class with appropriate input data, and then calling
104 `create_test_case()` on each.
Werner Lewis169034a2022-08-23 16:07:37 +0100105 """
Werner Lewis6d654c62022-08-25 09:56:51 +0100106 raise NotImplementedError
Werner Lewis2b527a32022-08-24 12:42:00 +0100107
108 @classmethod
109 def generate_tests(cls) -> Iterator[test_case.TestCase]:
110 """Generate test cases for the class and its subclasses.
111
112 In classes with `test_function` set, `generate_function_tests()` is
113 used to generate test cases first.
114 In all classes, this method will iterate over its subclasses, and
115 yield from `generate_tests()` in each.
116
117 Calling this method on a class X will yield test cases from all classes
118 derived from X.
119 """
120 if cls.test_function:
121 yield from cls.generate_function_tests()
Werner Lewisfbb75e32022-08-24 11:30:03 +0100122 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
123 yield from subclass.generate_tests()
124
125
126class TestGenerator:
127 """Generate test data."""
128 def __init__(self, options) -> None:
129 self.test_suite_directory = self.get_option(options, 'directory',
130 'tests/suites')
131
132 @staticmethod
133 def get_option(options, name: str, default: T) -> T:
134 value = getattr(options, name, None)
135 return default if value is None else value
136
137 def filename_for(self, basename: str) -> str:
138 """The location of the data file with the specified base name."""
139 return posixpath.join(self.test_suite_directory, basename + '.data')
140
141 def write_test_data_file(self, basename: str,
142 test_cases: Iterable[test_case.TestCase]) -> None:
143 """Write the test cases to a .data file.
144
145 The output file is ``basename + '.data'`` in the test suite directory.
146 """
147 filename = self.filename_for(basename)
148 test_case.write_data_file(filename, test_cases)
149
150 # Note that targets whose names contain 'test_format' have their content
151 # validated by `abi_check.py`.
Werner Lewise3ad22e2022-08-25 10:02:06 +0100152 TARGETS = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
Werner Lewisfbb75e32022-08-24 11:30:03 +0100153
154 def generate_target(self, name: str, *target_args) -> None:
155 """Generate cases and write to data file for a target.
156
157 For target callables which require arguments, override this function
158 and pass these arguments using super() (see PSATestGenerator).
159 """
160 test_cases = self.TARGETS[name](*target_args)
161 self.write_test_data_file(name, test_cases)
162
163def main(args, generator_class: Type[TestGenerator] = TestGenerator):
164 """Command line entry point."""
165 parser = argparse.ArgumentParser(description=__doc__)
166 parser.add_argument('--list', action='store_true',
167 help='List available targets and exit')
168 parser.add_argument('--list-for-cmake', action='store_true',
169 help='Print \';\'-separated list of available targets and exit')
170 parser.add_argument('--directory', metavar='DIR',
171 help='Output directory (default: tests/suites)')
172 parser.add_argument('targets', nargs='*', metavar='TARGET',
173 help='Target file to generate (default: all; "-": none)')
174 options = parser.parse_args(args)
175 build_tree.chdir_to_root()
176 generator = generator_class(options)
177 if options.list:
178 for name in sorted(generator.TARGETS):
179 print(generator.filename_for(name))
180 return
181 # List in a cmake list format (i.e. ';'-separated)
182 if options.list_for_cmake:
183 print(';'.join(generator.filename_for(name)
184 for name in sorted(generator.TARGETS)), end='')
185 return
186 if options.targets:
187 # Allow "-" as a special case so you can run
188 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
189 # ``$targets`` is empty or not.
190 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
191 for target in options.targets
192 if target != '-']
193 else:
194 options.targets = sorted(generator.TARGETS)
195 for target in options.targets:
196 generator.generate_target(target)