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