blob: c9a73c4adb6d270793ff5456f00da737cb0172e7 [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
Werner Lewis52ae3262022-09-14 16:26:54 +010038 Child classes of this class represent an output file, and can be referred
39 to as file targets. These indicate where test cases will be written to for
40 all subclasses of the file target, which is set by `target_basename`.
Werner Lewis6ef54362022-08-25 12:29:46 +010041
Werner Lewisfbb75e32022-08-24 11:30:03 +010042 Attributes:
Werner Lewis55e638c2022-08-23 14:21:53 +010043 count: Counter for test cases from this class.
44 case_description: Short description of the test case. This may be
45 automatically generated using the class, or manually set.
Werner Lewis466f0362022-08-31 17:01:38 +010046 dependencies: A list of dependencies required for the test case.
Werner Lewis858cffd2022-09-14 13:02:40 +010047 show_test_count: Toggle for inclusion of `count` in the test description.
Werner Lewis55e638c2022-08-23 14:21:53 +010048 target_basename: Basename of file to write generated tests to. This
49 should be specified in a child class of BaseTarget.
50 test_function: Test function which the class generates cases for.
51 test_name: A common name or description of the test function. This can
Werner Lewis6ef54362022-08-25 12:29:46 +010052 be `test_function`, a clearer equivalent, or a short summary of the
53 test function's purpose.
Werner Lewisfbb75e32022-08-24 11:30:03 +010054 """
55 count = 0
Werner Lewis55e638c2022-08-23 14:21:53 +010056 case_description = ""
Werner Lewisaaf3b792022-08-31 17:16:44 +010057 dependencies = [] # type: List[str]
Werner Lewis858cffd2022-09-14 13:02:40 +010058 show_test_count = True
Werner Lewis55e638c2022-08-23 14:21:53 +010059 target_basename = ""
60 test_function = ""
61 test_name = ""
Werner Lewisfbb75e32022-08-24 11:30:03 +010062
Werner Lewiscfd47682022-08-24 17:04:07 +010063 def __new__(cls, *args, **kwargs):
Werner Lewisa195ce72022-08-24 18:09:10 +010064 # pylint: disable=unused-argument
Werner Lewiscfd47682022-08-24 17:04:07 +010065 cls.count += 1
66 return super().__new__(cls)
Werner Lewisfbb75e32022-08-24 11:30:03 +010067
Werner Lewis169034a2022-08-23 16:07:37 +010068 @abstractmethod
Werner Lewis55e638c2022-08-23 14:21:53 +010069 def arguments(self) -> List[str]:
Werner Lewis169034a2022-08-23 16:07:37 +010070 """Get the list of arguments for the test case.
71
72 Override this method to provide the list of arguments required for
Werner Lewis6ef54362022-08-25 12:29:46 +010073 the `test_function`.
Werner Lewis169034a2022-08-23 16:07:37 +010074
75 Returns:
76 List of arguments required for the test function.
77 """
Werner Lewis6d654c62022-08-25 09:56:51 +010078 raise NotImplementedError
Werner Lewisfbb75e32022-08-24 11:30:03 +010079
Werner Lewisfbb75e32022-08-24 11:30:03 +010080 def description(self) -> str:
Werner Lewis6ef54362022-08-25 12:29:46 +010081 """Create a test case description.
Werner Lewis169034a2022-08-23 16:07:37 +010082
83 Creates a description of the test case, including a name for the test
Werner Lewis858cffd2022-09-14 13:02:40 +010084 function, an optional case count, and a description of the specific
85 test case. This should inform a reader what is being tested, and
86 provide context for the test case.
Werner Lewis169034a2022-08-23 16:07:37 +010087
88 Returns:
89 Description for the test case.
90 """
Werner Lewis858cffd2022-09-14 13:02:40 +010091 if self.show_test_count:
92 return "{} #{} {}".format(
93 self.test_name, self.count, self.case_description
94 ).strip()
95 else:
96 return "{} {}".format(self.test_name, self.case_description).strip()
Werner Lewisfbb75e32022-08-24 11:30:03 +010097
Werner Lewis169034a2022-08-23 16:07:37 +010098
Werner Lewisfbb75e32022-08-24 11:30:03 +010099 def create_test_case(self) -> test_case.TestCase:
Werner Lewis6ef54362022-08-25 12:29:46 +0100100 """Generate TestCase from the instance."""
Werner Lewisfbb75e32022-08-24 11:30:03 +0100101 tc = test_case.TestCase()
Werner Lewis55e638c2022-08-23 14:21:53 +0100102 tc.set_description(self.description())
103 tc.set_function(self.test_function)
104 tc.set_arguments(self.arguments())
Werner Lewis466f0362022-08-31 17:01:38 +0100105 tc.set_dependencies(self.dependencies)
Werner Lewisfbb75e32022-08-24 11:30:03 +0100106
107 return tc
108
109 @classmethod
Werner Lewis2b527a32022-08-24 12:42:00 +0100110 @abstractmethod
111 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Werner Lewis6ef54362022-08-25 12:29:46 +0100112 """Generate test cases for the class test function.
Werner Lewis169034a2022-08-23 16:07:37 +0100113
Werner Lewis2b527a32022-08-24 12:42:00 +0100114 This will be called in classes where `test_function` is set.
115 Implementations should yield TestCase objects, by creating instances
116 of the class with appropriate input data, and then calling
117 `create_test_case()` on each.
Werner Lewis169034a2022-08-23 16:07:37 +0100118 """
Werner Lewis6d654c62022-08-25 09:56:51 +0100119 raise NotImplementedError
Werner Lewis2b527a32022-08-24 12:42:00 +0100120
121 @classmethod
122 def generate_tests(cls) -> Iterator[test_case.TestCase]:
123 """Generate test cases for the class and its subclasses.
124
125 In classes with `test_function` set, `generate_function_tests()` is
Werner Lewis81f24442022-08-25 16:27:05 +0100126 called to generate test cases first.
Werner Lewis2b527a32022-08-24 12:42:00 +0100127
Werner Lewis6ef54362022-08-25 12:29:46 +0100128 In all classes, this method will iterate over its subclasses, and
129 yield from `generate_tests()` in each. Calling this method on a class X
130 will yield test cases from all classes derived from X.
Werner Lewis2b527a32022-08-24 12:42:00 +0100131 """
132 if cls.test_function:
133 yield from cls.generate_function_tests()
Werner Lewisfbb75e32022-08-24 11:30:03 +0100134 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
135 yield from subclass.generate_tests()
136
137
138class TestGenerator:
Werner Lewis34d6d3e2022-09-14 12:59:32 +0100139 """Generate test cases and write to data files."""
Werner Lewisfbb75e32022-08-24 11:30:03 +0100140 def __init__(self, options) -> None:
Werner Lewis00d02422022-09-14 13:39:20 +0100141 self.test_suite_directory = getattr(options, 'directory', 'tests/suites')
Werner Lewis34d6d3e2022-09-14 12:59:32 +0100142 # Update `targets` with an entry for each child class of BaseTarget.
143 # Each entry represents a file generated by the BaseTarget framework,
144 # and enables generating the .data files using the CLI.
Werner Lewisa4668a62022-09-02 11:56:34 +0100145 self.targets.update({
146 subclass.target_basename: subclass.generate_tests
147 for subclass in BaseTarget.__subclasses__()
148 })
Werner Lewisfbb75e32022-08-24 11:30:03 +0100149
150 def filename_for(self, basename: str) -> str:
151 """The location of the data file with the specified base name."""
152 return posixpath.join(self.test_suite_directory, basename + '.data')
153
154 def write_test_data_file(self, basename: str,
155 test_cases: Iterable[test_case.TestCase]) -> None:
156 """Write the test cases to a .data file.
157
158 The output file is ``basename + '.data'`` in the test suite directory.
159 """
160 filename = self.filename_for(basename)
161 test_case.write_data_file(filename, test_cases)
162
163 # Note that targets whose names contain 'test_format' have their content
164 # validated by `abi_check.py`.
Werner Lewisa4668a62022-09-02 11:56:34 +0100165 targets = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
Werner Lewisfbb75e32022-08-24 11:30:03 +0100166
167 def generate_target(self, name: str, *target_args) -> None:
168 """Generate cases and write to data file for a target.
169
170 For target callables which require arguments, override this function
171 and pass these arguments using super() (see PSATestGenerator).
172 """
Werner Lewisa4668a62022-09-02 11:56:34 +0100173 test_cases = self.targets[name](*target_args)
Werner Lewisfbb75e32022-08-24 11:30:03 +0100174 self.write_test_data_file(name, test_cases)
175
176def main(args, generator_class: Type[TestGenerator] = TestGenerator):
177 """Command line entry point."""
178 parser = argparse.ArgumentParser(description=__doc__)
179 parser.add_argument('--list', action='store_true',
180 help='List available targets and exit')
181 parser.add_argument('--list-for-cmake', action='store_true',
182 help='Print \';\'-separated list of available targets and exit')
Werner Lewis00d02422022-09-14 13:39:20 +0100183 parser.add_argument('--directory', metavar='DIR',
Werner Lewisfbb75e32022-08-24 11:30:03 +0100184 help='Output directory (default: tests/suites)')
Werner Lewis00d02422022-09-14 13:39:20 +0100185 # The `--directory` option is interpreted relative to the directory from
186 # which the script is invoked, but the default is relative to the root of
187 # the mbedtls tree. The default should not be set above, but instead after
188 # `build_tree.chdir_to_root()` is called.
Werner Lewisfbb75e32022-08-24 11:30:03 +0100189 parser.add_argument('targets', nargs='*', metavar='TARGET',
190 help='Target file to generate (default: all; "-": none)')
191 options = parser.parse_args(args)
192 build_tree.chdir_to_root()
193 generator = generator_class(options)
194 if options.list:
Werner Lewisa4668a62022-09-02 11:56:34 +0100195 for name in sorted(generator.targets):
Werner Lewisfbb75e32022-08-24 11:30:03 +0100196 print(generator.filename_for(name))
197 return
198 # List in a cmake list format (i.e. ';'-separated)
199 if options.list_for_cmake:
200 print(';'.join(generator.filename_for(name)
Werner Lewisa4668a62022-09-02 11:56:34 +0100201 for name in sorted(generator.targets)), end='')
Werner Lewisfbb75e32022-08-24 11:30:03 +0100202 return
Werner Lewisa4668a62022-09-02 11:56:34 +0100203 if options.targets:
204 # Allow "-" as a special case so you can run
205 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
206 # ``$targets`` is empty or not.
207 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
Werner Lewis56013082022-09-02 12:57:37 +0100208 for target in options.targets
209 if target != '-']
Werner Lewisa4668a62022-09-02 11:56:34 +0100210 else:
211 options.targets = sorted(generator.targets)
Werner Lewisfbb75e32022-08-24 11:30:03 +0100212 for target in options.targets:
213 generator.generate_target(target)