Bug 1893067 - Add actions key to glean urlbar metrics. r=mak,urlbar-reviewers
[gecko.git] / testing / gtest / rungtests.py
blobde035eca3e18fe3fb94d4742381bef5a272f7d94
1 #!/usr/bin/env python
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/.
7 import argparse
8 import os
9 import sys
11 import mozcrash
12 import mozinfo
13 import mozlog
14 import mozprocess
15 from mozrunner.utils import get_stack_fixer_function
17 log = mozlog.unstructured.getLogger("gtest")
20 class GTests(object):
21 # Time (seconds) in which process will be killed if it produces no output.
22 TEST_PROC_NO_OUTPUT_TIMEOUT = 300
24 def gtest_timeout_value(self):
25 # Time (seconds) to wait for test process to complete
26 if mozinfo.info["tsan"]:
27 return 3600
28 else:
29 return 2400
31 def run_gtest(
32 self,
33 prog,
34 xre_path,
35 cwd,
36 symbols_path=None,
37 utility_path=None,
39 """
40 Run a single C++ unit test program.
42 Arguments:
43 * prog: The path to the test program to run.
44 * env: The environment to use for running the program.
45 * cwd: The directory to run tests from (support files will be found
46 in this direcotry).
47 * symbols_path: A path to a directory containing Breakpad-formatted
48 symbol files for producing stack traces on crash.
49 * utility_path: A path to a directory containing utility programs.
50 currently used to locate a stack fixer to provide
51 symbols symbols for assertion stacks.
53 Return True if the program exits with a zero status, False otherwise.
54 """
55 self.xre_path = xre_path
56 env = self.build_environment()
57 log.info("Running gtest")
59 if cwd and not os.path.isdir(cwd):
60 os.makedirs(cwd)
62 stack_fixer = None
63 if utility_path:
64 stack_fixer = get_stack_fixer_function(utility_path, symbols_path)
66 GTests.run_gtest.timed_out = False
68 def output_line_handler(proc, line):
69 if stack_fixer:
70 print(stack_fixer(line))
71 else:
72 print(line)
74 def proc_timeout_handler(proc):
75 GTests.run_gtest.timed_out = True
76 log.testFail(
77 "gtest | timed out after %d seconds", self.gtest_timeout_value()
79 mozcrash.kill_and_get_minidump(proc.pid, cwd, utility_path)
81 def output_timeout_handler(proc):
82 GTests.run_gtest.timed_out = True
83 log.testFail(
84 "gtest | timed out after %d seconds without output",
85 GTests.TEST_PROC_NO_OUTPUT_TIMEOUT,
87 mozcrash.kill_and_get_minidump(proc.pid, cwd, utility_path)
89 proc = mozprocess.run_and_wait(
90 [prog, "-unittest", "--gtest_death_test_style=threadsafe"],
91 cwd=cwd,
92 env=env,
93 output_line_handler=output_line_handler,
94 timeout=self.gtest_timeout_value(),
95 timeout_handler=proc_timeout_handler,
96 output_timeout=GTests.TEST_PROC_NO_OUTPUT_TIMEOUT,
97 output_timeout_handler=output_timeout_handler,
100 log.info("gtest | process wait complete, returncode=%s" % proc.returncode)
101 if mozcrash.check_for_crashes(cwd, symbols_path, test_name="gtest"):
102 # mozcrash will output the log failure line for us.
103 return False
104 if GTests.run_gtest.timed_out:
105 return False
106 result = proc.returncode == 0
107 if not result:
108 log.testFail("gtest | test failed with return code %d", proc.returncode)
109 return result
111 def build_core_environment(self, env={}):
113 Add environment variables likely to be used across all platforms, including remote systems.
115 env["MOZ_XRE_DIR"] = self.xre_path
116 env["MOZ_GMP_PATH"] = os.pathsep.join(
117 os.path.join(self.xre_path, p, "1.0")
118 for p in ("gmp-fake", "gmp-fakeopenh264")
120 env["XPCOM_DEBUG_BREAK"] = "stack-and-abort"
121 env["MOZ_CRASHREPORTER_NO_REPORT"] = "1"
122 env["MOZ_CRASHREPORTER"] = "1"
123 env["MOZ_DISABLE_NONLOCAL_CONNECTIONS"] = "1"
124 env["MOZ_RUN_GTEST"] = "1"
125 # Normally we run with GTest default output, override this to use the TBPL test format.
126 env["MOZ_TBPL_PARSER"] = "1"
128 if not mozinfo.has_sandbox:
129 # Bug 1082193 - This is horrible. Our linux build boxes run CentOS 6,
130 # which is too old to support sandboxing. Disable sandbox for gtests
131 # on machines which don't support sandboxing until they can be
132 # upgraded, or gtests are run on test machines instead.
133 env["MOZ_DISABLE_GMP_SANDBOX"] = "1"
135 return env
137 def build_environment(self):
139 Create and return a dictionary of all the appropriate env variables
140 and values. On a remote system, we overload this to set different
141 values and are missing things like os.environ and PATH.
143 if not os.path.isdir(self.xre_path):
144 raise Exception("xre_path does not exist: %s", self.xre_path)
145 env = dict(os.environ)
146 env = self.build_core_environment(env)
147 env["PERFHERDER_ALERTING_ENABLED"] = "1"
148 pathvar = ""
149 if mozinfo.os == "linux":
150 pathvar = "LD_LIBRARY_PATH"
151 # disable alerts for unstable tests (Bug 1369807)
152 del env["PERFHERDER_ALERTING_ENABLED"]
153 elif mozinfo.os == "mac":
154 pathvar = "DYLD_LIBRARY_PATH"
155 elif mozinfo.os == "win":
156 pathvar = "PATH"
157 if pathvar:
158 if pathvar in env:
159 env[pathvar] = "%s%s%s" % (self.xre_path, os.pathsep, env[pathvar])
160 else:
161 env[pathvar] = self.xre_path
163 symbolizer_path = None
164 if mozinfo.info["asan"]:
165 symbolizer_path = "ASAN_SYMBOLIZER_PATH"
166 elif mozinfo.info["tsan"]:
167 symbolizer_path = "TSAN_SYMBOLIZER_PATH"
169 if symbolizer_path is not None:
170 # Use llvm-symbolizer for ASan/TSan if available/required
171 if symbolizer_path in env and os.path.isfile(env[symbolizer_path]):
172 llvmsym = env[symbolizer_path]
173 else:
174 llvmsym = os.path.join(
175 self.xre_path, "llvm-symbolizer" + mozinfo.info["bin_suffix"]
177 if os.path.isfile(llvmsym):
178 env[symbolizer_path] = llvmsym
179 log.info("Using LLVM symbolizer at %s", llvmsym)
180 else:
181 # This should be |testFail| instead of |info|. See bug 1050891.
182 log.info("Failed to find LLVM symbolizer at %s", llvmsym)
184 # webrender needs gfx.webrender.all=true, gtest doesn't use prefs
185 env["MOZ_WEBRENDER"] = "1"
186 env["MOZ_ACCELERATED"] = "1"
188 return env
191 class gtestOptions(argparse.ArgumentParser):
192 def __init__(self):
193 super(gtestOptions, self).__init__()
195 self.add_argument(
196 "--cwd",
197 dest="cwd",
198 default=os.getcwd(),
199 help="absolute path to directory from which " "to run the binary",
201 self.add_argument(
202 "--xre-path",
203 dest="xre_path",
204 default=None,
205 help="absolute path to directory containing XRE " "(probably xulrunner)",
207 self.add_argument(
208 "--symbols-path",
209 dest="symbols_path",
210 default=None,
211 help="absolute path to directory containing breakpad "
212 "symbols, or the URL of a zip file containing "
213 "symbols",
215 self.add_argument(
216 "--utility-path",
217 dest="utility_path",
218 default=None,
219 help="path to a directory containing utility program binaries",
221 self.add_argument("args", nargs=argparse.REMAINDER)
224 def update_mozinfo():
225 """walk up directories to find mozinfo.json update the info"""
226 path = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
227 dirs = set()
228 while path != os.path.expanduser("~"):
229 if path in dirs:
230 break
231 dirs.add(path)
232 path = os.path.split(path)[0]
233 mozinfo.find_and_update_from_json(*dirs)
236 def main():
237 parser = gtestOptions()
238 options = parser.parse_args()
239 args = options.args
240 if not args:
241 print("Usage: %s <binary>" % sys.argv[0])
242 sys.exit(1)
243 if not options.xre_path:
244 print("Error: --xre-path is required")
245 sys.exit(1)
246 if not options.utility_path:
247 print("Warning: --utility-path is required to process assertion stacks")
249 update_mozinfo()
250 prog = os.path.abspath(args[0])
251 options.xre_path = os.path.abspath(options.xre_path)
252 tester = GTests()
253 try:
254 result = tester.run_gtest(
255 prog,
256 options.xre_path,
257 options.cwd,
258 symbols_path=options.symbols_path,
259 utility_path=options.utility_path,
261 except Exception as e:
262 log.error(str(e))
263 result = False
264 exit_code = 0 if result else 1
265 log.info("rungtests.py exits with code %s" % exit_code)
266 sys.exit(exit_code)
269 if __name__ == "__main__":
270 main()