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