blob: 3ad699c917522ea93f81ba0a2836e4f55438f4ee [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 Lewisb03420f2022-08-25 12:29:46 +010037 This should be derived from for file Targets.
38
Werner Lewisdcad1e92022-08-24 11:30:03 +010039 Attributes:
Werner Lewis70d3f3d2022-08-23 14:21:53 +010040 count: Counter for test cases from this class.
41 case_description: Short description of the test case. This may be
42 automatically generated using the class, or manually set.
43 target_basename: Basename of file to write generated tests to. This
44 should be specified in a child class of BaseTarget.
45 test_function: Test function which the class generates cases for.
46 test_name: A common name or description of the test function. This can
Werner Lewisb03420f2022-08-25 12:29:46 +010047 be `test_function`, a clearer equivalent, or a short summary of the
48 test function's purpose.
Werner Lewisdcad1e92022-08-24 11:30:03 +010049 """
50 count = 0
Werner Lewis70d3f3d2022-08-23 14:21:53 +010051 case_description = ""
52 target_basename = ""
53 test_function = ""
54 test_name = ""
Werner Lewisdcad1e92022-08-24 11:30:03 +010055
Werner Lewiscace1aa2022-08-24 17:04:07 +010056 def __new__(cls, *args, **kwargs):
Werner Lewis486d2582022-08-24 18:09:10 +010057 # pylint: disable=unused-argument
Werner Lewiscace1aa2022-08-24 17:04:07 +010058 cls.count += 1
59 return super().__new__(cls)
Werner Lewisdcad1e92022-08-24 11:30:03 +010060
Werner Lewis008d90d2022-08-23 16:07:37 +010061 @abstractmethod
Werner Lewis70d3f3d2022-08-23 14:21:53 +010062 def arguments(self) -> List[str]:
Werner Lewis008d90d2022-08-23 16:07:37 +010063 """Get the list of arguments for the test case.
64
65 Override this method to provide the list of arguments required for
Werner Lewisb03420f2022-08-25 12:29:46 +010066 the `test_function`.
Werner Lewis008d90d2022-08-23 16:07:37 +010067
68 Returns:
69 List of arguments required for the test function.
70 """
Werner Lewisd77d33d2022-08-25 09:56:51 +010071 raise NotImplementedError
Werner Lewisdcad1e92022-08-24 11:30:03 +010072
Werner Lewisdcad1e92022-08-24 11:30:03 +010073 def description(self) -> str:
Werner Lewisb03420f2022-08-25 12:29:46 +010074 """Create a test case description.
Werner Lewis008d90d2022-08-23 16:07:37 +010075
76 Creates a description of the test case, including a name for the test
Werner Lewisb03420f2022-08-25 12:29:46 +010077 function, a case number, and a description the specific test case.
78 This should inform a reader what is being tested, and provide context
79 for the test case.
Werner Lewis008d90d2022-08-23 16:07:37 +010080
81 Returns:
82 Description for the test case.
83 """
Werner Lewis6d041422022-08-24 17:20:29 +010084 return "{} #{} {}".format(
85 self.test_name, self.count, self.case_description
86 ).strip()
Werner Lewisdcad1e92022-08-24 11:30:03 +010087
Werner Lewis008d90d2022-08-23 16:07:37 +010088
Werner Lewisdcad1e92022-08-24 11:30:03 +010089 def create_test_case(self) -> test_case.TestCase:
Werner Lewisb03420f2022-08-25 12:29:46 +010090 """Generate TestCase from the instance."""
Werner Lewisdcad1e92022-08-24 11:30:03 +010091 tc = test_case.TestCase()
Werner Lewis70d3f3d2022-08-23 14:21:53 +010092 tc.set_description(self.description())
93 tc.set_function(self.test_function)
94 tc.set_arguments(self.arguments())
Werner Lewisdcad1e92022-08-24 11:30:03 +010095
96 return tc
97
98 @classmethod
Werner Lewisc34d0372022-08-24 12:42:00 +010099 @abstractmethod
100 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Werner Lewisb03420f2022-08-25 12:29:46 +0100101 """Generate test cases for the class test function.
Werner Lewis008d90d2022-08-23 16:07:37 +0100102
Werner Lewisc34d0372022-08-24 12:42:00 +0100103 This will be called in classes where `test_function` is set.
104 Implementations should yield TestCase objects, by creating instances
105 of the class with appropriate input data, and then calling
106 `create_test_case()` on each.
Werner Lewis008d90d2022-08-23 16:07:37 +0100107 """
Werner Lewisd77d33d2022-08-25 09:56:51 +0100108 raise NotImplementedError
Werner Lewisc34d0372022-08-24 12:42:00 +0100109
110 @classmethod
111 def generate_tests(cls) -> Iterator[test_case.TestCase]:
112 """Generate test cases for the class and its subclasses.
113
114 In classes with `test_function` set, `generate_function_tests()` is
115 used to generate test cases first.
Werner Lewisc34d0372022-08-24 12:42:00 +0100116
Werner Lewisb03420f2022-08-25 12:29:46 +0100117 In all classes, this method will iterate over its subclasses, and
118 yield from `generate_tests()` in each. Calling this method on a class X
119 will yield test cases from all classes derived from X.
Werner Lewisc34d0372022-08-24 12:42:00 +0100120 """
121 if cls.test_function:
122 yield from cls.generate_function_tests()
Werner Lewisdcad1e92022-08-24 11:30:03 +0100123 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
124 yield from subclass.generate_tests()
125
126
127class TestGenerator:
128 """Generate test data."""
129 def __init__(self, options) -> None:
130 self.test_suite_directory = self.get_option(options, 'directory',
131 'tests/suites')
132
133 @staticmethod
134 def get_option(options, name: str, default: T) -> T:
135 value = getattr(options, name, None)
136 return default if value is None else value
137
138 def filename_for(self, basename: str) -> str:
139 """The location of the data file with the specified base name."""
140 return posixpath.join(self.test_suite_directory, basename + '.data')
141
142 def write_test_data_file(self, basename: str,
143 test_cases: Iterable[test_case.TestCase]) -> None:
144 """Write the test cases to a .data file.
145
146 The output file is ``basename + '.data'`` in the test suite directory.
147 """
148 filename = self.filename_for(basename)
149 test_case.write_data_file(filename, test_cases)
150
151 # Note that targets whose names contain 'test_format' have their content
152 # validated by `abi_check.py`.
Werner Lewis412c4972022-08-25 10:02:06 +0100153 TARGETS = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
Werner Lewisdcad1e92022-08-24 11:30:03 +0100154
155 def generate_target(self, name: str, *target_args) -> None:
156 """Generate cases and write to data file for a target.
157
158 For target callables which require arguments, override this function
159 and pass these arguments using super() (see PSATestGenerator).
160 """
161 test_cases = self.TARGETS[name](*target_args)
162 self.write_test_data_file(name, test_cases)
163
164def main(args, generator_class: Type[TestGenerator] = TestGenerator):
165 """Command line entry point."""
166 parser = argparse.ArgumentParser(description=__doc__)
167 parser.add_argument('--list', action='store_true',
168 help='List available targets and exit')
169 parser.add_argument('targets', nargs='*', metavar='TARGET',
Werner Lewis6f67bae2022-08-25 13:21:45 +0100170 default=sorted(generator_class.TARGETS),
Werner Lewisdcad1e92022-08-24 11:30:03 +0100171 help='Target file to generate (default: all; "-": none)')
172 options = parser.parse_args(args)
173 generator = generator_class(options)
174 if options.list:
175 for name in sorted(generator.TARGETS):
176 print(generator.filename_for(name))
177 return
Werner Lewisac863902022-08-25 12:49:41 +0100178 # Allow "-" as a special case so you can run
179 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
180 # ``$targets`` is empty or not.
181 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
182 for target in options.targets
183 if target != '-']
Werner Lewisdcad1e92022-08-24 11:30:03 +0100184 for target in options.targets:
185 generator.generate_target(target)