blob: 9551e2186749cea20c117f21737c816175aef3d9 [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.
Werner Lewis169034a2022-08-23 16:07:37 +01006
7Class structure:
8
9Target classes are directly derived from test_generation.BaseTarget,
10representing a target file. These indicate where test cases will be written
11to in classes derived from the Target. Multiple Target classes must not
12represent the same target_basename.
13
14Each subclass derived from a Target can either be:
15 - A concrete class, representing a test function, which generates test cases.
16 - An abstract class containing shared methods and attributes, not associated
17 with a test function. An example is BignumOperation, which provides common
18 features used in binary bignum operations.
19
20
21Adding test generation for a function:
22
23A subclass representing the test function should be added, deriving from a
24Target class or a descendant. This subclass must set/implement the following:
25 - test_function: the function name from the associated .function file.
26 - arguments(): generation of the arguments required for the test_function.
27 - generate_function_test(): generation of the test cases for the function.
28
29Additional details and other attributes/methods are given in the documentation
30of BaseTarget in test_generation.py.
Werner Lewis8b2df742022-07-08 13:54:57 +010031"""
32
33# Copyright The Mbed TLS Contributors
34# SPDX-License-Identifier: Apache-2.0
35#
36# Licensed under the Apache License, Version 2.0 (the "License"); you may
37# not use this file except in compliance with the License.
38# You may obtain a copy of the License at
39#
40# http://www.apache.org/licenses/LICENSE-2.0
41#
42# Unless required by applicable law or agreed to in writing, software
43# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
44# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
45# See the License for the specific language governing permissions and
46# limitations under the License.
47
Werner Lewis8b2df742022-07-08 13:54:57 +010048import itertools
Werner Lewis8b2df742022-07-08 13:54:57 +010049import sys
Werner Lewis169034a2022-08-23 16:07:37 +010050
Werner Lewis699e1262022-08-24 12:18:25 +010051from abc import ABCMeta, abstractmethod
Werner Lewisfbb75e32022-08-24 11:30:03 +010052from typing import Callable, Dict, Iterator, List, Optional, Tuple, TypeVar
Werner Lewis8b2df742022-07-08 13:54:57 +010053
54import scripts_path # pylint: disable=unused-import
Werner Lewis8b2df742022-07-08 13:54:57 +010055from mbedtls_dev import test_case
Werner Lewisfbb75e32022-08-24 11:30:03 +010056from mbedtls_dev import test_generation
Werner Lewis8b2df742022-07-08 13:54:57 +010057
58T = TypeVar('T') #pylint: disable=invalid-name
59
60def hex_to_int(val):
61 return int(val, 16) if val else 0
62
63def quote_str(val):
64 return "\"{}\"".format(val)
65
66
Werner Lewis699e1262022-08-24 12:18:25 +010067class BignumTarget(test_generation.BaseTarget, metaclass=ABCMeta):
Werner Lewis8b2df742022-07-08 13:54:57 +010068 """Target for bignum (mpi) test case generation."""
Werner Lewis55e638c2022-08-23 14:21:53 +010069 target_basename = 'test_suite_mpi.generated'
Werner Lewis8b2df742022-07-08 13:54:57 +010070
71
Werner Lewis699e1262022-08-24 12:18:25 +010072class BignumOperation(BignumTarget, metaclass=ABCMeta):
Werner Lewis169034a2022-08-23 16:07:37 +010073 """Common features for test cases covering binary bignum operations.
74
75 This adds functionality common in binary operation tests. This includes
76 generation of case descriptions, using descriptions of values and symbols
77 to represent the operation or result.
Werner Lewis8b2df742022-07-08 13:54:57 +010078
79 Attributes:
Werner Lewis169034a2022-08-23 16:07:37 +010080 symbol: Symbol used for the operation in case description.
81 input_values: List of values to use as test case inputs. These are
82 combined to produce pairs of values.
Werner Lewis55e638c2022-08-23 14:21:53 +010083 input_cases: List of tuples containing pairs of test case inputs. This
Werner Lewis8b2df742022-07-08 13:54:57 +010084 can be used to implement specific pairs of inputs.
85 """
Werner Lewis55e638c2022-08-23 14:21:53 +010086 symbol = ""
87 input_values = [
Werner Lewis8b2df742022-07-08 13:54:57 +010088 "", "0", "7b", "-7b",
89 "0000000000000000123", "-0000000000000000123",
90 "1230000000000000000", "-1230000000000000000"
Werner Lewisc442f6a2022-07-20 14:13:44 +010091 ] # type: List[str]
92 input_cases = [] # type: List[Tuple[str, ...]]
Werner Lewis8b2df742022-07-08 13:54:57 +010093
94 def __init__(self, val_l: str, val_r: str) -> None:
Werner Lewis8b2df742022-07-08 13:54:57 +010095 self.arg_l = val_l
96 self.arg_r = val_r
97 self.int_l = hex_to_int(val_l)
98 self.int_r = hex_to_int(val_r)
99
Werner Lewis55e638c2022-08-23 14:21:53 +0100100 def arguments(self):
101 return [quote_str(self.arg_l), quote_str(self.arg_r), self.result()]
Werner Lewis8b2df742022-07-08 13:54:57 +0100102
Werner Lewis8b2df742022-07-08 13:54:57 +0100103 def description(self):
Werner Lewis169034a2022-08-23 16:07:37 +0100104 """Generate a description for the test case.
105
106 If not set, case_description uses the form A `symbol` B, where symbol
107 is used to represent the operation. Descriptions of each value are
108 generated to provide some context to the test case.
109 """
Werner Lewis55e638c2022-08-23 14:21:53 +0100110 if not self.case_description:
111 self.case_description = "{} {} {}".format(
112 self.value_description(self.arg_l),
113 self.symbol,
114 self.value_description(self.arg_r)
115 )
116 return super().description()
Werner Lewis8b2df742022-07-08 13:54:57 +0100117
Werner Lewis169034a2022-08-23 16:07:37 +0100118 @abstractmethod
Werner Lewis699e1262022-08-24 12:18:25 +0100119 def result(self) -> str:
Werner Lewis169034a2022-08-23 16:07:37 +0100120 """Get the result of the operation.
121
122 This may be calculated during initialization and stored as `_result`,
123 or calculated when the method is called.
124 """
125 pass
Werner Lewis8b2df742022-07-08 13:54:57 +0100126
127 @staticmethod
Werner Lewis55e638c2022-08-23 14:21:53 +0100128 def value_description(val) -> str:
Werner Lewis169034a2022-08-23 16:07:37 +0100129 """Generate a description of the argument val.
130
131 This produces a simple description of the value, which are used in test
Werner Lewis699e1262022-08-24 12:18:25 +0100132 case naming, to add context to the test cases.
Werner Lewis169034a2022-08-23 16:07:37 +0100133 """
Werner Lewis8b2df742022-07-08 13:54:57 +0100134 if val == "":
135 return "0 (null)"
136 if val == "0":
137 return "0 (1 limb)"
138
139 if val[0] == "-":
140 tmp = "negative"
141 val = val[1:]
142 else:
143 tmp = "positive"
144 if val[0] == "0":
145 tmp += " with leading zero limb"
146 elif len(val) > 10:
147 tmp = "large " + tmp
148 return tmp
149
150 @classmethod
151 def get_value_pairs(cls) -> Iterator[Tuple[str, ...]]:
Werner Lewis169034a2022-08-23 16:07:37 +0100152 """Generator for pairs of inputs.
153
154 Combinations are first generated from all input values, and then
155 specific cases provided.
156 """
Werner Lewis92c876a2022-08-23 16:07:19 +0100157 yield from itertools.combinations(cls.input_values, 2)
158 yield from cls.input_cases
Werner Lewis8b2df742022-07-08 13:54:57 +0100159
160 @classmethod
Werner Lewis2b527a32022-08-24 12:42:00 +0100161 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
162 for l_value, r_value in cls.get_value_pairs():
163 cur_op = cls(l_value, r_value)
164 yield cur_op.create_test_case()
Werner Lewis8b2df742022-07-08 13:54:57 +0100165
166
167class BignumCmp(BignumOperation):
168 """Target for bignum comparison test cases."""
169 count = 0
Werner Lewis55e638c2022-08-23 14:21:53 +0100170 test_function = "mbedtls_mpi_cmp_mpi"
171 test_name = "MPI compare"
Werner Lewis8b2df742022-07-08 13:54:57 +0100172 input_cases = [
173 ("-2", "-3"),
174 ("-2", "-2"),
175 ("2b4", "2b5"),
176 ("2b5", "2b6")
177 ]
178
179 def __init__(self, val_l, val_r):
180 super().__init__(val_l, val_r)
Werner Lewis6c70d742022-08-24 16:37:44 +0100181 self._result = int(self.int_l > self.int_r) - int(self.int_l < self.int_r)
Werner Lewis55e638c2022-08-23 14:21:53 +0100182 self.symbol = ["<", "==", ">"][self._result + 1]
Werner Lewis8b2df742022-07-08 13:54:57 +0100183
Werner Lewis8b2df742022-07-08 13:54:57 +0100184 def result(self):
185 return str(self._result)
186
187
Werner Lewis69a92ce2022-07-18 15:49:43 +0100188class BignumCmpAbs(BignumCmp):
Werner Lewis169034a2022-08-23 16:07:37 +0100189 """Target for bignum comparison, absolute variant."""
Werner Lewis69a92ce2022-07-18 15:49:43 +0100190 count = 0
Werner Lewis55e638c2022-08-23 14:21:53 +0100191 test_function = "mbedtls_mpi_cmp_abs"
192 test_name = "MPI compare (abs)"
Werner Lewis69a92ce2022-07-18 15:49:43 +0100193
194 def __init__(self, val_l, val_r):
195 super().__init__(val_l.strip("-"), val_r.strip("-"))
196
197
Werner Lewis86caf852022-07-18 17:22:58 +0100198class BignumAdd(BignumOperation):
199 """Target for bignum addition test cases."""
200 count = 0
Werner Lewis55e638c2022-08-23 14:21:53 +0100201 test_function = "mbedtls_mpi_add_mpi"
202 test_name = "MPI add"
Werner Lewis86caf852022-07-18 17:22:58 +0100203 input_cases = list(itertools.combinations(
204 [
205 "1c67967269c6", "9cde3",
206 "-1c67967269c6", "-9cde3",
207 ], 2
208 ))
209
210 def __init__(self, val_l, val_r):
211 super().__init__(val_l, val_r)
Werner Lewis55e638c2022-08-23 14:21:53 +0100212 self.symbol = "+"
Werner Lewis86caf852022-07-18 17:22:58 +0100213
Werner Lewis86caf852022-07-18 17:22:58 +0100214 def result(self):
215 return quote_str(hex(self.int_l + self.int_r).replace("0x", "", 1))
216
217
Werner Lewisfbb75e32022-08-24 11:30:03 +0100218class BignumTestGenerator(test_generation.TestGenerator):
219 """Test generator subclass including bignum targets."""
Werner Lewis8b2df742022-07-08 13:54:57 +0100220 TARGETS = {
Werner Lewis55e638c2022-08-23 14:21:53 +0100221 subclass.target_basename: subclass.generate_tests for subclass in
Werner Lewisfbb75e32022-08-24 11:30:03 +0100222 test_generation.BaseTarget.__subclasses__()
223 } # type: Dict[str, Callable[[], test_case.TestCase]]
Werner Lewis8b2df742022-07-08 13:54:57 +0100224
225if __name__ == '__main__':
Werner Lewisfbb75e32022-08-24 11:30:03 +0100226 test_generation.main(sys.argv[1:], BignumTestGenerator)