blob: bb70b9c72e5c8e3ab3f317fcf7ebb34e3b2cede7 [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
26from typing import Callable, Dict, Iterable, List, Type, TypeVar
27
28from mbedtls_dev import build_tree
29from mbedtls_dev import test_case
30
31T = TypeVar('T') #pylint: disable=invalid-name
32
33
34class BaseTarget:
35 """Base target for test case generation.
36
37 Attributes:
Werner Lewis55e638c2022-08-23 14:21:53 +010038 count: Counter for test cases from this class.
39 case_description: Short description of the test case. This may be
40 automatically generated using the class, or manually set.
41 target_basename: Basename of file to write generated tests to. This
42 should be specified in a child class of BaseTarget.
43 test_function: Test function which the class generates cases for.
44 test_name: A common name or description of the test function. This can
45 be the function's name, or a short summary of its purpose.
Werner Lewisfbb75e32022-08-24 11:30:03 +010046 """
47 count = 0
Werner Lewis55e638c2022-08-23 14:21:53 +010048 case_description = ""
49 target_basename = ""
50 test_function = ""
51 test_name = ""
Werner Lewisfbb75e32022-08-24 11:30:03 +010052
53 def __init__(self) -> None:
54 type(self).count += 1
55
Werner Lewis55e638c2022-08-23 14:21:53 +010056 def arguments(self) -> List[str]:
Werner Lewisfbb75e32022-08-24 11:30:03 +010057 return []
58
Werner Lewisfbb75e32022-08-24 11:30:03 +010059 def description(self) -> str:
60 """Create a numbered test description."""
Werner Lewis55e638c2022-08-23 14:21:53 +010061 return "{} #{} {}".format(self.test_name, self.count, self.case_description)
Werner Lewisfbb75e32022-08-24 11:30:03 +010062
63 def create_test_case(self) -> test_case.TestCase:
64 """Generate test case from the current object."""
65 tc = test_case.TestCase()
Werner Lewis55e638c2022-08-23 14:21:53 +010066 tc.set_description(self.description())
67 tc.set_function(self.test_function)
68 tc.set_arguments(self.arguments())
Werner Lewisfbb75e32022-08-24 11:30:03 +010069
70 return tc
71
72 @classmethod
73 def generate_tests(cls):
74 """Generate test cases for the target subclasses."""
75 for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
76 yield from subclass.generate_tests()
77
78
79class TestGenerator:
80 """Generate test data."""
81 def __init__(self, options) -> None:
82 self.test_suite_directory = self.get_option(options, 'directory',
83 'tests/suites')
84
85 @staticmethod
86 def get_option(options, name: str, default: T) -> T:
87 value = getattr(options, name, None)
88 return default if value is None else value
89
90 def filename_for(self, basename: str) -> str:
91 """The location of the data file with the specified base name."""
92 return posixpath.join(self.test_suite_directory, basename + '.data')
93
94 def write_test_data_file(self, basename: str,
95 test_cases: Iterable[test_case.TestCase]) -> None:
96 """Write the test cases to a .data file.
97
98 The output file is ``basename + '.data'`` in the test suite directory.
99 """
100 filename = self.filename_for(basename)
101 test_case.write_data_file(filename, test_cases)
102
103 # Note that targets whose names contain 'test_format' have their content
104 # validated by `abi_check.py`.
105 TARGETS = {} # type: Dict[str, Callable[..., test_case.TestCase]]
106
107 def generate_target(self, name: str, *target_args) -> None:
108 """Generate cases and write to data file for a target.
109
110 For target callables which require arguments, override this function
111 and pass these arguments using super() (see PSATestGenerator).
112 """
113 test_cases = self.TARGETS[name](*target_args)
114 self.write_test_data_file(name, test_cases)
115
116def main(args, generator_class: Type[TestGenerator] = TestGenerator):
117 """Command line entry point."""
118 parser = argparse.ArgumentParser(description=__doc__)
119 parser.add_argument('--list', action='store_true',
120 help='List available targets and exit')
121 parser.add_argument('--list-for-cmake', action='store_true',
122 help='Print \';\'-separated list of available targets and exit')
123 parser.add_argument('--directory', metavar='DIR',
124 help='Output directory (default: tests/suites)')
125 parser.add_argument('targets', nargs='*', metavar='TARGET',
126 help='Target file to generate (default: all; "-": none)')
127 options = parser.parse_args(args)
128 build_tree.chdir_to_root()
129 generator = generator_class(options)
130 if options.list:
131 for name in sorted(generator.TARGETS):
132 print(generator.filename_for(name))
133 return
134 # List in a cmake list format (i.e. ';'-separated)
135 if options.list_for_cmake:
136 print(';'.join(generator.filename_for(name)
137 for name in sorted(generator.TARGETS)), end='')
138 return
139 if options.targets:
140 # Allow "-" as a special case so you can run
141 # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
142 # ``$targets`` is empty or not.
143 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
144 for target in options.targets
145 if target != '-']
146 else:
147 options.targets = sorted(generator.TARGETS)
148 for target in options.targets:
149 generator.generate_target(target)