- add sources.
[platform/framework/web/crosswalk.git] / src / tools / heapcheck / chrome_tests.py
1 #!/usr/bin/env python
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.
5
6 ''' Runs various chrome tests through heapcheck_test.py.
7
8 Most of this code is copied from ../valgrind/chrome_tests.py.
9 TODO(glider): put common functions to a standalone module.
10 '''
11
12 import glob
13 import logging
14 import multiprocessing
15 import optparse
16 import os
17 import stat
18 import sys
19
20 import logging_utils
21 import path_utils
22
23 import common
24 import heapcheck_test
25
26 class TestNotFound(Exception): pass
27
28 def Dir2IsNewer(dir1, dir2):
29   if dir2 is None or not os.path.isdir(dir2):
30     return False
31   if dir1 is None or not os.path.isdir(dir1):
32     return True
33   return os.stat(dir2)[stat.ST_MTIME] > os.stat(dir1)[stat.ST_MTIME]
34
35 def FindNewestDir(dirs):
36   newest_dir = None
37   for dir in dirs:
38     if Dir2IsNewer(newest_dir, dir):
39       newest_dir = dir
40   return newest_dir
41
42 def File2IsNewer(file1, file2):
43   if file2 is None or not os.path.isfile(file2):
44     return False
45   if file1 is None or not os.path.isfile(file1):
46     return True
47   return os.stat(file2)[stat.ST_MTIME] > os.stat(file1)[stat.ST_MTIME]
48
49 def FindDirContainingNewestFile(dirs, file):
50   """Searches for the directory containing the newest copy of |file|.
51
52   Args:
53     dirs: A list of paths to the directories to search among.
54     file: A string containing the file name to search.
55
56   Returns:
57     The string representing the the directory containing the newest copy of
58     |file|.
59
60   Raises:
61     IOError: |file| was not found.
62   """
63   newest_dir = None
64   newest_file = None
65   for dir in dirs:
66     the_file = os.path.join(dir, file)
67     if File2IsNewer(newest_file, the_file):
68       newest_dir = dir
69       newest_file = the_file
70   if newest_dir is None:
71     raise IOError("cannot find file %s anywhere, have you built it?" % file)
72   return newest_dir
73
74 class ChromeTests(object):
75   '''This class is derived from the chrome_tests.py file in ../purify/.
76   '''
77
78   def __init__(self, options, args, test):
79     # The known list of tests.
80     # Recognise the original abbreviations as well as full executable names.
81     self._test_list = {
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,
116     }
117
118     if test not in self._test_list:
119       raise TestNotFound("Unknown test: %s" % test)
120
121     self._options = options
122     self._args = args
123     self._test = test
124
125     script_dir = path_utils.ScriptDir()
126
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))
131
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('\\', '/')
135
136     heapcheck_test_script = os.path.join(script_dir, "heapcheck_test.py")
137     self._command_preamble = [heapcheck_test_script]
138
139   def _DefaultCommand(self, module, exe=None, heapcheck_test_args=None):
140     '''Generates the default command array that most tests will use.
141
142     Args:
143       module: The module name (corresponds to the dir in src/ where the test
144               data resides).
145       exe: The executable name.
146       heapcheck_test_args: additional arguments to append to the command line.
147     Returns:
148       A string with the command to run the test.
149     '''
150     if not self._options.build_dir:
151       dirs = [
152         os.path.join(self._source_dir, "xcodebuild", "Debug"),
153         os.path.join(self._source_dir, "out", "Debug"),
154       ]
155       if exe:
156         self._options.build_dir = FindDirContainingNewestFile(dirs, exe)
157       else:
158         self._options.build_dir = FindNewestDir(dirs)
159
160     cmd = list(self._command_preamble)
161
162     if heapcheck_test_args != None:
163       for arg in heapcheck_test_args:
164         cmd.append(arg)
165     if exe:
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)
172     return cmd
173
174   def Suppressions(self):
175     '''Builds the list of available suppressions files.'''
176     ret = []
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)
184     return ret
185
186   def Run(self):
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]()
190
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|.
194
195     Args:
196       name: the test executable name.
197       cmd: the test running command line to be modified.
198     '''
199     filters = []
200     directory = path_utils.ScriptDir()
201     gtest_filter_files = [
202         os.path.join(directory, name + ".gtest-heapcheck.txt"),
203         # TODO(glider): Linux vs. CrOS?
204     ]
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)
212         continue
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():
217           continue
218         line = line.rstrip()
219         filters.append(line)
220     gtest_filter = self._options.gtest_filter
221     if len(filters):
222       if gtest_filter:
223         gtest_filter += ":"
224         if gtest_filter.find("-") < 0:
225           gtest_filter += "-"
226       else:
227         gtest_filter = "-"
228       gtest_filter += ":".join(filters)
229     if gtest_filter:
230       cmd.append("--gtest_filter=%s" % gtest_filter)
231
232   def SimpleTest(self, module, name, heapcheck_test_args=None, cmd_args=None):
233     '''Builds the command line and runs the specified test.
234
235     Args:
236       module: The module name (corresponds to the dir in src/ where the test
237               data resides).
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.
241     '''
242     cmd = self._DefaultCommand(module, name, heapcheck_test_args)
243     supp = self.Suppressions()
244     self._ReadGtestFilterFile(name, cmd)
245     if cmd_args:
246       cmd.extend(["--"])
247       cmd.extend(cmd_args)
248
249     # Sets LD_LIBRARY_PATH to the build folder so external libraries can be
250     # loaded.
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))
254     else:
255       os.putenv("LD_LIBRARY_PATH", self._options.build_dir)
256     return heapcheck_test.RunTool(cmd, supp, module)
257
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")
261
262   def TestAsh(self):
263     return self.SimpleTest("ash", "ash_unittests")
264
265   def TestAura(self):
266     return self.SimpleTest("aura", "aura_unittests")
267
268   def TestBase(self):
269     return self.SimpleTest("base", "base_unittests")
270
271   def TestBrowser(self):
272     return self.SimpleTest("chrome", "browser_tests")
273
274   def TestChromeOS(self):
275     return self.SimpleTest("chromeos", "chromeos_unittests")
276
277   def TestComponents(self):
278     return self.SimpleTest("components", "components_unittests")
279
280   def TestCompositor(self):
281     return self.SimpleTest("compositor", "compositor_unittests")
282
283   def TestContent(self):
284     return self.SimpleTest("content", "content_unittests")
285
286   def TestContentBrowser(self):
287     return self.SimpleTest("content", "content_browsertests")
288
289   def TestCourgette(self):
290     return self.SimpleTest("courgette", "courgette_unittests")
291
292   def TestCrypto(self):
293     return self.SimpleTest("crypto", "crypto_unittests")
294
295   def TestDevice(self):
296     return self.SimpleTest("device", "device_unittests")
297
298   def TestGPU(self):
299     return self.SimpleTest("gpu", "gpu_unittests")
300
301   def TestIpc(self):
302     return self.SimpleTest("ipc", "ipc_tests")
303
304   def TestJingle(self):
305     return self.SimpleTest("chrome", "jingle_unittests")
306
307   def TestMedia(self):
308     return self.SimpleTest("chrome", "media_unittests")
309
310   def TestMessageCenter(self):
311     return self.SimpleTest("message_center", "message_center_unittests")
312
313   def TestNet(self):
314     return self.SimpleTest("net", "net_unittests")
315
316   def TestPPAPI(self):
317     return self.SimpleTest("chrome", "ppapi_unittests")
318
319   def TestPrinting(self):
320     return self.SimpleTest("chrome", "printing_unittests")
321
322   def TestRemoting(self):
323     return self.SimpleTest("chrome", "remoting_unittests")
324
325   def TestSync(self):
326     return self.SimpleTest("chrome", "sync_unit_tests")
327
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")
334
335   def TestUIUnit(self):
336     return self.SimpleTest("chrome", "ui_unittests")
337
338   def TestUnit(self):
339     return self.SimpleTest("chrome", "unit_tests")
340
341   def TestURL(self):
342     return self.SimpleTest("chrome", "url_unittests")
343
344   def TestSql(self):
345     return self.SimpleTest("chrome", "sql_unittests")
346
347   def TestViews(self):
348     return self.SimpleTest("views", "views_unittests")
349
350   def TestLayoutChunk(self, chunk_num, chunk_size):
351     '''Runs tests [chunk_num*chunk_size .. (chunk_num+1)*chunk_size).
352
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
355     the list of tests.
356     '''
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")
364
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"))
372       for f in old_files:
373         os.remove(f)
374     else:
375       os.makedirs(out_dir)
376
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
385                   "--fully-parallel",
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.
390                   "--no-show-results",
391                   "--nocheck-sys-deps"]
392
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");
400     if (chunk_size > 0):
401       script_cmd.append("--run-chunk=%d:%d" % (chunk_num, chunk_size))
402     if len(self._args):
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])
406       else:
407         script_cmd.extend(self._args)
408     self._ReadGtestFilterFile("layout", script_cmd)
409
410     # Now run script_cmd with the wrapper in cmd
411     cmd.extend(["--"])
412     cmd.extend(script_cmd)
413     supp = self.Suppressions()
414     return heapcheck_test.RunTool(cmd, supp, "layout")
415
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)
427     chunk_num = 0
428     chunk_file = os.path.join("heapcheck_layout_chunk.txt")
429
430     logging.info("Reading state from " + chunk_file)
431     try:
432       f = open(chunk_file)
433       if f:
434         str = f.read()
435         if len(str):
436           chunk_num = int(str)
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:
441           chunk_num = 0
442         f.close()
443     except IOError, (errno, strerror):
444       logging.error("error reading from file %s (%d, %s)" % (chunk_file,
445                     errno, strerror))
446     ret = self.TestLayoutChunk(chunk_num, chunk_size)
447
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)
452     try:
453       f = open(chunk_file, "w")
454       chunk_num += 1
455       f.write("%d" % chunk_num)
456       f.close()
457     except IOError, (errno, strerror):
458       logging.error("error writing to file %s (%d, %s)" % (chunk_file, errno,
459                     strerror))
460
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.
464     return ret
465
466
467 def main():
468   if not sys.platform.startswith('linux'):
469     logging.error("Heap checking works only on Linux at the moment.")
470     return 1
471   parser = optparse.OptionParser("usage: %prog -b <dir> -t <test> "
472                                  "[-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.")
488
489   options, args = parser.parse_args()
490
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),
496                                    options.target)
497
498   if options.verbose:
499     logging_utils.config_root(logging.DEBUG)
500   else:
501     logging_utils.config_root()
502
503   if not options.test or not len(options.test):
504     parser.error("--test not specified")
505
506   for t in options.test:
507     tests = ChromeTests(options, args, t)
508     ret = tests.Run()
509     if ret:
510       return ret
511   return 0
512
513
514 if __name__ == "__main__":
515   sys.exit(main())