blob: 3d703eec7d945e5f0d4a2a9910b23dbfb11d67a4 [file] [log] [blame]
Gilles Peskine04904252022-09-16 22:02:37 +02001"""Common code for test data generation.
2
3This module defines classes that are of general use to automatically
4generate .data files for unit tests, as well as a main function.
Werner Lewisfbb75e32022-08-24 11:30:03 +01005
6These are used both by generate_psa_tests.py and generate_bignum_tests.py.
7"""
8
9# Copyright The Mbed TLS Contributors
10# SPDX-License-Identifier: Apache-2.0
11#
12# Licensed under the Apache License, Version 2.0 (the "License"); you may
13# not use this file except in compliance with the License.
14# You may obtain a copy of the License at
15#
16# http://www.apache.org/licenses/LICENSE-2.0
17#
18# Unless required by applicable law or agreed to in writing, software
19# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
20# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21# See the License for the specific language governing permissions and
22# limitations under the License.
23
24import argparse
25import os
26import posixpath
27import re
Janos Follath0cd89672022-11-09 12:14:14 +000028import inspect
Werner Lewis169034a2022-08-23 16:07:37 +010029
Werner Lewis699e1262022-08-24 12:18:25 +010030from abc import ABCMeta, abstractmethod
Werner Lewis2b527a32022-08-24 12:42:00 +010031from typing import Callable, Dict, Iterable, Iterator, List, Type, TypeVar
Werner Lewisfbb75e32022-08-24 11:30:03 +010032
Gilles Peskine15997bd2022-09-16 22:35:18 +020033from . import build_tree
34from . import test_case
Werner Lewisfbb75e32022-08-24 11:30:03 +010035
36T = TypeVar('T') #pylint: disable=invalid-name
37
38
Janos Follath0cd89672022-11-09 12:14:14 +000039class BaseTest(metaclass=ABCMeta):
40 """Base class for test case generation.
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 test_function: Test function which the class generates cases for.
49 test_name: A common name or description of the test function. This can
Werner Lewis6ef54362022-08-25 12:29:46 +010050 be `test_function`, a clearer equivalent, or a short summary of the
51 test function's purpose.
Werner Lewisfbb75e32022-08-24 11:30:03 +010052 """
53 count = 0
Werner Lewis55e638c2022-08-23 14:21:53 +010054 case_description = ""
Werner Lewisaaf3b792022-08-31 17:16:44 +010055 dependencies = [] # type: List[str]
Werner Lewis858cffd2022-09-14 13:02:40 +010056 show_test_count = True
Werner Lewis55e638c2022-08-23 14:21:53 +010057 test_function = ""
58 test_name = ""
Werner Lewisfbb75e32022-08-24 11:30:03 +010059
Werner Lewiscfd47682022-08-24 17:04:07 +010060 def __new__(cls, *args, **kwargs):
Werner Lewisa195ce72022-08-24 18:09:10 +010061 # pylint: disable=unused-argument
Werner Lewiscfd47682022-08-24 17:04:07 +010062 cls.count += 1
63 return super().__new__(cls)
Werner Lewisfbb75e32022-08-24 11:30:03 +010064
Werner Lewis169034a2022-08-23 16:07:37 +010065 @abstractmethod
Werner Lewis55e638c2022-08-23 14:21:53 +010066 def arguments(self) -> List[str]:
Werner Lewis169034a2022-08-23 16:07:37 +010067 """Get the list of arguments for the test case.
68
69 Override this method to provide the list of arguments required for
Werner Lewis6ef54362022-08-25 12:29:46 +010070 the `test_function`.
Werner Lewis169034a2022-08-23 16:07:37 +010071
72 Returns:
73 List of arguments required for the test function.
74 """
Werner Lewis6d654c62022-08-25 09:56:51 +010075 raise NotImplementedError
Werner Lewisfbb75e32022-08-24 11:30:03 +010076
Werner Lewisfbb75e32022-08-24 11:30:03 +010077 def description(self) -> str:
Werner Lewis6ef54362022-08-25 12:29:46 +010078 """Create a test case description.
Werner Lewis169034a2022-08-23 16:07:37 +010079
80 Creates a description of the test case, including a name for the test
Werner Lewis858cffd2022-09-14 13:02:40 +010081 function, an optional case count, and a description of the specific
82 test case. This should inform a reader what is being tested, and
83 provide context for the test case.
Werner Lewis169034a2022-08-23 16:07:37 +010084
85 Returns:
86 Description for the test case.
87 """
Werner Lewis858cffd2022-09-14 13:02:40 +010088 if self.show_test_count:
89 return "{} #{} {}".format(
90 self.test_name, self.count, self.case_description
91 ).strip()
92 else:
93 return "{} {}".format(self.test_name, self.case_description).strip()
Werner Lewisfbb75e32022-08-24 11:30:03 +010094
Werner Lewis169034a2022-08-23 16:07:37 +010095
Werner Lewisfbb75e32022-08-24 11:30:03 +010096 def create_test_case(self) -> test_case.TestCase:
Werner Lewis6ef54362022-08-25 12:29:46 +010097 """Generate TestCase from the instance."""
Werner Lewisfbb75e32022-08-24 11:30:03 +010098 tc = test_case.TestCase()
Werner Lewis55e638c2022-08-23 14:21:53 +010099 tc.set_description(self.description())
100 tc.set_function(self.test_function)
101 tc.set_arguments(self.arguments())
Werner Lewis466f0362022-08-31 17:01:38 +0100102 tc.set_dependencies(self.dependencies)
Werner Lewisfbb75e32022-08-24 11:30:03 +0100103
104 return tc
105
106 @classmethod
Werner Lewis2b527a32022-08-24 12:42:00 +0100107 @abstractmethod
108 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Werner Lewis6ef54362022-08-25 12:29:46 +0100109 """Generate test cases for the class test function.
Werner Lewis169034a2022-08-23 16:07:37 +0100110
Werner Lewis2b527a32022-08-24 12:42:00 +0100111 This will be called in classes where `test_function` is set.
112 Implementations should yield TestCase objects, by creating instances
113 of the class with appropriate input data, and then calling
114 `create_test_case()` on each.
Werner Lewis169034a2022-08-23 16:07:37 +0100115 """
Werner Lewis6d654c62022-08-25 09:56:51 +0100116 raise NotImplementedError
Werner Lewis2b527a32022-08-24 12:42:00 +0100117
Janos Follath0cd89672022-11-09 12:14:14 +0000118
119class BaseTarget:
120 """Base target for test case generation.
121
122 Child classes of this class represent an output file, and can be referred
123 to as file targets. These indicate where test cases will be written to for
124 all subclasses of the file target, which is set by `target_basename`.
125
126 Attributes:
127 target_basename: Basename of file to write generated tests to. This
128 should be specified in a child class of BaseTarget.
129 """
130 target_basename = ""
131
Werner Lewis2b527a32022-08-24 12:42:00 +0100132 @classmethod
133 def generate_tests(cls) -> Iterator[test_case.TestCase]:
134 """Generate test cases for the class and its subclasses.
135
136 In classes with `test_function` set, `generate_function_tests()` is
Werner Lewis81f24442022-08-25 16:27:05 +0100137 called to generate test cases first.
Werner Lewis2b527a32022-08-24 12:42:00 +0100138
Werner Lewis6ef54362022-08-25 12:29:46 +0100139 In all classes, this method will iterate over its subclasses, and
140 yield from `generate_tests()` in each. Calling this method on a class X
141 will yield test cases from all classes derived from X.
Werner Lewis2b527a32022-08-24 12:42:00 +0100142 """
Janos Follath0cd89672022-11-09 12:14:14 +0000143 if issubclass(cls, BaseTest) and not inspect.isabstract(cls):
Werner Lewis2b527a32022-08-24 12:42:00 +0100144 yield from cls.generate_function_tests()
Werner Lewisfbb75e32022-08-24 11:30:03 +0100145 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
146 yield from subclass.generate_tests()
147
148
149class TestGenerator:
Werner Lewis34d6d3e2022-09-14 12:59:32 +0100150 """Generate test cases and write to data files."""
Werner Lewisfbb75e32022-08-24 11:30:03 +0100151 def __init__(self, options) -> None:
Gilles Peskine7b3fa652022-09-16 22:22:53 +0200152 self.test_suite_directory = options.directory
Werner Lewis34d6d3e2022-09-14 12:59:32 +0100153 # Update `targets` with an entry for each child class of BaseTarget.
154 # Each entry represents a file generated by the BaseTarget framework,
155 # and enables generating the .data files using the CLI.
Werner Lewisa4668a62022-09-02 11:56:34 +0100156 self.targets.update({
157 subclass.target_basename: subclass.generate_tests
158 for subclass in BaseTarget.__subclasses__()
Werner Lewis99e81782022-09-30 16:28:43 +0100159 if subclass.target_basename
Werner Lewisa4668a62022-09-02 11:56:34 +0100160 })
Werner Lewisfbb75e32022-08-24 11:30:03 +0100161
162 def filename_for(self, basename: str) -> str:
163 """The location of the data file with the specified base name."""
164 return posixpath.join(self.test_suite_directory, basename + '.data')
165
166 def write_test_data_file(self, basename: str,
167 test_cases: Iterable[test_case.TestCase]) -> None:
168 """Write the test cases to a .data file.
169
170 The output file is ``basename + '.data'`` in the test suite directory.
171 """
172 filename = self.filename_for(basename)
173 test_case.write_data_file(filename, test_cases)
174
175 # Note that targets whose names contain 'test_format' have their content
176 # validated by `abi_check.py`.
Werner Lewisa4668a62022-09-02 11:56:34 +0100177 targets = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
Werner Lewisfbb75e32022-08-24 11:30:03 +0100178
179 def generate_target(self, name: str, *target_args) -> None:
180 """Generate cases and write to data file for a target.
181
182 For target callables which require arguments, override this function
183 and pass these arguments using super() (see PSATestGenerator).
184 """
Werner Lewisa4668a62022-09-02 11:56:34 +0100185 test_cases = self.targets[name](*target_args)
Werner Lewisfbb75e32022-08-24 11:30:03 +0100186 self.write_test_data_file(name, test_cases)
187
Werner Lewisc2fb5402022-09-16 17:03:54 +0100188def main(args, description: str, generator_class: Type[TestGenerator] = TestGenerator):
Werner Lewisfbb75e32022-08-24 11:30:03 +0100189 """Command line entry point."""
Werner Lewisc2fb5402022-09-16 17:03:54 +0100190 parser = argparse.ArgumentParser(description=description)
Werner Lewisfbb75e32022-08-24 11:30:03 +0100191 parser.add_argument('--list', action='store_true',
192 help='List available targets and exit')
193 parser.add_argument('--list-for-cmake', action='store_true',
194 help='Print \';\'-separated list of available targets and exit')
Gilles Peskine7b3fa652022-09-16 22:22:53 +0200195 # If specified explicitly, this option may be a path relative to the
196 # current directory when the script is invoked. The default value
197 # is relative to the mbedtls root, which we don't know yet. So we
198 # can't set a string as the default value here.
Werner Lewis00d02422022-09-14 13:39:20 +0100199 parser.add_argument('--directory', metavar='DIR',
Werner Lewisfbb75e32022-08-24 11:30:03 +0100200 help='Output directory (default: tests/suites)')
201 parser.add_argument('targets', nargs='*', metavar='TARGET',
202 help='Target file to generate (default: all; "-": none)')
203 options = parser.parse_args(args)
Gilles Peskine7b3fa652022-09-16 22:22:53 +0200204
205 # Change to the mbedtls root, to keep things simple. But first, adjust
206 # command line options that might be relative paths.
207 if options.directory is None:
208 options.directory = 'tests/suites'
209 else:
210 options.directory = os.path.abspath(options.directory)
Werner Lewisfbb75e32022-08-24 11:30:03 +0100211 build_tree.chdir_to_root()
Gilles Peskine7b3fa652022-09-16 22:22:53 +0200212
Werner Lewisfbb75e32022-08-24 11:30:03 +0100213 generator = generator_class(options)
214 if options.list:
Werner Lewisa4668a62022-09-02 11:56:34 +0100215 for name in sorted(generator.targets):
Werner Lewisfbb75e32022-08-24 11:30:03 +0100216 print(generator.filename_for(name))
217 return
218 # List in a cmake list format (i.e. ';'-separated)
219 if options.list_for_cmake:
220 print(';'.join(generator.filename_for(name)
Werner Lewisa4668a62022-09-02 11:56:34 +0100221 for name in sorted(generator.targets)), end='')
Werner Lewisfbb75e32022-08-24 11:30:03 +0100222 return
Werner Lewisa4668a62022-09-02 11:56:34 +0100223 if options.targets:
224 # Allow "-" as a special case so you can run
225 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
226 # ``$targets`` is empty or not.
227 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
Werner Lewis56013082022-09-02 12:57:37 +0100228 for target in options.targets
229 if target != '-']
Werner Lewisa4668a62022-09-02 11:56:34 +0100230 else:
231 options.targets = sorted(generator.targets)
Werner Lewisfbb75e32022-08-24 11:30:03 +0100232 for target in options.targets:
233 generator.generate_target(target)