1#!/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 7Class structure: 8 9Child classes of test_data_generation.BaseTarget (file targets) represent an output 10file. These indicate where test cases will be written to, for all subclasses of 11this target. Multiple file targets should not reuse a `target_basename`. 12 13Each subclass derived from a file target can either be: 14 - A concrete class, representing a test function, which generates test cases. 15 - An abstract class containing shared methods and attributes, not associated 16 with a test function. An example is BignumOperation, which provides 17 common features used for bignum binary operations. 18 19Both concrete and abstract subclasses can be derived from, to implement 20additional test cases (see BignumCmp and BignumCmpAbs for examples of deriving 21from abstract and concrete classes). 22 23 24Adding test case generation for a function: 25 26A subclass representing the test function should be added, deriving from a 27file target such as BignumTarget. This test class must set/implement the 28following: 29 - test_function: the function name from the associated .function file. 30 - test_name: a descriptive name or brief summary to refer to the test 31 function. 32 - arguments(): a method to generate the list of arguments required for the 33 test_function. 34 - generate_function_test(): a method to generate TestCases for the function. 35 This should create instances of the class with required input data, and 36 call `.create_test_case()` to yield the TestCase. 37 38Additional details and other attributes/methods are given in the documentation 39of BaseTarget in test_data_generation.py. 40""" 41 42# Copyright The Mbed TLS Contributors 43# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later 44 45import sys 46 47from abc import ABCMeta, abstractmethod 48from typing import Iterator, List, Tuple, TypeVar 49 50import scripts_path # pylint: disable=unused-import 51from mbedtls_dev import test_case 52from mbedtls_dev import test_data_generation 53 54T = TypeVar('T') #pylint: disable=invalid-name 55 56def hex_to_int(val: str) -> int: 57 """Implement the syntax accepted by mbedtls_test_read_mpi(). 58 59 This is a superset of what is accepted by mbedtls_test_read_mpi_core(). 60 """ 61 if val in ['', '-']: 62 return 0 63 return int(val, 16) 64 65def quote_str(val) -> str: 66 return "\"{}\"".format(val) 67 68def combination_pairs(values: List[T]) -> List[Tuple[T, T]]: 69 """Return all pair combinations from input values.""" 70 return [(x, y) for x in values for y in values] 71 72class BignumTarget(test_data_generation.BaseTarget, metaclass=ABCMeta): 73 #pylint: disable=abstract-method 74 """Target for bignum (legacy) test case generation.""" 75 target_basename = 'test_suite_bignum.generated' 76 77 78class BignumOperation(BignumTarget, metaclass=ABCMeta): 79 """Common features for bignum binary operations. 80 81 This adds functionality common in binary operation tests. This includes 82 generation of case descriptions, using descriptions of values and symbols 83 to represent the operation or result. 84 85 Attributes: 86 symbol: Symbol used for the operation in case description. 87 input_values: List of values to use as test case inputs. These are 88 combined to produce pairs of values. 89 input_cases: List of tuples containing pairs of test case inputs. This 90 can be used to implement specific pairs of inputs. 91 """ 92 symbol = "" 93 input_values = [ 94 "", "0", "-", "-0", 95 "7b", "-7b", 96 "0000000000000000123", "-0000000000000000123", 97 "1230000000000000000", "-1230000000000000000" 98 ] # type: List[str] 99 input_cases = [] # type: List[Tuple[str, str]] 100 101 def __init__(self, val_a: str, val_b: str) -> None: 102 self.arg_a = val_a 103 self.arg_b = val_b 104 self.int_a = hex_to_int(val_a) 105 self.int_b = hex_to_int(val_b) 106 107 def arguments(self) -> List[str]: 108 return [quote_str(self.arg_a), quote_str(self.arg_b), self.result()] 109 110 def description_suffix(self) -> str: 111 #pylint: disable=no-self-use # derived classes need self 112 """Text to add at the end of the test case description.""" 113 return "" 114 115 def description(self) -> str: 116 """Generate a description for the test case. 117 118 If not set, case_description uses the form A `symbol` B, where symbol 119 is used to represent the operation. Descriptions of each value are 120 generated to provide some context to the test case. 121 """ 122 if not self.case_description: 123 self.case_description = "{} {} {}".format( 124 self.value_description(self.arg_a), 125 self.symbol, 126 self.value_description(self.arg_b) 127 ) 128 description_suffix = self.description_suffix() 129 if description_suffix: 130 self.case_description += " " + description_suffix 131 return super().description() 132 133 @abstractmethod 134 def result(self) -> str: 135 """Get the result of the operation. 136 137 This could be calculated during initialization and stored as `_result` 138 and then returned, or calculated when the method is called. 139 """ 140 raise NotImplementedError 141 142 @staticmethod 143 def value_description(val) -> str: 144 """Generate a description of the argument val. 145 146 This produces a simple description of the value, which is used in test 147 case naming to add context. 148 """ 149 if val == "": 150 return "0 (null)" 151 if val == "-": 152 return "negative 0 (null)" 153 if val == "0": 154 return "0 (1 limb)" 155 156 if val[0] == "-": 157 tmp = "negative" 158 val = val[1:] 159 else: 160 tmp = "positive" 161 if val[0] == "0": 162 tmp += " with leading zero limb" 163 elif len(val) > 10: 164 tmp = "large " + tmp 165 return tmp 166 167 @classmethod 168 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]: 169 """Generator to yield pairs of inputs. 170 171 Combinations are first generated from all input values, and then 172 specific cases provided. 173 """ 174 yield from combination_pairs(cls.input_values) 175 yield from cls.input_cases 176 177 @classmethod 178 def generate_function_tests(cls) -> Iterator[test_case.TestCase]: 179 for a_value, b_value in cls.get_value_pairs(): 180 cur_op = cls(a_value, b_value) 181 yield cur_op.create_test_case() 182 183 184class BignumCmp(BignumOperation): 185 """Test cases for bignum value comparison.""" 186 count = 0 187 test_function = "mpi_cmp_mpi" 188 test_name = "MPI compare" 189 input_cases = [ 190 ("-2", "-3"), 191 ("-2", "-2"), 192 ("2b4", "2b5"), 193 ("2b5", "2b6") 194 ] 195 196 def __init__(self, val_a, val_b) -> None: 197 super().__init__(val_a, val_b) 198 self._result = int(self.int_a > self.int_b) - int(self.int_a < self.int_b) 199 self.symbol = ["<", "==", ">"][self._result + 1] 200 201 def result(self) -> str: 202 return str(self._result) 203 204 205class BignumCmpAbs(BignumCmp): 206 """Test cases for absolute bignum value comparison.""" 207 count = 0 208 test_function = "mpi_cmp_abs" 209 test_name = "MPI compare (abs)" 210 211 def __init__(self, val_a, val_b) -> None: 212 super().__init__(val_a.strip("-"), val_b.strip("-")) 213 214 215class BignumAdd(BignumOperation): 216 """Test cases for bignum value addition.""" 217 count = 0 218 symbol = "+" 219 test_function = "mpi_add_mpi" 220 test_name = "MPI add" 221 input_cases = combination_pairs( 222 [ 223 "1c67967269c6", "9cde3", 224 "-1c67967269c6", "-9cde3", 225 ] 226 ) 227 228 def __init__(self, val_a: str, val_b: str) -> None: 229 super().__init__(val_a, val_b) 230 self._result = self.int_a + self.int_b 231 232 def description_suffix(self) -> str: 233 if (self.int_a >= 0 and self.int_b >= 0): 234 return "" # obviously positive result or 0 235 if (self.int_a <= 0 and self.int_b <= 0): 236 return "" # obviously negative result or 0 237 # The sign of the result is not obvious, so indicate it 238 return ", result{}0".format('>' if self._result > 0 else 239 '<' if self._result < 0 else '=') 240 241 def result(self) -> str: 242 return quote_str("{:x}".format(self._result)) 243 244if __name__ == '__main__': 245 # Use the section of the docstring relevant to the CLI as description 246 test_data_generation.main(sys.argv[1:], "\n".join(__doc__.splitlines()[:4])) 247