2 # Copyright (c) 2012 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.
6 ''' Runs various chrome tests through heapcheck_test.py.
8 Most of this code is copied from ../valgrind/chrome_tests.py.
9 TODO(glider): put common functions to a standalone module.
14 import multiprocessing
26 class TestNotFound(Exception): pass
28 def Dir2IsNewer(dir1, dir2):
29 if dir2 is None or not os.path.isdir(dir2):
31 if dir1 is None or not os.path.isdir(dir1):
33 return os.stat(dir2)[stat.ST_MTIME] > os.stat(dir1)[stat.ST_MTIME]
35 def FindNewestDir(dirs):
38 if Dir2IsNewer(newest_dir, dir):
42 def File2IsNewer(file1, file2):
43 if file2 is None or not os.path.isfile(file2):
45 if file1 is None or not os.path.isfile(file1):
47 return os.stat(file2)[stat.ST_MTIME] > os.stat(file1)[stat.ST_MTIME]
49 def FindDirContainingNewestFile(dirs, file):
50 """Searches for the directory containing the newest copy of |file|.
53 dirs: A list of paths to the directories to search among.
54 file: A string containing the file name to search.
57 The string representing the the directory containing the newest copy of
61 IOError: |file| was not found.
66 the_file = os.path.join(dir, file)
67 if File2IsNewer(newest_file, the_file):
69 newest_file = the_file
70 if newest_dir is None:
71 raise IOError("cannot find file %s anywhere, have you built it?" % file)
74 class ChromeTests(object):
75 '''This class is derived from the chrome_tests.py file in ../purify/.
78 def __init__(self, options, args, test):
79 # The known list of tests.
80 # Recognise the original abbreviations as well as full executable names.
82 "app_list": self.TestAppList, "app_list_unittests": self.TestAppList,
83 "ash": self.TestAsh, "ash_unittests": self.TestAsh,
84 "aura": self.TestAura, "aura_unittests": self.TestAura,
85 "base": self.TestBase, "base_unittests": self.TestBase,
86 "browser": self.TestBrowser, "browser_tests": self.TestBrowser,
87 "chromeos": self.TestChromeOS, "chromeos_unittests": self.TestChromeOS,
88 "components": self.TestComponents,
89 "components_unittests": self.TestComponents,
90 "compositor": self.TestCompositor,
91 "compositor_unittests": self.TestCompositor,
92 "content": self.TestContent, "content_unittests": self.TestContent,
93 "content_browsertests": self.TestContentBrowser,
94 "courgette": self.TestCourgette,
95 "courgette_unittests": self.TestCourgette,
96 "crypto": self.TestCrypto, "crypto_unittests": self.TestCrypto,
97 "device": self.TestDevice, "device_unittests": self.TestDevice,
98 "gpu": self.TestGPU, "gpu_unittests": self.TestGPU,
99 "ipc": self.TestIpc, "ipc_tests": self.TestIpc,
100 "jingle": self.TestJingle, "jingle_unittests": self.TestJingle,
101 "layout": self.TestLayout, "layout_tests": self.TestLayout,
102 "media": self.TestMedia, "media_unittests": self.TestMedia,
103 "message_center": self.TestMessageCenter,
104 "message_center_unittests" : self.TestMessageCenter,
105 "net": self.TestNet, "net_unittests": self.TestNet,
106 "ppapi": self.TestPPAPI, "ppapi_unittests": self.TestPPAPI,
107 "printing": self.TestPrinting, "printing_unittests": self.TestPrinting,
108 "remoting": self.TestRemoting, "remoting_unittests": self.TestRemoting,
109 "sql": self.TestSql, "sql_unittests": self.TestSql,
110 "startup": self.TestStartup, "startup_tests": self.TestStartup,
111 "sync": self.TestSync, "sync_unit_tests": self.TestSync,
112 "ui_unit": self.TestUIUnit, "ui_unittests": self.TestUIUnit,
113 "unit": self.TestUnit, "unit_tests": self.TestUnit,
114 "url": self.TestURL, "url_unittests": self.TestURL,
115 "views": self.TestViews, "views_unittests": self.TestViews,
118 if test not in self._test_list:
119 raise TestNotFound("Unknown test: %s" % test)
121 self._options = options
125 script_dir = path_utils.ScriptDir()
127 # Compute the top of the tree (the "source dir") from the script dir (where
128 # this script lives). We assume that the script dir is in tools/heapcheck/
129 # relative to the top of the tree.
130 self._source_dir = os.path.dirname(os.path.dirname(script_dir))
132 # Since this path is used for string matching, make sure it's always
133 # an absolute Unix-style path.
134 self._source_dir = os.path.abspath(self._source_dir).replace('\\', '/')
136 heapcheck_test_script = os.path.join(script_dir, "heapcheck_test.py")
137 self._command_preamble = [heapcheck_test_script]
139 def _DefaultCommand(self, module, exe=None, heapcheck_test_args=None):
140 '''Generates the default command array that most tests will use.
143 module: The module name (corresponds to the dir in src/ where the test
145 exe: The executable name.
146 heapcheck_test_args: additional arguments to append to the command line.
148 A string with the command to run the test.
150 if not self._options.build_dir:
152 os.path.join(self._source_dir, "xcodebuild", "Debug"),
153 os.path.join(self._source_dir, "out", "Debug"),
156 self._options.build_dir = FindDirContainingNewestFile(dirs, exe)
158 self._options.build_dir = FindNewestDir(dirs)
160 cmd = list(self._command_preamble)
162 if heapcheck_test_args != None:
163 for arg in heapcheck_test_args:
166 cmd.append(os.path.join(self._options.build_dir, exe))
167 # Heapcheck runs tests slowly, so slow tests hurt more; show elapased time
168 # so we can find the slowpokes.
169 cmd.append("--gtest_print_time")
170 if self._options.gtest_repeat:
171 cmd.append("--gtest_repeat=%s" % self._options.gtest_repeat)
174 def Suppressions(self):
175 '''Builds the list of available suppressions files.'''
177 directory = path_utils.ScriptDir()
178 suppression_file = os.path.join(directory, "suppressions.txt")
179 if os.path.exists(suppression_file):
180 ret.append(suppression_file)
181 suppression_file = os.path.join(directory, "suppressions_linux.txt")
182 if os.path.exists(suppression_file):
183 ret.append(suppression_file)
187 '''Runs the test specified by command-line argument --test.'''
188 logging.info("running test %s" % (self._test))
189 return self._test_list[self._test]()
191 def _ReadGtestFilterFile(self, name, cmd):
192 '''Reads files which contain lists of tests to filter out with
193 --gtest_filter and appends the command-line option to |cmd|.
196 name: the test executable name.
197 cmd: the test running command line to be modified.
200 directory = path_utils.ScriptDir()
201 gtest_filter_files = [
202 os.path.join(directory, name + ".gtest-heapcheck.txt"),
203 # TODO(glider): Linux vs. CrOS?
205 logging.info("Reading gtest exclude filter files:")
206 for filename in gtest_filter_files:
207 # strip the leading absolute path (may be very long on the bot)
208 # and the following / or \.
209 readable_filename = filename.replace(self._source_dir, "")[1:]
210 if not os.path.exists(filename):
211 logging.info(" \"%s\" - not found" % readable_filename)
213 logging.info(" \"%s\" - OK" % readable_filename)
214 f = open(filename, 'r')
215 for line in f.readlines():
216 if line.startswith("#") or line.startswith("//") or line.isspace():
220 gtest_filter = self._options.gtest_filter
224 if gtest_filter.find("-") < 0:
228 gtest_filter += ":".join(filters)
230 cmd.append("--gtest_filter=%s" % gtest_filter)
232 def SimpleTest(self, module, name, heapcheck_test_args=None, cmd_args=None):
233 '''Builds the command line and runs the specified test.
236 module: The module name (corresponds to the dir in src/ where the test
238 name: The executable name.
239 heapcheck_test_args: Additional command line args for heap checker.
240 cmd_args: Additional command line args for the test.
242 cmd = self._DefaultCommand(module, name, heapcheck_test_args)
243 supp = self.Suppressions()
244 self._ReadGtestFilterFile(name, cmd)
249 # Sets LD_LIBRARY_PATH to the build folder so external libraries can be
251 if (os.getenv("LD_LIBRARY_PATH")):
252 os.putenv("LD_LIBRARY_PATH", "%s:%s" % (os.getenv("LD_LIBRARY_PATH"),
253 self._options.build_dir))
255 os.putenv("LD_LIBRARY_PATH", self._options.build_dir)
256 return heapcheck_test.RunTool(cmd, supp, module)
258 # TODO(glider): it's an overkill to define a method for each simple test.
259 def TestAppList(self):
260 return self.SimpleTest("app_list", "app_list_unittests")
263 return self.SimpleTest("ash", "ash_unittests")
266 return self.SimpleTest("aura", "aura_unittests")
269 return self.SimpleTest("base", "base_unittests")
271 def TestBrowser(self):
272 return self.SimpleTest("chrome", "browser_tests")
274 def TestChromeOS(self):
275 return self.SimpleTest("chromeos", "chromeos_unittests")
277 def TestComponents(self):
278 return self.SimpleTest("components", "components_unittests")
280 def TestCompositor(self):
281 return self.SimpleTest("compositor", "compositor_unittests")
283 def TestContent(self):
284 return self.SimpleTest("content", "content_unittests")
286 def TestContentBrowser(self):
287 return self.SimpleTest("content", "content_browsertests")
289 def TestCourgette(self):
290 return self.SimpleTest("courgette", "courgette_unittests")
292 def TestCrypto(self):
293 return self.SimpleTest("crypto", "crypto_unittests")
295 def TestDevice(self):
296 return self.SimpleTest("device", "device_unittests")
299 return self.SimpleTest("gpu", "gpu_unittests")
302 return self.SimpleTest("ipc", "ipc_tests")
304 def TestJingle(self):
305 return self.SimpleTest("chrome", "jingle_unittests")
308 return self.SimpleTest("chrome", "media_unittests")
310 def TestMessageCenter(self):
311 return self.SimpleTest("message_center", "message_center_unittests")
314 return self.SimpleTest("net", "net_unittests")
317 return self.SimpleTest("chrome", "ppapi_unittests")
319 def TestPrinting(self):
320 return self.SimpleTest("chrome", "printing_unittests")
322 def TestRemoting(self):
323 return self.SimpleTest("chrome", "remoting_unittests")
326 return self.SimpleTest("chrome", "sync_unit_tests")
328 def TestStartup(self):
329 # We don't need the performance results, we're just looking for pointer
330 # errors, so set number of iterations down to the minimum.
331 os.putenv("STARTUP_TESTS_NUMCYCLES", "1")
332 logging.info("export STARTUP_TESTS_NUMCYCLES=1");
333 return self.SimpleTest("chrome", "startup_tests")
335 def TestUIUnit(self):
336 return self.SimpleTest("chrome", "ui_unittests")
339 return self.SimpleTest("chrome", "unit_tests")
342 return self.SimpleTest("chrome", "url_unittests")
345 return self.SimpleTest("chrome", "sql_unittests")
348 return self.SimpleTest("views", "views_unittests")
350 def TestLayoutChunk(self, chunk_num, chunk_size):
351 '''Runs tests [chunk_num*chunk_size .. (chunk_num+1)*chunk_size).
353 Wrap around to beginning of list at end. If chunk_size is zero, run all
354 tests in the list once. If a text file is given as argument, it is used as
357 # Build the ginormous commandline in 'cmd'.
358 # It's going to be roughly
359 # python heapcheck_test.py ... python run_webkit_tests.py ...
360 # but we'll use the --indirect flag to heapcheck_test.py
361 # to avoid heapchecking python.
362 # Start by building the heapcheck_test.py commandline.
363 cmd = self._DefaultCommand("webkit")
365 # Now build script_cmd, the run_webkits_tests.py commandline
366 # Store each chunk in its own directory so that we can find the data later
367 chunk_dir = os.path.join("layout", "chunk_%05d" % chunk_num)
368 out_dir = os.path.join(path_utils.ScriptDir(), "latest")
369 out_dir = os.path.join(out_dir, chunk_dir)
370 if os.path.exists(out_dir):
371 old_files = glob.glob(os.path.join(out_dir, "*.txt"))
377 script = os.path.join(self._source_dir, "webkit", "tools", "layout_tests",
378 "run_webkit_tests.py")
379 # While Heapcheck is not memory bound like Valgrind for running layout tests
380 # in parallel, it is still CPU bound. Many machines have hyper-threading
381 # turned on, so the real number of cores is actually half.
382 jobs = max(1, int(multiprocessing.cpu_count() * 0.5))
383 script_cmd = ["python", script, "-v",
384 "--run-singly", # run a separate DumpRenderTree for each test
386 "--child-processes=%d" % jobs,
387 "--time-out-ms=200000",
388 "--no-retry-failures", # retrying takes too much time
389 # http://crbug.com/176908: Don't launch a browser when done.
391 "--nocheck-sys-deps"]
393 # Pass build mode to run_webkit_tests.py. We aren't passed it directly,
394 # so parse it out of build_dir. run_webkit_tests.py can only handle
395 # the two values "Release" and "Debug".
396 # TODO(Hercules): unify how all our scripts pass around build mode
397 # (--mode / --target / --build-dir / --debug)
398 if self._options.build_dir.endswith("Debug"):
399 script_cmd.append("--debug");
401 script_cmd.append("--run-chunk=%d:%d" % (chunk_num, chunk_size))
403 # if the arg is a txt file, then treat it as a list of tests
404 if os.path.isfile(self._args[0]) and self._args[0][-4:] == ".txt":
405 script_cmd.append("--test-list=%s" % self._args[0])
407 script_cmd.extend(self._args)
408 self._ReadGtestFilterFile("layout", script_cmd)
410 # Now run script_cmd with the wrapper in cmd
412 cmd.extend(script_cmd)
413 supp = self.Suppressions()
414 return heapcheck_test.RunTool(cmd, supp, "layout")
416 def TestLayout(self):
417 '''Runs the layout tests.'''
418 # A "chunk file" is maintained in the local directory so that each test
419 # runs a slice of the layout tests of size chunk_size that increments with
420 # each run. Since tests can be added and removed from the layout tests at
421 # any time, this is not going to give exact coverage, but it will allow us
422 # to continuously run small slices of the layout tests under purify rather
423 # than having to run all of them in one shot.
424 chunk_size = self._options.num_tests
425 if (chunk_size == 0):
426 return self.TestLayoutChunk(0, 0)
428 chunk_file = os.path.join("heapcheck_layout_chunk.txt")
430 logging.info("Reading state from " + chunk_file)
437 # This should be enough so that we have a couple of complete runs
438 # of test data stored in the archive (although note that when we loop
439 # that we almost guaranteed won't be at the end of the test list)
440 if chunk_num > 10000:
443 except IOError, (errno, strerror):
444 logging.error("error reading from file %s (%d, %s)" % (chunk_file,
446 ret = self.TestLayoutChunk(chunk_num, chunk_size)
448 # Wait until after the test runs to completion to write out the new chunk
449 # number. This way, if the bot is killed, we'll start running again from
450 # the current chunk rather than skipping it.
451 logging.info("Saving state to " + chunk_file)
453 f = open(chunk_file, "w")
455 f.write("%d" % chunk_num)
457 except IOError, (errno, strerror):
458 logging.error("error writing to file %s (%d, %s)" % (chunk_file, errno,
461 # Since we're running small chunks of the layout tests, it's important to
462 # mark the ones that have errors in them. These won't be visible in the
463 # summary list for long, but will be useful for someone reviewing this bot.
468 if not sys.platform.startswith('linux'):
469 logging.error("Heap checking works only on Linux at the moment.")
471 parser = optparse.OptionParser("usage: %prog -b <dir> -t <test> "
473 parser.add_option("-b", "--build-dir",
474 help="the location of the output of the compiler output")
475 parser.add_option("--target", help="Debug or Release")
476 parser.add_option("-t", "--test", action="append", help="which test to run")
477 parser.add_option("--gtest_filter",
478 help="additional arguments to --gtest_filter")
479 parser.add_option("--gtest_repeat", help="argument for --gtest_repeat")
480 parser.add_option("-v", "--verbose", action="store_true", default=False,
481 help="verbose output - enable debug log messages")
482 # My machine can do about 120 layout tests/hour in release mode.
483 # Let's do 30 minutes worth per run.
484 # The CPU is mostly idle, so perhaps we can raise this when
485 # we figure out how to run them more efficiently.
486 parser.add_option("-n", "--num_tests", default=60, type="int",
487 help="for layout tests: # of subtests per run. 0 for all.")
489 options, args = parser.parse_args()
491 # Bake target into build_dir.
492 if options.target and options.build_dir:
493 assert (options.target !=
494 os.path.basename(os.path.dirname(options.build_dir)))
495 options.build_dir = os.path.join(os.path.abspath(options.build_dir),
499 logging_utils.config_root(logging.DEBUG)
501 logging_utils.config_root()
503 if not options.test or not len(options.test):
504 parser.error("--test not specified")
506 for t in options.test:
507 tests = ChromeTests(options, args, t)
514 if __name__ == "__main__":