blob: 3abedd00f4c5436450638ca3d90317f7078e0352 [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
26from typing import Callable, Dict, Iterable, List, Type, TypeVar
27
28from mbedtls_dev import test_case
29
30T = TypeVar('T') #pylint: disable=invalid-name
31
32
33class BaseTarget:
34 """Base target for test case generation.
35
36 Attributes:
37 count: Counter for test class.
38 desc: Short description of test case.
39 func: Function which the class generates tests for.
40 gen_file: File to write generated tests to.
41 title: Description of the test function/purpose.
42 """
43 count = 0
44 desc = ""
45 func = ""
46 gen_file = ""
47 title = ""
48
49 def __init__(self) -> None:
50 type(self).count += 1
51
52 @property
53 def args(self) -> List[str]:
54 """Create list of arguments for test case."""
55 return []
56
57 @property
58 def description(self) -> str:
59 """Create a numbered test description."""
60 return "{} #{} {}".format(self.title, self.count, self.desc)
61
62 def create_test_case(self) -> test_case.TestCase:
63 """Generate test case from the current object."""
64 tc = test_case.TestCase()
65 tc.set_description(self.description)
66 tc.set_function(self.func)
67 tc.set_arguments(self.args)
68
69 return tc
70
71 @classmethod
72 def generate_tests(cls):
73 """Generate test cases for the target subclasses."""
74 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
75 yield from subclass.generate_tests()
76
77
78class TestGenerator:
79 """Generate test data."""
80 def __init__(self, options) -> None:
81 self.test_suite_directory = self.get_option(options, 'directory',
82 'tests/suites')
83
84 @staticmethod
85 def get_option(options, name: str, default: T) -> T:
86 value = getattr(options, name, None)
87 return default if value is None else value
88
89 def filename_for(self, basename: str) -> str:
90 """The location of the data file with the specified base name."""
91 return posixpath.join(self.test_suite_directory, basename + '.data')
92
93 def write_test_data_file(self, basename: str,
94 test_cases: Iterable[test_case.TestCase]) -> None:
95 """Write the test cases to a .data file.
96
97 The output file is ``basename + '.data'`` in the test suite directory.
98 """
99 filename = self.filename_for(basename)
100 test_case.write_data_file(filename, test_cases)
101
102 # Note that targets whose names contain 'test_format' have their content
103 # validated by `abi_check.py`.
104 TARGETS = {} # type: Dict[str, Callable[..., test_case.TestCase]]
105
106 def generate_target(self, name: str, *target_args) -> None:
107 """Generate cases and write to data file for a target.
108
109 For target callables which require arguments, override this function
110 and pass these arguments using super() (see PSATestGenerator).
111 """
112 test_cases = self.TARGETS[name](*target_args)
113 self.write_test_data_file(name, test_cases)
114
115def main(args, generator_class: Type[TestGenerator] = TestGenerator):
116 """Command line entry point."""
117 parser = argparse.ArgumentParser(description=__doc__)
118 parser.add_argument('--list', action='store_true',
119 help='List available targets and exit')
120 parser.add_argument('targets', nargs='*', metavar='TARGET',
121 help='Target file to generate (default: all; "-": none)')
122 options = parser.parse_args(args)
123 generator = generator_class(options)
124 if options.list:
125 for name in sorted(generator.TARGETS):
126 print(generator.filename_for(name))
127 return
128 if options.targets:
129 # Allow "-" as a special case so you can run
130 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
131 # ``$targets`` is empty or not.
132 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
133 for target in options.targets
134 if target != '-']
135 else:
136 options.targets = sorted(generator.TARGETS)
137 for target in options.targets:
138 generator.generate_target(target)