blob: e833008b59a7954e56ae8a0a12da60f25011fd74 [file] [log] [blame]
Werner Lewisfbb75e32022-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 Lewis169034a2022-08-23 16:07:37 +010025
Werner Lewis699e1262022-08-24 12:18:25 +010026from abc import ABCMeta, abstractmethod
Werner Lewis2b527a32022-08-24 12:42:00 +010027from typing import Callable, Dict, Iterable, Iterator, List, Type, TypeVar
Werner Lewisfbb75e32022-08-24 11:30:03 +010028
29from mbedtls_dev import build_tree
30from mbedtls_dev import test_case
31
32T = TypeVar('T') #pylint: disable=invalid-name
33
34
Werner Lewis699e1262022-08-24 12:18:25 +010035class BaseTarget(metaclass=ABCMeta):
Werner Lewisfbb75e32022-08-24 11:30:03 +010036 """Base target for test case generation.
37
Werner Lewis81f24442022-08-25 16:27:05 +010038 Derive directly from this class when adding new file Targets, setting
39 `target_basename`.
Werner Lewis6ef54362022-08-25 12:29:46 +010040
Werner Lewisfbb75e32022-08-24 11:30:03 +010041 Attributes:
Werner Lewis55e638c2022-08-23 14:21:53 +010042 count: Counter for test cases from this class.
43 case_description: Short description of the test case. This may be
44 automatically generated using the class, or manually set.
45 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 Lewis6ef54362022-08-25 12:29:46 +010049 be `test_function`, a clearer equivalent, or a short summary of the
50 test function's purpose.
Werner Lewisfbb75e32022-08-24 11:30:03 +010051 """
52 count = 0
Werner Lewis55e638c2022-08-23 14:21:53 +010053 case_description = ""
54 target_basename = ""
55 test_function = ""
56 test_name = ""
Werner Lewisfbb75e32022-08-24 11:30:03 +010057
Werner Lewiscfd47682022-08-24 17:04:07 +010058 def __new__(cls, *args, **kwargs):
Werner Lewisa195ce72022-08-24 18:09:10 +010059 # pylint: disable=unused-argument
Werner Lewiscfd47682022-08-24 17:04:07 +010060 cls.count += 1
61 return super().__new__(cls)
Werner Lewisfbb75e32022-08-24 11:30:03 +010062
Werner Lewis169034a2022-08-23 16:07:37 +010063 @abstractmethod
Werner Lewis55e638c2022-08-23 14:21:53 +010064 def arguments(self) -> List[str]:
Werner Lewis169034a2022-08-23 16:07:37 +010065 """Get the list of arguments for the test case.
66
67 Override this method to provide the list of arguments required for
Werner Lewis6ef54362022-08-25 12:29:46 +010068 the `test_function`.
Werner Lewis169034a2022-08-23 16:07:37 +010069
70 Returns:
71 List of arguments required for the test function.
72 """
Werner Lewis6d654c62022-08-25 09:56:51 +010073 raise NotImplementedError
Werner Lewisfbb75e32022-08-24 11:30:03 +010074
Werner Lewisfbb75e32022-08-24 11:30:03 +010075 def description(self) -> str:
Werner Lewis6ef54362022-08-25 12:29:46 +010076 """Create a test case description.
Werner Lewis169034a2022-08-23 16:07:37 +010077
78 Creates a description of the test case, including a name for the test
Werner Lewis6ef54362022-08-25 12:29:46 +010079 function, a case number, and a description the specific test case.
80 This should inform a reader what is being tested, and provide context
81 for the test case.
Werner Lewis169034a2022-08-23 16:07:37 +010082
83 Returns:
84 Description for the test case.
85 """
Werner Lewisd03d2a32022-08-24 17:20:29 +010086 return "{} #{} {}".format(
87 self.test_name, self.count, self.case_description
88 ).strip()
Werner Lewisfbb75e32022-08-24 11:30:03 +010089
Werner Lewis169034a2022-08-23 16:07:37 +010090
Werner Lewisfbb75e32022-08-24 11:30:03 +010091 def create_test_case(self) -> test_case.TestCase:
Werner Lewis6ef54362022-08-25 12:29:46 +010092 """Generate TestCase from the instance."""
Werner Lewisfbb75e32022-08-24 11:30:03 +010093 tc = test_case.TestCase()
Werner Lewis55e638c2022-08-23 14:21:53 +010094 tc.set_description(self.description())
95 tc.set_function(self.test_function)
96 tc.set_arguments(self.arguments())
Werner Lewisfbb75e32022-08-24 11:30:03 +010097
98 return tc
99
100 @classmethod
Werner Lewis2b527a32022-08-24 12:42:00 +0100101 @abstractmethod
102 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Werner Lewis6ef54362022-08-25 12:29:46 +0100103 """Generate test cases for the class test function.
Werner Lewis169034a2022-08-23 16:07:37 +0100104
Werner Lewis2b527a32022-08-24 12:42:00 +0100105 This will be called in classes where `test_function` is set.
106 Implementations should yield TestCase objects, by creating instances
107 of the class with appropriate input data, and then calling
108 `create_test_case()` on each.
Werner Lewis169034a2022-08-23 16:07:37 +0100109 """
Werner Lewis6d654c62022-08-25 09:56:51 +0100110 raise NotImplementedError
Werner Lewis2b527a32022-08-24 12:42:00 +0100111
112 @classmethod
113 def generate_tests(cls) -> Iterator[test_case.TestCase]:
114 """Generate test cases for the class and its subclasses.
115
116 In classes with `test_function` set, `generate_function_tests()` is
Werner Lewis81f24442022-08-25 16:27:05 +0100117 called to generate test cases first.
Werner Lewis2b527a32022-08-24 12:42:00 +0100118
Werner Lewis6ef54362022-08-25 12:29:46 +0100119 In all classes, this method will iterate over its subclasses, and
120 yield from `generate_tests()` in each. Calling this method on a class X
121 will yield test cases from all classes derived from X.
Werner Lewis2b527a32022-08-24 12:42:00 +0100122 """
123 if cls.test_function:
124 yield from cls.generate_function_tests()
Werner Lewisfbb75e32022-08-24 11:30:03 +0100125 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
126 yield from subclass.generate_tests()
127
128
129class TestGenerator:
130 """Generate test data."""
131 def __init__(self, options) -> None:
Werner Lewisf156c432022-08-25 11:30:17 +0100132 self.test_suite_directory = getattr(options, 'directory')
Werner Lewisfbb75e32022-08-24 11:30:03 +0100133
134 def filename_for(self, basename: str) -> str:
135 """The location of the data file with the specified base name."""
136 return posixpath.join(self.test_suite_directory, basename + '.data')
137
138 def write_test_data_file(self, basename: str,
139 test_cases: Iterable[test_case.TestCase]) -> None:
140 """Write the test cases to a .data file.
141
142 The output file is ``basename + '.data'`` in the test suite directory.
143 """
144 filename = self.filename_for(basename)
145 test_case.write_data_file(filename, test_cases)
146
147 # Note that targets whose names contain 'test_format' have their content
148 # validated by `abi_check.py`.
Werner Lewise3ad22e2022-08-25 10:02:06 +0100149 TARGETS = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
Werner Lewisfbb75e32022-08-24 11:30:03 +0100150
151 def generate_target(self, name: str, *target_args) -> None:
152 """Generate cases and write to data file for a target.
153
154 For target callables which require arguments, override this function
155 and pass these arguments using super() (see PSATestGenerator).
156 """
157 test_cases = self.TARGETS[name](*target_args)
158 self.write_test_data_file(name, test_cases)
159
160def main(args, generator_class: Type[TestGenerator] = TestGenerator):
161 """Command line entry point."""
162 parser = argparse.ArgumentParser(description=__doc__)
163 parser.add_argument('--list', action='store_true',
164 help='List available targets and exit')
165 parser.add_argument('--list-for-cmake', action='store_true',
166 help='Print \';\'-separated list of available targets and exit')
Werner Lewisf156c432022-08-25 11:30:17 +0100167 parser.add_argument('--directory', default="tests/suites", metavar='DIR',
Werner Lewisfbb75e32022-08-24 11:30:03 +0100168 help='Output directory (default: tests/suites)')
169 parser.add_argument('targets', nargs='*', metavar='TARGET',
Werner Lewis76f45622022-08-25 13:21:45 +0100170 default=sorted(generator_class.TARGETS),
Werner Lewisfbb75e32022-08-24 11:30:03 +0100171 help='Target file to generate (default: all; "-": none)')
172 options = parser.parse_args(args)
173 build_tree.chdir_to_root()
174 generator = generator_class(options)
175 if options.list:
176 for name in sorted(generator.TARGETS):
177 print(generator.filename_for(name))
178 return
179 # List in a cmake list format (i.e. ';'-separated)
180 if options.list_for_cmake:
181 print(';'.join(generator.filename_for(name)
182 for name in sorted(generator.TARGETS)), end='')
183 return
Werner Lewis9df9faa2022-08-25 12:49:41 +0100184 # Allow "-" as a special case so you can run
185 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
186 # ``$targets`` is empty or not.
187 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
188 for target in options.targets
189 if target != '-']
Werner Lewisfbb75e32022-08-24 11:30:03 +0100190 for target in options.targets:
191 generator.generate_target(target)