test_data_generation.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. """Common code for test data generation.
  2. This module defines classes that are of general use to automatically
  3. generate .data files for unit tests, as well as a main function.
  4. These are used both by generate_psa_tests.py and generate_bignum_tests.py.
  5. """
  6. # Copyright The Mbed TLS Contributors
  7. # SPDX-License-Identifier: Apache-2.0
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  10. # not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  17. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. import argparse
  21. import os
  22. import posixpath
  23. import re
  24. import inspect
  25. from abc import ABCMeta, abstractmethod
  26. from typing import Callable, Dict, Iterable, Iterator, List, Type, TypeVar
  27. from . import build_tree
  28. from . import test_case
  29. T = TypeVar('T') #pylint: disable=invalid-name
  30. class BaseTest(metaclass=ABCMeta):
  31. """Base class for test case generation.
  32. Attributes:
  33. count: Counter for test cases from this class.
  34. case_description: Short description of the test case. This may be
  35. automatically generated using the class, or manually set.
  36. dependencies: A list of dependencies required for the test case.
  37. show_test_count: Toggle for inclusion of `count` in the test description.
  38. test_function: Test function which the class generates cases for.
  39. test_name: A common name or description of the test function. This can
  40. be `test_function`, a clearer equivalent, or a short summary of the
  41. test function's purpose.
  42. """
  43. count = 0
  44. case_description = ""
  45. dependencies = [] # type: List[str]
  46. show_test_count = True
  47. test_function = ""
  48. test_name = ""
  49. def __new__(cls, *args, **kwargs):
  50. # pylint: disable=unused-argument
  51. cls.count += 1
  52. return super().__new__(cls)
  53. @abstractmethod
  54. def arguments(self) -> List[str]:
  55. """Get the list of arguments for the test case.
  56. Override this method to provide the list of arguments required for
  57. the `test_function`.
  58. Returns:
  59. List of arguments required for the test function.
  60. """
  61. raise NotImplementedError
  62. def description(self) -> str:
  63. """Create a test case description.
  64. Creates a description of the test case, including a name for the test
  65. function, an optional case count, and a description of the specific
  66. test case. This should inform a reader what is being tested, and
  67. provide context for the test case.
  68. Returns:
  69. Description for the test case.
  70. """
  71. if self.show_test_count:
  72. return "{} #{} {}".format(
  73. self.test_name, self.count, self.case_description
  74. ).strip()
  75. else:
  76. return "{} {}".format(self.test_name, self.case_description).strip()
  77. def create_test_case(self) -> test_case.TestCase:
  78. """Generate TestCase from the instance."""
  79. tc = test_case.TestCase()
  80. tc.set_description(self.description())
  81. tc.set_function(self.test_function)
  82. tc.set_arguments(self.arguments())
  83. tc.set_dependencies(self.dependencies)
  84. return tc
  85. @classmethod
  86. @abstractmethod
  87. def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
  88. """Generate test cases for the class test function.
  89. This will be called in classes where `test_function` is set.
  90. Implementations should yield TestCase objects, by creating instances
  91. of the class with appropriate input data, and then calling
  92. `create_test_case()` on each.
  93. """
  94. raise NotImplementedError
  95. class BaseTarget:
  96. #pylint: disable=too-few-public-methods
  97. """Base target for test case generation.
  98. Child classes of this class represent an output file, and can be referred
  99. to as file targets. These indicate where test cases will be written to for
  100. all subclasses of the file target, which is set by `target_basename`.
  101. Attributes:
  102. target_basename: Basename of file to write generated tests to. This
  103. should be specified in a child class of BaseTarget.
  104. """
  105. target_basename = ""
  106. @classmethod
  107. def generate_tests(cls) -> Iterator[test_case.TestCase]:
  108. """Generate test cases for the class and its subclasses.
  109. In classes with `test_function` set, `generate_function_tests()` is
  110. called to generate test cases first.
  111. In all classes, this method will iterate over its subclasses, and
  112. yield from `generate_tests()` in each. Calling this method on a class X
  113. will yield test cases from all classes derived from X.
  114. """
  115. if issubclass(cls, BaseTest) and not inspect.isabstract(cls):
  116. #pylint: disable=no-member
  117. yield from cls.generate_function_tests()
  118. for subclass in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
  119. yield from subclass.generate_tests()
  120. class TestGenerator:
  121. """Generate test cases and write to data files."""
  122. def __init__(self, options) -> None:
  123. self.test_suite_directory = options.directory
  124. # Update `targets` with an entry for each child class of BaseTarget.
  125. # Each entry represents a file generated by the BaseTarget framework,
  126. # and enables generating the .data files using the CLI.
  127. self.targets.update({
  128. subclass.target_basename: subclass.generate_tests
  129. for subclass in BaseTarget.__subclasses__()
  130. if subclass.target_basename
  131. })
  132. def filename_for(self, basename: str) -> str:
  133. """The location of the data file with the specified base name."""
  134. return posixpath.join(self.test_suite_directory, basename + '.data')
  135. def write_test_data_file(self, basename: str,
  136. test_cases: Iterable[test_case.TestCase]) -> None:
  137. """Write the test cases to a .data file.
  138. The output file is ``basename + '.data'`` in the test suite directory.
  139. """
  140. filename = self.filename_for(basename)
  141. test_case.write_data_file(filename, test_cases)
  142. # Note that targets whose names contain 'test_format' have their content
  143. # validated by `abi_check.py`.
  144. targets = {} # type: Dict[str, Callable[..., Iterable[test_case.TestCase]]]
  145. def generate_target(self, name: str, *target_args) -> None:
  146. """Generate cases and write to data file for a target.
  147. For target callables which require arguments, override this function
  148. and pass these arguments using super() (see PSATestGenerator).
  149. """
  150. test_cases = self.targets[name](*target_args)
  151. self.write_test_data_file(name, test_cases)
  152. def main(args, description: str, generator_class: Type[TestGenerator] = TestGenerator):
  153. """Command line entry point."""
  154. parser = argparse.ArgumentParser(description=description)
  155. parser.add_argument('--list', action='store_true',
  156. help='List available targets and exit')
  157. parser.add_argument('--list-for-cmake', action='store_true',
  158. help='Print \';\'-separated list of available targets and exit')
  159. # If specified explicitly, this option may be a path relative to the
  160. # current directory when the script is invoked. The default value
  161. # is relative to the mbedtls root, which we don't know yet. So we
  162. # can't set a string as the default value here.
  163. parser.add_argument('--directory', metavar='DIR',
  164. help='Output directory (default: tests/suites)')
  165. parser.add_argument('targets', nargs='*', metavar='TARGET',
  166. help='Target file to generate (default: all; "-": none)')
  167. options = parser.parse_args(args)
  168. # Change to the mbedtls root, to keep things simple. But first, adjust
  169. # command line options that might be relative paths.
  170. if options.directory is None:
  171. options.directory = 'tests/suites'
  172. else:
  173. options.directory = os.path.abspath(options.directory)
  174. build_tree.chdir_to_root()
  175. generator = generator_class(options)
  176. if options.list:
  177. for name in sorted(generator.targets):
  178. print(generator.filename_for(name))
  179. return
  180. # List in a cmake list format (i.e. ';'-separated)
  181. if options.list_for_cmake:
  182. print(';'.join(generator.filename_for(name)
  183. for name in sorted(generator.targets)), end='')
  184. return
  185. if options.targets:
  186. # Allow "-" as a special case so you can run
  187. # ``generate_xxx_tests.py - $targets`` and it works uniformly whether
  188. # ``$targets`` is empty or not.
  189. options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
  190. for target in options.targets
  191. if target != '-']
  192. else:
  193. options.targets = sorted(generator.targets)
  194. for target in options.targets:
  195. generator.generate_target(target)