blob: 652b9a1f82dd2c121e70d5988b03e630e93c4b91 [file] [log] [blame]
Werner Lewisfbb75e32022-08-24 11:30:03 +01001#!/usr/bin/env python3
2"""Common test generation classes and main function.
3
4These are used both by generate_psa_tests.py and generate_bignum_tests.py.
5"""
6
7# Copyright The Mbed TLS Contributors
8# SPDX-License-Identifier: Apache-2.0
9#
10# Licensed under the Apache License, Version 2.0 (the "License"); you may
11# not use this file except in compliance with the License.
12# You may obtain a copy of the License at
13#
14# http://www.apache.org/licenses/LICENSE-2.0
15#
16# Unless required by applicable law or agreed to in writing, software
17# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19# See the License for the specific language governing permissions and
20# limitations under the License.
21
22import argparse
23import os
24import posixpath
25import re
Werner Lewis169034a2022-08-23 16:07:37 +010026
Werner Lewis699e1262022-08-24 12:18:25 +010027from abc import ABCMeta, abstractmethod
Werner Lewis2b527a32022-08-24 12:42:00 +010028from typing import Callable, Dict, Iterable, Iterator, List, Type, TypeVar
Werner Lewisfbb75e32022-08-24 11:30:03 +010029
30from mbedtls_dev import build_tree
31from mbedtls_dev import test_case
32
33T = TypeVar('T') #pylint: disable=invalid-name
34
35
Werner Lewis699e1262022-08-24 12:18:25 +010036class BaseTarget(metaclass=ABCMeta):
Werner Lewisfbb75e32022-08-24 11:30:03 +010037 """Base target for test case generation.
38
39 Attributes:
Werner Lewis55e638c2022-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
47 be the function's name, or a short summary of its purpose.
Werner Lewisfbb75e32022-08-24 11:30:03 +010048 """
49 count = 0
Werner Lewis55e638c2022-08-23 14:21:53 +010050 case_description = ""
51 target_basename = ""
52 test_function = ""
53 test_name = ""
Werner Lewisfbb75e32022-08-24 11:30:03 +010054
Werner Lewiscfd47682022-08-24 17:04:07 +010055 def __new__(cls, *args, **kwargs):
Werner Lewisa195ce72022-08-24 18:09:10 +010056 # pylint: disable=unused-argument
Werner Lewiscfd47682022-08-24 17:04:07 +010057 cls.count += 1
58 return super().__new__(cls)
Werner Lewisfbb75e32022-08-24 11:30:03 +010059
Werner Lewis169034a2022-08-23 16:07:37 +010060 @abstractmethod
Werner Lewis55e638c2022-08-23 14:21:53 +010061 def arguments(self) -> List[str]:
Werner Lewis169034a2022-08-23 16:07:37 +010062 """Get the list of arguments for the test case.
63
64 Override this method to provide the list of arguments required for
65 generating the test_function.
66
67 Returns:
68 List of arguments required for the test function.
69 """
70 pass
Werner Lewisfbb75e32022-08-24 11:30:03 +010071
Werner Lewisfbb75e32022-08-24 11:30:03 +010072 def description(self) -> str:
Werner Lewis169034a2022-08-23 16:07:37 +010073 """Create a test description.
74
75 Creates a description of the test case, including a name for the test
76 function, and describing the specific test case. This should inform a
77 reader of the purpose of the case. The case description may be
78 generated in the class, or provided manually as needed.
79
80 Returns:
81 Description for the test case.
82 """
Werner Lewisd03d2a32022-08-24 17:20:29 +010083 return "{} #{} {}".format(
84 self.test_name, self.count, self.case_description
85 ).strip()
Werner Lewisfbb75e32022-08-24 11:30:03 +010086
Werner Lewis169034a2022-08-23 16:07:37 +010087
Werner Lewisfbb75e32022-08-24 11:30:03 +010088 def create_test_case(self) -> test_case.TestCase:
Werner Lewis169034a2022-08-23 16:07:37 +010089 """Generate TestCase from the current object."""
Werner Lewisfbb75e32022-08-24 11:30:03 +010090 tc = test_case.TestCase()
Werner Lewis55e638c2022-08-23 14:21:53 +010091 tc.set_description(self.description())
92 tc.set_function(self.test_function)
93 tc.set_arguments(self.arguments())
Werner Lewisfbb75e32022-08-24 11:30:03 +010094
95 return tc
96
97 @classmethod
Werner Lewis2b527a32022-08-24 12:42:00 +010098 @abstractmethod
99 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
100 """Generate test cases for the test function.
Werner Lewis169034a2022-08-23 16:07:37 +0100101
Werner Lewis2b527a32022-08-24 12:42:00 +0100102 This will be called in classes where `test_function` is set.
103 Implementations should yield TestCase objects, by creating instances
104 of the class with appropriate input data, and then calling
105 `create_test_case()` on each.
Werner Lewis169034a2022-08-23 16:07:37 +0100106 """
Werner Lewis2b527a32022-08-24 12:42:00 +0100107 pass
108
109 @classmethod
110 def generate_tests(cls) -> Iterator[test_case.TestCase]:
111 """Generate test cases for the class and its subclasses.
112
113 In classes with `test_function` set, `generate_function_tests()` is
114 used to generate test cases first.
115 In all classes, this method will iterate over its subclasses, and
116 yield from `generate_tests()` in each.
117
118 Calling this method on a class X will yield test cases from all classes
119 derived from X.
120 """
121 if cls.test_function:
122 yield from cls.generate_function_tests()
Werner Lewisfbb75e32022-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`.
153 TARGETS = {} # type: Dict[str, Callable[..., test_case.TestCase]]
154
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('--list-for-cmake', action='store_true',
170 help='Print \';\'-separated list of available targets and exit')
171 parser.add_argument('--directory', metavar='DIR',
172 help='Output directory (default: tests/suites)')
173 parser.add_argument('targets', nargs='*', metavar='TARGET',
174 help='Target file to generate (default: all; "-": none)')
175 options = parser.parse_args(args)
176 build_tree.chdir_to_root()
177 generator = generator_class(options)
178 if options.list:
179 for name in sorted(generator.TARGETS):
180 print(generator.filename_for(name))
181 return
182 # List in a cmake list format (i.e. ';'-separated)
183 if options.list_for_cmake:
184 print(';'.join(generator.filename_for(name)
185 for name in sorted(generator.TARGETS)), end='')
186 return
187 if options.targets:
188 # Allow "-" as a special case so you can run
189 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
190 # ``$targets`` is empty or not.
191 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
192 for target in options.targets
193 if target != '-']
194 else:
195 options.targets = sorted(generator.TARGETS)
196 for target in options.targets:
197 generator.generate_target(target)