blob: 727f8d5f6b2679b9e8920c6d96f30c871d891984 [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.
44 target_basename: Basename of file to write generated tests to. This
45 should be specified in a child class of BaseTarget.
46 test_function: Test function which the class generates cases for.
47 test_name: A common name or description of the test function. This can
Werner Lewisb03420f2022-08-25 12:29:46 +010048 be `test_function`, a clearer equivalent, or a short summary of the
49 test function's purpose.
Werner Lewisdcad1e92022-08-24 11:30:03 +010050 """
51 count = 0
Werner Lewis70d3f3d2022-08-23 14:21:53 +010052 case_description = ""
53 target_basename = ""
54 test_function = ""
55 test_name = ""
Werner Lewisdcad1e92022-08-24 11:30:03 +010056
Werner Lewiscace1aa2022-08-24 17:04:07 +010057 def __new__(cls, *args, **kwargs):
Werner Lewis486d2582022-08-24 18:09:10 +010058 # pylint: disable=unused-argument
Werner Lewiscace1aa2022-08-24 17:04:07 +010059 cls.count += 1
60 return super().__new__(cls)
Werner Lewisdcad1e92022-08-24 11:30:03 +010061
Werner Lewis008d90d2022-08-23 16:07:37 +010062 @abstractmethod
Werner Lewis70d3f3d2022-08-23 14:21:53 +010063 def arguments(self) -> List[str]:
Werner Lewis008d90d2022-08-23 16:07:37 +010064 """Get the list of arguments for the test case.
65
66 Override this method to provide the list of arguments required for
Werner Lewisb03420f2022-08-25 12:29:46 +010067 the `test_function`.
Werner Lewis008d90d2022-08-23 16:07:37 +010068
69 Returns:
70 List of arguments required for the test function.
71 """
Werner Lewisd77d33d2022-08-25 09:56:51 +010072 raise NotImplementedError
Werner Lewisdcad1e92022-08-24 11:30:03 +010073
Werner Lewisdcad1e92022-08-24 11:30:03 +010074 def description(self) -> str:
Werner Lewisb03420f2022-08-25 12:29:46 +010075 """Create a test case description.
Werner Lewis008d90d2022-08-23 16:07:37 +010076
77 Creates a description of the test case, including a name for the test
Werner Lewisb03420f2022-08-25 12:29:46 +010078 function, a case number, and a description the specific test case.
79 This should inform a reader what is being tested, and provide context
80 for the test case.
Werner Lewis008d90d2022-08-23 16:07:37 +010081
82 Returns:
83 Description for the test case.
84 """
Werner Lewis6d041422022-08-24 17:20:29 +010085 return "{} #{} {}".format(
86 self.test_name, self.count, self.case_description
87 ).strip()
Werner Lewisdcad1e92022-08-24 11:30:03 +010088
Werner Lewis008d90d2022-08-23 16:07:37 +010089
Werner Lewisdcad1e92022-08-24 11:30:03 +010090 def create_test_case(self) -> test_case.TestCase:
Werner Lewisb03420f2022-08-25 12:29:46 +010091 """Generate TestCase from the instance."""
Werner Lewisdcad1e92022-08-24 11:30:03 +010092 tc = test_case.TestCase()
Werner Lewis70d3f3d2022-08-23 14:21:53 +010093 tc.set_description(self.description())
94 tc.set_function(self.test_function)
95 tc.set_arguments(self.arguments())
Werner Lewisdcad1e92022-08-24 11:30:03 +010096
97 return tc
98
99 @classmethod
Werner Lewisc34d0372022-08-24 12:42:00 +0100100 @abstractmethod
101 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Werner Lewisb03420f2022-08-25 12:29:46 +0100102 """Generate test cases for the class test function.
Werner Lewis008d90d2022-08-23 16:07:37 +0100103
Werner Lewisc34d0372022-08-24 12:42:00 +0100104 This will be called in classes where `test_function` is set.
105 Implementations should yield TestCase objects, by creating instances
106 of the class with appropriate input data, and then calling
107 `create_test_case()` on each.
Werner Lewis008d90d2022-08-23 16:07:37 +0100108 """
Werner Lewisd77d33d2022-08-25 09:56:51 +0100109 raise NotImplementedError
Werner Lewisc34d0372022-08-24 12:42:00 +0100110
111 @classmethod
112 def generate_tests(cls) -> Iterator[test_case.TestCase]:
113 """Generate test cases for the class and its subclasses.
114
115 In classes with `test_function` set, `generate_function_tests()` is
Werner Lewis2b0f7d82022-08-25 16:27:05 +0100116 called to generate test cases first.
Werner Lewisc34d0372022-08-24 12:42:00 +0100117
Werner Lewisb03420f2022-08-25 12:29:46 +0100118 In all classes, this method will iterate over its subclasses, and
119 yield from `generate_tests()` in each. Calling this method on a class X
120 will yield test cases from all classes derived from X.
Werner Lewisc34d0372022-08-24 12:42:00 +0100121 """
122 if cls.test_function:
123 yield from cls.generate_function_tests()
Werner Lewisdcad1e92022-08-24 11:30:03 +0100124 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
125 yield from subclass.generate_tests()
126
127
128class TestGenerator:
129 """Generate test data."""
130 def __init__(self, options) -> None:
131 self.test_suite_directory = self.get_option(options, 'directory',
132 'tests/suites')
133
134 @staticmethod
135 def get_option(options, name: str, default: T) -> T:
136 value = getattr(options, name, None)
137 return default if value is None else value
138
139 def filename_for(self, basename: str) -> str:
140 """The location of the data file with the specified base name."""
141 return posixpath.join(self.test_suite_directory, basename + '.data')
142
143 def write_test_data_file(self, basename: str,
144 test_cases: Iterable[test_case.TestCase]) -> None:
145 """Write the test cases to a .data file.
146
147 The output file is ``basename + '.data'`` in the test suite directory.
148 """
149 filename = self.filename_for(basename)
150 test_case.write_data_file(filename, test_cases)
151
152 # Note that targets whose names contain 'test_format' have their content
153 # validated by `abi_check.py`.
Werner Lewis412c4972022-08-25 10:02:06 +0100154 TARGETS = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
Werner Lewisdcad1e92022-08-24 11:30:03 +0100155
156 def generate_target(self, name: str, *target_args) -> None:
157 """Generate cases and write to data file for a target.
158
159 For target callables which require arguments, override this function
160 and pass these arguments using super() (see PSATestGenerator).
161 """
162 test_cases = self.TARGETS[name](*target_args)
163 self.write_test_data_file(name, test_cases)
164
165def main(args, generator_class: Type[TestGenerator] = TestGenerator):
166 """Command line entry point."""
167 parser = argparse.ArgumentParser(description=__doc__)
168 parser.add_argument('--list', action='store_true',
169 help='List available targets and exit')
170 parser.add_argument('targets', nargs='*', metavar='TARGET',
Werner Lewis6f67bae2022-08-25 13:21:45 +0100171 default=sorted(generator_class.TARGETS),
Werner Lewisdcad1e92022-08-24 11:30:03 +0100172 help='Target file to generate (default: all; "-": none)')
173 options = parser.parse_args(args)
174 generator = generator_class(options)
175 if options.list:
176 for name in sorted(generator.TARGETS):
177 print(generator.filename_for(name))
178 return
Werner Lewisac863902022-08-25 12:49:41 +0100179 # Allow "-" as a special case so you can run
180 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
181 # ``$targets`` is empty or not.
182 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
183 for target in options.targets
184 if target != '-']
Werner Lewisdcad1e92022-08-24 11:30:03 +0100185 for target in options.targets:
186 generator.generate_target(target)