blob: 376046858bc495c753be54824b727807ad44c463 [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
Gilles Peskinef8d031f2022-10-14 15:21:49 +020032from mbedtls_dev import build_tree
Werner Lewisdcad1e92022-08-24 11:30:03 +010033from mbedtls_dev import test_case
34
35T = TypeVar('T') #pylint: disable=invalid-name
36
37
Werner Lewis47e37b32022-08-24 12:18:25 +010038class BaseTarget(metaclass=ABCMeta):
Werner Lewisdcad1e92022-08-24 11:30:03 +010039 """Base target for test case generation.
40
Werner Lewis64334d92022-09-14 16:26:54 +010041 Child classes of this class represent an output file, and can be referred
42 to as file targets. These indicate where test cases will be written to for
43 all subclasses of the file target, which is set by `target_basename`.
Werner Lewisb03420f2022-08-25 12:29:46 +010044
Werner Lewisdcad1e92022-08-24 11:30:03 +010045 Attributes:
Werner Lewis70d3f3d2022-08-23 14:21:53 +010046 count: Counter for test cases from this class.
47 case_description: Short description of the test case. This may be
48 automatically generated using the class, or manually set.
Werner Lewis486b3412022-08-31 17:01:38 +010049 dependencies: A list of dependencies required for the test case.
Werner Lewis113ddd02022-09-14 13:02:40 +010050 show_test_count: Toggle for inclusion of `count` in the test description.
Werner Lewis70d3f3d2022-08-23 14:21:53 +010051 target_basename: Basename of file to write generated tests to. This
52 should be specified in a child class of BaseTarget.
53 test_function: Test function which the class generates cases for.
54 test_name: A common name or description of the test function. This can
Werner Lewisb03420f2022-08-25 12:29:46 +010055 be `test_function`, a clearer equivalent, or a short summary of the
56 test function's purpose.
Werner Lewisdcad1e92022-08-24 11:30:03 +010057 """
58 count = 0
Werner Lewis70d3f3d2022-08-23 14:21:53 +010059 case_description = ""
Werner Lewis6cc5e5f2022-08-31 17:16:44 +010060 dependencies = [] # type: List[str]
Werner Lewis113ddd02022-09-14 13:02:40 +010061 show_test_count = True
Werner Lewis70d3f3d2022-08-23 14:21:53 +010062 target_basename = ""
63 test_function = ""
64 test_name = ""
Werner Lewisdcad1e92022-08-24 11:30:03 +010065
Werner Lewiscace1aa2022-08-24 17:04:07 +010066 def __new__(cls, *args, **kwargs):
Werner Lewis486d2582022-08-24 18:09:10 +010067 # pylint: disable=unused-argument
Werner Lewiscace1aa2022-08-24 17:04:07 +010068 cls.count += 1
69 return super().__new__(cls)
Werner Lewisdcad1e92022-08-24 11:30:03 +010070
Werner Lewis008d90d2022-08-23 16:07:37 +010071 @abstractmethod
Werner Lewis70d3f3d2022-08-23 14:21:53 +010072 def arguments(self) -> List[str]:
Werner Lewis008d90d2022-08-23 16:07:37 +010073 """Get the list of arguments for the test case.
74
75 Override this method to provide the list of arguments required for
Werner Lewisb03420f2022-08-25 12:29:46 +010076 the `test_function`.
Werner Lewis008d90d2022-08-23 16:07:37 +010077
78 Returns:
79 List of arguments required for the test function.
80 """
Werner Lewisd77d33d2022-08-25 09:56:51 +010081 raise NotImplementedError
Werner Lewisdcad1e92022-08-24 11:30:03 +010082
Werner Lewisdcad1e92022-08-24 11:30:03 +010083 def description(self) -> str:
Werner Lewisb03420f2022-08-25 12:29:46 +010084 """Create a test case description.
Werner Lewis008d90d2022-08-23 16:07:37 +010085
86 Creates a description of the test case, including a name for the test
Werner Lewis113ddd02022-09-14 13:02:40 +010087 function, an optional case count, and a description of the specific
88 test case. This should inform a reader what is being tested, and
89 provide context for the test case.
Werner Lewis008d90d2022-08-23 16:07:37 +010090
91 Returns:
92 Description for the test case.
93 """
Werner Lewis113ddd02022-09-14 13:02:40 +010094 if self.show_test_count:
95 return "{} #{} {}".format(
96 self.test_name, self.count, self.case_description
97 ).strip()
98 else:
99 return "{} {}".format(self.test_name, self.case_description).strip()
Werner Lewisdcad1e92022-08-24 11:30:03 +0100100
Werner Lewis008d90d2022-08-23 16:07:37 +0100101
Werner Lewisdcad1e92022-08-24 11:30:03 +0100102 def create_test_case(self) -> test_case.TestCase:
Werner Lewisb03420f2022-08-25 12:29:46 +0100103 """Generate TestCase from the instance."""
Werner Lewisdcad1e92022-08-24 11:30:03 +0100104 tc = test_case.TestCase()
Werner Lewis70d3f3d2022-08-23 14:21:53 +0100105 tc.set_description(self.description())
106 tc.set_function(self.test_function)
107 tc.set_arguments(self.arguments())
Werner Lewis486b3412022-08-31 17:01:38 +0100108 tc.set_dependencies(self.dependencies)
Werner Lewisdcad1e92022-08-24 11:30:03 +0100109
110 return tc
111
112 @classmethod
Werner Lewisc34d0372022-08-24 12:42:00 +0100113 @abstractmethod
114 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Werner Lewisb03420f2022-08-25 12:29:46 +0100115 """Generate test cases for the class test function.
Werner Lewis008d90d2022-08-23 16:07:37 +0100116
Werner Lewisc34d0372022-08-24 12:42:00 +0100117 This will be called in classes where `test_function` is set.
118 Implementations should yield TestCase objects, by creating instances
119 of the class with appropriate input data, and then calling
120 `create_test_case()` on each.
Werner Lewis008d90d2022-08-23 16:07:37 +0100121 """
Werner Lewisd77d33d2022-08-25 09:56:51 +0100122 raise NotImplementedError
Werner Lewisc34d0372022-08-24 12:42:00 +0100123
124 @classmethod
125 def generate_tests(cls) -> Iterator[test_case.TestCase]:
126 """Generate test cases for the class and its subclasses.
127
128 In classes with `test_function` set, `generate_function_tests()` is
Werner Lewis2b0f7d82022-08-25 16:27:05 +0100129 called to generate test cases first.
Werner Lewisc34d0372022-08-24 12:42:00 +0100130
Werner Lewisb03420f2022-08-25 12:29:46 +0100131 In all classes, this method will iterate over its subclasses, and
132 yield from `generate_tests()` in each. Calling this method on a class X
133 will yield test cases from all classes derived from X.
Werner Lewisc34d0372022-08-24 12:42:00 +0100134 """
135 if cls.test_function:
136 yield from cls.generate_function_tests()
Werner Lewisdcad1e92022-08-24 11:30:03 +0100137 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
138 yield from subclass.generate_tests()
139
140
141class TestGenerator:
Werner Lewisf5182762022-09-14 12:59:32 +0100142 """Generate test cases and write to data files."""
Gilles Peskine48815402022-10-14 15:01:52 +0200143 def __init__(self, _options) -> None:
144 self.test_suite_directory = '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
Werner Lewisdcad1e92022-08-24 11:30:03 +0100153 def filename_for(self, basename: str) -> str:
154 """The location of the data file with the specified base name."""
155 return posixpath.join(self.test_suite_directory, basename + '.data')
156
157 def write_test_data_file(self, basename: str,
158 test_cases: Iterable[test_case.TestCase]) -> None:
159 """Write the test cases to a .data file.
160
161 The output file is ``basename + '.data'`` in the test suite directory.
162 """
163 filename = self.filename_for(basename)
164 test_case.write_data_file(filename, test_cases)
165
166 # Note that targets whose names contain 'test_format' have their content
167 # validated by `abi_check.py`.
Werner Lewis0d07e862022-09-02 11:56:34 +0100168 targets = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
Werner Lewisdcad1e92022-08-24 11:30:03 +0100169
170 def generate_target(self, name: str, *target_args) -> None:
171 """Generate cases and write to data file for a target.
172
173 For target callables which require arguments, override this function
174 and pass these arguments using super() (see PSATestGenerator).
175 """
Werner Lewis0d07e862022-09-02 11:56:34 +0100176 test_cases = self.targets[name](*target_args)
Werner Lewisdcad1e92022-08-24 11:30:03 +0100177 self.write_test_data_file(name, test_cases)
178
Werner Lewis4ed94a42022-09-16 17:03:54 +0100179def main(args, description: str, generator_class: Type[TestGenerator] = TestGenerator):
Werner Lewisdcad1e92022-08-24 11:30:03 +0100180 """Command line entry point."""
Werner Lewis4ed94a42022-09-16 17:03:54 +0100181 parser = argparse.ArgumentParser(description=description)
Werner Lewisdcad1e92022-08-24 11:30:03 +0100182 parser.add_argument('--list', action='store_true',
183 help='List available targets and exit')
184 parser.add_argument('targets', nargs='*', metavar='TARGET',
185 help='Target file to generate (default: all; "-": none)')
Gilles Peskinef8d031f2022-10-14 15:21:49 +0200186
187 # Change to the mbedtls root, to keep things simple.
188 # Note that if any command line options refer to paths, they need to
189 # be adjusted first.
190 build_tree.chdir_to_root()
191
Werner Lewisdcad1e92022-08-24 11:30:03 +0100192 options = parser.parse_args(args)
193 generator = generator_class(options)
194 if options.list:
Werner Lewis0d07e862022-09-02 11:56:34 +0100195 for name in sorted(generator.targets):
Werner Lewisdcad1e92022-08-24 11:30:03 +0100196 print(generator.filename_for(name))
197 return
Werner Lewis0d07e862022-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 Lewise53be352022-09-02 12:57:37 +0100203 for target in options.targets
204 if target != '-']
Werner Lewis0d07e862022-09-02 11:56:34 +0100205 else:
206 options.targets = sorted(generator.targets)
Werner Lewisdcad1e92022-08-24 11:30:03 +0100207 for target in options.targets:
208 generator.generate_target(target)