autotest.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. #!/usr/bin/env python3
  2. # Copyright 2020 The Chromium Authors. All rights reserved.
  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. This script finds the appropriate test suites for the specified test file or
  7. directory, builds it, then runs it with the (optionally) specified filter,
  8. passing any extra args on to the test runner.
  9. Examples:
  10. # Run the test target for bit_cast_unittest.cc. Use a custom test filter instead
  11. # of the automatically generated one.
  12. autotest.py -C out/Desktop bit_cast_unittest.cc --gtest_filter=BitCastTest*
  13. # Find and run UrlUtilitiesUnitTest.java's tests, pass remaining parameters to
  14. # the test binary.
  15. autotest.py -C out/Android UrlUtilitiesUnitTest --fast-local-dev -v
  16. # Run all tests under base/strings
  17. autotest.py -C out/foo --run-all base/strings
  18. # Run only the test on line 11. Useful when running autotest.py from your text
  19. # editor.
  20. autotest.py -C out/foo --line 11 base/strings/strcat_unittest.cc
  21. """
  22. import argparse
  23. import locale
  24. import os
  25. import json
  26. import re
  27. import subprocess
  28. import sys
  29. from enum import Enum
  30. from pathlib import Path
  31. USE_PYTHON_3 = f'This script will only run under python3.'
  32. SRC_DIR = Path(__file__).parent.parent.resolve()
  33. sys.path.append(str(SRC_DIR / 'build' / 'android'))
  34. from pylib import constants
  35. DEPOT_TOOLS_DIR = SRC_DIR / 'third_party' / 'depot_tools'
  36. DEBUG = False
  37. # Some test suites use suffixes that would also match non-test-suite targets.
  38. # Those test suites should be manually added here.
  39. _OTHER_TEST_TARGETS = [
  40. '//chrome/test:browser_tests',
  41. '//chrome/test:unit_tests',
  42. ]
  43. _TEST_TARGET_REGEX = re.compile(
  44. r'(_browsertests|_junit_tests|_perftests|_test_.*apk|_unittests|' +
  45. r'_wpr_tests)$')
  46. TEST_FILE_NAME_REGEX = re.compile(r'(.*Test\.java)|(.*_[a-z]*test\.cc)')
  47. # Some tests don't directly include gtest.h and instead include it via gmock.h
  48. # or a test_utils.h file, so make sure these cases are captured. Also include
  49. # files that use <...> for #includes instead of quotes.
  50. GTEST_INCLUDE_REGEX = re.compile(
  51. r'#include.*(gtest|gmock|_test_utils|browser_test)\.h("|>)')
  52. def ExitWithMessage(*args):
  53. print(*args, file=sys.stderr)
  54. sys.exit(1)
  55. class TestValidity(Enum):
  56. NOT_A_TEST = 0 # Does not match test file regex.
  57. MAYBE_A_TEST = 1 # Matches test file regex, but doesn't include gtest files.
  58. VALID_TEST = 2 # Matches test file regex and includes gtest files.
  59. def IsTestFile(file_path):
  60. if not TEST_FILE_NAME_REGEX.match(file_path):
  61. return TestValidity.NOT_A_TEST
  62. if file_path.endswith('.cc'):
  63. # Try a bit harder to remove non-test files for c++. Without this,
  64. # 'autotest.py base/' finds non-test files.
  65. try:
  66. with open(file_path, 'r', encoding='utf-8') as f:
  67. if GTEST_INCLUDE_REGEX.search(f.read()) is not None:
  68. return TestValidity.VALID_TEST
  69. except IOError:
  70. pass
  71. # It may still be a test file, even if it doesn't include a gtest file.
  72. return TestValidity.MAYBE_A_TEST
  73. return TestValidity.VALID_TEST
  74. class CommandError(Exception):
  75. """Exception thrown when a subcommand fails."""
  76. def __init__(self, command, return_code, output=None):
  77. Exception.__init__(self)
  78. self.command = command
  79. self.return_code = return_code
  80. self.output = output
  81. def __str__(self):
  82. message = (f'\n***\nERROR: Error while running command {self.command}'
  83. f'.\nExit status: {self.return_code}\n')
  84. if self.output:
  85. message += f'Output:\n{self.output}\n'
  86. message += '***'
  87. return message
  88. def StreamCommandOrExit(cmd, **kwargs):
  89. try:
  90. subprocess.check_call(cmd, **kwargs)
  91. except subprocess.CalledProcessError as e:
  92. sys.exit(1)
  93. def RunCommand(cmd, **kwargs):
  94. try:
  95. # Set an encoding to convert the binary output to a string.
  96. return subprocess.check_output(
  97. cmd, **kwargs, encoding=locale.getpreferredencoding())
  98. except subprocess.CalledProcessError as e:
  99. raise CommandError(e.cmd, e.returncode, e.output) from None
  100. def BuildTestTargetsWithNinja(out_dir, targets, dry_run):
  101. """Builds the specified targets with ninja"""
  102. # Use autoninja from PATH to match version used for manual builds.
  103. ninja_path = 'autoninja'
  104. if sys.platform.startswith('win32'):
  105. ninja_path += '.bat'
  106. cmd = [ninja_path, '-C', out_dir] + targets
  107. print('Building: ' + ' '.join(cmd))
  108. if (dry_run):
  109. return True
  110. try:
  111. subprocess.check_call(cmd)
  112. except subprocess.CalledProcessError as e:
  113. return False
  114. return True
  115. def RecursiveMatchFilename(folder, filename):
  116. current_dir = os.path.split(folder)[-1]
  117. if current_dir.startswith('out') or current_dir.startswith('.'):
  118. return [[], []]
  119. exact = []
  120. close = []
  121. with os.scandir(folder) as it:
  122. for entry in it:
  123. if (entry.is_symlink()):
  124. continue
  125. if (entry.is_file() and filename in entry.path and
  126. not os.path.basename(entry.path).startswith('.')):
  127. file_validity = IsTestFile(entry.path)
  128. if file_validity is TestValidity.VALID_TEST:
  129. exact.append(entry.path)
  130. elif file_validity is TestValidity.MAYBE_A_TEST:
  131. close.append(entry.path)
  132. if entry.is_dir():
  133. # On Windows, junctions are like a symlink that python interprets as a
  134. # directory, leading to exceptions being thrown. We can just catch and
  135. # ignore these exceptions like we would ignore symlinks.
  136. try:
  137. matches = RecursiveMatchFilename(entry.path, filename)
  138. exact += matches[0]
  139. close += matches[1]
  140. except FileNotFoundError as e:
  141. if DEBUG:
  142. print(f'Failed to scan directory "{entry}" - junction?')
  143. pass
  144. return [exact, close]
  145. def FindTestFilesInDirectory(directory):
  146. test_files = []
  147. if DEBUG:
  148. print('Test files:')
  149. for root, _, files in os.walk(directory):
  150. for f in files:
  151. path = os.path.join(root, f)
  152. file_validity = IsTestFile(path)
  153. if file_validity is TestValidity.VALID_TEST:
  154. if DEBUG:
  155. print(path)
  156. test_files.append(path)
  157. elif DEBUG and file_validity is TestValidity.MAYBE_A_TEST:
  158. print(path + ' matched but doesn\'t include gtest files, skipping.')
  159. return test_files
  160. def FindMatchingTestFiles(target):
  161. # Return early if there's an exact file match.
  162. if os.path.isfile(target):
  163. # If the target is a C++ implementation file, try to guess the test file.
  164. if target.endswith('.cc') or target.endswith('.h'):
  165. target_validity = IsTestFile(target)
  166. if target_validity is TestValidity.VALID_TEST:
  167. return [target]
  168. alternate = f"{target.rsplit('.', 1)[0]}_unittest.cc"
  169. alt_validity = TestValidity.NOT_A_TEST if not os.path.isfile(
  170. alternate) else IsTestFile(alternate)
  171. if alt_validity is TestValidity.VALID_TEST:
  172. return [alternate]
  173. # If neither the target nor its alternative were valid, check if they just
  174. # didn't include the gtest files before deciding to exit.
  175. if target_validity is TestValidity.MAYBE_A_TEST:
  176. return [target]
  177. if alt_validity is TestValidity.MAYBE_A_TEST:
  178. return [alternate]
  179. ExitWithMessage(f"{target} doesn't look like a test file")
  180. return [target]
  181. # If this is a directory, return all the test files it contains.
  182. if os.path.isdir(target):
  183. files = FindTestFilesInDirectory(target)
  184. if not files:
  185. ExitWithMessage('No tests found in directory')
  186. return files
  187. if sys.platform.startswith('win32') and os.path.altsep in target:
  188. # Use backslash as the path separator on Windows to match os.scandir().
  189. if DEBUG:
  190. print('Replacing ' + os.path.altsep + ' with ' + os.path.sep + ' in: '
  191. + target)
  192. target = target.replace(os.path.altsep, os.path.sep)
  193. if DEBUG:
  194. print('Finding files with full path containing: ' + target)
  195. [exact, close] = RecursiveMatchFilename(SRC_DIR, target)
  196. if DEBUG:
  197. if exact:
  198. print('Found exact matching file(s):')
  199. print('\n'.join(exact))
  200. if close:
  201. print('Found possible matching file(s):')
  202. print('\n'.join(close))
  203. test_files = exact if len(exact) > 0 else close
  204. if len(test_files) > 1:
  205. # Arbitrarily capping at 10 results so we don't print the name of every file
  206. # in the repo if the target is poorly specified.
  207. test_files = test_files[:10]
  208. ExitWithMessage(f'Target "{target}" is ambiguous. Matching files: '
  209. f'{test_files}')
  210. if not test_files:
  211. ExitWithMessage(f'Target "{target}" did not match any files.')
  212. return test_files
  213. def IsTestTarget(target):
  214. if _TEST_TARGET_REGEX.search(target):
  215. return True
  216. return target in _OTHER_TEST_TARGETS
  217. def HaveUserPickTarget(paths, targets):
  218. # Cap to 10 targets for convenience [0-9].
  219. targets = targets[:10]
  220. target_list = '\n'.join(f'{i}. {t}' for i, t in enumerate(targets))
  221. user_input = input(f'Target "{paths}" is used by multiple test targets.\n' +
  222. target_list + '\nPlease pick a target: ')
  223. try:
  224. value = int(user_input)
  225. return targets[value]
  226. except (ValueError, IndexError):
  227. print('Try again')
  228. return HaveUserPickTarget(paths, targets)
  229. # A persistent cache to avoid running gn on repeated runs of autotest.
  230. class TargetCache:
  231. def __init__(self, out_dir):
  232. self.out_dir = out_dir
  233. self.path = os.path.join(out_dir, 'autotest_cache')
  234. self.gold_mtime = self.GetBuildNinjaMtime()
  235. self.cache = {}
  236. try:
  237. mtime, cache = json.load(open(self.path, 'r'))
  238. if mtime == self.gold_mtime:
  239. self.cache = cache
  240. except Exception:
  241. pass
  242. def Save(self):
  243. with open(self.path, 'w') as f:
  244. json.dump([self.gold_mtime, self.cache], f)
  245. def Find(self, test_paths):
  246. key = ' '.join(test_paths)
  247. return self.cache.get(key, None)
  248. def Store(self, test_paths, test_targets):
  249. key = ' '.join(test_paths)
  250. self.cache[key] = test_targets
  251. def GetBuildNinjaMtime(self):
  252. return os.path.getmtime(os.path.join(self.out_dir, 'build.ninja'))
  253. def IsStillValid(self):
  254. return self.GetBuildNinjaMtime() == self.gold_mtime
  255. def FindTestTargets(target_cache, out_dir, paths, run_all):
  256. # Normalize paths, so they can be cached.
  257. paths = [os.path.realpath(p) for p in paths]
  258. test_targets = target_cache.Find(paths)
  259. used_cache = True
  260. if not test_targets:
  261. used_cache = False
  262. # Use gn refs to recursively find all targets that depend on |path|, filter
  263. # internal gn targets, and match against well-known test suffixes, falling
  264. # back to a list of known test targets if that fails.
  265. gn_path = os.path.join(DEPOT_TOOLS_DIR, 'gn')
  266. if sys.platform.startswith('win32'):
  267. gn_path += '.bat'
  268. cmd = [gn_path, 'refs', out_dir, '--all'] + paths
  269. targets = RunCommand(cmd).splitlines()
  270. targets = [t for t in targets if '__' not in t]
  271. test_targets = [t for t in targets if IsTestTarget(t)]
  272. if not test_targets:
  273. ExitWithMessage(
  274. f'Target(s) "{paths}" did not match any test targets. Consider adding'
  275. f' one of the following targets to the top of {__file__}: {targets}')
  276. target_cache.Store(paths, test_targets)
  277. target_cache.Save()
  278. if len(test_targets) > 1:
  279. if run_all:
  280. print(f'Warning, found {len(test_targets)} test targets.',
  281. file=sys.stderr)
  282. if len(test_targets) > 10:
  283. ExitWithMessage('Your query likely involves non-test sources.')
  284. print('Trying to run all of them!', file=sys.stderr)
  285. else:
  286. test_targets = [HaveUserPickTarget(paths, test_targets)]
  287. test_targets = list(set([t.split(':')[-1] for t in test_targets]))
  288. return (test_targets, used_cache)
  289. def RunTestTargets(out_dir, targets, gtest_filter, extra_args, dry_run,
  290. no_try_android_wrappers, no_fast_local_dev):
  291. for target in targets:
  292. # Look for the Android wrapper script first.
  293. path = os.path.join(out_dir, 'bin', f'run_{target}')
  294. if no_try_android_wrappers or not os.path.isfile(path):
  295. # If the wrapper is not found or disabled use the Desktop target
  296. # which is an executable.
  297. path = os.path.join(out_dir, target)
  298. elif not no_fast_local_dev:
  299. # Usually want this flag when developing locally.
  300. extra_args = extra_args + ['--fast-local-dev']
  301. cmd = [path, f'--gtest_filter={gtest_filter}'] + extra_args
  302. print('Running test: ' + ' '.join(cmd))
  303. if not dry_run:
  304. StreamCommandOrExit(cmd)
  305. def BuildCppTestFilter(filenames, line):
  306. make_filter_command = [
  307. sys.executable, SRC_DIR / 'tools' / 'make_gtest_filter.py'
  308. ]
  309. if line:
  310. make_filter_command += ['--line', str(line)]
  311. else:
  312. make_filter_command += ['--class-only']
  313. make_filter_command += filenames
  314. return RunCommand(make_filter_command).strip()
  315. def BuildJavaTestFilter(filenames):
  316. return ':'.join('*.{}*'.format(os.path.splitext(os.path.basename(f))[0])
  317. for f in filenames)
  318. def BuildTestFilter(filenames, line):
  319. java_files = [f for f in filenames if f.endswith('.java')]
  320. cc_files = [f for f in filenames if f.endswith('.cc')]
  321. filters = []
  322. if java_files:
  323. filters.append(BuildJavaTestFilter(java_files))
  324. if cc_files:
  325. filters.append(BuildCppTestFilter(cc_files, line))
  326. return ':'.join(filters)
  327. def main():
  328. parser = argparse.ArgumentParser(
  329. description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
  330. parser.add_argument('--out-dir',
  331. '--output-directory',
  332. '-C',
  333. metavar='OUT_DIR',
  334. help='output directory of the build')
  335. parser.add_argument(
  336. '--run-all',
  337. action='store_true',
  338. help='Run all tests for the file or directory, instead of just one')
  339. parser.add_argument('--line',
  340. type=int,
  341. help='run only the test on this line number. c++ only.')
  342. parser.add_argument(
  343. '--gtest_filter', '-f', metavar='FILTER', help='test filter')
  344. parser.add_argument(
  345. '--dry-run',
  346. '-n',
  347. action='store_true',
  348. help='Print ninja and test run commands without executing them.')
  349. parser.add_argument(
  350. '--no-try-android-wrappers',
  351. action='store_true',
  352. help='Do not try to use Android test wrappers to run tests.')
  353. parser.add_argument('--no-fast-local-dev',
  354. action='store_true',
  355. help='Do not add --fast-local-dev for Android tests.')
  356. parser.add_argument('file',
  357. metavar='FILE_NAME',
  358. help='test suite file (eg. FooTest.java)')
  359. args, _extras = parser.parse_known_args()
  360. if args.out_dir:
  361. constants.SetOutputDirectory(args.out_dir)
  362. constants.CheckOutputDirectory()
  363. out_dir: str = constants.GetOutDirectory()
  364. if not os.path.isdir(out_dir):
  365. parser.error(f'OUT_DIR "{out_dir}" does not exist.')
  366. target_cache = TargetCache(out_dir)
  367. filenames = FindMatchingTestFiles(args.file)
  368. targets, used_cache = FindTestTargets(target_cache, out_dir, filenames,
  369. args.run_all)
  370. gtest_filter = args.gtest_filter
  371. if not gtest_filter:
  372. gtest_filter = BuildTestFilter(filenames, args.line)
  373. if not gtest_filter:
  374. ExitWithMessage('Failed to derive a gtest filter')
  375. assert targets
  376. build_ok = BuildTestTargetsWithNinja(out_dir, targets, args.dry_run)
  377. # If we used the target cache, it's possible we chose the wrong target because
  378. # a gn file was changed. The build step above will check for gn modifications
  379. # and update build.ninja. Use this opportunity the verify the cache is still
  380. # valid.
  381. if used_cache and not target_cache.IsStillValid():
  382. target_cache = TargetCache(out_dir)
  383. new_targets, _ = FindTestTargets(target_cache, out_dir, filenames,
  384. args.run_all)
  385. if targets != new_targets:
  386. # Note that this can happen, for example, if you rename a test target.
  387. print('gn config was changed, trying to build again', file=sys.stderr)
  388. targets = new_targets
  389. build_ok = BuildTestTargetsWithNinja(out_dir, targets, args.dry_run)
  390. if not build_ok: sys.exit(1)
  391. RunTestTargets(out_dir, targets, gtest_filter, _extras, args.dry_run,
  392. args.no_try_android_wrappers, args.no_fast_local_dev)
  393. if __name__ == '__main__':
  394. sys.exit(main())