blob: 712c7996bf4d76d598e40bef8097ffdd647d8fb5 [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
27from abc import abstractmethod
Werner Lewisfbb75e32022-08-24 11:30:03 +010028from typing import Callable, Dict, Iterable, List, Type, TypeVar
29
30from mbedtls_dev import build_tree
31from mbedtls_dev import test_case
32
33T = TypeVar('T') #pylint: disable=invalid-name
34
35
36class BaseTarget:
37 """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
55 def __init__(self) -> None:
56 type(self).count += 1
57
Werner Lewis169034a2022-08-23 16:07:37 +010058 @abstractmethod
Werner Lewis55e638c2022-08-23 14:21:53 +010059 def arguments(self) -> List[str]:
Werner Lewis169034a2022-08-23 16:07:37 +010060 """Get the list of arguments for the test case.
61
62 Override this method to provide the list of arguments required for
63 generating the test_function.
64
65 Returns:
66 List of arguments required for the test function.
67 """
68 pass
Werner Lewisfbb75e32022-08-24 11:30:03 +010069
Werner Lewisfbb75e32022-08-24 11:30:03 +010070 def description(self) -> str:
Werner Lewis169034a2022-08-23 16:07:37 +010071 """Create a test description.
72
73 Creates a description of the test case, including a name for the test
74 function, and describing the specific test case. This should inform a
75 reader of the purpose of the case. The case description may be
76 generated in the class, or provided manually as needed.
77
78 Returns:
79 Description for the test case.
80 """
Werner Lewis55e638c2022-08-23 14:21:53 +010081 return "{} #{} {}".format(self.test_name, self.count, self.case_description)
Werner Lewisfbb75e32022-08-24 11:30:03 +010082
Werner Lewis169034a2022-08-23 16:07:37 +010083
Werner Lewisfbb75e32022-08-24 11:30:03 +010084 def create_test_case(self) -> test_case.TestCase:
Werner Lewis169034a2022-08-23 16:07:37 +010085 """Generate TestCase from the current object."""
Werner Lewisfbb75e32022-08-24 11:30:03 +010086 tc = test_case.TestCase()
Werner Lewis55e638c2022-08-23 14:21:53 +010087 tc.set_description(self.description())
88 tc.set_function(self.test_function)
89 tc.set_arguments(self.arguments())
Werner Lewisfbb75e32022-08-24 11:30:03 +010090
91 return tc
92
93 @classmethod
94 def generate_tests(cls):
Werner Lewis169034a2022-08-23 16:07:37 +010095 """Generate test cases for the target subclasses.
96
97 Classes will iterate over its subclasses, calling this method in each.
98 In abstract classes, no further changes are needed, as there is no
99 function to generate tests for.
100 In classes which do implement a test function, this should be overrided
101 and a means to use `create_test_case()` should be added. In most cases
102 the subclasses can still be iterated over, as either the class will
103 have none, or it may continue.
104 """
Werner Lewisfbb75e32022-08-24 11:30:03 +0100105 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
106 yield from subclass.generate_tests()
107
108
109class TestGenerator:
110 """Generate test data."""
111 def __init__(self, options) -> None:
112 self.test_suite_directory = self.get_option(options, 'directory',
113 'tests/suites')
114
115 @staticmethod
116 def get_option(options, name: str, default: T) -> T:
117 value = getattr(options, name, None)
118 return default if value is None else value
119
120 def filename_for(self, basename: str) -> str:
121 """The location of the data file with the specified base name."""
122 return posixpath.join(self.test_suite_directory, basename + '.data')
123
124 def write_test_data_file(self, basename: str,
125 test_cases: Iterable[test_case.TestCase]) -> None:
126 """Write the test cases to a .data file.
127
128 The output file is ``basename + '.data'`` in the test suite directory.
129 """
130 filename = self.filename_for(basename)
131 test_case.write_data_file(filename, test_cases)
132
133 # Note that targets whose names contain 'test_format' have their content
134 # validated by `abi_check.py`.
135 TARGETS = {} # type: Dict[str, Callable[..., test_case.TestCase]]
136
137 def generate_target(self, name: str, *target_args) -> None:
138 """Generate cases and write to data file for a target.
139
140 For target callables which require arguments, override this function
141 and pass these arguments using super() (see PSATestGenerator).
142 """
143 test_cases = self.TARGETS[name](*target_args)
144 self.write_test_data_file(name, test_cases)
145
146def main(args, generator_class: Type[TestGenerator] = TestGenerator):
147 """Command line entry point."""
148 parser = argparse.ArgumentParser(description=__doc__)
149 parser.add_argument('--list', action='store_true',
150 help='List available targets and exit')
151 parser.add_argument('--list-for-cmake', action='store_true',
152 help='Print \';\'-separated list of available targets and exit')
153 parser.add_argument('--directory', metavar='DIR',
154 help='Output directory (default: tests/suites)')
155 parser.add_argument('targets', nargs='*', metavar='TARGET',
156 help='Target file to generate (default: all; "-": none)')
157 options = parser.parse_args(args)
158 build_tree.chdir_to_root()
159 generator = generator_class(options)
160 if options.list:
161 for name in sorted(generator.TARGETS):
162 print(generator.filename_for(name))
163 return
164 # List in a cmake list format (i.e. ';'-separated)
165 if options.list_for_cmake:
166 print(';'.join(generator.filename_for(name)
167 for name in sorted(generator.TARGETS)), end='')
168 return
169 if options.targets:
170 # Allow "-" as a special case so you can run
171 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
172 # ``$targets`` is empty or not.
173 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
174 for target in options.targets
175 if target != '-']
176 else:
177 options.targets = sorted(generator.TARGETS)
178 for target in options.targets:
179 generator.generate_target(target)