blob: c6e6a116caf75cfce18b62f3669dbb6b8349a277 [file] [log] [blame]
Werner Lewis8b2df742022-07-08 13:54:57 +01001#!/usr/bin/env python3
2"""Generate test data for bignum functions.
3
4With no arguments, generate all test data. With non-option arguments,
5generate only the specified files.
6"""
7
8# Copyright The Mbed TLS Contributors
9# SPDX-License-Identifier: Apache-2.0
10#
11# Licensed under the Apache License, Version 2.0 (the "License"); you may
12# not use this file except in compliance with the License.
13# You may obtain a copy of the License at
14#
15# http://www.apache.org/licenses/LICENSE-2.0
16#
17# Unless required by applicable law or agreed to in writing, software
18# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
19# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20# See the License for the specific language governing permissions and
21# limitations under the License.
22
23import argparse
24import itertools
25import os
26import posixpath
27import re
28import sys
29from typing import Iterable, Iterator, Optional, Tuple, TypeVar
30
31import scripts_path # pylint: disable=unused-import
32from mbedtls_dev import build_tree
33from mbedtls_dev import test_case
34
35T = TypeVar('T') #pylint: disable=invalid-name
36
37def hex_to_int(val):
38 return int(val, 16) if val else 0
39
40def quote_str(val):
41 return "\"{}\"".format(val)
42
43
44class BaseTarget:
45 """Base target for test case generation.
46
47 Attributes:
48 count: Counter for test class.
49 desc: Short description of test case.
50 func: Function which the class generates tests for.
51 gen_file: File to write generated tests to.
52 title: Description of the test function/purpose.
53 """
54 count = 0
55 desc = None
56 func = None
57 gen_file = ""
58 title = None
59
60 def __init__(self) -> None:
61 type(self).count += 1
62
63 @property
64 def args(self) -> Iterable[str]:
65 """Create list of arguments for test case."""
66 return []
67
68 @property
69 def description(self) -> str:
70 """Create a numbered test description."""
71 return "{} #{} {}".format(self.title, self.count, self.desc)
72
73 def create_test_case(self) -> test_case.TestCase:
74 """Generate test case from the current object."""
75 tc = test_case.TestCase()
76 tc.set_description(self.description)
77 tc.set_function(self.func)
78 tc.set_arguments(self.args)
79
80 return tc
81
82 @classmethod
83 def generate_tests(cls):
84 """Generate test cases for the target subclasses."""
85 for subclass in cls.__subclasses__():
86 yield from subclass.generate_tests()
87
88
89class BignumTarget(BaseTarget):
90 """Target for bignum (mpi) test case generation."""
91 gen_file = 'test_suite_mpi.generated'
92
93
94class BignumOperation(BignumTarget):
95 """Common features for test cases covering bignum operations.
96
97 Attributes:
98 symb: Symbol used for operation in description.
99 input_vals: List of values used to generate test case args.
100 input_cases: List of tuples containing test case inputs. This
101 can be used to implement specific pairs of inputs.
102 """
103 symb = ""
104 input_vals = [
105 "", "0", "7b", "-7b",
106 "0000000000000000123", "-0000000000000000123",
107 "1230000000000000000", "-1230000000000000000"
108 ]
109 input_cases = []
110
111 def __init__(self, val_l: str, val_r: str) -> None:
112 super().__init__()
113
114 self.arg_l = val_l
115 self.arg_r = val_r
116 self.int_l = hex_to_int(val_l)
117 self.int_r = hex_to_int(val_r)
118
119 @property
120 def args(self):
121 return [quote_str(self.arg_l), quote_str(self.arg_r), self.result]
122
123 @property
124 def description(self):
125 desc = self.desc if self.desc else "{} {} {}".format(
126 self.val_desc(self.arg_l),
127 self.symb,
128 self.val_desc(self.arg_r)
129 )
130 return "{} #{} {}".format(self.title, self.count, desc)
131
132 @property
133 def result(self) -> Optional[str]:
134 return None
135
136 @staticmethod
137 def val_desc(val) -> str:
138 """Generate description of the argument val."""
139 if val == "":
140 return "0 (null)"
141 if val == "0":
142 return "0 (1 limb)"
143
144 if val[0] == "-":
145 tmp = "negative"
146 val = val[1:]
147 else:
148 tmp = "positive"
149 if val[0] == "0":
150 tmp += " with leading zero limb"
151 elif len(val) > 10:
152 tmp = "large " + tmp
153 return tmp
154
155 @classmethod
156 def get_value_pairs(cls) -> Iterator[Tuple[str, ...]]:
157 """Generate value pairs."""
158 for pair in set(
159 list(itertools.combinations(cls.input_vals, 2)) +
160 cls.input_cases
161 ):
162 yield pair
163
164 @classmethod
165 def generate_tests(cls) -> Iterator[test_case.TestCase]:
166 if cls.func is not None:
167 # Generate tests for the current class
168 for l_value, r_value in cls.get_value_pairs():
169 cur_op = cls(l_value, r_value)
170 yield cur_op.create_test_case()
171 # Once current class completed, check descendants
172 yield from super().generate_tests()
173
174
175class BignumCmp(BignumOperation):
176 """Target for bignum comparison test cases."""
177 count = 0
178 func = "mbedtls_mpi_cmp_mpi"
179 title = "MPI compare"
180 input_cases = [
181 ("-2", "-3"),
182 ("-2", "-2"),
183 ("2b4", "2b5"),
184 ("2b5", "2b6")
185 ]
186
187 def __init__(self, val_l, val_r):
188 super().__init__(val_l, val_r)
189 self._result = (self.int_l > self.int_r) - (self.int_l < self.int_r)
190 self.symb = ["<", "==", ">"][self._result + 1]
191
192 @property
193 def result(self):
194 return str(self._result)
195
196
197class TestGenerator:
198 """Generate test data."""
199
200 def __init__(self, options) -> None:
201 self.test_suite_directory = self.get_option(options, 'directory',
202 'tests/suites')
203
204 @staticmethod
205 def get_option(options, name: str, default: T) -> T:
206 value = getattr(options, name, None)
207 return default if value is None else value
208
209 def filename_for(self, basename: str) -> str:
210 """The location of the data file with the specified base name."""
211 return posixpath.join(self.test_suite_directory, basename + '.data')
212
213 def write_test_data_file(self, basename: str,
214 test_cases: Iterable[test_case.TestCase]) -> None:
215 """Write the test cases to a .data file.
216
217 The output file is ``basename + '.data'`` in the test suite directory.
218 """
219 filename = self.filename_for(basename)
220 test_case.write_data_file(filename, test_cases)
221
222 # Note that targets whose names contain 'test_format' have their content
223 # validated by `abi_check.py`.
224 TARGETS = {
225 subclass.gen_file: subclass.generate_tests for subclass in
226 BaseTarget.__subclasses__()
227 }
228
229 def generate_target(self, name: str) -> None:
230 test_cases = self.TARGETS[name]()
231 self.write_test_data_file(name, test_cases)
232
233def main(args):
234 """Command line entry point."""
235 parser = argparse.ArgumentParser(description=__doc__)
236 parser.add_argument('--list', action='store_true',
237 help='List available targets and exit')
238 parser.add_argument('--list-for-cmake', action='store_true',
239 help='Print \';\'-separated list of available targets and exit')
240 parser.add_argument('--directory', metavar='DIR',
241 help='Output directory (default: tests/suites)')
242 parser.add_argument('targets', nargs='*', metavar='TARGET',
243 help='Target file to generate (default: all; "-": none)')
244 options = parser.parse_args(args)
245 build_tree.chdir_to_root()
246 generator = TestGenerator(options)
247 if options.list:
248 for name in sorted(generator.TARGETS):
249 print(generator.filename_for(name))
250 return
251 # List in a cmake list format (i.e. ';'-separated)
252 if options.list_for_cmake:
253 print(';'.join(generator.filename_for(name)
254 for name in sorted(generator.TARGETS)), end='')
255 return
256 if options.targets:
257 # Allow "-" as a special case so you can run
258 # ``generate_bignum_tests.py - $targets`` and it works uniformly whether
259 # ``$targets`` is empty or not.
260 options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
261 for target in options.targets
262 if target != '-']
263 else:
264 options.targets = sorted(generator.TARGETS)
265 for target in options.targets:
266 generator.generate_target(target)
267
268if __name__ == '__main__':
269 main(sys.argv[1:])