blob: ea391c332e5a7007659f44e2344ea4a6bce050c1 [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
27from abc import abstractmethod
Werner Lewisdcad1e92022-08-24 11:30:03 +010028from typing import Callable, Dict, Iterable, List, Type, TypeVar
29
30from mbedtls_dev import test_case
31
32T = TypeVar('T') #pylint: disable=invalid-name
33
34
35class BaseTarget:
36 """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
93 def generate_tests(cls):
Werner Lewis008d90d2022-08-23 16:07:37 +010094 """Generate test cases for the target subclasses.
95
96 Classes will iterate over its subclasses, calling this method in each.
97 In abstract classes, no further changes are needed, as there is no
98 function to generate tests for.
99 In classes which do implement a test function, this should be overrided
100 and a means to use `create_test_case()` should be added. In most cases
101 the subclasses can still be iterated over, as either the class will
102 have none, or it may continue.
103 """
Werner Lewisdcad1e92022-08-24 11:30:03 +0100104 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
105 yield from subclass.generate_tests()
106
107
108class TestGenerator:
109 """Generate test data."""
110 def __init__(self, options) -> None:
111 self.test_suite_directory = self.get_option(options, 'directory',
112 'tests/suites')
113
114 @staticmethod
115 def get_option(options, name: str, default: T) -> T:
116 value = getattr(options, name, None)
117 return default if value is None else value
118
119 def filename_for(self, basename: str) -> str:
120 """The location of the data file with the specified base name."""
121 return posixpath.join(self.test_suite_directory, basename + '.data')
122
123 def write_test_data_file(self, basename: str,
124 test_cases: Iterable[test_case.TestCase]) -> None:
125 """Write the test cases to a .data file.
126
127 The output file is ``basename + '.data'`` in the test suite directory.
128 """
129 filename = self.filename_for(basename)
130 test_case.write_data_file(filename, test_cases)
131
132 # Note that targets whose names contain 'test_format' have their content
133 # validated by `abi_check.py`.
134 TARGETS = {} # type: Dict[str, Callable[..., test_case.TestCase]]
135
136 def generate_target(self, name: str, *target_args) -> None:
137 """Generate cases and write to data file for a target.
138
139 For target callables which require arguments, override this function
140 and pass these arguments using super() (see PSATestGenerator).
141 """
142 test_cases = self.TARGETS[name](*target_args)
143 self.write_test_data_file(name, test_cases)
144
145def main(args, generator_class: Type[TestGenerator] = TestGenerator):
146 """Command line entry point."""
147 parser = argparse.ArgumentParser(description=__doc__)
148 parser.add_argument('--list', action='store_true',
149 help='List available targets and exit')
150 parser.add_argument('targets', nargs='*', metavar='TARGET',
151 help='Target file to generate (default: all; "-": none)')
152 options = parser.parse_args(args)
153 generator = generator_class(options)
154 if options.list:
155 for name in sorted(generator.TARGETS):
156 print(generator.filename_for(name))
157 return
158 if options.targets:
159 # Allow "-" as a special case so you can run
160 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
161 # ``$targets`` is empty or not.
162 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
163 for target in options.targets
164 if target != '-']
165 else:
166 options.targets = sorted(generator.TARGETS)
167 for target in options.targets:
168 generator.generate_target(target)