test_config_script.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #!/usr/bin/env python3
  2. """Test helper for the Mbed TLS configuration file tool
  3. Run config.py with various parameters and write the results to files.
  4. This is a harness to help regression testing, not a functional tester.
  5. Sample usage:
  6. test_config_script.py -d old
  7. ## Modify config.py and/or config.h ##
  8. test_config_script.py -d new
  9. diff -ru old new
  10. """
  11. ## Copyright The Mbed TLS Contributors
  12. ## SPDX-License-Identifier: Apache-2.0
  13. ##
  14. ## Licensed under the Apache License, Version 2.0 (the "License"); you may
  15. ## not use this file except in compliance with the License.
  16. ## You may obtain a copy of the License at
  17. ##
  18. ## http://www.apache.org/licenses/LICENSE-2.0
  19. ##
  20. ## Unless required by applicable law or agreed to in writing, software
  21. ## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  22. ## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. ## See the License for the specific language governing permissions and
  24. ## limitations under the License.
  25. import argparse
  26. import glob
  27. import os
  28. import re
  29. import shutil
  30. import subprocess
  31. OUTPUT_FILE_PREFIX = 'config-'
  32. def output_file_name(directory, stem, extension):
  33. return os.path.join(directory,
  34. '{}{}.{}'.format(OUTPUT_FILE_PREFIX,
  35. stem, extension))
  36. def cleanup_directory(directory):
  37. """Remove old output files."""
  38. for extension in []:
  39. pattern = output_file_name(directory, '*', extension)
  40. filenames = glob.glob(pattern)
  41. for filename in filenames:
  42. os.remove(filename)
  43. def prepare_directory(directory):
  44. """Create the output directory if it doesn't exist yet.
  45. If there are old output files, remove them.
  46. """
  47. if os.path.exists(directory):
  48. cleanup_directory(directory)
  49. else:
  50. os.makedirs(directory)
  51. def guess_presets_from_help(help_text):
  52. """Figure out what presets the script supports.
  53. help_text should be the output from running the script with --help.
  54. """
  55. # Try the output format from config.py
  56. hits = re.findall(r'\{([-\w,]+)\}', help_text)
  57. for hit in hits:
  58. words = set(hit.split(','))
  59. if 'get' in words and 'set' in words and 'unset' in words:
  60. words.remove('get')
  61. words.remove('set')
  62. words.remove('unset')
  63. return words
  64. # Try the output format from config.pl
  65. hits = re.findall(r'\n +([-\w]+) +- ', help_text)
  66. if hits:
  67. return hits
  68. raise Exception("Unable to figure out supported presets. Pass the '-p' option.")
  69. def list_presets(options):
  70. """Return the list of presets to test.
  71. The list is taken from the command line if present, otherwise it is
  72. extracted from running the config script with --help.
  73. """
  74. if options.presets:
  75. return re.split(r'[ ,]+', options.presets)
  76. else:
  77. help_text = subprocess.run([options.script, '--help'],
  78. check=False, # config.pl --help returns 255
  79. stdout=subprocess.PIPE,
  80. stderr=subprocess.STDOUT).stdout
  81. return guess_presets_from_help(help_text.decode('ascii'))
  82. def run_one(options, args, stem_prefix='', input_file=None):
  83. """Run the config script with the given arguments.
  84. Take the original content from input_file if specified, defaulting
  85. to options.input_file if input_file is None.
  86. Write the following files, where xxx contains stem_prefix followed by
  87. a filename-friendly encoding of args:
  88. * config-xxx.h: modified file.
  89. * config-xxx.out: standard output.
  90. * config-xxx.err: standard output.
  91. * config-xxx.status: exit code.
  92. Return ("xxx+", "path/to/config-xxx.h") which can be used as
  93. stem_prefix and input_file to call this function again with new args.
  94. """
  95. if input_file is None:
  96. input_file = options.input_file
  97. stem = stem_prefix + '-'.join(args)
  98. data_filename = output_file_name(options.output_directory, stem, 'h')
  99. stdout_filename = output_file_name(options.output_directory, stem, 'out')
  100. stderr_filename = output_file_name(options.output_directory, stem, 'err')
  101. status_filename = output_file_name(options.output_directory, stem, 'status')
  102. shutil.copy(input_file, data_filename)
  103. # Pass only the file basename, not the full path, to avoid getting the
  104. # directory name in error messages, which would make comparisons
  105. # between output directories more difficult.
  106. cmd = [os.path.abspath(options.script),
  107. '-f', os.path.basename(data_filename)]
  108. with open(stdout_filename, 'wb') as out:
  109. with open(stderr_filename, 'wb') as err:
  110. status = subprocess.call(cmd + args,
  111. cwd=options.output_directory,
  112. stdin=subprocess.DEVNULL,
  113. stdout=out, stderr=err)
  114. with open(status_filename, 'w') as status_file:
  115. status_file.write('{}\n'.format(status))
  116. return stem + "+", data_filename
  117. ### A list of symbols to test with.
  118. ### This script currently tests what happens when you change a symbol from
  119. ### having a value to not having a value or vice versa. This is not
  120. ### necessarily useful behavior, and we may not consider it a bug if
  121. ### config.py stops handling that case correctly.
  122. TEST_SYMBOLS = [
  123. 'CUSTOM_SYMBOL', # does not exist
  124. 'MBEDTLS_AES_C', # set, no value
  125. 'MBEDTLS_MPI_MAX_SIZE', # unset, has a value
  126. 'MBEDTLS_NO_UDBL_DIVISION', # unset, in "System support"
  127. 'MBEDTLS_PLATFORM_ZEROIZE_ALT', # unset, in "Customisation configuration options"
  128. ]
  129. def run_all(options):
  130. """Run all the command lines to test."""
  131. presets = list_presets(options)
  132. for preset in presets:
  133. run_one(options, [preset])
  134. for symbol in TEST_SYMBOLS:
  135. run_one(options, ['get', symbol])
  136. (stem, filename) = run_one(options, ['set', symbol])
  137. run_one(options, ['get', symbol], stem_prefix=stem, input_file=filename)
  138. run_one(options, ['--force', 'set', symbol])
  139. (stem, filename) = run_one(options, ['set', symbol, 'value'])
  140. run_one(options, ['get', symbol], stem_prefix=stem, input_file=filename)
  141. run_one(options, ['--force', 'set', symbol, 'value'])
  142. run_one(options, ['unset', symbol])
  143. def main():
  144. """Command line entry point."""
  145. parser = argparse.ArgumentParser(description=__doc__,
  146. formatter_class=argparse.RawDescriptionHelpFormatter)
  147. parser.add_argument('-d', metavar='DIR',
  148. dest='output_directory', required=True,
  149. help="""Output directory.""")
  150. parser.add_argument('-f', metavar='FILE',
  151. dest='input_file', default='include/mbedtls/config.h',
  152. help="""Config file (default: %(default)s).""")
  153. parser.add_argument('-p', metavar='PRESET,...',
  154. dest='presets',
  155. help="""Presets to test (default: guessed from --help).""")
  156. parser.add_argument('-s', metavar='FILE',
  157. dest='script', default='scripts/config.py',
  158. help="""Configuration script (default: %(default)s).""")
  159. options = parser.parse_args()
  160. prepare_directory(options.output_directory)
  161. run_all(options)
  162. if __name__ == '__main__':
  163. main()