Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 1 | """Common test generation classes and main function. |
| 2 | |
| 3 | These 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 | |
| 21 | import argparse |
| 22 | import os |
| 23 | import posixpath |
| 24 | import re |
Werner Lewis | 169034a | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 25 | |
Werner Lewis | 699e126 | 2022-08-24 12:18:25 +0100 | [diff] [blame] | 26 | from abc import ABCMeta, abstractmethod |
Werner Lewis | 2b527a3 | 2022-08-24 12:42:00 +0100 | [diff] [blame] | 27 | from typing import Callable, Dict, Iterable, Iterator, List, Type, TypeVar |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 28 | |
| 29 | from mbedtls_dev import build_tree |
| 30 | from mbedtls_dev import test_case |
| 31 | |
| 32 | T = TypeVar('T') #pylint: disable=invalid-name |
| 33 | |
| 34 | |
Werner Lewis | 699e126 | 2022-08-24 12:18:25 +0100 | [diff] [blame] | 35 | class BaseTarget(metaclass=ABCMeta): |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 36 | """Base target for test case generation. |
| 37 | |
Werner Lewis | 81f2444 | 2022-08-25 16:27:05 +0100 | [diff] [blame] | 38 | Derive directly from this class when adding new file Targets, setting |
| 39 | `target_basename`. |
Werner Lewis | 6ef5436 | 2022-08-25 12:29:46 +0100 | [diff] [blame] | 40 | |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 41 | Attributes: |
Werner Lewis | 55e638c | 2022-08-23 14:21:53 +0100 | [diff] [blame] | 42 | 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 Lewis | 466f036 | 2022-08-31 17:01:38 +0100 | [diff] [blame] | 45 | dependencies: A list of dependencies required for the test case. |
Werner Lewis | 55e638c | 2022-08-23 14:21:53 +0100 | [diff] [blame] | 46 | target_basename: Basename of file to write generated tests to. This |
| 47 | should be specified in a child class of BaseTarget. |
| 48 | 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 Lewis | 6ef5436 | 2022-08-25 12:29:46 +0100 | [diff] [blame] | 50 | be `test_function`, a clearer equivalent, or a short summary of the |
| 51 | test function's purpose. |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 52 | """ |
| 53 | count = 0 |
Werner Lewis | 55e638c | 2022-08-23 14:21:53 +0100 | [diff] [blame] | 54 | case_description = "" |
Werner Lewis | aaf3b79 | 2022-08-31 17:16:44 +0100 | [diff] [blame^] | 55 | dependencies = [] # type: List[str] |
Werner Lewis | 55e638c | 2022-08-23 14:21:53 +0100 | [diff] [blame] | 56 | target_basename = "" |
| 57 | test_function = "" |
| 58 | test_name = "" |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 59 | |
Werner Lewis | cfd4768 | 2022-08-24 17:04:07 +0100 | [diff] [blame] | 60 | def __new__(cls, *args, **kwargs): |
Werner Lewis | a195ce7 | 2022-08-24 18:09:10 +0100 | [diff] [blame] | 61 | # pylint: disable=unused-argument |
Werner Lewis | cfd4768 | 2022-08-24 17:04:07 +0100 | [diff] [blame] | 62 | cls.count += 1 |
| 63 | return super().__new__(cls) |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 64 | |
Werner Lewis | 169034a | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 65 | @abstractmethod |
Werner Lewis | 55e638c | 2022-08-23 14:21:53 +0100 | [diff] [blame] | 66 | def arguments(self) -> List[str]: |
Werner Lewis | 169034a | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 67 | """Get the list of arguments for the test case. |
| 68 | |
| 69 | Override this method to provide the list of arguments required for |
Werner Lewis | 6ef5436 | 2022-08-25 12:29:46 +0100 | [diff] [blame] | 70 | the `test_function`. |
Werner Lewis | 169034a | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 71 | |
| 72 | Returns: |
| 73 | List of arguments required for the test function. |
| 74 | """ |
Werner Lewis | 6d654c6 | 2022-08-25 09:56:51 +0100 | [diff] [blame] | 75 | raise NotImplementedError |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 76 | |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 77 | def description(self) -> str: |
Werner Lewis | 6ef5436 | 2022-08-25 12:29:46 +0100 | [diff] [blame] | 78 | """Create a test case description. |
Werner Lewis | 169034a | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 79 | |
| 80 | Creates a description of the test case, including a name for the test |
Werner Lewis | 6ef5436 | 2022-08-25 12:29:46 +0100 | [diff] [blame] | 81 | function, a case number, and a description the specific test case. |
| 82 | This should inform a reader what is being tested, and provide context |
| 83 | for the test case. |
Werner Lewis | 169034a | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 84 | |
| 85 | Returns: |
| 86 | Description for the test case. |
| 87 | """ |
Werner Lewis | d03d2a3 | 2022-08-24 17:20:29 +0100 | [diff] [blame] | 88 | return "{} #{} {}".format( |
| 89 | self.test_name, self.count, self.case_description |
| 90 | ).strip() |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 91 | |
Werner Lewis | 169034a | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 92 | |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 93 | def create_test_case(self) -> test_case.TestCase: |
Werner Lewis | 6ef5436 | 2022-08-25 12:29:46 +0100 | [diff] [blame] | 94 | """Generate TestCase from the instance.""" |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 95 | tc = test_case.TestCase() |
Werner Lewis | 55e638c | 2022-08-23 14:21:53 +0100 | [diff] [blame] | 96 | tc.set_description(self.description()) |
| 97 | tc.set_function(self.test_function) |
| 98 | tc.set_arguments(self.arguments()) |
Werner Lewis | 466f036 | 2022-08-31 17:01:38 +0100 | [diff] [blame] | 99 | tc.set_dependencies(self.dependencies) |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 100 | |
| 101 | return tc |
| 102 | |
| 103 | @classmethod |
Werner Lewis | 2b527a3 | 2022-08-24 12:42:00 +0100 | [diff] [blame] | 104 | @abstractmethod |
| 105 | def generate_function_tests(cls) -> Iterator[test_case.TestCase]: |
Werner Lewis | 6ef5436 | 2022-08-25 12:29:46 +0100 | [diff] [blame] | 106 | """Generate test cases for the class test function. |
Werner Lewis | 169034a | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 107 | |
Werner Lewis | 2b527a3 | 2022-08-24 12:42:00 +0100 | [diff] [blame] | 108 | This will be called in classes where `test_function` is set. |
| 109 | Implementations should yield TestCase objects, by creating instances |
| 110 | of the class with appropriate input data, and then calling |
| 111 | `create_test_case()` on each. |
Werner Lewis | 169034a | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 112 | """ |
Werner Lewis | 6d654c6 | 2022-08-25 09:56:51 +0100 | [diff] [blame] | 113 | raise NotImplementedError |
Werner Lewis | 2b527a3 | 2022-08-24 12:42:00 +0100 | [diff] [blame] | 114 | |
| 115 | @classmethod |
| 116 | def generate_tests(cls) -> Iterator[test_case.TestCase]: |
| 117 | """Generate test cases for the class and its subclasses. |
| 118 | |
| 119 | In classes with `test_function` set, `generate_function_tests()` is |
Werner Lewis | 81f2444 | 2022-08-25 16:27:05 +0100 | [diff] [blame] | 120 | called to generate test cases first. |
Werner Lewis | 2b527a3 | 2022-08-24 12:42:00 +0100 | [diff] [blame] | 121 | |
Werner Lewis | 6ef5436 | 2022-08-25 12:29:46 +0100 | [diff] [blame] | 122 | In all classes, this method will iterate over its subclasses, and |
| 123 | yield from `generate_tests()` in each. Calling this method on a class X |
| 124 | will yield test cases from all classes derived from X. |
Werner Lewis | 2b527a3 | 2022-08-24 12:42:00 +0100 | [diff] [blame] | 125 | """ |
| 126 | if cls.test_function: |
| 127 | yield from cls.generate_function_tests() |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 128 | for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__): |
| 129 | yield from subclass.generate_tests() |
| 130 | |
| 131 | |
| 132 | class TestGenerator: |
| 133 | """Generate test data.""" |
| 134 | def __init__(self, options) -> None: |
Werner Lewis | f156c43 | 2022-08-25 11:30:17 +0100 | [diff] [blame] | 135 | self.test_suite_directory = getattr(options, 'directory') |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 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 Lewis | e3ad22e | 2022-08-25 10:02:06 +0100 | [diff] [blame] | 152 | TARGETS = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]] |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 153 | |
| 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 | |
| 163 | def 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') |
Werner Lewis | f156c43 | 2022-08-25 11:30:17 +0100 | [diff] [blame] | 170 | parser.add_argument('--directory', default="tests/suites", metavar='DIR', |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 171 | help='Output directory (default: tests/suites)') |
| 172 | parser.add_argument('targets', nargs='*', metavar='TARGET', |
Werner Lewis | 76f4562 | 2022-08-25 13:21:45 +0100 | [diff] [blame] | 173 | default=sorted(generator_class.TARGETS), |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 174 | help='Target file to generate (default: all; "-": none)') |
| 175 | options = parser.parse_args(args) |
| 176 | build_tree.chdir_to_root() |
| 177 | generator = generator_class(options) |
| 178 | if options.list: |
| 179 | for name in sorted(generator.TARGETS): |
| 180 | print(generator.filename_for(name)) |
| 181 | return |
| 182 | # List in a cmake list format (i.e. ';'-separated) |
| 183 | if options.list_for_cmake: |
| 184 | print(';'.join(generator.filename_for(name) |
| 185 | for name in sorted(generator.TARGETS)), end='') |
| 186 | return |
Werner Lewis | 9df9faa | 2022-08-25 12:49:41 +0100 | [diff] [blame] | 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 != '-'] |
Werner Lewis | fbb75e3 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 193 | for target in options.targets: |
| 194 | generator.generate_target(target) |