blob: 59b3b08e4610bdbe799aaef8a63ff13d0286b645 [file] [log] [blame]
Werner Lewisdcad1e92022-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 Lewis008d90d2022-08-23 16:07:37 +010026
Werner Lewis47e37b32022-08-24 12:18:25 +010027from abc import ABCMeta, abstractmethod
Werner Lewisc34d0372022-08-24 12:42:00 +010028from typing import Callable, Dict, Iterable, Iterator, List, Type, TypeVar
Werner Lewisdcad1e92022-08-24 11:30:03 +010029
30from mbedtls_dev import test_case
31
32T = TypeVar('T') #pylint: disable=invalid-name
33
34
Werner Lewis47e37b32022-08-24 12:18:25 +010035class BaseTarget(metaclass=ABCMeta):
Werner Lewisdcad1e92022-08-24 11:30:03 +010036 """Base target for test case generation.
37
38 Attributes:
Werner Lewis70d3f3d2022-08-23 14:21:53 +010039 count: Counter for test cases from this class.
40 case_description: Short description of the test case. This may be
41 automatically generated using the class, or manually set.
42 target_basename: Basename of file to write generated tests to. This
43 should be specified in a child class of BaseTarget.
44 test_function: Test function which the class generates cases for.
45 test_name: A common name or description of the test function. This can
46 be the function's name, or a short summary of its purpose.
Werner Lewisdcad1e92022-08-24 11:30:03 +010047 """
48 count = 0
Werner Lewis70d3f3d2022-08-23 14:21:53 +010049 case_description = ""
50 target_basename = ""
51 test_function = ""
52 test_name = ""
Werner Lewisdcad1e92022-08-24 11:30:03 +010053
54 def __init__(self) -> None:
55 type(self).count += 1
56
Werner Lewis008d90d2022-08-23 16:07:37 +010057 @abstractmethod
Werner Lewis70d3f3d2022-08-23 14:21:53 +010058 def arguments(self) -> List[str]:
Werner Lewis008d90d2022-08-23 16:07:37 +010059 """Get the list of arguments for the test case.
60
61 Override this method to provide the list of arguments required for
62 generating the test_function.
63
64 Returns:
65 List of arguments required for the test function.
66 """
67 pass
Werner Lewisdcad1e92022-08-24 11:30:03 +010068
Werner Lewisdcad1e92022-08-24 11:30:03 +010069 def description(self) -> str:
Werner Lewis008d90d2022-08-23 16:07:37 +010070 """Create a test description.
71
72 Creates a description of the test case, including a name for the test
73 function, and describing the specific test case. This should inform a
74 reader of the purpose of the case. The case description may be
75 generated in the class, or provided manually as needed.
76
77 Returns:
78 Description for the test case.
79 """
Werner Lewis70d3f3d2022-08-23 14:21:53 +010080 return "{} #{} {}".format(self.test_name, self.count, self.case_description)
Werner Lewisdcad1e92022-08-24 11:30:03 +010081
Werner Lewis008d90d2022-08-23 16:07:37 +010082
Werner Lewisdcad1e92022-08-24 11:30:03 +010083 def create_test_case(self) -> test_case.TestCase:
Werner Lewis008d90d2022-08-23 16:07:37 +010084 """Generate TestCase from the current object."""
Werner Lewisdcad1e92022-08-24 11:30:03 +010085 tc = test_case.TestCase()
Werner Lewis70d3f3d2022-08-23 14:21:53 +010086 tc.set_description(self.description())
87 tc.set_function(self.test_function)
88 tc.set_arguments(self.arguments())
Werner Lewisdcad1e92022-08-24 11:30:03 +010089
90 return tc
91
92 @classmethod
Werner Lewisc34d0372022-08-24 12:42:00 +010093 @abstractmethod
94 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
95 """Generate test cases for the test function.
Werner Lewis008d90d2022-08-23 16:07:37 +010096
Werner Lewisc34d0372022-08-24 12:42:00 +010097 This will be called in classes where `test_function` is set.
98 Implementations should yield TestCase objects, by creating instances
99 of the class with appropriate input data, and then calling
100 `create_test_case()` on each.
Werner Lewis008d90d2022-08-23 16:07:37 +0100101 """
Werner Lewisc34d0372022-08-24 12:42:00 +0100102 pass
103
104 @classmethod
105 def generate_tests(cls) -> Iterator[test_case.TestCase]:
106 """Generate test cases for the class and its subclasses.
107
108 In classes with `test_function` set, `generate_function_tests()` is
109 used to generate test cases first.
110 In all classes, this method will iterate over its subclasses, and
111 yield from `generate_tests()` in each.
112
113 Calling this method on a class X will yield test cases from all classes
114 derived from X.
115 """
116 if cls.test_function:
117 yield from cls.generate_function_tests()
Werner Lewisdcad1e92022-08-24 11:30:03 +0100118 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
119 yield from subclass.generate_tests()
120
121
122class TestGenerator:
123 """Generate test data."""
124 def __init__(self, options) -> None:
125 self.test_suite_directory = self.get_option(options, 'directory',
126 'tests/suites')
127
128 @staticmethod
129 def get_option(options, name: str, default: T) -> T:
130 value = getattr(options, name, None)
131 return default if value is None else value
132
133 def filename_for(self, basename: str) -> str:
134 """The location of the data file with the specified base name."""
135 return posixpath.join(self.test_suite_directory, basename + '.data')
136
137 def write_test_data_file(self, basename: str,
138 test_cases: Iterable[test_case.TestCase]) -> None:
139 """Write the test cases to a .data file.
140
141 The output file is ``basename + '.data'`` in the test suite directory.
142 """
143 filename = self.filename_for(basename)
144 test_case.write_data_file(filename, test_cases)
145
146 # Note that targets whose names contain 'test_format' have their content
147 # validated by `abi_check.py`.
148 TARGETS = {} # type: Dict[str, Callable[..., test_case.TestCase]]
149
150 def generate_target(self, name: str, *target_args) -> None:
151 """Generate cases and write to data file for a target.
152
153 For target callables which require arguments, override this function
154 and pass these arguments using super() (see PSATestGenerator).
155 """
156 test_cases = self.TARGETS[name](*target_args)
157 self.write_test_data_file(name, test_cases)
158
159def main(args, generator_class: Type[TestGenerator] = TestGenerator):
160 """Command line entry point."""
161 parser = argparse.ArgumentParser(description=__doc__)
162 parser.add_argument('--list', action='store_true',
163 help='List available targets and exit')
164 parser.add_argument('targets', nargs='*', metavar='TARGET',
165 help='Target file to generate (default: all; "-": none)')
166 options = parser.parse_args(args)
167 generator = generator_class(options)
168 if options.list:
169 for name in sorted(generator.TARGETS):
170 print(generator.filename_for(name))
171 return
172 if options.targets:
173 # Allow "-" as a special case so you can run
174 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
175 # ``$targets`` is empty or not.
176 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
177 for target in options.targets
178 if target != '-']
179 else:
180 options.targets = sorted(generator.TARGETS)
181 for target in options.targets:
182 generator.generate_target(target)