blob: 2b90ef4b790c69244ae337059151461b5d09deb9 [file] [log] [blame]
Gilles Peskinebd5147c2022-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 Lewisdcad1e92022-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
Werner Lewis008d90d2022-08-23 16:07:37 +010028
Werner Lewis47e37b32022-08-24 12:18:25 +010029from abc import ABCMeta, abstractmethod
Werner Lewisc34d0372022-08-24 12:42:00 +010030from typing import Callable, Dict, Iterable, Iterator, List, Type, TypeVar
Werner Lewisdcad1e92022-08-24 11:30:03 +010031
32from mbedtls_dev import test_case
33
34T = TypeVar('T') #pylint: disable=invalid-name
35
36
Werner Lewis47e37b32022-08-24 12:18:25 +010037class BaseTarget(metaclass=ABCMeta):
Werner Lewisdcad1e92022-08-24 11:30:03 +010038 """Base target for test case generation.
39
Werner Lewis64334d92022-09-14 16:26:54 +010040 Child classes of this class represent an output file, and can be referred
41 to as file targets. These indicate where test cases will be written to for
42 all subclasses of the file target, which is set by `target_basename`.
Werner Lewisb03420f2022-08-25 12:29:46 +010043
Werner Lewisdcad1e92022-08-24 11:30:03 +010044 Attributes:
Werner Lewis70d3f3d2022-08-23 14:21:53 +010045 count: Counter for test cases from this class.
46 case_description: Short description of the test case. This may be
47 automatically generated using the class, or manually set.
Werner Lewis486b3412022-08-31 17:01:38 +010048 dependencies: A list of dependencies required for the test case.
Werner Lewis113ddd02022-09-14 13:02:40 +010049 show_test_count: Toggle for inclusion of `count` in the test description.
Werner Lewis70d3f3d2022-08-23 14:21:53 +010050 target_basename: Basename of file to write generated tests to. This
51 should be specified in a child class of BaseTarget.
52 test_function: Test function which the class generates cases for.
53 test_name: A common name or description of the test function. This can
Werner Lewisb03420f2022-08-25 12:29:46 +010054 be `test_function`, a clearer equivalent, or a short summary of the
55 test function's purpose.
Werner Lewisdcad1e92022-08-24 11:30:03 +010056 """
57 count = 0
Werner Lewis70d3f3d2022-08-23 14:21:53 +010058 case_description = ""
Werner Lewis6cc5e5f2022-08-31 17:16:44 +010059 dependencies = [] # type: List[str]
Werner Lewis113ddd02022-09-14 13:02:40 +010060 show_test_count = True
Werner Lewis70d3f3d2022-08-23 14:21:53 +010061 target_basename = ""
62 test_function = ""
63 test_name = ""
Werner Lewisdcad1e92022-08-24 11:30:03 +010064
Werner Lewiscace1aa2022-08-24 17:04:07 +010065 def __new__(cls, *args, **kwargs):
Werner Lewis486d2582022-08-24 18:09:10 +010066 # pylint: disable=unused-argument
Werner Lewiscace1aa2022-08-24 17:04:07 +010067 cls.count += 1
68 return super().__new__(cls)
Werner Lewisdcad1e92022-08-24 11:30:03 +010069
Werner Lewis008d90d2022-08-23 16:07:37 +010070 @abstractmethod
Werner Lewis70d3f3d2022-08-23 14:21:53 +010071 def arguments(self) -> List[str]:
Werner Lewis008d90d2022-08-23 16:07:37 +010072 """Get the list of arguments for the test case.
73
74 Override this method to provide the list of arguments required for
Werner Lewisb03420f2022-08-25 12:29:46 +010075 the `test_function`.
Werner Lewis008d90d2022-08-23 16:07:37 +010076
77 Returns:
78 List of arguments required for the test function.
79 """
Werner Lewisd77d33d2022-08-25 09:56:51 +010080 raise NotImplementedError
Werner Lewisdcad1e92022-08-24 11:30:03 +010081
Werner Lewisdcad1e92022-08-24 11:30:03 +010082 def description(self) -> str:
Werner Lewisb03420f2022-08-25 12:29:46 +010083 """Create a test case description.
Werner Lewis008d90d2022-08-23 16:07:37 +010084
85 Creates a description of the test case, including a name for the test
Werner Lewis113ddd02022-09-14 13:02:40 +010086 function, an optional case count, and a description of the specific
87 test case. This should inform a reader what is being tested, and
88 provide context for the test case.
Werner Lewis008d90d2022-08-23 16:07:37 +010089
90 Returns:
91 Description for the test case.
92 """
Werner Lewis113ddd02022-09-14 13:02:40 +010093 if self.show_test_count:
94 return "{} #{} {}".format(
95 self.test_name, self.count, self.case_description
96 ).strip()
97 else:
98 return "{} {}".format(self.test_name, self.case_description).strip()
Werner Lewisdcad1e92022-08-24 11:30:03 +010099
Werner Lewis008d90d2022-08-23 16:07:37 +0100100
Werner Lewisdcad1e92022-08-24 11:30:03 +0100101 def create_test_case(self) -> test_case.TestCase:
Werner Lewisb03420f2022-08-25 12:29:46 +0100102 """Generate TestCase from the instance."""
Werner Lewisdcad1e92022-08-24 11:30:03 +0100103 tc = test_case.TestCase()
Werner Lewis70d3f3d2022-08-23 14:21:53 +0100104 tc.set_description(self.description())
105 tc.set_function(self.test_function)
106 tc.set_arguments(self.arguments())
Werner Lewis486b3412022-08-31 17:01:38 +0100107 tc.set_dependencies(self.dependencies)
Werner Lewisdcad1e92022-08-24 11:30:03 +0100108
109 return tc
110
111 @classmethod
Werner Lewisc34d0372022-08-24 12:42:00 +0100112 @abstractmethod
113 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Werner Lewisb03420f2022-08-25 12:29:46 +0100114 """Generate test cases for the class test function.
Werner Lewis008d90d2022-08-23 16:07:37 +0100115
Werner Lewisc34d0372022-08-24 12:42:00 +0100116 This will be called in classes where `test_function` is set.
117 Implementations should yield TestCase objects, by creating instances
118 of the class with appropriate input data, and then calling
119 `create_test_case()` on each.
Werner Lewis008d90d2022-08-23 16:07:37 +0100120 """
Werner Lewisd77d33d2022-08-25 09:56:51 +0100121 raise NotImplementedError
Werner Lewisc34d0372022-08-24 12:42:00 +0100122
123 @classmethod
124 def generate_tests(cls) -> Iterator[test_case.TestCase]:
125 """Generate test cases for the class and its subclasses.
126
127 In classes with `test_function` set, `generate_function_tests()` is
Werner Lewis2b0f7d82022-08-25 16:27:05 +0100128 called to generate test cases first.
Werner Lewisc34d0372022-08-24 12:42:00 +0100129
Werner Lewisb03420f2022-08-25 12:29:46 +0100130 In all classes, this method will iterate over its subclasses, and
131 yield from `generate_tests()` in each. Calling this method on a class X
132 will yield test cases from all classes derived from X.
Werner Lewisc34d0372022-08-24 12:42:00 +0100133 """
134 if cls.test_function:
135 yield from cls.generate_function_tests()
Werner Lewisdcad1e92022-08-24 11:30:03 +0100136 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
137 yield from subclass.generate_tests()
138
139
140class TestGenerator:
Werner Lewisf5182762022-09-14 12:59:32 +0100141 """Generate test cases and write to data files."""
Werner Lewisdcad1e92022-08-24 11:30:03 +0100142 def __init__(self, options) -> None:
143 self.test_suite_directory = self.get_option(options, 'directory',
144 'tests/suites')
Werner Lewisf5182762022-09-14 12:59:32 +0100145 # Update `targets` with an entry for each child class of BaseTarget.
146 # Each entry represents a file generated by the BaseTarget framework,
147 # and enables generating the .data files using the CLI.
Werner Lewis0d07e862022-09-02 11:56:34 +0100148 self.targets.update({
149 subclass.target_basename: subclass.generate_tests
150 for subclass in BaseTarget.__subclasses__()
151 })
Werner Lewisdcad1e92022-08-24 11:30:03 +0100152
153 @staticmethod
154 def get_option(options, name: str, default: T) -> T:
155 value = getattr(options, name, None)
156 return default if value is None else value
157
158 def filename_for(self, basename: str) -> str:
159 """The location of the data file with the specified base name."""
160 return posixpath.join(self.test_suite_directory, basename + '.data')
161
162 def write_test_data_file(self, basename: str,
163 test_cases: Iterable[test_case.TestCase]) -> None:
164 """Write the test cases to a .data file.
165
166 The output file is ``basename + '.data'`` in the test suite directory.
167 """
168 filename = self.filename_for(basename)
169 test_case.write_data_file(filename, test_cases)
170
171 # Note that targets whose names contain 'test_format' have their content
172 # validated by `abi_check.py`.
Werner Lewis0d07e862022-09-02 11:56:34 +0100173 targets = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
Werner Lewisdcad1e92022-08-24 11:30:03 +0100174
175 def generate_target(self, name: str, *target_args) -> None:
176 """Generate cases and write to data file for a target.
177
178 For target callables which require arguments, override this function
179 and pass these arguments using super() (see PSATestGenerator).
180 """
Werner Lewis0d07e862022-09-02 11:56:34 +0100181 test_cases = self.targets[name](*target_args)
Werner Lewisdcad1e92022-08-24 11:30:03 +0100182 self.write_test_data_file(name, test_cases)
183
Werner Lewis4ed94a42022-09-16 17:03:54 +0100184def main(args, description: str, generator_class: Type[TestGenerator] = TestGenerator):
Werner Lewisdcad1e92022-08-24 11:30:03 +0100185 """Command line entry point."""
Werner Lewis4ed94a42022-09-16 17:03:54 +0100186 parser = argparse.ArgumentParser(description=description)
Werner Lewisdcad1e92022-08-24 11:30:03 +0100187 parser.add_argument('--list', action='store_true',
188 help='List available targets and exit')
189 parser.add_argument('targets', nargs='*', metavar='TARGET',
190 help='Target file to generate (default: all; "-": none)')
191 options = parser.parse_args(args)
192 generator = generator_class(options)
193 if options.list:
Werner Lewis0d07e862022-09-02 11:56:34 +0100194 for name in sorted(generator.targets):
Werner Lewisdcad1e92022-08-24 11:30:03 +0100195 print(generator.filename_for(name))
196 return
Werner Lewis0d07e862022-09-02 11:56:34 +0100197 if options.targets:
198 # Allow "-" as a special case so you can run
199 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
200 # ``$targets`` is empty or not.
201 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
Werner Lewise53be352022-09-02 12:57:37 +0100202 for target in options.targets
203 if target != '-']
Werner Lewis0d07e862022-09-02 11:56:34 +0100204 else:
205 options.targets = sorted(generator.targets)
Werner Lewisdcad1e92022-08-24 11:30:03 +0100206 for target in options.targets:
207 generator.generate_target(target)