main.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # Copyright (C) 2012 Google, Inc.
  2. # Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org)
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions
  6. # are met:
  7. # 1. Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # 2. Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
  14. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  15. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  16. # DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
  17. # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  18. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  19. # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  20. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  21. # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  22. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. """unit testing code for webkitpy."""
  24. import logging
  25. import multiprocessing
  26. import optparse
  27. import os
  28. import StringIO
  29. import sys
  30. import time
  31. import traceback
  32. import unittest
  33. from webkitpy.common.system.filesystem import FileSystem
  34. from webkitpy.test.finder import Finder
  35. from webkitpy.test.printer import Printer
  36. from webkitpy.test.runner import Runner, unit_test_name
  37. _log = logging.getLogger(__name__)
  38. def main():
  39. up = os.path.dirname
  40. webkit_root = up(up(up(up(up(os.path.abspath(__file__))))))
  41. tester = Tester()
  42. tester.add_tree(os.path.join(webkit_root, 'Tools', 'Scripts'), 'webkitpy')
  43. tester.add_tree(os.path.join(webkit_root, 'Source', 'WebKit2', 'Scripts'), 'webkit2')
  44. tester.skip(('webkitpy.common.checkout.scm.scm_unittest',), 'are really, really, slow', 31818)
  45. if sys.platform == 'win32':
  46. tester.skip(('webkitpy.common.checkout', 'webkitpy.common.config', 'webkitpy.tool'), 'fail horribly on win32', 54526)
  47. # This only needs to run on Unix, so don't worry about win32 for now.
  48. appengine_sdk_path = '/usr/local/google_appengine'
  49. if os.path.exists(appengine_sdk_path):
  50. if not appengine_sdk_path in sys.path:
  51. sys.path.append(appengine_sdk_path)
  52. import dev_appserver
  53. from google.appengine.dist import use_library
  54. use_library('django', '1.2')
  55. dev_appserver.fix_sys_path()
  56. tester.add_tree(os.path.join(webkit_root, 'Tools', 'QueueStatusServer'))
  57. else:
  58. _log.info('Skipping QueueStatusServer tests; the Google AppEngine Python SDK is not installed.')
  59. return not tester.run()
  60. class Tester(object):
  61. def __init__(self, filesystem=None):
  62. self.finder = Finder(filesystem or FileSystem())
  63. self.printer = Printer(sys.stderr)
  64. self._options = None
  65. def add_tree(self, top_directory, starting_subdirectory=None):
  66. self.finder.add_tree(top_directory, starting_subdirectory)
  67. def skip(self, names, reason, bugid):
  68. self.finder.skip(names, reason, bugid)
  69. def _parse_args(self, argv=None):
  70. parser = optparse.OptionParser(usage='usage: %prog [options] [args...]')
  71. parser.add_option('-a', '--all', action='store_true', default=False,
  72. help='run all the tests')
  73. parser.add_option('-c', '--coverage', action='store_true', default=False,
  74. help='generate code coverage info (requires http://pypi.python.org/pypi/coverage)')
  75. parser.add_option('-i', '--integration-tests', action='store_true', default=False,
  76. help='run integration tests as well as unit tests'),
  77. parser.add_option('-j', '--child-processes', action='store', type='int', default=(1 if sys.platform == 'win32' else multiprocessing.cpu_count()),
  78. help='number of tests to run in parallel (default=%default)')
  79. parser.add_option('-p', '--pass-through', action='store_true', default=False,
  80. help='be debugger friendly by passing captured output through to the system')
  81. parser.add_option('-q', '--quiet', action='store_true', default=False,
  82. help='run quietly (errors, warnings, and progress only)')
  83. parser.add_option('-t', '--timing', action='store_true', default=False,
  84. help='display per-test execution time (implies --verbose)')
  85. parser.add_option('-v', '--verbose', action='count', default=0,
  86. help='verbose output (specify once for individual test results, twice for debug messages)')
  87. parser.epilog = ('[args...] is an optional list of modules, test_classes, or individual tests. '
  88. 'If no args are given, all the tests will be run.')
  89. return parser.parse_args(argv)
  90. def run(self):
  91. self._options, args = self._parse_args()
  92. self.printer.configure(self._options)
  93. self.finder.clean_trees()
  94. names = self.finder.find_names(args, self._options.all)
  95. if not names:
  96. _log.error('No tests to run')
  97. return False
  98. return self._run_tests(names)
  99. def _run_tests(self, names):
  100. # Make sure PYTHONPATH is set up properly.
  101. sys.path = self.finder.additional_paths(sys.path) + sys.path
  102. # We autoinstall everything up so that we can run tests concurrently
  103. # and not have to worry about autoinstalling packages concurrently.
  104. self.printer.write_update("Checking autoinstalled packages ...")
  105. from webkitpy.thirdparty import autoinstall_everything
  106. installed_something = autoinstall_everything()
  107. # FIXME: There appears to be a bug in Python 2.6.1 that is causing multiprocessing
  108. # to hang after we install the packages in a clean checkout.
  109. if installed_something:
  110. _log.warning("We installed new packages, so running things serially at first")
  111. self._options.child_processes = 1
  112. if self._options.coverage:
  113. _log.warning("Checking code coverage, so running things serially")
  114. self._options.child_processes = 1
  115. import webkitpy.thirdparty.autoinstalled.coverage as coverage
  116. cov = coverage.coverage(omit=["/usr/*", "*/webkitpy/thirdparty/autoinstalled/*", "*/webkitpy/thirdparty/BeautifulSoup.py"])
  117. cov.start()
  118. self.printer.write_update("Checking imports ...")
  119. if not self._check_imports(names):
  120. return False
  121. self.printer.write_update("Finding the individual test methods ...")
  122. loader = _Loader()
  123. parallel_tests, serial_tests = self._test_names(loader, names)
  124. self.printer.write_update("Running the tests ...")
  125. self.printer.num_tests = len(parallel_tests) + len(serial_tests)
  126. start = time.time()
  127. test_runner = Runner(self.printer, loader)
  128. test_runner.run(parallel_tests, self._options.child_processes)
  129. test_runner.run(serial_tests, 1)
  130. self.printer.print_result(time.time() - start)
  131. if self._options.coverage:
  132. cov.stop()
  133. cov.save()
  134. cov.report(show_missing=False)
  135. return not self.printer.num_errors and not self.printer.num_failures
  136. def _check_imports(self, names):
  137. for name in names:
  138. if self.finder.is_module(name):
  139. # if we failed to load a name and it looks like a module,
  140. # try importing it directly, because loadTestsFromName()
  141. # produces lousy error messages for bad modules.
  142. try:
  143. __import__(name)
  144. except ImportError:
  145. _log.fatal('Failed to import %s:' % name)
  146. self._log_exception()
  147. return False
  148. return True
  149. def _test_names(self, loader, names):
  150. parallel_test_method_prefixes = ['test_']
  151. serial_test_method_prefixes = ['serial_test_']
  152. if self._options.integration_tests:
  153. parallel_test_method_prefixes.append('integration_test_')
  154. serial_test_method_prefixes.append('serial_integration_test_')
  155. parallel_tests = []
  156. loader.test_method_prefixes = parallel_test_method_prefixes
  157. for name in names:
  158. parallel_tests.extend(self._all_test_names(loader.loadTestsFromName(name, None)))
  159. serial_tests = []
  160. loader.test_method_prefixes = serial_test_method_prefixes
  161. for name in names:
  162. serial_tests.extend(self._all_test_names(loader.loadTestsFromName(name, None)))
  163. # loader.loadTestsFromName() will not verify that names begin with one of the test_method_prefixes
  164. # if the names were explicitly provided (e.g., MainTest.test_basic), so this means that any individual
  165. # tests will be included in both parallel_tests and serial_tests, and we need to de-dup them.
  166. serial_tests = list(set(serial_tests).difference(set(parallel_tests)))
  167. return (parallel_tests, serial_tests)
  168. def _all_test_names(self, suite):
  169. names = []
  170. if hasattr(suite, '_tests'):
  171. for t in suite._tests:
  172. names.extend(self._all_test_names(t))
  173. else:
  174. names.append(unit_test_name(suite))
  175. return names
  176. def _log_exception(self):
  177. s = StringIO.StringIO()
  178. traceback.print_exc(file=s)
  179. for l in s.buflist:
  180. _log.error(' ' + l.rstrip())
  181. class _Loader(unittest.TestLoader):
  182. test_method_prefixes = []
  183. def getTestCaseNames(self, testCaseClass):
  184. def isTestMethod(attrname, testCaseClass=testCaseClass):
  185. if not hasattr(getattr(testCaseClass, attrname), '__call__'):
  186. return False
  187. return (any(attrname.startswith(prefix) for prefix in self.test_method_prefixes))
  188. testFnNames = filter(isTestMethod, dir(testCaseClass))
  189. testFnNames.sort()
  190. return testFnNames
  191. if __name__ == '__main__':
  192. sys.exit(main())