blob: f1e085d4e3529da89eb43a42d56626351a77e34e [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):
56 cls.count += 1
57 return super().__new__(cls)
Werner Lewisfbb75e32022-08-24 11:30:03 +010058
Werner Lewis169034a2022-08-23 16:07:37 +010059 @abstractmethod
Werner Lewis55e638c2022-08-23 14:21:53 +010060 def arguments(self) -> List[str]:
Werner Lewis169034a2022-08-23 16:07:37 +010061 """Get the list of arguments for the test case.
62
63 Override this method to provide the list of arguments required for
64 generating the test_function.
65
66 Returns:
67 List of arguments required for the test function.
68 """
69 pass
Werner Lewisfbb75e32022-08-24 11:30:03 +010070
Werner Lewisfbb75e32022-08-24 11:30:03 +010071 def description(self) -> str:
Werner Lewis169034a2022-08-23 16:07:37 +010072 """Create a test description.
73
74 Creates a description of the test case, including a name for the test
75 function, and describing the specific test case. This should inform a
76 reader of the purpose of the case. The case description may be
77 generated in the class, or provided manually as needed.
78
79 Returns:
80 Description for the test case.
81 """
Werner Lewis55e638c2022-08-23 14:21:53 +010082 return "{} #{} {}".format(self.test_name, self.count, self.case_description)
Werner Lewisfbb75e32022-08-24 11:30:03 +010083
Werner Lewis169034a2022-08-23 16:07:37 +010084
Werner Lewisfbb75e32022-08-24 11:30:03 +010085 def create_test_case(self) -> test_case.TestCase:
Werner Lewis169034a2022-08-23 16:07:37 +010086 """Generate TestCase from the current object."""
Werner Lewisfbb75e32022-08-24 11:30:03 +010087 tc = test_case.TestCase()
Werner Lewis55e638c2022-08-23 14:21:53 +010088 tc.set_description(self.description())
89 tc.set_function(self.test_function)
90 tc.set_arguments(self.arguments())
Werner Lewisfbb75e32022-08-24 11:30:03 +010091
92 return tc
93
94 @classmethod
Werner Lewis2b527a32022-08-24 12:42:00 +010095 @abstractmethod
96 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
97 """Generate test cases for the test function.
Werner Lewis169034a2022-08-23 16:07:37 +010098
Werner Lewis2b527a32022-08-24 12:42:00 +010099 This will be called in classes where `test_function` is set.
100 Implementations should yield TestCase objects, by creating instances
101 of the class with appropriate input data, and then calling
102 `create_test_case()` on each.
Werner Lewis169034a2022-08-23 16:07:37 +0100103 """
Werner Lewis2b527a32022-08-24 12:42:00 +0100104 pass
105
106 @classmethod
107 def generate_tests(cls) -> Iterator[test_case.TestCase]:
108 """Generate test cases for the class and its subclasses.
109
110 In classes with `test_function` set, `generate_function_tests()` is
111 used to generate test cases first.
112 In all classes, this method will iterate over its subclasses, and
113 yield from `generate_tests()` in each.
114
115 Calling this method on a class X will yield test cases from all classes
116 derived from X.
117 """
118 if cls.test_function:
119 yield from cls.generate_function_tests()
Werner Lewisfbb75e32022-08-24 11:30:03 +0100120 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
121 yield from subclass.generate_tests()
122
123
124class TestGenerator:
125 """Generate test data."""
126 def __init__(self, options) -> None:
127 self.test_suite_directory = self.get_option(options, 'directory',
128 'tests/suites')
129
130 @staticmethod
131 def get_option(options, name: str, default: T) -> T:
132 value = getattr(options, name, None)
133 return default if value is None else value
134
135 def filename_for(self, basename: str) -> str:
136 """The location of the data file with the specified base name."""
137 return posixpath.join(self.test_suite_directory, basename + '.data')
138
139 def write_test_data_file(self, basename: str,
140 test_cases: Iterable[test_case.TestCase]) -> None:
141 """Write the test cases to a .data file.
142
143 The output file is ``basename + '.data'`` in the test suite directory.
144 """
145 filename = self.filename_for(basename)
146 test_case.write_data_file(filename, test_cases)
147
148 # Note that targets whose names contain 'test_format' have their content
149 # validated by `abi_check.py`.
150 TARGETS = {} # type: Dict[str, Callable[..., test_case.TestCase]]
151
152 def generate_target(self, name: str, *target_args) -> None:
153 """Generate cases and write to data file for a target.
154
155 For target callables which require arguments, override this function
156 and pass these arguments using super() (see PSATestGenerator).
157 """
158 test_cases = self.TARGETS[name](*target_args)
159 self.write_test_data_file(name, test_cases)
160
161def main(args, generator_class: Type[TestGenerator] = TestGenerator):
162 """Command line entry point."""
163 parser = argparse.ArgumentParser(description=__doc__)
164 parser.add_argument('--list', action='store_true',
165 help='List available targets and exit')
166 parser.add_argument('--list-for-cmake', action='store_true',
167 help='Print \';\'-separated list of available targets and exit')
168 parser.add_argument('--directory', metavar='DIR',
169 help='Output directory (default: tests/suites)')
170 parser.add_argument('targets', nargs='*', metavar='TARGET',
171 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
184 if options.targets:
185 # Allow "-" as a special case so you can run
186 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
187 # ``$targets`` is empty or not.
188 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
189 for target in options.targets
190 if target != '-']
191 else:
192 options.targets = sorted(generator.TARGETS)
193 for target in options.targets:
194 generator.generate_target(target)