Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | """Common test generation classes and main function. |
| 3 | |
| 4 | These are used both by generate_psa_tests.py and generate_bignum_tests.py. |
| 5 | """ |
| 6 | |
| 7 | # Copyright The Mbed TLS Contributors |
| 8 | # SPDX-License-Identifier: Apache-2.0 |
| 9 | # |
| 10 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 11 | # not use this file except in compliance with the License. |
| 12 | # You may obtain a copy of the License at |
| 13 | # |
| 14 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | # |
| 16 | # Unless required by applicable law or agreed to in writing, software |
| 17 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 18 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 19 | # See the License for the specific language governing permissions and |
| 20 | # limitations under the License. |
| 21 | |
| 22 | import argparse |
| 23 | import os |
| 24 | import posixpath |
| 25 | import re |
Werner Lewis | 008d90d | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 26 | |
Werner Lewis | 47e37b3 | 2022-08-24 12:18:25 +0100 | [diff] [blame] | 27 | from abc import ABCMeta, abstractmethod |
Werner Lewis | c34d037 | 2022-08-24 12:42:00 +0100 | [diff] [blame] | 28 | from typing import Callable, Dict, Iterable, Iterator, List, Type, TypeVar |
Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 29 | |
| 30 | from mbedtls_dev import test_case |
| 31 | |
| 32 | T = TypeVar('T') #pylint: disable=invalid-name |
| 33 | |
| 34 | |
Werner Lewis | 47e37b3 | 2022-08-24 12:18:25 +0100 | [diff] [blame] | 35 | class BaseTarget(metaclass=ABCMeta): |
Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 36 | """Base target for test case generation. |
| 37 | |
| 38 | Attributes: |
Werner Lewis | 70d3f3d | 2022-08-23 14:21:53 +0100 | [diff] [blame] | 39 | 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 Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 47 | """ |
| 48 | count = 0 |
Werner Lewis | 70d3f3d | 2022-08-23 14:21:53 +0100 | [diff] [blame] | 49 | case_description = "" |
| 50 | target_basename = "" |
| 51 | test_function = "" |
| 52 | test_name = "" |
Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 53 | |
Werner Lewis | cace1aa | 2022-08-24 17:04:07 +0100 | [diff] [blame^] | 54 | def __new__(cls, *args, **kwargs): |
| 55 | cls.count += 1 |
| 56 | return super().__new__(cls) |
Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 57 | |
Werner Lewis | 008d90d | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 58 | @abstractmethod |
Werner Lewis | 70d3f3d | 2022-08-23 14:21:53 +0100 | [diff] [blame] | 59 | def arguments(self) -> List[str]: |
Werner Lewis | 008d90d | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 60 | """Get the list of arguments for the test case. |
| 61 | |
| 62 | Override this method to provide the list of arguments required for |
| 63 | generating the test_function. |
| 64 | |
| 65 | Returns: |
| 66 | List of arguments required for the test function. |
| 67 | """ |
| 68 | pass |
Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 69 | |
Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 70 | def description(self) -> str: |
Werner Lewis | 008d90d | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 71 | """Create a test description. |
| 72 | |
| 73 | Creates a description of the test case, including a name for the test |
| 74 | function, and describing the specific test case. This should inform a |
| 75 | reader of the purpose of the case. The case description may be |
| 76 | generated in the class, or provided manually as needed. |
| 77 | |
| 78 | Returns: |
| 79 | Description for the test case. |
| 80 | """ |
Werner Lewis | 70d3f3d | 2022-08-23 14:21:53 +0100 | [diff] [blame] | 81 | return "{} #{} {}".format(self.test_name, self.count, self.case_description) |
Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 82 | |
Werner Lewis | 008d90d | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 83 | |
Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 84 | def create_test_case(self) -> test_case.TestCase: |
Werner Lewis | 008d90d | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 85 | """Generate TestCase from the current object.""" |
Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 86 | tc = test_case.TestCase() |
Werner Lewis | 70d3f3d | 2022-08-23 14:21:53 +0100 | [diff] [blame] | 87 | tc.set_description(self.description()) |
| 88 | tc.set_function(self.test_function) |
| 89 | tc.set_arguments(self.arguments()) |
Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 90 | |
| 91 | return tc |
| 92 | |
| 93 | @classmethod |
Werner Lewis | c34d037 | 2022-08-24 12:42:00 +0100 | [diff] [blame] | 94 | @abstractmethod |
| 95 | def generate_function_tests(cls) -> Iterator[test_case.TestCase]: |
| 96 | """Generate test cases for the test function. |
Werner Lewis | 008d90d | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 97 | |
Werner Lewis | c34d037 | 2022-08-24 12:42:00 +0100 | [diff] [blame] | 98 | This will be called in classes where `test_function` is set. |
| 99 | Implementations should yield TestCase objects, by creating instances |
| 100 | of the class with appropriate input data, and then calling |
| 101 | `create_test_case()` on each. |
Werner Lewis | 008d90d | 2022-08-23 16:07:37 +0100 | [diff] [blame] | 102 | """ |
Werner Lewis | c34d037 | 2022-08-24 12:42:00 +0100 | [diff] [blame] | 103 | pass |
| 104 | |
| 105 | @classmethod |
| 106 | def generate_tests(cls) -> Iterator[test_case.TestCase]: |
| 107 | """Generate test cases for the class and its subclasses. |
| 108 | |
| 109 | In classes with `test_function` set, `generate_function_tests()` is |
| 110 | used to generate test cases first. |
| 111 | In all classes, this method will iterate over its subclasses, and |
| 112 | yield from `generate_tests()` in each. |
| 113 | |
| 114 | Calling this method on a class X will yield test cases from all classes |
| 115 | derived from X. |
| 116 | """ |
| 117 | if cls.test_function: |
| 118 | yield from cls.generate_function_tests() |
Werner Lewis | dcad1e9 | 2022-08-24 11:30:03 +0100 | [diff] [blame] | 119 | for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__): |
| 120 | yield from subclass.generate_tests() |
| 121 | |
| 122 | |
| 123 | class TestGenerator: |
| 124 | """Generate test data.""" |
| 125 | def __init__(self, options) -> None: |
| 126 | self.test_suite_directory = self.get_option(options, 'directory', |
| 127 | 'tests/suites') |
| 128 | |
| 129 | @staticmethod |
| 130 | def get_option(options, name: str, default: T) -> T: |
| 131 | value = getattr(options, name, None) |
| 132 | return default if value is None else value |
| 133 | |
| 134 | def filename_for(self, basename: str) -> str: |
| 135 | """The location of the data file with the specified base name.""" |
| 136 | return posixpath.join(self.test_suite_directory, basename + '.data') |
| 137 | |
| 138 | def write_test_data_file(self, basename: str, |
| 139 | test_cases: Iterable[test_case.TestCase]) -> None: |
| 140 | """Write the test cases to a .data file. |
| 141 | |
| 142 | The output file is ``basename + '.data'`` in the test suite directory. |
| 143 | """ |
| 144 | filename = self.filename_for(basename) |
| 145 | test_case.write_data_file(filename, test_cases) |
| 146 | |
| 147 | # Note that targets whose names contain 'test_format' have their content |
| 148 | # validated by `abi_check.py`. |
| 149 | TARGETS = {} # type: Dict[str, Callable[..., test_case.TestCase]] |
| 150 | |
| 151 | def generate_target(self, name: str, *target_args) -> None: |
| 152 | """Generate cases and write to data file for a target. |
| 153 | |
| 154 | For target callables which require arguments, override this function |
| 155 | and pass these arguments using super() (see PSATestGenerator). |
| 156 | """ |
| 157 | test_cases = self.TARGETS[name](*target_args) |
| 158 | self.write_test_data_file(name, test_cases) |
| 159 | |
| 160 | def main(args, generator_class: Type[TestGenerator] = TestGenerator): |
| 161 | """Command line entry point.""" |
| 162 | parser = argparse.ArgumentParser(description=__doc__) |
| 163 | parser.add_argument('--list', action='store_true', |
| 164 | help='List available targets and exit') |
| 165 | parser.add_argument('targets', nargs='*', metavar='TARGET', |
| 166 | help='Target file to generate (default: all; "-": none)') |
| 167 | options = parser.parse_args(args) |
| 168 | generator = generator_class(options) |
| 169 | if options.list: |
| 170 | for name in sorted(generator.TARGETS): |
| 171 | print(generator.filename_for(name)) |
| 172 | return |
| 173 | if options.targets: |
| 174 | # Allow "-" as a special case so you can run |
| 175 | # ``generate_xxx_tests.py - $targets`` and it works uniformly whether |
| 176 | # ``$targets`` is empty or not. |
| 177 | options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target)) |
| 178 | for target in options.targets |
| 179 | if target != '-'] |
| 180 | else: |
| 181 | options.targets = sorted(generator.TARGETS) |
| 182 | for target in options.targets: |
| 183 | generator.generate_target(target) |