Upstream version 11.40.271.0
[platform/framework/web/crosswalk.git] / src / third_party / py_trace_event / src / run_tests
1 #!/usr/bin/env python
2 # Copyright 2011 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 import logging
6 import optparse
7 import os
8 import platform
9 import re
10 import sys
11 import types
12 import traceback
13 import unittest
14
15 def discover(dir, filters):
16   if hasattr(unittest.TestLoader, 'discover'):
17     return unittest.TestLoader().discover(dir, '*')
18
19   # poor mans unittest.discover
20   loader = unittest.TestLoader()
21   subsuites = []
22
23   for (dirpath, dirnames, filenames) in os.walk(dir):
24     for filename in [x for x in filenames if re.match('.*_test\.py$', x)]:
25       if filename.startswith('.') or filename.startswith('_'):
26         continue
27       fqn = dirpath.replace('/', '.') + '.' + re.match('(.+)\.py$', filename).group(1)
28
29       # load the test
30       try:
31         module = __import__(fqn,fromlist=[True])
32       except:
33         print "While importing [%s]\n" % fqn
34         traceback.print_exc()
35         continue
36
37       def test_is_selected(name):
38         for f in filters:
39           if re.search(f,name):
40             return True
41         return False
42
43       if hasattr(module, 'suite'):
44         base_suite = module.suite()
45       else:
46         base_suite = loader.loadTestsFromModule(module)
47       new_suite = unittest.TestSuite()
48       for t in base_suite:
49         if isinstance(t, unittest.TestSuite):
50           for i in t:
51             if test_is_selected(i.id()):
52               new_suite.addTest(i)
53         elif isinstance(t, unittest.TestCase):
54           if test_is_selected(t.id()):
55             new_suite.addTest(t)
56         else:
57           raise Exception("Wtf, expected TestSuite or TestCase, got %s" % t)
58
59       if new_suite.countTestCases():
60         subsuites.append(new_suite)
61
62   return unittest.TestSuite(subsuites)
63
64 def main():
65   parser = optparse.OptionParser()
66   parser.add_option(
67       '-v', '--verbose', action='count', default=0,
68       help='Increase verbosity level (repeat as needed)')
69   parser.add_option('--debug', dest='debug', action='store_true', default=False, help='Break into pdb when an assertion fails')
70   parser.add_option('--incremental', dest='incremental', action='store_true', default=False, help='Run tests one at a time.')
71   parser.add_option('--stop', dest='stop_on_error', action='store_true', default=False, help='Stop running tests on error.')
72   (options, args) = parser.parse_args()
73
74   if options.verbose >= 2:
75     logging.basicConfig(level=logging.DEBUG)
76   elif options.verbose:
77     logging.basicConfig(level=logging.INFO)
78   else:
79     logging.basicConfig(level=logging.WARNING)
80
81   # install hook on set_trace if --debug
82   if options.debug:
83     import exceptions
84     class DebuggingAssertionError(exceptions.AssertionError):
85       def __init__(self, *args):
86         exceptions.AssertionError.__init__(self, *args)
87         print "Assertion failed, entering PDB..."
88         import pdb
89         if hasattr(sys, '_getframe'):
90           pdb.Pdb().set_trace(sys._getframe().f_back.f_back)
91         else:
92           pdb.set_trace()
93     unittest.TestCase.failureException = DebuggingAssertionError
94
95     def hook(*args):
96       import traceback, pdb
97       traceback.print_exception(*args)
98       pdb.pm()
99     sys.excepthook = hook
100
101     import browser
102     browser.debug_mode = True
103
104   else:
105     def hook(exc, value, tb):
106       import traceback
107       if not str(value).startswith("_noprint"):
108         traceback.print_exception(exc, value, tb)
109       import src.message_loop
110       if src.message_loop.is_main_loop_running():
111         if not str(value).startswith("_noprint"):
112           print "Untrapped exception! Exiting message loop with exception."
113         src.message_loop.quit_main_loop(quit_with_exception=True)
114
115     sys.excepthook = hook
116
117   # make sure cwd is the base directory!
118   os.chdir(os.path.dirname(__file__))
119
120   if len(args) > 0:
121     suites = discover('trace_event_impl', args)
122   else:
123     suites = discover('trace_event_impl', ['.*'])
124
125   r = unittest.TextTestRunner()
126   if not options.incremental:
127     res = r.run(suites)
128     if res.wasSuccessful():
129       return 0
130     return 255
131   else:
132     ok = True
133     for s in suites:
134       if isinstance(s, unittest.TestSuite):
135         for t in s:
136           print '----------------------------------------------------------------------'
137           print 'Running %s' % str(t)
138           res = r.run(t)
139           if not res.wasSuccessful():
140             ok = False
141             if options.stop_on_error:
142               break
143         if ok == False and options.stop_on_error:
144           break
145       else:
146         res = r.run(s)
147         if not res.wasSuccessful():
148           ok = False
149           if options.stop_on_error:
150             break
151     if ok:
152       return 0
153     return 255
154
155 if __name__ == "__main__":
156   sys.exit(main())