blob: 64b8fe41475b14bbaf79e27eb6aa078af981aa33 [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
37 Attributes:
Werner Lewis70d3f3d2022-08-23 14:21:53 +010038 count: Counter for test cases from this class.
39 case_description: Short description of the test case. This may be
40 automatically generated using the class, or manually set.
41 target_basename: Basename of file to write generated tests to. This
42 should be specified in a child class of BaseTarget.
43 test_function: Test function which the class generates cases for.
44 test_name: A common name or description of the test function. This can
45 be the function's name, or a short summary of its purpose.
Werner Lewisdcad1e92022-08-24 11:30:03 +010046 """
47 count = 0
Werner Lewis70d3f3d2022-08-23 14:21:53 +010048 case_description = ""
49 target_basename = ""
50 test_function = ""
51 test_name = ""
Werner Lewisdcad1e92022-08-24 11:30:03 +010052
Werner Lewiscace1aa2022-08-24 17:04:07 +010053 def __new__(cls, *args, **kwargs):
Werner Lewis486d2582022-08-24 18:09:10 +010054 # pylint: disable=unused-argument
Werner Lewiscace1aa2022-08-24 17:04:07 +010055 cls.count += 1
56 return super().__new__(cls)
Werner Lewisdcad1e92022-08-24 11:30:03 +010057
Werner Lewis008d90d2022-08-23 16:07:37 +010058 @abstractmethod
Werner Lewis70d3f3d2022-08-23 14:21:53 +010059 def arguments(self) -> List[str]:
Werner Lewis008d90d2022-08-23 16:07:37 +010060 """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 """
Werner Lewisd77d33d2022-08-25 09:56:51 +010068 raise NotImplementedError
Werner Lewisdcad1e92022-08-24 11:30:03 +010069
Werner Lewisdcad1e92022-08-24 11:30:03 +010070 def description(self) -> str:
Werner Lewis008d90d2022-08-23 16:07:37 +010071 """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 Lewis6d041422022-08-24 17:20:29 +010081 return "{} #{} {}".format(
82 self.test_name, self.count, self.case_description
83 ).strip()
Werner Lewisdcad1e92022-08-24 11:30:03 +010084
Werner Lewis008d90d2022-08-23 16:07:37 +010085
Werner Lewisdcad1e92022-08-24 11:30:03 +010086 def create_test_case(self) -> test_case.TestCase:
Werner Lewis008d90d2022-08-23 16:07:37 +010087 """Generate TestCase from the current object."""
Werner Lewisdcad1e92022-08-24 11:30:03 +010088 tc = test_case.TestCase()
Werner Lewis70d3f3d2022-08-23 14:21:53 +010089 tc.set_description(self.description())
90 tc.set_function(self.test_function)
91 tc.set_arguments(self.arguments())
Werner Lewisdcad1e92022-08-24 11:30:03 +010092
93 return tc
94
95 @classmethod
Werner Lewisc34d0372022-08-24 12:42:00 +010096 @abstractmethod
97 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
98 """Generate test cases for the test function.
Werner Lewis008d90d2022-08-23 16:07:37 +010099
Werner Lewisc34d0372022-08-24 12:42:00 +0100100 This will be called in classes where `test_function` is set.
101 Implementations should yield TestCase objects, by creating instances
102 of the class with appropriate input data, and then calling
103 `create_test_case()` on each.
Werner Lewis008d90d2022-08-23 16:07:37 +0100104 """
Werner Lewisd77d33d2022-08-25 09:56:51 +0100105 raise NotImplementedError
Werner Lewisc34d0372022-08-24 12:42:00 +0100106
107 @classmethod
108 def generate_tests(cls) -> Iterator[test_case.TestCase]:
109 """Generate test cases for the class and its subclasses.
110
111 In classes with `test_function` set, `generate_function_tests()` is
112 used to generate test cases first.
113 In all classes, this method will iterate over its subclasses, and
114 yield from `generate_tests()` in each.
115
116 Calling this method on a class X will yield test cases from all classes
117 derived from X.
118 """
119 if cls.test_function:
120 yield from cls.generate_function_tests()
Werner Lewisdcad1e92022-08-24 11:30:03 +0100121 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
122 yield from subclass.generate_tests()
123
124
125class TestGenerator:
126 """Generate test data."""
127 def __init__(self, options) -> None:
128 self.test_suite_directory = self.get_option(options, 'directory',
129 'tests/suites')
130
131 @staticmethod
132 def get_option(options, name: str, default: T) -> T:
133 value = getattr(options, name, None)
134 return default if value is None else value
135
136 def filename_for(self, basename: str) -> str:
137 """The location of the data file with the specified base name."""
138 return posixpath.join(self.test_suite_directory, basename + '.data')
139
140 def write_test_data_file(self, basename: str,
141 test_cases: Iterable[test_case.TestCase]) -> None:
142 """Write the test cases to a .data file.
143
144 The output file is ``basename + '.data'`` in the test suite directory.
145 """
146 filename = self.filename_for(basename)
147 test_case.write_data_file(filename, test_cases)
148
149 # Note that targets whose names contain 'test_format' have their content
150 # validated by `abi_check.py`.
Werner Lewis412c4972022-08-25 10:02:06 +0100151 TARGETS = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
Werner Lewisdcad1e92022-08-24 11:30:03 +0100152
153 def generate_target(self, name: str, *target_args) -> None:
154 """Generate cases and write to data file for a target.
155
156 For target callables which require arguments, override this function
157 and pass these arguments using super() (see PSATestGenerator).
158 """
159 test_cases = self.TARGETS[name](*target_args)
160 self.write_test_data_file(name, test_cases)
161
162def main(args, generator_class: Type[TestGenerator] = TestGenerator):
163 """Command line entry point."""
164 parser = argparse.ArgumentParser(description=__doc__)
165 parser.add_argument('--list', action='store_true',
166 help='List available targets and exit')
167 parser.add_argument('targets', nargs='*', metavar='TARGET',
168 help='Target file to generate (default: all; "-": none)')
169 options = parser.parse_args(args)
170 generator = generator_class(options)
171 if options.list:
172 for name in sorted(generator.TARGETS):
173 print(generator.filename_for(name))
174 return
175 if options.targets:
176 # Allow "-" as a special case so you can run
177 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
178 # ``$targets`` is empty or not.
179 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
180 for target in options.targets
181 if target != '-']
182 else:
183 options.targets = sorted(generator.TARGETS)
184 for target in options.targets:
185 generator.generate_target(target)