1 """Library for constructing an Mbed TLS test case.
4 # Copyright The Mbed TLS Contributors
5 # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
11 from typing import Iterable, List, Optional
13 from . import typing_util
15 def hex_string(data: bytes) -> str:
16 return '"' + binascii.hexlify(data).decode('ascii') + '"'
19 class MissingDescription(Exception):
22 class MissingFunction(Exception):
26 """An Mbed TLS test case."""
28 def __init__(self, description: Optional[str] = None):
29 self.comments = [] #type: List[str]
30 self.description = description #type: Optional[str]
31 self.dependencies = [] #type: List[str]
32 self.function = None #type: Optional[str]
33 self.arguments = [] #type: List[str]
35 def add_comment(self, *lines: str) -> None:
36 self.comments += lines
38 def set_description(self, description: str) -> None:
39 self.description = description
41 def set_dependencies(self, dependencies: List[str]) -> None:
42 self.dependencies = dependencies
44 def set_function(self, function: str) -> None:
45 self.function = function
47 def set_arguments(self, arguments: List[str]) -> None:
48 self.arguments = arguments
50 def check_completeness(self) -> None:
51 if self.description is None:
52 raise MissingDescription
53 if self.function is None:
56 def write(self, out: typing_util.Writable) -> None:
57 """Write the .data file paragraph for this test case.
59 The output starts and ends with a single newline character. If the
60 surrounding code writes lines (consisting of non-newline characters
61 and a final newline), you will end up with a blank line before, but
62 not after the test case.
64 self.check_completeness()
65 assert self.description is not None # guide mypy
66 assert self.function is not None # guide mypy
68 for line in self.comments:
69 out.write('# ' + line + '\n')
70 out.write(self.description + '\n')
72 out.write('depends_on:' + ':'.join(self.dependencies) + '\n')
73 out.write(self.function + ':' + ':'.join(self.arguments) + '\n')
75 def write_data_file(filename: str,
76 test_cases: Iterable[TestCase],
77 caller: Optional[str] = None) -> None:
78 """Write the test cases to the specified file.
80 If the file already exists, it is overwritten.
83 caller = os.path.basename(sys.argv[0])
84 tempfile = filename + '.new'
85 with open(tempfile, 'w') as out:
86 out.write('# Automatically generated by {}. Do not edit!\n'
90 out.write('\n# End of automatically generated file.\n')
91 os.replace(tempfile, filename)