runcppunittests.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. #!/usr/bin/env python
  2. #
  3. # This Source Code Form is subject to the terms of the Mozilla Public
  4. # License, v. 2.0. If a copy of the MPL was not distributed with this
  5. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. from __future__ import with_statement
  7. import sys, os, tempfile, shutil
  8. from optparse import OptionParser
  9. import manifestparser
  10. import mozprocess
  11. import mozinfo
  12. import mozcrash
  13. import mozfile
  14. import mozlog
  15. from contextlib import contextmanager
  16. from subprocess import PIPE
  17. SCRIPT_DIR = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
  18. class CPPUnitTests(object):
  19. # Time (seconds) to wait for test process to complete
  20. TEST_PROC_TIMEOUT = 900
  21. # Time (seconds) in which process will be killed if it produces no output.
  22. TEST_PROC_NO_OUTPUT_TIMEOUT = 300
  23. def run_one_test(self, prog, env, symbols_path=None, interactive=False,
  24. timeout_factor=1):
  25. """
  26. Run a single C++ unit test program.
  27. Arguments:
  28. * prog: The path to the test program to run.
  29. * env: The environment to use for running the program.
  30. * symbols_path: A path to a directory containing Breakpad-formatted
  31. symbol files for producing stack traces on crash.
  32. * timeout_factor: An optional test-specific timeout multiplier.
  33. Return True if the program exits with a zero status, False otherwise.
  34. """
  35. basename = os.path.basename(prog)
  36. self.log.test_start(basename)
  37. with mozfile.TemporaryDirectory() as tempdir:
  38. if interactive:
  39. # For tests run locally, via mach, print output directly
  40. proc = mozprocess.ProcessHandler([prog],
  41. cwd=tempdir,
  42. env=env,
  43. storeOutput=False)
  44. else:
  45. proc = mozprocess.ProcessHandler([prog],
  46. cwd=tempdir,
  47. env=env,
  48. storeOutput=True,
  49. processOutputLine=lambda _: None)
  50. #TODO: After bug 811320 is fixed, don't let .run() kill the process,
  51. # instead use a timeout in .wait() and then kill to get a stack.
  52. test_timeout = CPPUnitTests.TEST_PROC_TIMEOUT * timeout_factor
  53. proc.run(timeout=test_timeout,
  54. outputTimeout=CPPUnitTests.TEST_PROC_NO_OUTPUT_TIMEOUT)
  55. proc.wait()
  56. if proc.output:
  57. output = "\n%s" % "\n".join(proc.output)
  58. self.log.process_output(proc.pid, output, command=[prog])
  59. if proc.timedOut:
  60. message = "timed out after %d seconds" % CPPUnitTests.TEST_PROC_TIMEOUT
  61. self.log.test_end(basename, status='TIMEOUT', expected='PASS',
  62. message=message)
  63. return False
  64. if mozcrash.check_for_crashes(tempdir, symbols_path,
  65. test_name=basename):
  66. self.log.test_end(basename, status='CRASH', expected='PASS')
  67. return False
  68. result = proc.proc.returncode == 0
  69. if not result:
  70. self.log.test_end(basename, status='FAIL', expected='PASS',
  71. message=("test failed with return code %d" %
  72. proc.proc.returncode))
  73. else:
  74. self.log.test_end(basename, status='PASS', expected='PASS')
  75. return result
  76. def build_core_environment(self, env = {}):
  77. """
  78. Add environment variables likely to be used across all platforms, including remote systems.
  79. """
  80. env["MOZILLA_FIVE_HOME"] = self.xre_path
  81. env["MOZ_XRE_DIR"] = self.xre_path
  82. #TODO: switch this to just abort once all C++ unit tests have
  83. # been fixed to enable crash reporting
  84. env["XPCOM_DEBUG_BREAK"] = "stack-and-abort"
  85. env["MOZ_CRASHREPORTER_NO_REPORT"] = "1"
  86. return env
  87. def build_environment(self):
  88. """
  89. Create and return a dictionary of all the appropriate env variables and values.
  90. On a remote system, we overload this to set different values and are missing things like os.environ and PATH.
  91. """
  92. if not os.path.isdir(self.xre_path):
  93. raise Exception("xre_path does not exist: %s", self.xre_path)
  94. env = dict(os.environ)
  95. env = self.build_core_environment(env)
  96. pathvar = ""
  97. libpath = self.xre_path
  98. if mozinfo.os == "linux":
  99. pathvar = "LD_LIBRARY_PATH"
  100. elif mozinfo.os == "mac":
  101. applibpath = os.path.join(os.path.dirname(libpath), 'MacOS')
  102. if os.path.exists(applibpath):
  103. # Set the library load path to Contents/MacOS if we're run from
  104. # the app bundle.
  105. libpath = applibpath
  106. pathvar = "DYLD_LIBRARY_PATH"
  107. elif mozinfo.os == "win":
  108. pathvar = "PATH"
  109. if pathvar:
  110. if pathvar in env:
  111. env[pathvar] = "%s%s%s" % (libpath, os.pathsep, env[pathvar])
  112. else:
  113. env[pathvar] = libpath
  114. if mozinfo.info["asan"]:
  115. # Use llvm-symbolizer for ASan if available/required
  116. llvmsym = os.path.join(self.xre_path, "llvm-symbolizer")
  117. if os.path.isfile(llvmsym):
  118. env["ASAN_SYMBOLIZER_PATH"] = llvmsym
  119. self.log.info("ASan using symbolizer at %s" % llvmsym)
  120. else:
  121. self.log.info("Failed to find ASan symbolizer at %s" % llvmsym)
  122. # media/mtransport tests statically link in NSS, which
  123. # causes ODR violations. See bug 1215679.
  124. assert not 'ASAN_OPTIONS' in env
  125. env['ASAN_OPTIONS'] = 'detect_leaks=0:detect_odr_violation=0'
  126. return env
  127. def run_tests(self, programs, xre_path, symbols_path=None, interactive=False):
  128. """
  129. Run a set of C++ unit test programs.
  130. Arguments:
  131. * programs: An iterable containing (test path, test timeout factor) tuples
  132. * xre_path: A path to a directory containing a XUL Runtime Environment.
  133. * symbols_path: A path to a directory containing Breakpad-formatted
  134. symbol files for producing stack traces on crash.
  135. Returns True if all test programs exited with a zero status, False
  136. otherwise.
  137. """
  138. self.xre_path = xre_path
  139. self.log = mozlog.get_default_logger()
  140. self.log.suite_start(programs)
  141. env = self.build_environment()
  142. pass_count = 0
  143. fail_count = 0
  144. for prog in programs:
  145. test_path = prog[0]
  146. timeout_factor = prog[1]
  147. single_result = self.run_one_test(test_path, env, symbols_path,
  148. interactive, timeout_factor)
  149. if single_result:
  150. pass_count += 1
  151. else:
  152. fail_count += 1
  153. self.log.suite_end()
  154. # Mozharness-parseable summary formatting.
  155. self.log.info("Result summary:")
  156. self.log.info("cppunittests INFO | Passed: %d" % pass_count)
  157. self.log.info("cppunittests INFO | Failed: %d" % fail_count)
  158. return fail_count == 0
  159. class CPPUnittestOptions(OptionParser):
  160. def __init__(self):
  161. OptionParser.__init__(self)
  162. self.add_option("--xre-path",
  163. action = "store", type = "string", dest = "xre_path",
  164. default = None,
  165. help = "absolute path to directory containing XRE (probably xulrunner)")
  166. self.add_option("--symbols-path",
  167. action = "store", type = "string", dest = "symbols_path",
  168. default = None,
  169. help = "absolute path to directory containing breakpad symbols, or the URL of a zip file containing symbols")
  170. self.add_option("--manifest-path",
  171. action = "store", type = "string", dest = "manifest_path",
  172. default = None,
  173. help = "path to test manifest, if different from the path to test binaries")
  174. def extract_unittests_from_args(args, environ, manifest_path):
  175. """Extract unittests from args, expanding directories as needed"""
  176. mp = manifestparser.TestManifest(strict=True)
  177. tests = []
  178. binary_path = None
  179. if manifest_path:
  180. mp.read(manifest_path)
  181. binary_path = os.path.abspath(args[0])
  182. else:
  183. for p in args:
  184. if os.path.isdir(p):
  185. try:
  186. mp.read(os.path.join(p, 'cppunittest.ini'))
  187. except IOError:
  188. files = [os.path.abspath(os.path.join(p, x)) for x in os.listdir(p)]
  189. tests.extend((f, 1) for f in files
  190. if os.access(f, os.R_OK | os.X_OK))
  191. else:
  192. tests.append((os.path.abspath(p), 1))
  193. # we skip the existence check here because not all tests are built
  194. # for all platforms (and it will fail on Windows anyway)
  195. active_tests = mp.active_tests(exists=False, disabled=False, **environ)
  196. suffix = '.exe' if mozinfo.isWin else ''
  197. if binary_path:
  198. tests.extend([(os.path.join(binary_path, test['relpath'] + suffix), int(test.get('requesttimeoutfactor', 1))) for test in active_tests])
  199. else:
  200. tests.extend([(test['path'] + suffix, int(test.get('requesttimeoutfactor', 1))) for test in active_tests])
  201. # skip non-existing tests
  202. tests = [test for test in tests if os.path.isfile(test[0])]
  203. return tests
  204. def update_mozinfo():
  205. """walk up directories to find mozinfo.json update the info"""
  206. path = SCRIPT_DIR
  207. dirs = set()
  208. while path != os.path.expanduser('~'):
  209. if path in dirs:
  210. break
  211. dirs.add(path)
  212. path = os.path.split(path)[0]
  213. mozinfo.find_and_update_from_json(*dirs)
  214. def run_test_harness(options, args):
  215. update_mozinfo()
  216. progs = extract_unittests_from_args(args, mozinfo.info, options.manifest_path)
  217. options.xre_path = os.path.abspath(options.xre_path)
  218. tester = CPPUnitTests()
  219. result = tester.run_tests(progs, options.xre_path, options.symbols_path)
  220. return result
  221. def main():
  222. parser = CPPUnittestOptions()
  223. mozlog.commandline.add_logging_group(parser)
  224. options, args = parser.parse_args()
  225. if not args:
  226. print >>sys.stderr, """Usage: %s <test binary> [<test binary>...]""" % sys.argv[0]
  227. sys.exit(1)
  228. if not options.xre_path:
  229. print >>sys.stderr, """Error: --xre-path is required"""
  230. sys.exit(1)
  231. if options.manifest_path and len(args) > 1:
  232. print >>sys.stderr, "Error: multiple arguments not supported with --test-manifest"
  233. sys.exit(1)
  234. log = mozlog.commandline.setup_logging("cppunittests", options,
  235. {"tbpl": sys.stdout})
  236. try:
  237. result = run_test_harness(options, args)
  238. except Exception as e:
  239. log.error(str(e))
  240. result = False
  241. sys.exit(0 if result else 1)
  242. if __name__ == '__main__':
  243. main()