• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_tests(): 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
44#
45# Licensed under the Apache License, Version 2.0 (the "License"); you may
46# not use this file except in compliance with the License.
47# You may obtain a copy of the License at
48#
49# http://www.apache.org/licenses/LICENSE-2.0
50#
51# Unless required by applicable law or agreed to in writing, software
52# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
53# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
54# See the License for the specific language governing permissions and
55# limitations under the License.
56
57import sys
58
59from abc import ABCMeta
60from typing import List
61
62import scripts_path # pylint: disable=unused-import
63from mbedtls_dev import test_case
64from mbedtls_dev import test_data_generation
65from mbedtls_dev import bignum_common
66# Import modules containing additional test classes
67# Test function classes in these modules will be registered by
68# the framework
69from mbedtls_dev import bignum_core, bignum_mod_raw, bignum_mod # pylint: disable=unused-import
70
71class BignumTarget(test_data_generation.BaseTarget):
72    #pylint: disable=too-few-public-methods
73    """Target for bignum (legacy) test case generation."""
74    target_basename = 'test_suite_bignum.generated'
75
76
77class BignumOperation(bignum_common.OperationCommon, BignumTarget,
78                      metaclass=ABCMeta):
79    #pylint: disable=abstract-method
80    """Common features for bignum operations in legacy tests."""
81    unique_combinations_only = True
82    input_values = [
83        "", "0", "-", "-0",
84        "7b", "-7b",
85        "0000000000000000123", "-0000000000000000123",
86        "1230000000000000000", "-1230000000000000000"
87    ]
88
89    def description_suffix(self) -> str:
90        #pylint: disable=no-self-use # derived classes need self
91        """Text to add at the end of the test case description."""
92        return ""
93
94    def description(self) -> str:
95        """Generate a description for the test case.
96
97        If not set, case_description uses the form A `symbol` B, where symbol
98        is used to represent the operation. Descriptions of each value are
99        generated to provide some context to the test case.
100        """
101        if not self.case_description:
102            self.case_description = "{} {} {}".format(
103                self.value_description(self.arg_a),
104                self.symbol,
105                self.value_description(self.arg_b)
106            )
107            description_suffix = self.description_suffix()
108            if description_suffix:
109                self.case_description += " " + description_suffix
110        return super().description()
111
112    @staticmethod
113    def value_description(val) -> str:
114        """Generate a description of the argument val.
115
116        This produces a simple description of the value, which is used in test
117        case naming to add context.
118        """
119        if val == "":
120            return "0 (null)"
121        if val == "-":
122            return "negative 0 (null)"
123        if val == "0":
124            return "0 (1 limb)"
125
126        if val[0] == "-":
127            tmp = "negative"
128            val = val[1:]
129        else:
130            tmp = "positive"
131        if val[0] == "0":
132            tmp += " with leading zero limb"
133        elif len(val) > 10:
134            tmp = "large " + tmp
135        return tmp
136
137
138class BignumCmp(BignumOperation):
139    """Test cases for bignum value comparison."""
140    count = 0
141    test_function = "mpi_cmp_mpi"
142    test_name = "MPI compare"
143    input_cases = [
144        ("-2", "-3"),
145        ("-2", "-2"),
146        ("2b4", "2b5"),
147        ("2b5", "2b6")
148        ]
149
150    def __init__(self, val_a, val_b) -> None:
151        super().__init__(val_a, val_b)
152        self._result = int(self.int_a > self.int_b) - int(self.int_a < self.int_b)
153        self.symbol = ["<", "==", ">"][self._result + 1]
154
155    def result(self) -> List[str]:
156        return [str(self._result)]
157
158
159class BignumCmpAbs(BignumCmp):
160    """Test cases for absolute bignum value comparison."""
161    count = 0
162    test_function = "mpi_cmp_abs"
163    test_name = "MPI compare (abs)"
164
165    def __init__(self, val_a, val_b) -> None:
166        super().__init__(val_a.strip("-"), val_b.strip("-"))
167
168
169class BignumAdd(BignumOperation):
170    """Test cases for bignum value addition."""
171    count = 0
172    symbol = "+"
173    test_function = "mpi_add_mpi"
174    test_name = "MPI add"
175    input_cases = bignum_common.combination_pairs(
176        [
177            "1c67967269c6", "9cde3",
178            "-1c67967269c6", "-9cde3",
179        ]
180    )
181
182    def __init__(self, val_a: str, val_b: str) -> None:
183        super().__init__(val_a, val_b)
184        self._result = self.int_a + self.int_b
185
186    def description_suffix(self) -> str:
187        if (self.int_a >= 0 and self.int_b >= 0):
188            return "" # obviously positive result or 0
189        if (self.int_a <= 0 and self.int_b <= 0):
190            return "" # obviously negative result or 0
191        # The sign of the result is not obvious, so indicate it
192        return ", result{}0".format('>' if self._result > 0 else
193                                    '<' if self._result < 0 else '=')
194
195    def result(self) -> List[str]:
196        return [bignum_common.quote_str("{:x}".format(self._result))]
197
198if __name__ == '__main__':
199    # Use the section of the docstring relevant to the CLI as description
200    test_data_generation.main(sys.argv[1:], "\n".join(__doc__.splitlines()[:4]))
201