blob: 00d559af6a1d0b0f72b9a0b2152049a9100ef558 [file] [log] [blame]
Werner Lewisdcad1e92022-08-24 11:30:03 +01001"""Common test generation classes and main function.
2
3These 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
21import argparse
22import os
23import posixpath
24import re
Werner Lewis008d90d2022-08-23 16:07:37 +010025
Werner Lewis47e37b32022-08-24 12:18:25 +010026from abc import ABCMeta, abstractmethod
Werner Lewisc34d0372022-08-24 12:42:00 +010027from typing import Callable, Dict, Iterable, Iterator, List, Type, TypeVar
Werner Lewisdcad1e92022-08-24 11:30:03 +010028
29from mbedtls_dev import test_case
30
31T = TypeVar('T') #pylint: disable=invalid-name
32
33
Werner Lewis47e37b32022-08-24 12:18:25 +010034class BaseTarget(metaclass=ABCMeta):
Werner Lewisdcad1e92022-08-24 11:30:03 +010035 """Base target for test case generation.
36
Werner Lewis2b0f7d82022-08-25 16:27:05 +010037 Derive directly from this class when adding new file Targets, setting
38 `target_basename`.
Werner Lewisb03420f2022-08-25 12:29:46 +010039
Werner Lewisdcad1e92022-08-24 11:30:03 +010040 Attributes:
Werner Lewis70d3f3d2022-08-23 14:21:53 +010041 count: Counter for test cases from this class.
42 case_description: Short description of the test case. This may be
43 automatically generated using the class, or manually set.
Werner Lewis486b3412022-08-31 17:01:38 +010044 dependencies: A list of dependencies required for the test case.
Werner Lewis70d3f3d2022-08-23 14:21:53 +010045 target_basename: Basename of file to write generated tests to. This
46 should be specified in a child class of BaseTarget.
47 test_function: Test function which the class generates cases for.
48 test_name: A common name or description of the test function. This can
Werner Lewisb03420f2022-08-25 12:29:46 +010049 be `test_function`, a clearer equivalent, or a short summary of the
50 test function's purpose.
Werner Lewisdcad1e92022-08-24 11:30:03 +010051 """
52 count = 0
Werner Lewis70d3f3d2022-08-23 14:21:53 +010053 case_description = ""
Werner Lewis486b3412022-08-31 17:01:38 +010054 dependencies: List[str] = []
Werner Lewis70d3f3d2022-08-23 14:21:53 +010055 target_basename = ""
56 test_function = ""
57 test_name = ""
Werner Lewisdcad1e92022-08-24 11:30:03 +010058
Werner Lewiscace1aa2022-08-24 17:04:07 +010059 def __new__(cls, *args, **kwargs):
Werner Lewis486d2582022-08-24 18:09:10 +010060 # pylint: disable=unused-argument
Werner Lewiscace1aa2022-08-24 17:04:07 +010061 cls.count += 1
62 return super().__new__(cls)
Werner Lewisdcad1e92022-08-24 11:30:03 +010063
Werner Lewis008d90d2022-08-23 16:07:37 +010064 @abstractmethod
Werner Lewis70d3f3d2022-08-23 14:21:53 +010065 def arguments(self) -> List[str]:
Werner Lewis008d90d2022-08-23 16:07:37 +010066 """Get the list of arguments for the test case.
67
68 Override this method to provide the list of arguments required for
Werner Lewisb03420f2022-08-25 12:29:46 +010069 the `test_function`.
Werner Lewis008d90d2022-08-23 16:07:37 +010070
71 Returns:
72 List of arguments required for the test function.
73 """
Werner Lewisd77d33d2022-08-25 09:56:51 +010074 raise NotImplementedError
Werner Lewisdcad1e92022-08-24 11:30:03 +010075
Werner Lewisdcad1e92022-08-24 11:30:03 +010076 def description(self) -> str:
Werner Lewisb03420f2022-08-25 12:29:46 +010077 """Create a test case description.
Werner Lewis008d90d2022-08-23 16:07:37 +010078
79 Creates a description of the test case, including a name for the test
Werner Lewisb03420f2022-08-25 12:29:46 +010080 function, a case number, and a description the specific test case.
81 This should inform a reader what is being tested, and provide context
82 for the test case.
Werner Lewis008d90d2022-08-23 16:07:37 +010083
84 Returns:
85 Description for the test case.
86 """
Werner Lewis6d041422022-08-24 17:20:29 +010087 return "{} #{} {}".format(
88 self.test_name, self.count, self.case_description
89 ).strip()
Werner Lewisdcad1e92022-08-24 11:30:03 +010090
Werner Lewis008d90d2022-08-23 16:07:37 +010091
Werner Lewisdcad1e92022-08-24 11:30:03 +010092 def create_test_case(self) -> test_case.TestCase:
Werner Lewisb03420f2022-08-25 12:29:46 +010093 """Generate TestCase from the instance."""
Werner Lewisdcad1e92022-08-24 11:30:03 +010094 tc = test_case.TestCase()
Werner Lewis70d3f3d2022-08-23 14:21:53 +010095 tc.set_description(self.description())
96 tc.set_function(self.test_function)
97 tc.set_arguments(self.arguments())
Werner Lewis486b3412022-08-31 17:01:38 +010098 tc.set_dependencies(self.dependencies)
Werner Lewisdcad1e92022-08-24 11:30:03 +010099
100 return tc
101
102 @classmethod
Werner Lewisc34d0372022-08-24 12:42:00 +0100103 @abstractmethod
104 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Werner Lewisb03420f2022-08-25 12:29:46 +0100105 """Generate test cases for the class test function.
Werner Lewis008d90d2022-08-23 16:07:37 +0100106
Werner Lewisc34d0372022-08-24 12:42:00 +0100107 This will be called in classes where `test_function` is set.
108 Implementations should yield TestCase objects, by creating instances
109 of the class with appropriate input data, and then calling
110 `create_test_case()` on each.
Werner Lewis008d90d2022-08-23 16:07:37 +0100111 """
Werner Lewisd77d33d2022-08-25 09:56:51 +0100112 raise NotImplementedError
Werner Lewisc34d0372022-08-24 12:42:00 +0100113
114 @classmethod
115 def generate_tests(cls) -> Iterator[test_case.TestCase]:
116 """Generate test cases for the class and its subclasses.
117
118 In classes with `test_function` set, `generate_function_tests()` is
Werner Lewis2b0f7d82022-08-25 16:27:05 +0100119 called to generate test cases first.
Werner Lewisc34d0372022-08-24 12:42:00 +0100120
Werner Lewisb03420f2022-08-25 12:29:46 +0100121 In all classes, this method will iterate over its subclasses, and
122 yield from `generate_tests()` in each. Calling this method on a class X
123 will yield test cases from all classes derived from X.
Werner Lewisc34d0372022-08-24 12:42:00 +0100124 """
125 if cls.test_function:
126 yield from cls.generate_function_tests()
Werner Lewisdcad1e92022-08-24 11:30:03 +0100127 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
128 yield from subclass.generate_tests()
129
130
131class TestGenerator:
132 """Generate test data."""
133 def __init__(self, options) -> None:
134 self.test_suite_directory = self.get_option(options, 'directory',
135 'tests/suites')
136
137 @staticmethod
138 def get_option(options, name: str, default: T) -> T:
139 value = getattr(options, name, None)
140 return default if value is None else value
141
142 def filename_for(self, basename: str) -> str:
143 """The location of the data file with the specified base name."""
144 return posixpath.join(self.test_suite_directory, basename + '.data')
145
146 def write_test_data_file(self, basename: str,
147 test_cases: Iterable[test_case.TestCase]) -> None:
148 """Write the test cases to a .data file.
149
150 The output file is ``basename + '.data'`` in the test suite directory.
151 """
152 filename = self.filename_for(basename)
153 test_case.write_data_file(filename, test_cases)
154
155 # Note that targets whose names contain 'test_format' have their content
156 # validated by `abi_check.py`.
Werner Lewis412c4972022-08-25 10:02:06 +0100157 TARGETS = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
Werner Lewisdcad1e92022-08-24 11:30:03 +0100158
159 def generate_target(self, name: str, *target_args) -> None:
160 """Generate cases and write to data file for a target.
161
162 For target callables which require arguments, override this function
163 and pass these arguments using super() (see PSATestGenerator).
164 """
165 test_cases = self.TARGETS[name](*target_args)
166 self.write_test_data_file(name, test_cases)
167
168def main(args, generator_class: Type[TestGenerator] = TestGenerator):
169 """Command line entry point."""
170 parser = argparse.ArgumentParser(description=__doc__)
171 parser.add_argument('--list', action='store_true',
172 help='List available targets and exit')
173 parser.add_argument('targets', nargs='*', metavar='TARGET',
Werner Lewis6f67bae2022-08-25 13:21:45 +0100174 default=sorted(generator_class.TARGETS),
Werner Lewisdcad1e92022-08-24 11:30:03 +0100175 help='Target file to generate (default: all; "-": none)')
176 options = parser.parse_args(args)
177 generator = generator_class(options)
178 if options.list:
179 for name in sorted(generator.TARGETS):
180 print(generator.filename_for(name))
181 return
Werner Lewisac863902022-08-25 12:49:41 +0100182 # Allow "-" as a special case so you can run
183 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
184 # ``$targets`` is empty or not.
185 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
186 for target in options.targets
187 if target != '-']
Werner Lewisdcad1e92022-08-24 11:30:03 +0100188 for target in options.targets:
189 generator.generate_target(target)