Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Avi Drissman | 7601e4b | 2022-09-15 20:11:09 | [diff] [blame] | 2 | # Copyright 2020 The Chromium Authors |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | """Builds and runs a test by filename. |
| 6 | |
Edman Anjos | af38a3e | 2023-06-06 21:16:49 | [diff] [blame] | 7 | This script finds the appropriate test suites for the specified test files or |
| 8 | directories, builds it, then runs it with the (optionally) specified filter, |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 9 | passing any extra args on to the test runner. |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 10 | |
| 11 | Examples: |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 12 | # Run the test target for bit_cast_unittest.cc. Use a custom test filter instead |
| 13 | # of the automatically generated one. |
| 14 | autotest.py -C out/Desktop bit_cast_unittest.cc --gtest_filter=BitCastTest* |
| 15 | |
| 16 | # Find and run UrlUtilitiesUnitTest.java's tests, pass remaining parameters to |
| 17 | # the test binary. |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 18 | autotest.py -C out/Android UrlUtilitiesUnitTest --fast-local-dev -v |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 19 | |
Edman Anjos | af38a3e | 2023-06-06 21:16:49 | [diff] [blame] | 20 | # Run all tests under base/strings. |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 21 | autotest.py -C out/foo --run-all base/strings |
| 22 | |
Edman Anjos | af38a3e | 2023-06-06 21:16:49 | [diff] [blame] | 23 | # Run tests in multiple files or directories. |
| 24 | autotest.py -C out/foo base/strings base/pickle_unittest.cc |
| 25 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 26 | # Run only the test on line 11. Useful when running autotest.py from your text |
| 27 | # editor. |
| 28 | autotest.py -C out/foo --line 11 base/strings/strcat_unittest.cc |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 29 | """ |
| 30 | |
| 31 | import argparse |
Erik Staab | 473a9d6 | 2024-08-26 19:23:11 | [diff] [blame] | 32 | import json |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 33 | import locale |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 34 | import os |
| 35 | import re |
Andrew Grieve | 5c59eaf | 2023-07-10 19:06:42 | [diff] [blame] | 36 | import shlex |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 37 | import subprocess |
| 38 | import sys |
| 39 | |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 40 | from enum import Enum |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 41 | from pathlib import Path |
| 42 | |
Erik Staab | 473a9d6 | 2024-08-26 19:23:11 | [diff] [blame] | 43 | # Don't write pyc files to the src tree, which show up in version control |
| 44 | # in some environments. |
| 45 | sys.dont_write_bytecode = True |
| 46 | |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 47 | USE_PYTHON_3 = f'This script will only run under python3.' |
| 48 | |
| 49 | SRC_DIR = Path(__file__).parent.parent.resolve() |
Andrew Grieve | 5c59eaf | 2023-07-10 19:06:42 | [diff] [blame] | 50 | sys.path.append(str(SRC_DIR / 'build')) |
| 51 | import gn_helpers |
| 52 | |
Peter Wen | f3df5de | 2021-03-11 18:12:22 | [diff] [blame] | 53 | sys.path.append(str(SRC_DIR / 'build' / 'android')) |
| 54 | from pylib import constants |
| 55 | |
| 56 | DEPOT_TOOLS_DIR = SRC_DIR / 'third_party' / 'depot_tools' |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 57 | DEBUG = False |
| 58 | |
Michael Thiessen | 772fb80 | 2020-03-31 17:29:38 | [diff] [blame] | 59 | # Some test suites use suffixes that would also match non-test-suite targets. |
| 60 | # Those test suites should be manually added here. |
Andrew Grieve | 714cbd8 | 2023-07-06 21:43:20 | [diff] [blame] | 61 | _TEST_TARGET_ALLOWLIST = [ |
Edman Anjos | 1e4c9ca | 2023-02-28 17:25:16 | [diff] [blame] | 62 | # Running ash_pixeltests requires the --no-try-android-wrappers flag. |
| 63 | '//ash:ash_pixeltests', |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 64 | '//chrome/test:browser_tests', |
William Liu | 2537099 | 2023-01-05 19:59:30 | [diff] [blame] | 65 | '//chrome/test:interactive_ui_tests', |
Michael Thiessen | 772fb80 | 2020-03-31 17:29:38 | [diff] [blame] | 66 | '//chrome/test:unit_tests', |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 67 | ] |
| 68 | |
Dan Harrington | 75aa826 | 2024-01-24 16:43:47 | [diff] [blame] | 69 | _TEST_TARGET_REGEX = re.compile( |
| 70 | r'(_browsertests|_perftests|_wpr_tests|_unittests)$') |
Andrew Grieve | 0973e6f | 2021-02-10 16:22:29 | [diff] [blame] | 71 | |
Edman Anjos | a2a5572 | 2024-02-01 18:08:18 | [diff] [blame] | 72 | _PREF_MAPPING_FILE_PATTERN = re.escape( |
| 73 | str(Path('components') / 'policy' / 'test' / 'data' / 'pref_mapping') + |
| 74 | r'/') + r'.*\.json' |
| 75 | |
Edman Anjos | 12859c5 | 2025-03-14 14:38:27 | [diff] [blame] | 76 | TEST_FILE_NAME_REGEX = re.compile( |
| 77 | r'(.*Test\.java)' + |
| 78 | r'|(.*_[a-z]*test(?:_win|_mac|_linux|_chromeos|_android)?\.cc)' + r'|(' + |
| 79 | _PREF_MAPPING_FILE_PATTERN + r')') |
Mario Bianucci | 2b0725e | 2020-11-04 17:19:00 | [diff] [blame] | 80 | |
| 81 | # Some tests don't directly include gtest.h and instead include it via gmock.h |
| 82 | # or a test_utils.h file, so make sure these cases are captured. Also include |
| 83 | # files that use <...> for #includes instead of quotes. |
Tushar Agarwal | 165b325 | 2022-05-20 15:03:11 | [diff] [blame] | 84 | GTEST_INCLUDE_REGEX = re.compile( |
| 85 | r'#include.*(gtest|gmock|_test_utils|browser_test)\.h("|>)') |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 86 | |
| 87 | |
| 88 | def ExitWithMessage(*args): |
| 89 | print(*args, file=sys.stderr) |
| 90 | sys.exit(1) |
| 91 | |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 92 | |
| 93 | class TestValidity(Enum): |
| 94 | NOT_A_TEST = 0 # Does not match test file regex. |
| 95 | MAYBE_A_TEST = 1 # Matches test file regex, but doesn't include gtest files. |
| 96 | VALID_TEST = 2 # Matches test file regex and includes gtest files. |
| 97 | |
| 98 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 99 | def IsTestFile(file_path): |
| 100 | if not TEST_FILE_NAME_REGEX.match(file_path): |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 101 | return TestValidity.NOT_A_TEST |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 102 | if file_path.endswith('.cc'): |
| 103 | # Try a bit harder to remove non-test files for c++. Without this, |
| 104 | # 'autotest.py base/' finds non-test files. |
| 105 | try: |
Mario Bianucci | 2b0725e | 2020-11-04 17:19:00 | [diff] [blame] | 106 | with open(file_path, 'r', encoding='utf-8') as f: |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 107 | if GTEST_INCLUDE_REGEX.search(f.read()) is not None: |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 108 | return TestValidity.VALID_TEST |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 109 | except IOError: |
| 110 | pass |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 111 | # It may still be a test file, even if it doesn't include a gtest file. |
| 112 | return TestValidity.MAYBE_A_TEST |
| 113 | return TestValidity.VALID_TEST |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 114 | |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 115 | |
| 116 | class CommandError(Exception): |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 117 | """Exception thrown when a subcommand fails.""" |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 118 | |
| 119 | def __init__(self, command, return_code, output=None): |
| 120 | Exception.__init__(self) |
| 121 | self.command = command |
| 122 | self.return_code = return_code |
| 123 | self.output = output |
| 124 | |
| 125 | def __str__(self): |
| 126 | message = (f'\n***\nERROR: Error while running command {self.command}' |
| 127 | f'.\nExit status: {self.return_code}\n') |
| 128 | if self.output: |
| 129 | message += f'Output:\n{self.output}\n' |
| 130 | message += '***' |
| 131 | return message |
| 132 | |
| 133 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 134 | def StreamCommandOrExit(cmd, **kwargs): |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 135 | try: |
| 136 | subprocess.check_call(cmd, **kwargs) |
| 137 | except subprocess.CalledProcessError as e: |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 138 | sys.exit(1) |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 139 | |
| 140 | |
| 141 | def RunCommand(cmd, **kwargs): |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 142 | try: |
| 143 | # Set an encoding to convert the binary output to a string. |
| 144 | return subprocess.check_output( |
| 145 | cmd, **kwargs, encoding=locale.getpreferredencoding()) |
| 146 | except subprocess.CalledProcessError as e: |
| 147 | raise CommandError(e.cmd, e.returncode, e.output) from None |
| 148 | |
| 149 | |
Andrew Grieve | 5c59eaf | 2023-07-10 19:06:42 | [diff] [blame] | 150 | def BuildTestTargets(out_dir, targets, dry_run): |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 151 | """Builds the specified targets with ninja""" |
Andrew Grieve | 5c59eaf | 2023-07-10 19:06:42 | [diff] [blame] | 152 | cmd = gn_helpers.CreateBuildCommand(out_dir) + targets |
| 153 | print('Building: ' + shlex.join(cmd)) |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 154 | if (dry_run): |
Michael Thiessen | 3a9ba6e | 2020-11-30 18:05:32 | [diff] [blame] | 155 | return True |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 156 | try: |
| 157 | subprocess.check_call(cmd) |
| 158 | except subprocess.CalledProcessError as e: |
| 159 | return False |
| 160 | return True |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 161 | |
| 162 | |
| 163 | def RecursiveMatchFilename(folder, filename): |
| 164 | current_dir = os.path.split(folder)[-1] |
| 165 | if current_dir.startswith('out') or current_dir.startswith('.'): |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 166 | return [[], []] |
| 167 | exact = [] |
| 168 | close = [] |
Gary Tong | 2333f94 | 2025-03-06 16:17:17 | [diff] [blame] | 169 | try: |
| 170 | with os.scandir(folder) as it: |
| 171 | for entry in it: |
| 172 | if (entry.is_symlink()): |
| 173 | continue |
| 174 | if (entry.is_file() and filename in entry.path and |
| 175 | not os.path.basename(entry.path).startswith('.')): |
| 176 | file_validity = IsTestFile(entry.path) |
| 177 | if file_validity is TestValidity.VALID_TEST: |
| 178 | exact.append(entry.path) |
| 179 | elif file_validity is TestValidity.MAYBE_A_TEST: |
| 180 | close.append(entry.path) |
| 181 | if entry.is_dir(): |
| 182 | # On Windows, junctions are like a symlink that python interprets as a |
| 183 | # directory, leading to exceptions being thrown. We can just catch and |
| 184 | # ignore these exceptions like we would ignore symlinks. |
| 185 | try: |
| 186 | matches = RecursiveMatchFilename(entry.path, filename) |
| 187 | exact += matches[0] |
| 188 | close += matches[1] |
| 189 | except FileNotFoundError as e: |
| 190 | if DEBUG: |
| 191 | print(f'Failed to scan directory "{entry}" - junction?') |
| 192 | pass |
| 193 | except PermissionError: |
| 194 | print(f'Permission error while scanning {folder}') |
| 195 | |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 196 | return [exact, close] |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 197 | |
| 198 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 199 | def FindTestFilesInDirectory(directory): |
| 200 | test_files = [] |
Mario Bianucci | 2b0725e | 2020-11-04 17:19:00 | [diff] [blame] | 201 | if DEBUG: |
| 202 | print('Test files:') |
Peter Wen | f3df5de | 2021-03-11 18:12:22 | [diff] [blame] | 203 | for root, _, files in os.walk(directory): |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 204 | for f in files: |
| 205 | path = os.path.join(root, f) |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 206 | file_validity = IsTestFile(path) |
| 207 | if file_validity is TestValidity.VALID_TEST: |
Mario Bianucci | 2b0725e | 2020-11-04 17:19:00 | [diff] [blame] | 208 | if DEBUG: |
| 209 | print(path) |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 210 | test_files.append(path) |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 211 | elif DEBUG and file_validity is TestValidity.MAYBE_A_TEST: |
| 212 | print(path + ' matched but doesn\'t include gtest files, skipping.') |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 213 | return test_files |
| 214 | |
| 215 | |
| 216 | def FindMatchingTestFiles(target): |
| 217 | # Return early if there's an exact file match. |
| 218 | if os.path.isfile(target): |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 219 | # If the target is a C++ implementation file, try to guess the test file. |
| 220 | if target.endswith('.cc') or target.endswith('.h'): |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 221 | target_validity = IsTestFile(target) |
| 222 | if target_validity is TestValidity.VALID_TEST: |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 223 | return [target] |
| 224 | alternate = f"{target.rsplit('.', 1)[0]}_unittest.cc" |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 225 | alt_validity = TestValidity.NOT_A_TEST if not os.path.isfile( |
| 226 | alternate) else IsTestFile(alternate) |
| 227 | if alt_validity is TestValidity.VALID_TEST: |
| 228 | return [alternate] |
| 229 | |
| 230 | # If neither the target nor its alternative were valid, check if they just |
| 231 | # didn't include the gtest files before deciding to exit. |
| 232 | if target_validity is TestValidity.MAYBE_A_TEST: |
| 233 | return [target] |
| 234 | if alt_validity is TestValidity.MAYBE_A_TEST: |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 235 | return [alternate] |
| 236 | ExitWithMessage(f"{target} doesn't look like a test file") |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 237 | return [target] |
| 238 | # If this is a directory, return all the test files it contains. |
| 239 | if os.path.isdir(target): |
| 240 | files = FindTestFilesInDirectory(target) |
| 241 | if not files: |
| 242 | ExitWithMessage('No tests found in directory') |
| 243 | return files |
| 244 | |
Jesse McKenna | 08e0848 | 2020-05-07 18:25:38 | [diff] [blame] | 245 | if sys.platform.startswith('win32') and os.path.altsep in target: |
| 246 | # Use backslash as the path separator on Windows to match os.scandir(). |
| 247 | if DEBUG: |
| 248 | print('Replacing ' + os.path.altsep + ' with ' + os.path.sep + ' in: ' |
| 249 | + target) |
| 250 | target = target.replace(os.path.altsep, os.path.sep) |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 251 | if DEBUG: |
| 252 | print('Finding files with full path containing: ' + target) |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 253 | |
| 254 | [exact, close] = RecursiveMatchFilename(SRC_DIR, target) |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 255 | if DEBUG: |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 256 | if exact: |
| 257 | print('Found exact matching file(s):') |
| 258 | print('\n'.join(exact)) |
| 259 | if close: |
| 260 | print('Found possible matching file(s):') |
| 261 | print('\n'.join(close)) |
| 262 | |
Andrew Grieve | 85b22a7 | 2023-09-06 14:36:10 | [diff] [blame] | 263 | if len(exact) >= 1: |
| 264 | # Given "Foo", don't ask to disambiguate ModFoo.java vs Foo.java. |
| 265 | more_exact = [ |
| 266 | p for p in exact if os.path.basename(p) in (target, f'{target}.java') |
| 267 | ] |
| 268 | if len(more_exact) == 1: |
| 269 | test_files = more_exact |
| 270 | else: |
| 271 | test_files = exact |
| 272 | else: |
| 273 | test_files = close |
| 274 | |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 275 | if len(test_files) > 1: |
Andrew Grieve | 0fd579d | 2023-03-27 21:09:20 | [diff] [blame] | 276 | if len(test_files) < 10: |
| 277 | test_files = [HaveUserPickFile(test_files)] |
| 278 | else: |
| 279 | # Arbitrarily capping at 10 results so we don't print the name of every |
| 280 | # file in the repo if the target is poorly specified. |
| 281 | test_files = test_files[:10] |
| 282 | ExitWithMessage(f'Target "{target}" is ambiguous. Matching files: ' |
| 283 | f'{test_files}') |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 284 | if not test_files: |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 285 | ExitWithMessage(f'Target "{target}" did not match any files.') |
Mario Bianucci | e4cd3e2 | 2020-12-02 01:33:39 | [diff] [blame] | 286 | return test_files |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 287 | |
| 288 | |
Andrew Grieve | 0fd579d | 2023-03-27 21:09:20 | [diff] [blame] | 289 | def HaveUserPickFile(paths): |
| 290 | paths = sorted(paths, key=lambda p: (len(p), p)) |
| 291 | path_list = '\n'.join(f'{i}. {t}' for i, t in enumerate(paths)) |
| 292 | |
| 293 | while True: |
| 294 | user_input = input(f'Please choose the path you mean.\n{path_list}\n') |
| 295 | try: |
| 296 | value = int(user_input) |
| 297 | return paths[value] |
| 298 | except (ValueError, IndexError): |
| 299 | print('Try again') |
| 300 | |
| 301 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 302 | def HaveUserPickTarget(paths, targets): |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 303 | # Cap to 10 targets for convenience [0-9]. |
| 304 | targets = targets[:10] |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 305 | target_list = '\n'.join(f'{i}. {t}' for i, t in enumerate(targets)) |
| 306 | |
| 307 | user_input = input(f'Target "{paths}" is used by multiple test targets.\n' + |
Svend Larsen | 275cd15 | 2024-12-20 15:35:08 | [diff] [blame] | 308 | target_list + '\nPlease pick a target by its numeric index' |
| 309 | 'listed below: ') |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 310 | try: |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 311 | value = int(user_input) |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 312 | return targets[value] |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 313 | except (ValueError, IndexError): |
Svend Larsen | 275cd15 | 2024-12-20 15:35:08 | [diff] [blame] | 314 | print('Value entered was not a numeric index listed above. Trying again.') |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 315 | return HaveUserPickTarget(paths, targets) |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 316 | |
| 317 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 318 | # A persistent cache to avoid running gn on repeated runs of autotest. |
| 319 | class TargetCache: |
| 320 | def __init__(self, out_dir): |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 321 | self.out_dir = out_dir |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 322 | self.path = os.path.join(out_dir, 'autotest_cache') |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 323 | self.gold_mtime = self.GetBuildNinjaMtime() |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 324 | self.cache = {} |
| 325 | try: |
| 326 | mtime, cache = json.load(open(self.path, 'r')) |
| 327 | if mtime == self.gold_mtime: |
| 328 | self.cache = cache |
| 329 | except Exception: |
| 330 | pass |
| 331 | |
| 332 | def Save(self): |
| 333 | with open(self.path, 'w') as f: |
| 334 | json.dump([self.gold_mtime, self.cache], f) |
| 335 | |
| 336 | def Find(self, test_paths): |
| 337 | key = ' '.join(test_paths) |
| 338 | return self.cache.get(key, None) |
| 339 | |
| 340 | def Store(self, test_paths, test_targets): |
| 341 | key = ' '.join(test_paths) |
| 342 | self.cache[key] = test_targets |
| 343 | |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 344 | def GetBuildNinjaMtime(self): |
| 345 | return os.path.getmtime(os.path.join(self.out_dir, 'build.ninja')) |
| 346 | |
| 347 | def IsStillValid(self): |
| 348 | return self.GetBuildNinjaMtime() == self.gold_mtime |
| 349 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 350 | |
Andrew Grieve | 714cbd8 | 2023-07-06 21:43:20 | [diff] [blame] | 351 | def _TestTargetsFromGnRefs(targets): |
| 352 | # First apply allowlists: |
| 353 | ret = [t for t in targets if '__' not in t] |
| 354 | ret = [ |
| 355 | t for t in ret |
| 356 | if _TEST_TARGET_REGEX.search(t) or t in _TEST_TARGET_ALLOWLIST |
| 357 | ] |
| 358 | if ret: |
| 359 | return ret |
| 360 | |
| 361 | _SUBTARGET_SUFFIXES = ( |
| 362 | '__java_binary', # robolectric_binary() |
| 363 | '__test_runner_script', # test() targets |
| 364 | '__test_apk', # instrumentation_test_apk() targets |
| 365 | ) |
| 366 | ret = [] |
| 367 | for suffix in _SUBTARGET_SUFFIXES: |
| 368 | ret.extend(t[:-len(suffix)] for t in targets if t.endswith(suffix)) |
| 369 | |
| 370 | return ret |
| 371 | |
| 372 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 373 | def FindTestTargets(target_cache, out_dir, paths, run_all): |
| 374 | # Normalize paths, so they can be cached. |
| 375 | paths = [os.path.realpath(p) for p in paths] |
| 376 | test_targets = target_cache.Find(paths) |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 377 | used_cache = True |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 378 | if not test_targets: |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 379 | used_cache = False |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 380 | |
| 381 | # Use gn refs to recursively find all targets that depend on |path|, filter |
| 382 | # internal gn targets, and match against well-known test suffixes, falling |
| 383 | # back to a list of known test targets if that fails. |
Henrique Nakashima | 9378d40 | 2025-05-01 19:26:34 | [diff] [blame] | 384 | gn_path = os.path.join(DEPOT_TOOLS_DIR, 'gn.py') |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 385 | |
Henrique Nakashima | 9378d40 | 2025-05-01 19:26:34 | [diff] [blame] | 386 | cmd = [sys.executable, gn_path, 'refs', out_dir, '--all'] + paths |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 387 | targets = RunCommand(cmd).splitlines() |
Andrew Grieve | 714cbd8 | 2023-07-06 21:43:20 | [diff] [blame] | 388 | test_targets = _TestTargetsFromGnRefs(targets) |
| 389 | |
| 390 | # If not targets were identified as tests by looking at their names, ask GN |
| 391 | # if any are executables. |
| 392 | if not test_targets and targets: |
| 393 | test_targets = RunCommand(cmd + ['--type=executable']).splitlines() |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 394 | |
| 395 | if not test_targets: |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 396 | ExitWithMessage( |
Andrew Grieve | 714cbd8 | 2023-07-06 21:43:20 | [diff] [blame] | 397 | f'"{paths}" did not match any test targets. Consider adding' |
| 398 | f' one of the following targets to _TEST_TARGET_ALLOWLIST within ' |
| 399 | f'{__file__}: \n' + '\n'.join(targets)) |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 400 | |
Andrew Grieve | 99f0a64 | 2023-09-13 16:26:02 | [diff] [blame] | 401 | test_targets.sort() |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 402 | target_cache.Store(paths, test_targets) |
| 403 | target_cache.Save() |
| 404 | |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 405 | if len(test_targets) > 1: |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 406 | if run_all: |
| 407 | print(f'Warning, found {len(test_targets)} test targets.', |
| 408 | file=sys.stderr) |
| 409 | if len(test_targets) > 10: |
| 410 | ExitWithMessage('Your query likely involves non-test sources.') |
| 411 | print('Trying to run all of them!', file=sys.stderr) |
| 412 | else: |
| 413 | test_targets = [HaveUserPickTarget(paths, test_targets)] |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 414 | |
Andrew Grieve | 99f0a64 | 2023-09-13 16:26:02 | [diff] [blame] | 415 | # Remove the // prefix to turn GN label into ninja target. |
| 416 | test_targets = [t[2:] for t in test_targets] |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 417 | |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 418 | return (test_targets, used_cache) |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 419 | |
| 420 | |
Edman Anjos | a2a5572 | 2024-02-01 18:08:18 | [diff] [blame] | 421 | def RunTestTargets(out_dir, targets, gtest_filter, pref_mapping_filter, |
| 422 | extra_args, dry_run, no_try_android_wrappers, |
| 423 | no_fast_local_dev): |
Olivier Li | 2a89d35 | 2021-05-05 15:26:54 | [diff] [blame] | 424 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 425 | for target in targets: |
Andrew Grieve | 99f0a64 | 2023-09-13 16:26:02 | [diff] [blame] | 426 | target_binary = target.split(':')[1] |
Olivier Li | 2a89d35 | 2021-05-05 15:26:54 | [diff] [blame] | 427 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 428 | # Look for the Android wrapper script first. |
Andrew Grieve | 99f0a64 | 2023-09-13 16:26:02 | [diff] [blame] | 429 | path = os.path.join(out_dir, 'bin', f'run_{target_binary}') |
Olivier Li | 2a89d35 | 2021-05-05 15:26:54 | [diff] [blame] | 430 | if no_try_android_wrappers or not os.path.isfile(path): |
| 431 | # If the wrapper is not found or disabled use the Desktop target |
| 432 | # which is an executable. |
Andrew Grieve | 99f0a64 | 2023-09-13 16:26:02 | [diff] [blame] | 433 | path = os.path.join(out_dir, target_binary) |
Andrew Grieve | 5d6db89 | 2022-02-23 16:06:06 | [diff] [blame] | 434 | elif not no_fast_local_dev: |
| 435 | # Usually want this flag when developing locally. |
| 436 | extra_args = extra_args + ['--fast-local-dev'] |
Olivier Li | 2a89d35 | 2021-05-05 15:26:54 | [diff] [blame] | 437 | |
Edman Anjos | a2a5572 | 2024-02-01 18:08:18 | [diff] [blame] | 438 | cmd = [path, f'--gtest_filter={gtest_filter}'] |
| 439 | if pref_mapping_filter: |
| 440 | cmd.append(f'--test_policy_to_pref_mappings_filter={pref_mapping_filter}') |
| 441 | cmd.extend(extra_args) |
| 442 | |
Andrew Grieve | 5c59eaf | 2023-07-10 19:06:42 | [diff] [blame] | 443 | print('Running test: ' + shlex.join(cmd)) |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 444 | if not dry_run: |
| 445 | StreamCommandOrExit(cmd) |
| 446 | |
| 447 | |
| 448 | def BuildCppTestFilter(filenames, line): |
Mario Bianucci | 2b0725e | 2020-11-04 17:19:00 | [diff] [blame] | 449 | make_filter_command = [ |
Roman Sorokin | 25b3476 | 2022-02-02 16:31:27 | [diff] [blame] | 450 | sys.executable, SRC_DIR / 'tools' / 'make_gtest_filter.py' |
Mario Bianucci | 2b0725e | 2020-11-04 17:19:00 | [diff] [blame] | 451 | ] |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 452 | if line: |
| 453 | make_filter_command += ['--line', str(line)] |
| 454 | else: |
| 455 | make_filter_command += ['--class-only'] |
| 456 | make_filter_command += filenames |
| 457 | return RunCommand(make_filter_command).strip() |
| 458 | |
| 459 | |
| 460 | def BuildJavaTestFilter(filenames): |
Michael Thiessen | 00fb08f | 2020-09-19 02:07:34 | [diff] [blame] | 461 | return ':'.join('*.{}*'.format(os.path.splitext(os.path.basename(f))[0]) |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 462 | for f in filenames) |
| 463 | |
| 464 | |
Edman Anjos | a2a5572 | 2024-02-01 18:08:18 | [diff] [blame] | 465 | _PREF_MAPPING_GTEST_FILTER = '*PolicyPrefsTest.PolicyToPrefsMapping*' |
| 466 | |
| 467 | _PREF_MAPPING_FILE_REGEX = re.compile(_PREF_MAPPING_FILE_PATTERN) |
| 468 | |
| 469 | SPECIAL_TEST_FILTERS = [(_PREF_MAPPING_FILE_REGEX, _PREF_MAPPING_GTEST_FILTER)] |
| 470 | |
| 471 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 472 | def BuildTestFilter(filenames, line): |
| 473 | java_files = [f for f in filenames if f.endswith('.java')] |
| 474 | cc_files = [f for f in filenames if f.endswith('.cc')] |
| 475 | filters = [] |
| 476 | if java_files: |
| 477 | filters.append(BuildJavaTestFilter(java_files)) |
| 478 | if cc_files: |
| 479 | filters.append(BuildCppTestFilter(cc_files, line)) |
Edman Anjos | a2a5572 | 2024-02-01 18:08:18 | [diff] [blame] | 480 | for regex, gtest_filter in SPECIAL_TEST_FILTERS: |
| 481 | if any(True for f in filenames if regex.match(f)): |
| 482 | filters.append(gtest_filter) |
| 483 | break |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 484 | return ':'.join(filters) |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 485 | |
| 486 | |
Edman Anjos | a2a5572 | 2024-02-01 18:08:18 | [diff] [blame] | 487 | def BuildPrefMappingTestFilter(filenames): |
| 488 | mapping_files = [f for f in filenames if _PREF_MAPPING_FILE_REGEX.match(f)] |
| 489 | if not mapping_files: |
| 490 | return None |
| 491 | names_without_extension = [Path(f).stem for f in mapping_files] |
| 492 | return ':'.join(names_without_extension) |
| 493 | |
| 494 | |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 495 | def main(): |
| 496 | parser = argparse.ArgumentParser( |
| 497 | description=__doc__, formatter_class=argparse.RawTextHelpFormatter) |
Andrew Grieve | 9a2c08b | 2020-09-21 14:58:34 | [diff] [blame] | 498 | parser.add_argument('--out-dir', |
Edman Anjos | 03e2d97 | 2024-01-29 10:58:31 | [diff] [blame] | 499 | '--out_dir', |
Peter Wen | f3df5de | 2021-03-11 18:12:22 | [diff] [blame] | 500 | '--output-directory', |
Edman Anjos | 03e2d97 | 2024-01-29 10:58:31 | [diff] [blame] | 501 | '--output_directory', |
Andrew Grieve | 9a2c08b | 2020-09-21 14:58:34 | [diff] [blame] | 502 | '-C', |
| 503 | metavar='OUT_DIR', |
| 504 | help='output directory of the build') |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 505 | parser.add_argument( |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 506 | '--run-all', |
Edman Anjos | 03e2d97 | 2024-01-29 10:58:31 | [diff] [blame] | 507 | '--run_all', |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 508 | action='store_true', |
| 509 | help='Run all tests for the file or directory, instead of just one') |
| 510 | parser.add_argument('--line', |
| 511 | type=int, |
| 512 | help='run only the test on this line number. c++ only.') |
Edman Anjos | 03e2d97 | 2024-01-29 10:58:31 | [diff] [blame] | 513 | parser.add_argument('--gtest-filter', |
| 514 | '--gtest_filter', |
Michael Thiessen | 53ba6a8 | 2022-11-30 02:37:52 | [diff] [blame] | 515 | '-f', |
| 516 | metavar='FILTER', |
| 517 | help='test filter') |
Edman Anjos | a2a5572 | 2024-02-01 18:08:18 | [diff] [blame] | 518 | parser.add_argument('--test-policy-to-pref-mappings-filter', |
| 519 | '--test_policy_to_pref_mappings_filter', |
| 520 | metavar='FILTER', |
| 521 | help='policy pref mappings test filter') |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 522 | parser.add_argument( |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 523 | '--dry-run', |
Edman Anjos | 03e2d97 | 2024-01-29 10:58:31 | [diff] [blame] | 524 | '--dry_run', |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 525 | '-n', |
| 526 | action='store_true', |
| 527 | help='Print ninja and test run commands without executing them.') |
Olivier Li | 2a89d35 | 2021-05-05 15:26:54 | [diff] [blame] | 528 | parser.add_argument( |
| 529 | '--no-try-android-wrappers', |
Edman Anjos | 03e2d97 | 2024-01-29 10:58:31 | [diff] [blame] | 530 | '--no_try_android_wrappers', |
Olivier Li | 2a89d35 | 2021-05-05 15:26:54 | [diff] [blame] | 531 | action='store_true', |
| 532 | help='Do not try to use Android test wrappers to run tests.') |
Andrew Grieve | 5d6db89 | 2022-02-23 16:06:06 | [diff] [blame] | 533 | parser.add_argument('--no-fast-local-dev', |
Edman Anjos | 03e2d97 | 2024-01-29 10:58:31 | [diff] [blame] | 534 | '--no_fast_local_dev', |
Andrew Grieve | 5d6db89 | 2022-02-23 16:06:06 | [diff] [blame] | 535 | action='store_true', |
| 536 | help='Do not add --fast-local-dev for Android tests.') |
Edman Anjos | af38a3e | 2023-06-06 21:16:49 | [diff] [blame] | 537 | parser.add_argument('files', |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 538 | metavar='FILE_NAME', |
Edman Anjos | 03e2d97 | 2024-01-29 10:58:31 | [diff] [blame] | 539 | nargs='+', |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 540 | help='test suite file (eg. FooTest.java)') |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 541 | |
| 542 | args, _extras = parser.parse_known_args() |
| 543 | |
Peter Wen | f3df5de | 2021-03-11 18:12:22 | [diff] [blame] | 544 | if args.out_dir: |
| 545 | constants.SetOutputDirectory(args.out_dir) |
| 546 | constants.CheckOutputDirectory() |
| 547 | out_dir: str = constants.GetOutDirectory() |
| 548 | |
| 549 | if not os.path.isdir(out_dir): |
| 550 | parser.error(f'OUT_DIR "{out_dir}" does not exist.') |
| 551 | target_cache = TargetCache(out_dir) |
Edman Anjos | af38a3e | 2023-06-06 21:16:49 | [diff] [blame] | 552 | filenames = [] |
| 553 | for file in args.files: |
| 554 | filenames.extend(FindMatchingTestFiles(file)) |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 555 | |
Peter Wen | f3df5de | 2021-03-11 18:12:22 | [diff] [blame] | 556 | targets, used_cache = FindTestTargets(target_cache, out_dir, filenames, |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 557 | args.run_all) |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 558 | |
| 559 | gtest_filter = args.gtest_filter |
| 560 | if not gtest_filter: |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 561 | gtest_filter = BuildTestFilter(filenames, args.line) |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 562 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 563 | if not gtest_filter: |
| 564 | ExitWithMessage('Failed to derive a gtest filter') |
| 565 | |
Edman Anjos | a2a5572 | 2024-02-01 18:08:18 | [diff] [blame] | 566 | pref_mapping_filter = args.test_policy_to_pref_mappings_filter |
| 567 | if not pref_mapping_filter: |
| 568 | pref_mapping_filter = BuildPrefMappingTestFilter(filenames) |
| 569 | |
Dan Harrington | fd50794 | 2020-09-08 18:30:14 | [diff] [blame] | 570 | assert targets |
Andrew Grieve | 5c59eaf | 2023-07-10 19:06:42 | [diff] [blame] | 571 | build_ok = BuildTestTargets(out_dir, targets, args.dry_run) |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 572 | |
| 573 | # If we used the target cache, it's possible we chose the wrong target because |
| 574 | # a gn file was changed. The build step above will check for gn modifications |
| 575 | # and update build.ninja. Use this opportunity the verify the cache is still |
| 576 | # valid. |
| 577 | if used_cache and not target_cache.IsStillValid(): |
Peter Wen | f3df5de | 2021-03-11 18:12:22 | [diff] [blame] | 578 | target_cache = TargetCache(out_dir) |
| 579 | new_targets, _ = FindTestTargets(target_cache, out_dir, filenames, |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 580 | args.run_all) |
| 581 | if targets != new_targets: |
| 582 | # Note that this can happen, for example, if you rename a test target. |
| 583 | print('gn config was changed, trying to build again', file=sys.stderr) |
| 584 | targets = new_targets |
Andrew Grieve | 5c59eaf | 2023-07-10 19:06:42 | [diff] [blame] | 585 | build_ok = BuildTestTargets(out_dir, targets, args.dry_run) |
Dan Harrington | bd1fa35 | 2021-05-14 21:02:10 | [diff] [blame] | 586 | |
| 587 | if not build_ok: sys.exit(1) |
Dan Harrington | 9239268 | 2020-09-16 15:34:24 | [diff] [blame] | 588 | |
Edman Anjos | a2a5572 | 2024-02-01 18:08:18 | [diff] [blame] | 589 | RunTestTargets(out_dir, targets, gtest_filter, pref_mapping_filter, _extras, |
| 590 | args.dry_run, args.no_try_android_wrappers, |
| 591 | args.no_fast_local_dev) |
Michael Thiessen | f61b1bc | 2020-03-23 18:44:50 | [diff] [blame] | 592 | |
| 593 | |
| 594 | if __name__ == '__main__': |
| 595 | sys.exit(main()) |