generate_bignum_tests.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. #!/usr/bin/env python3
  2. """Generate test data for bignum functions.
  3. With no arguments, generate all test data. With non-option arguments,
  4. generate only the specified files.
  5. Class structure:
  6. Child classes of test_data_generation.BaseTarget (file targets) represent an output
  7. file. These indicate where test cases will be written to, for all subclasses of
  8. this target. Multiple file targets should not reuse a `target_basename`.
  9. Each subclass derived from a file target can either be:
  10. - A concrete class, representing a test function, which generates test cases.
  11. - An abstract class containing shared methods and attributes, not associated
  12. with a test function. An example is BignumOperation, which provides
  13. common features used for bignum binary operations.
  14. Both concrete and abstract subclasses can be derived from, to implement
  15. additional test cases (see BignumCmp and BignumCmpAbs for examples of deriving
  16. from abstract and concrete classes).
  17. Adding test case generation for a function:
  18. A subclass representing the test function should be added, deriving from a
  19. file target such as BignumTarget. This test class must set/implement the
  20. following:
  21. - test_function: the function name from the associated .function file.
  22. - test_name: a descriptive name or brief summary to refer to the test
  23. function.
  24. - arguments(): a method to generate the list of arguments required for the
  25. test_function.
  26. - generate_function_tests(): a method to generate TestCases for the function.
  27. This should create instances of the class with required input data, and
  28. call `.create_test_case()` to yield the TestCase.
  29. Additional details and other attributes/methods are given in the documentation
  30. of BaseTarget in test_data_generation.py.
  31. """
  32. # Copyright The Mbed TLS Contributors
  33. # SPDX-License-Identifier: Apache-2.0
  34. #
  35. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  36. # not use this file except in compliance with the License.
  37. # You may obtain a copy of the License at
  38. #
  39. # http://www.apache.org/licenses/LICENSE-2.0
  40. #
  41. # Unless required by applicable law or agreed to in writing, software
  42. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  43. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  44. # See the License for the specific language governing permissions and
  45. # limitations under the License.
  46. import sys
  47. from abc import ABCMeta
  48. from typing import List
  49. import scripts_path # pylint: disable=unused-import
  50. from mbedtls_dev import test_data_generation
  51. from mbedtls_dev import bignum_common
  52. # Import modules containing additional test classes
  53. # Test function classes in these modules will be registered by
  54. # the framework
  55. from mbedtls_dev import bignum_core, bignum_mod_raw, bignum_mod # pylint: disable=unused-import
  56. class BignumTarget(test_data_generation.BaseTarget):
  57. #pylint: disable=too-few-public-methods
  58. """Target for bignum (legacy) test case generation."""
  59. target_basename = 'test_suite_bignum.generated'
  60. class BignumOperation(bignum_common.OperationCommon, BignumTarget,
  61. metaclass=ABCMeta):
  62. #pylint: disable=abstract-method
  63. """Common features for bignum operations in legacy tests."""
  64. unique_combinations_only = True
  65. input_values = [
  66. "", "0", "-", "-0",
  67. "7b", "-7b",
  68. "0000000000000000123", "-0000000000000000123",
  69. "1230000000000000000", "-1230000000000000000"
  70. ]
  71. def description_suffix(self) -> str:
  72. #pylint: disable=no-self-use # derived classes need self
  73. """Text to add at the end of the test case description."""
  74. return ""
  75. def description(self) -> str:
  76. """Generate a description for the test case.
  77. If not set, case_description uses the form A `symbol` B, where symbol
  78. is used to represent the operation. Descriptions of each value are
  79. generated to provide some context to the test case.
  80. """
  81. if not self.case_description:
  82. self.case_description = "{} {} {}".format(
  83. self.value_description(self.arg_a),
  84. self.symbol,
  85. self.value_description(self.arg_b)
  86. )
  87. description_suffix = self.description_suffix()
  88. if description_suffix:
  89. self.case_description += " " + description_suffix
  90. return super().description()
  91. @staticmethod
  92. def value_description(val) -> str:
  93. """Generate a description of the argument val.
  94. This produces a simple description of the value, which is used in test
  95. case naming to add context.
  96. """
  97. if val == "":
  98. return "0 (null)"
  99. if val == "-":
  100. return "negative 0 (null)"
  101. if val == "0":
  102. return "0 (1 limb)"
  103. if val[0] == "-":
  104. tmp = "negative"
  105. val = val[1:]
  106. else:
  107. tmp = "positive"
  108. if val[0] == "0":
  109. tmp += " with leading zero limb"
  110. elif len(val) > 10:
  111. tmp = "large " + tmp
  112. return tmp
  113. class BignumCmp(BignumOperation):
  114. """Test cases for bignum value comparison."""
  115. count = 0
  116. test_function = "mpi_cmp_mpi"
  117. test_name = "MPI compare"
  118. input_cases = [
  119. ("-2", "-3"),
  120. ("-2", "-2"),
  121. ("2b4", "2b5"),
  122. ("2b5", "2b6")
  123. ]
  124. def __init__(self, val_a, val_b) -> None:
  125. super().__init__(val_a, val_b)
  126. self._result = int(self.int_a > self.int_b) - int(self.int_a < self.int_b)
  127. self.symbol = ["<", "==", ">"][self._result + 1]
  128. def result(self) -> List[str]:
  129. return [str(self._result)]
  130. class BignumCmpAbs(BignumCmp):
  131. """Test cases for absolute bignum value comparison."""
  132. count = 0
  133. test_function = "mpi_cmp_abs"
  134. test_name = "MPI compare (abs)"
  135. def __init__(self, val_a, val_b) -> None:
  136. super().__init__(val_a.strip("-"), val_b.strip("-"))
  137. class BignumAdd(BignumOperation):
  138. """Test cases for bignum value addition."""
  139. count = 0
  140. symbol = "+"
  141. test_function = "mpi_add_mpi"
  142. test_name = "MPI add"
  143. input_cases = bignum_common.combination_pairs(
  144. [
  145. "1c67967269c6", "9cde3",
  146. "-1c67967269c6", "-9cde3",
  147. ]
  148. )
  149. def __init__(self, val_a: str, val_b: str) -> None:
  150. super().__init__(val_a, val_b)
  151. self._result = self.int_a + self.int_b
  152. def description_suffix(self) -> str:
  153. if (self.int_a >= 0 and self.int_b >= 0):
  154. return "" # obviously positive result or 0
  155. if (self.int_a <= 0 and self.int_b <= 0):
  156. return "" # obviously negative result or 0
  157. # The sign of the result is not obvious, so indicate it
  158. return ", result{}0".format('>' if self._result > 0 else
  159. '<' if self._result < 0 else '=')
  160. def result(self) -> List[str]:
  161. return [bignum_common.quote_str("{:x}".format(self._result))]
  162. if __name__ == '__main__':
  163. # Use the section of the docstring relevant to the CLI as description
  164. test_data_generation.main(sys.argv[1:], "\n".join(__doc__.splitlines()[:4]))