run-qtwebkit-tests 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
  4. #This library is free software; you can redistribute it and/or
  5. #modify it under the terms of the GNU Library General Public
  6. #License as published by the Free Software Foundation; either
  7. #version 2 of the License, or (at your option) any later version.
  8. #This library is distributed in the hope that it will be useful,
  9. #but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. #Library General Public License for more details.
  12. #You should have received a copy of the GNU Library General Public License
  13. #along with this library; see the file COPYING.LIB. If not, write to
  14. #the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  15. #Boston, MA 02110-1301, USA.
  16. from __future__ import with_statement
  17. import sys
  18. import os
  19. import re
  20. import logging
  21. from subprocess import Popen, PIPE, STDOUT
  22. from optparse import OptionParser
  23. class Log(object):
  24. def __init__(self, name):
  25. self._log = logging.getLogger(name)
  26. self.debug = self._log.debug
  27. self.warn = self._log.warn
  28. self.error = self._log.error
  29. self.exception = self._log.exception
  30. self.info = self._log.info
  31. class Options(Log):
  32. """ Option manager. It parses and checks script's parameters, sets an internal variable. """
  33. def __init__(self, args):
  34. Log.__init__(self, "Options")
  35. log = self._log
  36. opt = OptionParser("%prog [options] [PathToSearch].\nTry -h or --help.")
  37. opt.add_option("-j", "--parallel-level", action="store", type="int",
  38. dest="parallel_level", default=None,
  39. help="Number of parallel processes executing the Qt's tests. Default: cpu count.")
  40. opt.add_option("-v", "--verbose", action="store", type="int",
  41. dest="verbose", default=2,
  42. help="Verbose level (0 - quiet, 1 - errors only, 2 - infos and warnings, 3 - debug information). Default: %default.")
  43. opt.add_option("", "--tests-options", action="store", type="string",
  44. dest="tests_options", default="",
  45. help="Parameters passed to Qt's tests (for example '-eventdelay 123').")
  46. opt.add_option("-o", "--output-file", action="store", type="string",
  47. dest="output_file", default="/tmp/qtwebkittests.html",
  48. help="File where results will be stored. The file will be overwritten. Default: %default.")
  49. opt.add_option("-b", "--browser", action="store", dest="browser",
  50. default="xdg-open",
  51. help="Browser in which results will be opened. Default %default.")
  52. opt.add_option("", "--do-not-open-results", action="store_false",
  53. dest="open_results", default=True,
  54. help="The results shouldn't pop-up in a browser automatically")
  55. opt.add_option("-d", "--developer-mode", action="store_true",
  56. dest="developer", default=False,
  57. help="Special mode for debugging. In general it simulates human behavior, running all autotests. In the mode everything is executed synchronously, no html output will be generated, no changes or transformation will be applied to stderr or stdout. In this mode options; parallel-level, output-file, browser and do-not-open-results will be ignored.")
  58. opt.add_option("-t", "--timeout", action="store", type="int",
  59. dest="timeout", default=0,
  60. help="Timeout in seconds for each testsuite. Zero value means that there is not timeout. Default: %default.")
  61. opt.add_option("--release", action="store_true", dest="release", default=True,
  62. help="Run API tests in WebKitBuild/Release/... directory. It is ignored if PathToSearch is passed.")
  63. opt.add_option("--debug", action="store_false", dest="release",
  64. help="Run API tests in WebKitBuild/Debug/... directory. It is ignored if PathToSearch is passed.")
  65. opt.add_option("-2", "--webkit2", action="store_true", dest="webkit2", default=False,
  66. help="Run WebKit2 API tests. Default: Run WebKit1 API tests. It is ignored if PathToSearch is passed.")
  67. self._o, self._a = opt.parse_args(args)
  68. verbose = self._o.verbose
  69. if verbose == 0:
  70. logging.basicConfig(level=logging.CRITICAL,)
  71. elif verbose == 1:
  72. logging.basicConfig(level=logging.ERROR,)
  73. elif verbose == 2:
  74. logging.basicConfig(level=logging.INFO,)
  75. elif verbose == 3:
  76. logging.basicConfig(level=logging.DEBUG,)
  77. else:
  78. logging.basicConfig(level=logging.INFO,)
  79. log.warn("Bad verbose level, switching to default.")
  80. if self._o.release:
  81. configuration = "Release"
  82. else:
  83. configuration = "Debug"
  84. if self._o.webkit2:
  85. test_directory = "WebKit2/UIProcess/API/qt/tests/"
  86. else:
  87. test_directory = "WebKit/qt/tests/"
  88. try:
  89. if len(self._a) == 0:
  90. self._o.path = "WebKitBuild/%s/Source/%s" % (configuration, test_directory)
  91. else:
  92. if len(self._a) > 1:
  93. raise IndexError("Only one directory should be provided.")
  94. self._o.path = self._a[0]
  95. if not os.path.exists(self._o.path):
  96. raise Exception("Given path doesn't exist.")
  97. except IndexError:
  98. log.error("Bad usage. Please try -h or --help.")
  99. sys.exit(1)
  100. except Exception:
  101. log.error("Path '%s' doesn't exist", self._o.path)
  102. sys.exit(2)
  103. if self._o.developer:
  104. if not self._o.parallel_level is None:
  105. log.warn("Developer mode sets parallel-level option to one.")
  106. self._o.parallel_level = 1
  107. self._o.open_results = False
  108. def __getattr__(self, attr):
  109. """ Maps all options properties into this object (remove one level of indirection). """
  110. return getattr(self._o, attr)
  111. def run_test(args):
  112. """ Runs one given test.
  113. args should contain a tuple with 3 elements;
  114. TestSuiteResult containing full file name of an autotest executable.
  115. str with options that should be passed to the autotest executable
  116. bool if true then the stdout will be buffered and separated from the stderr, if it is false
  117. then the stdout and the stderr will be merged together and left unbuffered (the TestSuiteResult output will be None).
  118. int time after which the autotest executable would be killed
  119. """
  120. log = logging.getLogger("Exec")
  121. test_suite, options, buffered, timeout = args
  122. timer = None
  123. try:
  124. log.info("Running... %s", test_suite.test_file_name())
  125. if buffered:
  126. tst = Popen([test_suite.test_file_name()] + options.split(), stdout=PIPE, stderr=None)
  127. else:
  128. tst = Popen([test_suite.test_file_name()] + options.split(), stdout=None, stderr=STDOUT)
  129. if timeout:
  130. from threading import Timer
  131. log.debug("Setting timeout timer %i sec on %s (process %s)", timeout, test_suite.test_file_name(), tst.pid)
  132. def process_killer():
  133. try:
  134. try:
  135. tst.terminate()
  136. except AttributeError:
  137. # Workaround for python version < 2.6 it can be removed as soon as we drop support for python2.5
  138. try:
  139. import ctypes
  140. PROCESS_TERMINATE = 1
  141. handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, tst.pid)
  142. ctypes.windll.kernel32.TerminateProcess(handle, -1)
  143. ctypes.windll.kernel32.CloseHandle(handle)
  144. except AttributeError:
  145. # windll is not accessible so we are on *nix like system
  146. import signal
  147. os.kill(tst.pid, signal.SIGTERM)
  148. log.error("Timeout, process '%s' (%i) was terminated", test_suite.test_file_name(), tst.pid)
  149. except OSError, e:
  150. # the process was finished before got killed
  151. pass
  152. timer = Timer(timeout, process_killer)
  153. timer.start()
  154. except OSError, e:
  155. log.exception("Can't open an autotest file: '%s'. Skipping the test...", e.filename)
  156. else:
  157. test_suite.set_output(tst.communicate()[0]) # takes stdout only, in developer mode it would be None.
  158. log.info("Finished %s", test_suite.test_file_name())
  159. if timeout:
  160. timer.cancel()
  161. return test_suite
  162. class TestSuiteResult(object):
  163. """ Keeps information about a test. """
  164. def __init__(self):
  165. self._output = None
  166. self._test_file_name = None
  167. def set_output(self, xml):
  168. if xml:
  169. self._output = xml.strip()
  170. def output(self):
  171. return self._output
  172. def set_test_file_name(self, file_name):
  173. self._test_file_name = file_name
  174. def test_file_name(self):
  175. return self._test_file_name
  176. class Main(Log):
  177. """ The main script. All real work is done in run() method. """
  178. def __init__(self, options):
  179. Log.__init__(self, "Main")
  180. self._options = options
  181. if options.parallel_level > 1 or options.parallel_level is None:
  182. try:
  183. from multiprocessing import Pool
  184. except ImportError:
  185. self.warn("Import Error: the multiprocessing module couldn't be loaded (may be lack of python-multiprocessing package?). The Qt autotests will be executed one by one.")
  186. options.parallel_level = 1
  187. if options.parallel_level == 1:
  188. class Pool(object):
  189. """ A hack, created to avoid problems with multiprocessing module, this class is single thread replacement for the multiprocessing.Pool class. """
  190. def __init__(self, processes):
  191. pass
  192. def imap_unordered(self, func, files):
  193. return map(func, files)
  194. def map(self, func, files):
  195. return map(func, files)
  196. self._Pool = Pool
  197. def run(self):
  198. """ Find && execute && publish results of all test. "All in one" function. """
  199. # This is needed for Qt finding our QML modules. The current code makes our
  200. # two existing API tests (WK1 API and WK2 UI process API) work correctly.
  201. qml_import_path = self._options.path + "../../../../imports"
  202. qml_import_path += ":" + self._options.path + "../../../../../../imports"
  203. os.putenv("QML_IMPORT_PATH", qml_import_path)
  204. path = os.getenv("PATH")
  205. path += ":" + self._options.path + "../../../../../../bin"
  206. os.putenv("PATH", path)
  207. self.debug("Searching executables...")
  208. tests_executables = self.find_tests_paths(self._options.path)
  209. self.debug("Found: %s", len(tests_executables))
  210. self.debug("Executing tests...")
  211. results = self.run_tests(tests_executables)
  212. if not self._options.developer:
  213. self.debug("Transforming...")
  214. transformed_results = self.transform(results)
  215. self.debug("Publishing...")
  216. self.announce_results(transformed_results)
  217. def find_tests_paths(self, path):
  218. """ Finds all tests executables inside the given path. """
  219. executables = []
  220. for root, dirs, files in os.walk(path):
  221. # Check only for a file that name starts from 'tst_' and that we can execute.
  222. filtered_path = filter(lambda w: w.startswith('tst_') and os.access(os.path.join(root, w), os.X_OK), files)
  223. filtered_path = map(lambda w: os.path.join(root, w), filtered_path)
  224. for file_name in filtered_path:
  225. r = TestSuiteResult()
  226. r.set_test_file_name(file_name)
  227. executables.append(r)
  228. return executables
  229. def run_tests(self, files):
  230. """ Executes given files by using a pool of workers. """
  231. workers = self._Pool(processes=self._options.parallel_level)
  232. # to each file add options.
  233. self.debug("Using %s the workers pool, number of workers %i", repr(workers), self._options.parallel_level)
  234. package = map(lambda w: [w, self._options.tests_options, not self._options.developer, self._options.timeout], files)
  235. self.debug("Generated packages for workers: %s", repr(package))
  236. results = workers.map(run_test, package) # Collects results.
  237. return results
  238. def transform(self, results):
  239. """ Transforms list of the results to specialized versions. """
  240. stdout = self.convert_to_stdout(results)
  241. html = self.convert_to_html(results)
  242. return {"stdout": stdout, "html": html}
  243. def announce_results(self, results):
  244. """ Shows the results. """
  245. self.announce_results_stdout(results['stdout'])
  246. self.announce_results_html(results['html'])
  247. def announce_results_stdout(self, results):
  248. """ Show the results by printing to the stdout."""
  249. print(results)
  250. def announce_results_html(self, results):
  251. """ Shows the result by creating a html file and calling a web browser to render it. """
  252. with file(self._options.output_file, 'w') as f:
  253. f.write(results)
  254. if self._options.open_results:
  255. Popen(self._options.browser + " " + self._options.output_file, stdout=None, stderr=None, shell=True)
  256. def check_crash_occurences(self, results):
  257. """ Checks if any test crashes and it sums them """
  258. totals = [0,0,0]
  259. crash_count = 0
  260. txt = []
  261. #collecting results into one container with checking crash
  262. for result in results:
  263. found = None
  264. if result.output():
  265. txt.append(result.output())
  266. found = re.search(r"([0-9]+) passed, ([0-9]+) failed, ([0-9]+) skipped", result.output())
  267. if found:
  268. totals = reduce(lambda x, y: (int(x[0]) + int(y[0]), int(x[1]) + int(y[1]), int(x[2]) + int(y[2])), (totals, found.groups()))
  269. else:
  270. txt.append('CRASHED: %s' % result.test_file_name())
  271. crash_count += 1
  272. self.warn("Missing sub-summary: %s" % result.test_file_name())
  273. txt='\n\n'.join(txt)
  274. totals = list(totals)
  275. totals.append(crash_count)
  276. totals = map(str, totals)
  277. return txt, totals
  278. def convert_to_stdout(self, results):
  279. """ Converts results, that they could be nicely presented in the stdout. """
  280. txt, totals = self.check_crash_occurences(results)
  281. totals = "%s passed, %s failed, %s skipped, %s crashed" % (totals[0], totals[1], totals[2], totals[3])
  282. txt += '\n' + '*' * 70
  283. txt += "\n**" + ("TOTALS: " + totals).center(66) + '**'
  284. txt += '\n' + '*' * 70 + '\n'
  285. return txt
  286. def convert_to_html(self, results):
  287. """ Converts results, that they could showed as a html page. """
  288. txt, totals = self.check_crash_occurences(results)
  289. txt = txt.replace('&', '&amp;').replace('<', "&lt;").replace('>', "&gt;")
  290. # Add a color and a style.
  291. txt = re.sub(r"([* ]+(Finished)[ a-z_A-Z0-9]+[*]+)",
  292. lambda w: r"",
  293. txt)
  294. txt = re.sub(r"([*]+[ a-z_A-Z0-9]+[*]+)",
  295. lambda w: "<case class='good'><br><br><b>" + w.group(0) + r"</b></case>",
  296. txt)
  297. txt = re.sub(r"(Config: Using QTest library)((.)+)",
  298. lambda w: "\n<case class='good'><br><i>" + w.group(0) + r"</i> ",
  299. txt)
  300. txt = re.sub(r"\n(PASS)((.)+)",
  301. lambda w: "</case>\n<case class='good'><br><status class='pass'>" + w.group(1) + r"</status>" + w.group(2),
  302. txt)
  303. txt = re.sub(r"\n(FAIL!)((.)+)",
  304. lambda w: "</case>\n<case class='bad'><br><status class='fail'>" + w.group(1) + r"</status>" + w.group(2),
  305. txt)
  306. txt = re.sub(r"\n(XPASS)((.)+)",
  307. lambda w: "</case>\n<case class='bad'><br><status class='xpass'>" + w.group(1) + r"</status>" + w.group(2),
  308. txt)
  309. txt = re.sub(r"\n(XFAIL)((.)+)",
  310. lambda w: "</case>\n<case class='good'><br><status class='xfail'>" + w.group(1) + r"</status>" + w.group(2),
  311. txt)
  312. txt = re.sub(r"\n(SKIP)((.)+)",
  313. lambda w: "</case>\n<case class='good'><br><status class='xfail'>" + w.group(1) + r"</status>" + w.group(2),
  314. txt)
  315. txt = re.sub(r"\n(QWARN)((.)+)",
  316. lambda w: "</case>\n<case class='bad'><br><status class='warn'>" + w.group(1) + r"</status>" + w.group(2),
  317. txt)
  318. txt = re.sub(r"\n(RESULT)((.)+)",
  319. lambda w: "</case>\n<case class='good'><br><status class='benchmark'>" + w.group(1) + r"</status>" + w.group(2),
  320. txt)
  321. txt = re.sub(r"\n(QFATAL|CRASHED)((.)+)",
  322. lambda w: "</case>\n<case class='bad'><br><status class='crash'>" + w.group(1) + r"</status>" + w.group(2),
  323. txt)
  324. txt = re.sub(r"\n(Totals:)([0-9', a-z]*)",
  325. lambda w: "</case>\n<case class='good'><br><b>" + w.group(1) + r"</b>" + w.group(2) + "</case>",
  326. txt)
  327. # Find total count of failed, skipped, passed and crashed tests.
  328. totals = "%s passed, %s failed, %s skipped, %s crashed." % (totals[0], totals[1], totals[2], totals[3])
  329. # Create a header of the html source.
  330. txt = """
  331. <html>
  332. <head>
  333. <script>
  334. function init() {
  335. // Try to find the right styleSheet (this document could be embedded in an other html doc)
  336. for (i = document.styleSheets.length - 1; i >= 0; --i) {
  337. if (document.styleSheets[i].cssRules[0].selectorText == "case.good") {
  338. resultStyleSheet = i;
  339. return;
  340. }
  341. }
  342. // The styleSheet hasn't been found, but it should be the last one.
  343. resultStyleSheet = document.styleSheets.length - 1;
  344. }
  345. function hide() {
  346. document.styleSheets[resultStyleSheet].cssRules[0].style.display='none';
  347. }
  348. function show() {
  349. document.styleSheets[resultStyleSheet].cssRules[0].style.display='';
  350. }
  351. </script>
  352. <style type="text/css">
  353. case.good {color:black}
  354. case.bad {color:black}
  355. status.pass {color:green}
  356. status.crash {color:red}
  357. status.fail {color:red}
  358. status.xpass {color:663300}
  359. status.xfail {color:004500}
  360. status.benchmark {color:000088}
  361. status.warn {color:orange}
  362. status.crash {color:red; text-decoration:blink; background-color:black}
  363. </style>
  364. </head>
  365. <body onload="init()">
  366. <center>
  367. <h1>Qt's autotests results</h1>%(totals)s<br>
  368. <hr>
  369. <form>
  370. <input type="button" value="Show failures only" onclick="hide()"/>
  371. &nbsp;
  372. <input type="button" value="Show all" onclick="show()"/>
  373. </form>
  374. </center>
  375. <hr>
  376. %(results)s
  377. </body>
  378. </html>""" % {"totals": totals, "results": txt}
  379. return txt
  380. if __name__ == '__main__':
  381. options = Options(sys.argv[1:])
  382. main = Main(options)
  383. main.run()