blob: cb8e64305c89012f2d9799a219882e96dda2b932 [file] [log] [blame]
Zhizhou Yang81d651f2020-02-10 16:51:20 -08001#!/usr/bin/env python3
George Burgess IV78eb66d2019-03-11 13:53:20 -07002# -*- 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,
Zhizhou Yang81d651f2020-02-10 16:51:20 -080071 stderr=subprocess.STDOUT,
72 encoding='utf-8')
George Burgess IV78eb66d2019-03-11 13:53:20 -070073 stdout, _ = p.communicate()
74 exit_code = p.wait()
75 return exit_code, stdout
76
77
78def _python_test_to_spec(test_file):
79 """Given a .py file, convert it to a TestSpec."""
80 # Run tests in the directory they exist in, since some of them are sensitive
81 # to that.
82 test_directory = os.path.dirname(os.path.abspath(test_file))
83 file_name = os.path.basename(test_file)
84
85 if os.access(test_file, os.X_OK):
86 command = ['./' + file_name]
87 else:
Zhizhou Yang81d651f2020-02-10 16:51:20 -080088 # Assume the user wanted py3.
89 command = ['python3', file_name]
George Burgess IV78eb66d2019-03-11 13:53:20 -070090
91 return TestSpec(directory=test_directory, command=command)
92
93
94def _autodetect_python_tests_for(test_file):
95 """Given a test file, detect if there may be related tests."""
96 if not test_file.endswith('.py'):
97 return []
98
George Burgess IV367e8a92019-09-05 19:48:41 -070099 test_suffixes = ['_test.py', '_unittest.py']
100 if any(test_file.endswith(x) for x in test_suffixes):
101 test_files = [test_file]
102 else:
103 base = test_file[:-3]
104 candidates = (base + x for x in test_suffixes)
105 test_files = (x for x in candidates if os.path.exists(x))
106
107 return [_python_test_to_spec(test_file) for test_file in test_files]
George Burgess IV78eb66d2019-03-11 13:53:20 -0700108
109
110def _run_test_scripts(all_tests, show_successful_output=False):
111 """Runs a list of TestSpecs. Returns whether all of them succeeded."""
112 with contextlib.closing(multiprocessing.pool.ThreadPool()) as pool:
113 results = [pool.apply_async(_run_test, (test,)) for test in all_tests]
114
115 failures = []
116 for i, (test, future) in enumerate(zip(all_tests, results)):
117 # Add a bit more spacing between outputs.
118 if show_successful_output and i:
119 print('\n')
120
121 pretty_test = ' '.join(pipes.quote(test_arg) for test_arg in test.command)
122 pretty_directory = os.path.relpath(test.directory)
123 if pretty_directory == '.':
124 test_message = pretty_test
125 else:
126 test_message = '%s in %s/' % (pretty_test, pretty_directory)
127
128 print('## %s ... ' % test_message, end='')
129 # Be sure that the users sees which test is running.
130 sys.stdout.flush()
131
132 exit_code, stdout = future.get()
133 if not exit_code:
134 print('PASS')
135 else:
136 print('FAIL')
137 failures.append(pretty_test)
138
139 if show_successful_output or exit_code:
140 sys.stdout.write(stdout)
141
142 if failures:
143 word = 'tests' if len(failures) > 1 else 'test'
144 print('%d %s failed: %s' % (len(failures), word, failures))
145
146 return not failures
147
148
149def _compress_list(l):
150 """Removes consecutive duplicate elements from |l|.
151
152 >>> _compress_list([])
153 []
154 >>> _compress_list([1, 1])
155 [1]
156 >>> _compress_list([1, 2, 1])
157 [1, 2, 1]
158 """
159 result = []
160 for e in l:
161 if result and result[-1] == e:
162 continue
163 result.append(e)
164 return result
165
166
167def _fix_python_path(toolchain_utils):
168 pypath = os.environ.get('PYTHONPATH', '')
169 if pypath:
170 pypath = ':' + pypath
171 os.environ['PYTHONPATH'] = toolchain_utils + pypath
172
173
Tobias Bosch7f186702019-06-20 08:56:58 -0700174def _find_forced_subdir_python_tests(test_paths, toolchain_utils):
George Burgess IV78eb66d2019-03-11 13:53:20 -0700175 assert all(os.path.isabs(path) for path in test_paths)
176
177 # Directories under toolchain_utils for which any change will cause all tests
178 # in that directory to be rerun. Includes changes in subdirectories.
179 all_dirs = {
180 'crosperf',
181 'cros_utils',
182 }
183
184 relative_paths = [
185 _make_relative_to_toolchain_utils(toolchain_utils, path)
186 for path in test_paths
187 ]
188
189 gather_test_dirs = set()
190
191 for path in relative_paths:
192 top_level_dir = path.split('/')[0]
193 if top_level_dir in all_dirs:
194 gather_test_dirs.add(top_level_dir)
195
196 results = []
197 for d in sorted(gather_test_dirs):
198 results += _gather_python_tests_in(os.path.join(toolchain_utils, d))
199 return results
200
201
Tobias Bosch7f186702019-06-20 08:56:58 -0700202def _find_go_tests(test_paths):
203 """Returns TestSpecs for the go folders of the given files"""
204 assert all(os.path.isabs(path) for path in test_paths)
205
206 dirs_with_gofiles = set(
George Burgess IV367e8a92019-09-05 19:48:41 -0700207 os.path.dirname(p) for p in test_paths if p.endswith('.go'))
208 command = ['go', 'test', '-vet=all']
Tobias Bosch7f186702019-06-20 08:56:58 -0700209 # Note: We sort the directories to be deterministic.
210 return [
211 TestSpec(directory=d, command=command) for d in sorted(dirs_with_gofiles)
212 ]
213
214
George Burgess IV78eb66d2019-03-11 13:53:20 -0700215def main(argv):
216 default_toolchain_utils = os.path.abspath(os.path.dirname(__file__))
217
218 parser = argparse.ArgumentParser(description=__doc__)
219 parser.add_argument(
220 '--show_all_output',
221 action='store_true',
222 help='show stdout of successful tests')
223 parser.add_argument(
224 '--toolchain_utils',
225 default=default_toolchain_utils,
226 help='directory of toolchain-utils. Often auto-detected')
227 parser.add_argument(
228 'file', nargs='*', help='a file that we should run tests for')
229 args = parser.parse_args(argv)
230
231 modified_files = [os.path.abspath(f) for f in args.file]
232 show_all_output = args.show_all_output
233 toolchain_utils = args.toolchain_utils
234
235 if not modified_files:
236 print('No files given. Exit.')
237 return 0
238
239 _fix_python_path(toolchain_utils)
240
Tobias Bosch7f186702019-06-20 08:56:58 -0700241 tests_to_run = _find_forced_subdir_python_tests(modified_files,
242 toolchain_utils)
George Burgess IV78eb66d2019-03-11 13:53:20 -0700243 for f in modified_files:
244 tests_to_run += _autodetect_python_tests_for(f)
Tobias Bosch7f186702019-06-20 08:56:58 -0700245 tests_to_run += _find_go_tests(modified_files)
George Burgess IV78eb66d2019-03-11 13:53:20 -0700246
247 # TestSpecs have lists, so we can't use a set. We'd likely want to keep them
248 # sorted for determinism anyway.
249 tests_to_run.sort()
250 tests_to_run = _compress_list(tests_to_run)
251
252 success = _run_test_scripts(tests_to_run, show_all_output)
253 return 0 if success else 1
254
255
256if __name__ == '__main__':
257 sys.exit(main(sys.argv[1:]))