blob: 81af7ba27236f2b967e1b4b44e47fd674b950e83 [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 Lewis81f24442022-08-25 16:27:05 +010038 Derive directly from this class when adding new file Targets, setting
39 `target_basename`.
Werner Lewis6ef54362022-08-25 12:29:46 +010040
Werner Lewisfbb75e32022-08-24 11:30:03 +010041 Attributes:
Werner Lewis55e638c2022-08-23 14:21:53 +010042 count: Counter for test cases from this class.
43 case_description: Short description of the test case. This may be
44 automatically generated using the class, or manually set.
Werner Lewis466f0362022-08-31 17:01:38 +010045 dependencies: A list of dependencies required for the test case.
Werner Lewis858cffd2022-09-14 13:02:40 +010046 show_test_count: Toggle for inclusion of `count` in the test description.
Werner Lewis55e638c2022-08-23 14:21:53 +010047 target_basename: Basename of file to write generated tests to. This
48 should be specified in a child class of BaseTarget.
49 test_function: Test function which the class generates cases for.
50 test_name: A common name or description of the test function. This can
Werner Lewis6ef54362022-08-25 12:29:46 +010051 be `test_function`, a clearer equivalent, or a short summary of the
52 test function's purpose.
Werner Lewisfbb75e32022-08-24 11:30:03 +010053 """
54 count = 0
Werner Lewis55e638c2022-08-23 14:21:53 +010055 case_description = ""
Werner Lewisaaf3b792022-08-31 17:16:44 +010056 dependencies = [] # type: List[str]
Werner Lewis858cffd2022-09-14 13:02:40 +010057 show_test_count = True
Werner Lewis55e638c2022-08-23 14:21:53 +010058 target_basename = ""
59 test_function = ""
60 test_name = ""
Werner Lewisfbb75e32022-08-24 11:30:03 +010061
Werner Lewiscfd47682022-08-24 17:04:07 +010062 def __new__(cls, *args, **kwargs):
Werner Lewisa195ce72022-08-24 18:09:10 +010063 # pylint: disable=unused-argument
Werner Lewiscfd47682022-08-24 17:04:07 +010064 cls.count += 1
65 return super().__new__(cls)
Werner Lewisfbb75e32022-08-24 11:30:03 +010066
Werner Lewis169034a2022-08-23 16:07:37 +010067 @abstractmethod
Werner Lewis55e638c2022-08-23 14:21:53 +010068 def arguments(self) -> List[str]:
Werner Lewis169034a2022-08-23 16:07:37 +010069 """Get the list of arguments for the test case.
70
71 Override this method to provide the list of arguments required for
Werner Lewis6ef54362022-08-25 12:29:46 +010072 the `test_function`.
Werner Lewis169034a2022-08-23 16:07:37 +010073
74 Returns:
75 List of arguments required for the test function.
76 """
Werner Lewis6d654c62022-08-25 09:56:51 +010077 raise NotImplementedError
Werner Lewisfbb75e32022-08-24 11:30:03 +010078
Werner Lewisfbb75e32022-08-24 11:30:03 +010079 def description(self) -> str:
Werner Lewis6ef54362022-08-25 12:29:46 +010080 """Create a test case description.
Werner Lewis169034a2022-08-23 16:07:37 +010081
82 Creates a description of the test case, including a name for the test
Werner Lewis858cffd2022-09-14 13:02:40 +010083 function, an optional case count, and a description of the specific
84 test case. This should inform a reader what is being tested, and
85 provide context for the test case.
Werner Lewis169034a2022-08-23 16:07:37 +010086
87 Returns:
88 Description for the test case.
89 """
Werner Lewis858cffd2022-09-14 13:02:40 +010090 if self.show_test_count:
91 return "{} #{} {}".format(
92 self.test_name, self.count, self.case_description
93 ).strip()
94 else:
95 return "{} {}".format(self.test_name, self.case_description).strip()
Werner Lewisfbb75e32022-08-24 11:30:03 +010096
Werner Lewis169034a2022-08-23 16:07:37 +010097
Werner Lewisfbb75e32022-08-24 11:30:03 +010098 def create_test_case(self) -> test_case.TestCase:
Werner Lewis6ef54362022-08-25 12:29:46 +010099 """Generate TestCase from the instance."""
Werner Lewisfbb75e32022-08-24 11:30:03 +0100100 tc = test_case.TestCase()
Werner Lewis55e638c2022-08-23 14:21:53 +0100101 tc.set_description(self.description())
102 tc.set_function(self.test_function)
103 tc.set_arguments(self.arguments())
Werner Lewis466f0362022-08-31 17:01:38 +0100104 tc.set_dependencies(self.dependencies)
Werner Lewisfbb75e32022-08-24 11:30:03 +0100105
106 return tc
107
108 @classmethod
Werner Lewis2b527a32022-08-24 12:42:00 +0100109 @abstractmethod
110 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Werner Lewis6ef54362022-08-25 12:29:46 +0100111 """Generate test cases for the class test function.
Werner Lewis169034a2022-08-23 16:07:37 +0100112
Werner Lewis2b527a32022-08-24 12:42:00 +0100113 This will be called in classes where `test_function` is set.
114 Implementations should yield TestCase objects, by creating instances
115 of the class with appropriate input data, and then calling
116 `create_test_case()` on each.
Werner Lewis169034a2022-08-23 16:07:37 +0100117 """
Werner Lewis6d654c62022-08-25 09:56:51 +0100118 raise NotImplementedError
Werner Lewis2b527a32022-08-24 12:42:00 +0100119
120 @classmethod
121 def generate_tests(cls) -> Iterator[test_case.TestCase]:
122 """Generate test cases for the class and its subclasses.
123
124 In classes with `test_function` set, `generate_function_tests()` is
Werner Lewis81f24442022-08-25 16:27:05 +0100125 called to generate test cases first.
Werner Lewis2b527a32022-08-24 12:42:00 +0100126
Werner Lewis6ef54362022-08-25 12:29:46 +0100127 In all classes, this method will iterate over its subclasses, and
128 yield from `generate_tests()` in each. Calling this method on a class X
129 will yield test cases from all classes derived from X.
Werner Lewis2b527a32022-08-24 12:42:00 +0100130 """
131 if cls.test_function:
132 yield from cls.generate_function_tests()
Werner Lewisfbb75e32022-08-24 11:30:03 +0100133 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
134 yield from subclass.generate_tests()
135
136
137class TestGenerator:
Werner Lewis34d6d3e2022-09-14 12:59:32 +0100138 """Generate test cases and write to data files."""
Werner Lewisfbb75e32022-08-24 11:30:03 +0100139 def __init__(self, options) -> None:
Werner Lewisf156c432022-08-25 11:30:17 +0100140 self.test_suite_directory = getattr(options, 'directory')
Werner Lewis34d6d3e2022-09-14 12:59:32 +0100141 # Update `targets` with an entry for each child class of BaseTarget.
142 # Each entry represents a file generated by the BaseTarget framework,
143 # and enables generating the .data files using the CLI.
Werner Lewisa4668a62022-09-02 11:56:34 +0100144 self.targets.update({
145 subclass.target_basename: subclass.generate_tests
146 for subclass in BaseTarget.__subclasses__()
147 })
Werner Lewisfbb75e32022-08-24 11:30:03 +0100148
149 def filename_for(self, basename: str) -> str:
150 """The location of the data file with the specified base name."""
151 return posixpath.join(self.test_suite_directory, basename + '.data')
152
153 def write_test_data_file(self, basename: str,
154 test_cases: Iterable[test_case.TestCase]) -> None:
155 """Write the test cases to a .data file.
156
157 The output file is ``basename + '.data'`` in the test suite directory.
158 """
159 filename = self.filename_for(basename)
160 test_case.write_data_file(filename, test_cases)
161
162 # Note that targets whose names contain 'test_format' have their content
163 # validated by `abi_check.py`.
Werner Lewisa4668a62022-09-02 11:56:34 +0100164 targets = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
Werner Lewisfbb75e32022-08-24 11:30:03 +0100165
166 def generate_target(self, name: str, *target_args) -> None:
167 """Generate cases and write to data file for a target.
168
169 For target callables which require arguments, override this function
170 and pass these arguments using super() (see PSATestGenerator).
171 """
Werner Lewisa4668a62022-09-02 11:56:34 +0100172 test_cases = self.targets[name](*target_args)
Werner Lewisfbb75e32022-08-24 11:30:03 +0100173 self.write_test_data_file(name, test_cases)
174
175def main(args, generator_class: Type[TestGenerator] = TestGenerator):
176 """Command line entry point."""
177 parser = argparse.ArgumentParser(description=__doc__)
178 parser.add_argument('--list', action='store_true',
179 help='List available targets and exit')
180 parser.add_argument('--list-for-cmake', action='store_true',
181 help='Print \';\'-separated list of available targets and exit')
Werner Lewisf156c432022-08-25 11:30:17 +0100182 parser.add_argument('--directory', default="tests/suites", metavar='DIR',
Werner Lewisfbb75e32022-08-24 11:30:03 +0100183 help='Output directory (default: tests/suites)')
184 parser.add_argument('targets', nargs='*', metavar='TARGET',
185 help='Target file to generate (default: all; "-": none)')
186 options = parser.parse_args(args)
187 build_tree.chdir_to_root()
188 generator = generator_class(options)
189 if options.list:
Werner Lewisa4668a62022-09-02 11:56:34 +0100190 for name in sorted(generator.targets):
Werner Lewisfbb75e32022-08-24 11:30:03 +0100191 print(generator.filename_for(name))
192 return
193 # List in a cmake list format (i.e. ';'-separated)
194 if options.list_for_cmake:
195 print(';'.join(generator.filename_for(name)
Werner Lewisa4668a62022-09-02 11:56:34 +0100196 for name in sorted(generator.targets)), end='')
Werner Lewisfbb75e32022-08-24 11:30:03 +0100197 return
Werner Lewisa4668a62022-09-02 11:56:34 +0100198 if options.targets:
199 # Allow "-" as a special case so you can run
200 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
201 # ``$targets`` is empty or not.
202 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
Werner Lewis56013082022-09-02 12:57:37 +0100203 for target in options.targets
204 if target != '-']
Werner Lewisa4668a62022-09-02 11:56:34 +0100205 else:
206 options.targets = sorted(generator.targets)
Werner Lewisfbb75e32022-08-24 11:30:03 +0100207 for target in options.targets:
208 generator.generate_target(target)