blob: 6f77b12c061121f453e1e5a9a14b6c7c54aa5bdf [file] [log] [blame]
George Burgess IV78eb66d2019-03-11 13:53:20 -07001#!/usr/bin/env python2
2# -*- coding: utf-8 -*-
3#
4# Copyright 2019 The Chromium OS Authors. All rights reserved.
5# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8"""Runs tests for the given input files.
9
10Tries its best to autodetect all tests based on path name without being *too*
11aggressive.
12
13In short, there's a small set of directories in which, if you make any change,
14all of the tests in those directories get run. Additionally, if you change a
15python file named foo, it'll run foo_test.py or foo_unittest.py if either of
16those exist.
17
18All tests are run in parallel.
19"""
20
21# NOTE: An alternative mentioned on the initial CL for this
22# https://chromium-review.googlesource.com/c/chromiumos/third_party/toolchain-utils/+/1516414
23# is pytest. It looks like that brings some complexity (and makes use outside
24# of the chroot a bit more obnoxious?), but might be worth exploring if this
25# starts to grow quite complex on its own.
26
27from __future__ import print_function
28
29import argparse
30import collections
31import contextlib
32import multiprocessing.pool
33import os
34import pipes
35import subprocess
36import sys
37
38TestSpec = collections.namedtuple('TestSpec', ['directory', 'command'])
39
40
41def _make_relative_to_toolchain_utils(toolchain_utils, path):
42 """Cleans & makes a path relative to toolchain_utils.
43
44 Raises if that path isn't under toolchain_utils.
45 """
46 # abspath has the nice property that it removes any markers like './'.
47 as_abs = os.path.abspath(path)
48 result = os.path.relpath(as_abs, start=toolchain_utils)
49
50 if result.startswith('../'):
51 raise ValueError('Non toolchain-utils directory found: %s' % result)
52 return result
53
54
55def _gather_python_tests_in(subdir):
56 """Returns all files that appear to be Python tests in a given directory."""
57 test_files = (
58 os.path.join(subdir, file_name)
59 for file_name in os.listdir(subdir)
60 if file_name.endswith('_test.py') or file_name.endswith('_unittest.py'))
61 return [_python_test_to_spec(test_file) for test_file in test_files]
62
63
64def _run_test(test_spec):
65 """Runs a test."""
66 p = subprocess.Popen(
67 test_spec.command,
68 cwd=test_spec.directory,
69 stdin=open('/dev/null'),
70 stdout=subprocess.PIPE,
71 stderr=subprocess.STDOUT)
72 stdout, _ = p.communicate()
73 exit_code = p.wait()
74 return exit_code, stdout
75
76
77def _python_test_to_spec(test_file):
78 """Given a .py file, convert it to a TestSpec."""
79 # Run tests in the directory they exist in, since some of them are sensitive
80 # to that.
81 test_directory = os.path.dirname(os.path.abspath(test_file))
82 file_name = os.path.basename(test_file)
83
84 if os.access(test_file, os.X_OK):
85 command = ['./' + file_name]
86 else:
87 # Assume the user wanted py2.
88 command = ['python2', file_name]
89
90 return TestSpec(directory=test_directory, command=command)
91
92
93def _autodetect_python_tests_for(test_file):
94 """Given a test file, detect if there may be related tests."""
95 if not test_file.endswith('.py'):
96 return []
97
George Burgess IV367e8a92019-09-05 19:48:41 -070098 test_suffixes = ['_test.py', '_unittest.py']
99 if any(test_file.endswith(x) for x in test_suffixes):
100 test_files = [test_file]
101 else:
102 base = test_file[:-3]
103 candidates = (base + x for x in test_suffixes)
104 test_files = (x for x in candidates if os.path.exists(x))
105
106 return [_python_test_to_spec(test_file) for test_file in test_files]
George Burgess IV78eb66d2019-03-11 13:53:20 -0700107
108
109def _run_test_scripts(all_tests, show_successful_output=False):
110 """Runs a list of TestSpecs. Returns whether all of them succeeded."""
111 with contextlib.closing(multiprocessing.pool.ThreadPool()) as pool:
112 results = [pool.apply_async(_run_test, (test,)) for test in all_tests]
113
114 failures = []
115 for i, (test, future) in enumerate(zip(all_tests, results)):
116 # Add a bit more spacing between outputs.
117 if show_successful_output and i:
118 print('\n')
119
120 pretty_test = ' '.join(pipes.quote(test_arg) for test_arg in test.command)
121 pretty_directory = os.path.relpath(test.directory)
122 if pretty_directory == '.':
123 test_message = pretty_test
124 else:
125 test_message = '%s in %s/' % (pretty_test, pretty_directory)
126
127 print('## %s ... ' % test_message, end='')
128 # Be sure that the users sees which test is running.
129 sys.stdout.flush()
130
131 exit_code, stdout = future.get()
132 if not exit_code:
133 print('PASS')
134 else:
135 print('FAIL')
136 failures.append(pretty_test)
137
138 if show_successful_output or exit_code:
139 sys.stdout.write(stdout)
140
141 if failures:
142 word = 'tests' if len(failures) > 1 else 'test'
143 print('%d %s failed: %s' % (len(failures), word, failures))
144
145 return not failures
146
147
148def _compress_list(l):
149 """Removes consecutive duplicate elements from |l|.
150
151 >>> _compress_list([])
152 []
153 >>> _compress_list([1, 1])
154 [1]
155 >>> _compress_list([1, 2, 1])
156 [1, 2, 1]
157 """
158 result = []
159 for e in l:
160 if result and result[-1] == e:
161 continue
162 result.append(e)
163 return result
164
165
166def _fix_python_path(toolchain_utils):
167 pypath = os.environ.get('PYTHONPATH', '')
168 if pypath:
169 pypath = ':' + pypath
170 os.environ['PYTHONPATH'] = toolchain_utils + pypath
171
172
Tobias Bosch7f186702019-06-20 08:56:58 -0700173def _find_forced_subdir_python_tests(test_paths, toolchain_utils):
George Burgess IV78eb66d2019-03-11 13:53:20 -0700174 assert all(os.path.isabs(path) for path in test_paths)
175
176 # Directories under toolchain_utils for which any change will cause all tests
177 # in that directory to be rerun. Includes changes in subdirectories.
178 all_dirs = {
179 'crosperf',
180 'cros_utils',
181 }
182
183 relative_paths = [
184 _make_relative_to_toolchain_utils(toolchain_utils, path)
185 for path in test_paths
186 ]
187
188 gather_test_dirs = set()
189
190 for path in relative_paths:
191 top_level_dir = path.split('/')[0]
192 if top_level_dir in all_dirs:
193 gather_test_dirs.add(top_level_dir)
194
195 results = []
196 for d in sorted(gather_test_dirs):
197 results += _gather_python_tests_in(os.path.join(toolchain_utils, d))
198 return results
199
200
Tobias Bosch7f186702019-06-20 08:56:58 -0700201def _find_go_tests(test_paths):
202 """Returns TestSpecs for the go folders of the given files"""
203 assert all(os.path.isabs(path) for path in test_paths)
204
205 dirs_with_gofiles = set(
George Burgess IV367e8a92019-09-05 19:48:41 -0700206 os.path.dirname(p) for p in test_paths if p.endswith('.go'))
207 command = ['go', 'test', '-vet=all']
Tobias Bosch7f186702019-06-20 08:56:58 -0700208 # Note: We sort the directories to be deterministic.
209 return [
210 TestSpec(directory=d, command=command) for d in sorted(dirs_with_gofiles)
211 ]
212
213
George Burgess IV78eb66d2019-03-11 13:53:20 -0700214def main(argv):
215 default_toolchain_utils = os.path.abspath(os.path.dirname(__file__))
216
217 parser = argparse.ArgumentParser(description=__doc__)
218 parser.add_argument(
219 '--show_all_output',
220 action='store_true',
221 help='show stdout of successful tests')
222 parser.add_argument(
223 '--toolchain_utils',
224 default=default_toolchain_utils,
225 help='directory of toolchain-utils. Often auto-detected')
226 parser.add_argument(
227 'file', nargs='*', help='a file that we should run tests for')
228 args = parser.parse_args(argv)
229
230 modified_files = [os.path.abspath(f) for f in args.file]
231 show_all_output = args.show_all_output
232 toolchain_utils = args.toolchain_utils
233
234 if not modified_files:
235 print('No files given. Exit.')
236 return 0
237
238 _fix_python_path(toolchain_utils)
239
Tobias Bosch7f186702019-06-20 08:56:58 -0700240 tests_to_run = _find_forced_subdir_python_tests(modified_files,
241 toolchain_utils)
George Burgess IV78eb66d2019-03-11 13:53:20 -0700242 for f in modified_files:
243 tests_to_run += _autodetect_python_tests_for(f)
Tobias Bosch7f186702019-06-20 08:56:58 -0700244 tests_to_run += _find_go_tests(modified_files)
George Burgess IV78eb66d2019-03-11 13:53:20 -0700245
246 # TestSpecs have lists, so we can't use a set. We'd likely want to keep them
247 # sorted for determinism anyway.
248 tests_to_run.sort()
249 tests_to_run = _compress_list(tests_to_run)
250
251 success = _run_test_scripts(tests_to_run, show_all_output)
252 return 0 if success else 1
253
254
255if __name__ == '__main__':
256 sys.exit(main(sys.argv[1:]))