diff --git a/testing/mochitest/bisection.py b/testing/mochitest/bisection.py index 460d7408034..4ba3eaf2796 100644 --- a/testing/mochitest/bisection.py +++ b/testing/mochitest/bisection.py @@ -1,7 +1,9 @@ import math import mozinfo + class Bisect(object): + "Class for creating, bisecting and summarizing for --bisect-chunk option." def __init__(self, harness): @@ -34,23 +36,28 @@ class Bisect(object): if not options.totalChunks or not options.thisChunk: return tests - # The logic here is same as chunkifyTests.js, we need this for bisecting tests. + # The logic here is same as chunkifyTests.js, we need this for + # bisecting tests. if options.chunkByDir: tests_by_dir = {} test_dirs = [] for test in tests: directory = test.split("/") - directory = directory[0:min(options.chunkByDir, len(directory)-1)] + directory = directory[ + 0:min( + options.chunkByDir, + len(directory) - + 1)] directory = "/".join(directory) - if not directory in tests_by_dir: + if directory not in tests_by_dir: tests_by_dir[directory] = [test] test_dirs.append(directory) else: tests_by_dir[directory].append(test) tests_per_chunk = float(len(test_dirs)) / options.totalChunks - start = int(round((options.thisChunk-1) * tests_per_chunk)) + start = int(round((options.thisChunk - 1) * tests_per_chunk)) end = int(round((options.thisChunk) * tests_per_chunk)) test_dirs = test_dirs[start:end] return_tests = [] @@ -59,7 +66,7 @@ class Bisect(object): else: tests_per_chunk = float(len(tests)) / options.totalChunks - start = int(round((options.thisChunk-1) * tests_per_chunk)) + start = int(round((options.thisChunk - 1) * tests_per_chunk)) end = int(round(options.thisChunk * tests_per_chunk)) return_tests = tests[start:end] @@ -83,7 +90,8 @@ class Bisect(object): "This method is used to call other methods for setting up variables and getting the list of tests for bisection." if options.bisectChunk == "default": return tests - # The second condition in 'if' is required to verify that the failing test is the last one. + # The second condition in 'if' is required to verify that the failing + # test is the last one. elif 'loop' not in self.contents or not self.contents['tests'][-1].endswith(options.bisectChunk): tests = self.get_tests_for_bisection(options, tests) status = self.setup(tests) @@ -97,14 +105,16 @@ class Bisect(object): # Check whether sanity check has to be done. Also it is necessary to check whether options.bisectChunk is present # in self.expectedError as we do not want to run if it is "default". if status == -1 and options.bisectChunk in self.expectedError: - # In case we have a debug build, we don't want to run a sanity check, will take too much time. + # In case we have a debug build, we don't want to run a sanity + # check, will take too much time. if mozinfo.info['debug']: return status testBleedThrough = self.contents['testsToRun'][0] tests = self.contents['totalTests'] tests.remove(testBleedThrough) - # To make sure that the failing test is dependent on some other test. + # To make sure that the failing test is dependent on some other + # test. if options.bisectChunk in testBleedThrough: return status @@ -133,7 +143,7 @@ class Bisect(object): # self.contents['result'] will be expected error only if it fails. elif self.contents['result'] == "FAIL": self.contents['tests'] = self.contents['testsToRun'] - status = 1 # for initializing + status = 1 # for initializing # initialize if status: @@ -189,22 +199,35 @@ class Bisect(object): def summarize_chunk(self, options): "This method is used summarize the results after the list of tests is run." if options.bisectChunk == "default": - # if no expectedError that means all the tests have successfully passed. + # if no expectedError that means all the tests have successfully + # passed. if len(self.expectedError) == 0: return -1 options.bisectChunk = self.expectedError.keys()[0] - self.summary.append("\tFound Error in test: %s" % options.bisectChunk) + self.summary.append( + "\tFound Error in test: %s" % + options.bisectChunk) return 0 - # If options.bisectChunk is not in self.result then we need to move to the next run. + # If options.bisectChunk is not in self.result then we need to move to + # the next run. if options.bisectChunk not in self.result: return -1 self.summary.append("\tPass %d:" % self.contents['loop']) if len(self.contents['testsToRun']) > 1: - self.summary.append("\t\t%d test files(start,end,failing). [%s, %s, %s]" % (len(self.contents['testsToRun']), self.contents['testsToRun'][0], self.contents['testsToRun'][-2], self.contents['testsToRun'][-1])) + self.summary.append( + "\t\t%d test files(start,end,failing). [%s, %s, %s]" % (len( + self.contents['testsToRun']), + self.contents['testsToRun'][0], + self.contents['testsToRun'][ + -2], + self.contents['testsToRun'][ + -1])) else: - self.summary.append("\t\t1 test file [%s]" % self.contents['testsToRun'][0]) + self.summary.append( + "\t\t1 test file [%s]" % + self.contents['testsToRun'][0]) return self.check_for_intermittent(options) if self.result[options.bisectChunk] == "PASS": @@ -217,23 +240,32 @@ class Bisect(object): elif self.result[options.bisectChunk] == "FAIL": if 'expectedError' not in self.contents: - self.summary.append("\t\t%s failed." % self.contents['testsToRun'][-1]) - self.contents['expectedError'] = self.expectedError[options.bisectChunk] + self.summary.append("\t\t%s failed." % + self.contents['testsToRun'][-1]) + self.contents['expectedError'] = self.expectedError[ + options.bisectChunk] status = 0 elif self.expectedError[options.bisectChunk] == self.contents['expectedError']: - self.summary.append("\t\t%s failed with expected error." % self.contents['testsToRun'][-1]) + self.summary.append( + "\t\t%s failed with expected error." % self.contents['testsToRun'][-1]) self.contents['result'] = "FAIL" status = 0 - # This code checks for test-bleedthrough. Should work for any algorithm. + # This code checks for test-bleedthrough. Should work for any + # algorithm. numberOfTests = len(self.contents['testsToRun']) if numberOfTests < 3: - # This means that only 2 tests are run. Since the last test is the failing test itself therefore the bleedthrough test is the first test - self.summary.append("TEST-UNEXPECTED-FAIL | %s | Bleedthrough detected, this test is the root cause for many of the above failures" % self.contents['testsToRun'][0]) + # This means that only 2 tests are run. Since the last test + # is the failing test itself therefore the bleedthrough + # test is the first test + self.summary.append( + "TEST-UNEXPECTED-FAIL | %s | Bleedthrough detected, this test is the root cause for many of the above failures" % + self.contents['testsToRun'][0]) status = -1 else: - self.summary.append("\t\t%s failed with different error." % self.contents['testsToRun'][-1]) + self.summary.append( + "\t\t%s failed with different error." % self.contents['testsToRun'][-1]) status = -1 return status @@ -241,7 +273,9 @@ class Bisect(object): def check_for_intermittent(self, options): "This method is used to check whether a test is an intermittent." if self.result[options.bisectChunk] == "PASS": - self.summary.append("\t\tThe test %s passed." % self.contents['testsToRun'][0]) + self.summary.append( + "\t\tThe test %s passed." % + self.contents['testsToRun'][0]) if self.repeat > 0: # loop is set to 1 to again run the single test. self.contents['loop'] = 1 @@ -256,7 +290,9 @@ class Bisect(object): self.contents['loop'] = 2 return 1 elif self.result[options.bisectChunk] == "FAIL": - self.summary.append("\t\tThe test %s failed." % self.contents['testsToRun'][0]) + self.summary.append( + "\t\tThe test %s failed." % + self.contents['testsToRun'][0]) self.failcount += 1 self.contents['loop'] = 1 self.repeat -= 1 @@ -269,7 +305,9 @@ class Bisect(object): return -1 return 0 else: - self.summary.append("TEST-UNEXPECTED-FAIL | %s | Bleedthrough detected, this test is the root cause for many of the above failures" % self.contents['testsToRun'][0]) + self.summary.append( + "TEST-UNEXPECTED-FAIL | %s | Bleedthrough detected, this test is the root cause for many of the above failures" % + self.contents['testsToRun'][0]) return -1 def print_summary(self): diff --git a/testing/mochitest/mach_commands.py b/testing/mochitest/mach_commands.py index ae077fa7aa5..ee7b64a0206 100644 --- a/testing/mochitest/mach_commands.py +++ b/testing/mochitest/mach_commands.py @@ -81,6 +81,7 @@ FLAVORS = { class MochitestRunner(MozbuildObject): + """Easily run mochitests. This currently contains just the basics for running mochitests. We may want @@ -91,8 +92,12 @@ class MochitestRunner(MozbuildObject): import mozinfo appname = 'webapprt-stub' + mozinfo.info.get('bin_suffix', '') if sys.platform.startswith('darwin'): - appname = os.path.join(self.distdir, self.substs['MOZ_MACBUNDLE_NAME'], - 'Contents', 'Resources', appname) + appname = os.path.join( + self.distdir, + self.substs['MOZ_MACBUNDLE_NAME'], + 'Contents', + 'Resources', + appname) else: appname = os.path.join(self.distdir, 'bin', appname) return appname @@ -106,12 +111,24 @@ class MochitestRunner(MozbuildObject): sys.path.append(build_path) self.tests_dir = os.path.join(self.topobjdir, '_tests') - self.mochitest_dir = os.path.join(self.tests_dir, 'testing', 'mochitest') + self.mochitest_dir = os.path.join( + self.tests_dir, + 'testing', + 'mochitest') self.bin_dir = os.path.join(self.topobjdir, 'dist', 'bin') - def run_b2g_test(self, test_paths=None, b2g_home=None, xre_path=None, - total_chunks=None, this_chunk=None, no_window=None, - repeat=0, run_until_failure=False, chrome=False, **kwargs): + def run_b2g_test( + self, + test_paths=None, + b2g_home=None, + xre_path=None, + total_chunks=None, + this_chunk=None, + no_window=None, + repeat=0, + run_until_failure=False, + chrome=False, + **kwargs): """Runs a b2g mochitest. test_paths is an enumerable of paths to tests. It can be a relative path @@ -137,7 +154,7 @@ class MochitestRunner(MozbuildObject): path = os.path.join(self.mochitest_dir, 'runtestsb2g.py') with open(path, 'r') as fh: imp.load_module('mochitest', fh, path, - ('.py', 'r', imp.PY_SOURCE)) + ('.py', 'r', imp.PY_SOURCE)) import mochitest from mochitest_options import B2GOptions @@ -147,11 +164,19 @@ class MochitestRunner(MozbuildObject): if test_path: if chrome: - test_root_file = mozpack.path.join(self.mochitest_dir, 'chrome', test_path) + test_root_file = mozpack.path.join( + self.mochitest_dir, + 'chrome', + test_path) else: - test_root_file = mozpack.path.join(self.mochitest_dir, 'tests', test_path) + test_root_file = mozpack.path.join( + self.mochitest_dir, + 'tests', + test_path) if not os.path.exists(test_root_file): - print('Specified test path does not exist: %s' % test_root_file) + print( + 'Specified test path does not exist: %s' % + test_root_file) return 1 options.testPath = test_path @@ -163,7 +188,9 @@ class MochitestRunner(MozbuildObject): options.repeat = repeat options.runUntilFailure = run_until_failure - options.symbolsPath = os.path.join(self.distdir, 'crashreporter-symbols') + options.symbolsPath = os.path.join( + self.distdir, + 'crashreporter-symbols') options.consoleLevel = 'INFO' if conditions.is_b2g_desktop(self): @@ -190,15 +217,46 @@ class MochitestRunner(MozbuildObject): options.chrome = chrome return mochitest.run_remote_mochitests(parser, options) - def run_desktop_test(self, context, suite=None, test_paths=None, debugger=None, - debugger_args=None, slowscript=False, screenshot_on_fail = False, shuffle=False, closure_behaviour='auto', - rerun_failures=False, no_autorun=False, repeat=0, run_until_failure=False, - slow=False, chunk_by_dir=0, total_chunks=None, this_chunk=None, extraPrefs=[], - jsdebugger=False, debug_on_failure=False, start_at=None, end_at=None, - e10s=False, strict_content_sandbox=False, nested_oop=False, dmd=False, dump_output_directory=None, - dump_about_memory_after_test=False, dump_dmd_after_test=False, - install_extension=None, quiet=False, environment=[], app_override=None, bisectChunk=None, runByDir=False, - useTestMediaDevices=False, timeout=None, **kwargs): + def run_desktop_test( + self, + context, + suite=None, + test_paths=None, + debugger=None, + debugger_args=None, + slowscript=False, + screenshot_on_fail=False, + shuffle=False, + closure_behaviour='auto', + rerun_failures=False, + no_autorun=False, + repeat=0, + run_until_failure=False, + slow=False, + chunk_by_dir=0, + total_chunks=None, + this_chunk=None, + extraPrefs=[], + jsdebugger=False, + debug_on_failure=False, + start_at=None, + end_at=None, + e10s=False, + strict_content_sandbox=False, + nested_oop=False, + dmd=False, + dump_output_directory=None, + dump_about_memory_after_test=False, + dump_dmd_after_test=False, + install_extension=None, + quiet=False, + environment=[], + app_override=None, + bisectChunk=None, + runByDir=False, + useTestMediaDevices=False, + timeout=None, + **kwargs): """Runs a mochitest. test_paths are path to tests. They can be a relative path from the @@ -227,9 +285,12 @@ class MochitestRunner(MozbuildObject): # Make absolute paths relative before calling os.chdir() below. if test_paths: - test_paths = [self._wrap_path_argument(p).relpath() if os.path.isabs(p) else p for p in test_paths] + test_paths = [self._wrap_path_argument( + p).relpath() if os.path.isabs(p) else p for p in test_paths] - failure_file_path = os.path.join(self.statedir, 'mochitest_failures.json') + failure_file_path = os.path.join( + self.statedir, + 'mochitest_failures.json') if rerun_failures and not os.path.exists(failure_file_path): print('No failure file present. Did you run mochitests before?') @@ -241,7 +302,7 @@ class MochitestRunner(MozbuildObject): path = os.path.join(self.mochitest_dir, 'runtests.py') with open(path, 'r') as fh: imp.load_module('mochitest', fh, path, - ('.py', 'r', imp.PY_SOURCE)) + ('.py', 'r', imp.PY_SOURCE)) import mochitest from manifestparser import TestManifest @@ -253,7 +314,7 @@ class MochitestRunner(MozbuildObject): # Automation installs its own stream handler to stdout. Since we want # all logging to go through us, we just remove their handler. remove_handlers = [l for l in logging.getLogger().handlers - if isinstance(l, logging.StreamHandler)] + if isinstance(l, logging.StreamHandler)] for handler in remove_handlers: logging.getLogger().removeHandler(handler) @@ -308,7 +369,9 @@ class MochitestRunner(MozbuildObject): options.runSlower = slow options.testingModulesDir = os.path.join(self.tests_dir, 'modules') options.extraProfileFiles.append(os.path.join(self.distdir, 'plugins')) - options.symbolsPath = os.path.join(self.distdir, 'crashreporter-symbols') + options.symbolsPath = os.path.join( + self.distdir, + 'crashreporter-symbols') options.chunkByDir = chunk_by_dir options.totalChunks = total_chunks options.thisChunk = this_chunk @@ -329,11 +392,14 @@ class MochitestRunner(MozbuildObject): options.runByDir = runByDir options.useTestMediaDevices = useTestMediaDevices if timeout: - options.timeout = int(timeout) + options.timeout = int(timeout) options.failureFile = failure_file_path - if install_extension != None: - options.extensionsToInstall = [os.path.join(self.topsrcdir,install_extension)] + if install_extension is not None: + options.extensionsToInstall = [ + os.path.join( + self.topsrcdir, + install_extension)] for k, v in kwargs.iteritems(): setattr(options, k, v) @@ -341,18 +407,22 @@ class MochitestRunner(MozbuildObject): if test_paths: resolver = self._spawn(TestResolver) - tests = list(resolver.resolve_tests(paths=test_paths, flavor=flavor)) + tests = list( + resolver.resolve_tests( + paths=test_paths, + flavor=flavor)) if not tests: print('No tests could be found in the path specified. Please ' - 'specify a path that is a test file or is a directory ' - 'containing tests.') + 'specify a path that is a test file or is a directory ' + 'containing tests.') return 1 manifest = TestManifest() manifest.tests.extend(tests) - if len(tests) == 1 and closure_behaviour == 'auto' and suite == 'plain': + if len( + tests) == 1 and closure_behaviour == 'auto' and suite == 'plain': options.closeWhenDone = False options.manifestFile = manifest @@ -364,7 +434,7 @@ class MochitestRunner(MozbuildObject): options.debugger = debugger if debugger_args: - if options.debugger == None: + if options.debugger is None: print("--debugger-args passed, but no debugger specified.") return 1 options.debuggerArgs = debugger_args @@ -375,14 +445,22 @@ class MochitestRunner(MozbuildObject): elif app_override: options.app = app_override if options.gmp_path is None: - # Need to fix the location of gmp_fake which might not be shipped in the binary + # Need to fix the location of gmp_fake which might not be + # shipped in the binary bin_path = self.get_binary_path() - options.gmp_path = os.path.join(os.path.dirname(bin_path), 'gmp-fake', '1.0') + options.gmp_path = os.path.join( + os.path.dirname(bin_path), + 'gmp-fake', + '1.0') options.gmp_path += os.pathsep - options.gmp_path += os.path.join(os.path.dirname(bin_path), 'gmp-clearkey', '0.1') + options.gmp_path += os.path.join( + os.path.dirname(bin_path), + 'gmp-clearkey', + '0.1') - - logger_options = {key: value for key, value in vars(options).iteritems() if key.startswith('log')} + logger_options = { + key: value for key, + value in vars(options).iteritems() if key.startswith('log')} runner = mochitest.Mochitest(logger_options) options = opts.verifyOptions(options, runner) @@ -414,12 +492,17 @@ def MochitestCommand(func): # (modified) function. Here, we chain decorators onto the passed in # function. - debugger = CommandArgument('--debugger', '-d', metavar='DEBUGGER', + debugger = CommandArgument( + '--debugger', + '-d', + metavar='DEBUGGER', help='Debugger binary to run test in. Program name or path.') func = debugger(func) - debugger_args = CommandArgument('--debugger-args', - metavar='DEBUGGER_ARGS', help='Arguments to pass to the debugger.') + debugger_args = CommandArgument( + '--debugger-args', + metavar='DEBUGGER_ARGS', + help='Arguments to pass to the debugger.') func = debugger_args(func) # Bug 933807 introduced JS_DISABLE_SLOW_SCRIPT_SIGNALS to avoid clever @@ -427,219 +510,300 @@ def MochitestCommand(func): # code. If we don't pass this, the user will need to periodically type # "continue" to (safely) resume execution. There are ways to implement # automatic resuming; see the bug. - slowscript = CommandArgument('--slowscript', action='store_true', + slowscript = CommandArgument( + '--slowscript', + action='store_true', help='Do not set the JS_DISABLE_SLOW_SCRIPT_SIGNALS env variable; when not set, recoverable but misleading SIGSEGV instances may occur in Ion/Odin JIT code') func = slowscript(func) - screenshot_on_fail = CommandArgument('--screenshot-on-fail', action='store_true', + screenshot_on_fail = CommandArgument( + '--screenshot-on-fail', + action='store_true', help='Take screenshots on all test failures. Set $MOZ_UPLOAD_DIR to a directory for storing the screenshots.') func = screenshot_on_fail(func) shuffle = CommandArgument('--shuffle', action='store_true', - help='Shuffle execution order.') + help='Shuffle execution order.') func = shuffle(func) - keep_open = CommandArgument('--keep-open', action='store_const', - dest='closure_behaviour', const='open', default='auto', + keep_open = CommandArgument( + '--keep-open', + action='store_const', + dest='closure_behaviour', + const='open', + default='auto', help='Always keep the browser open after tests complete.') func = keep_open(func) - autoclose = CommandArgument('--auto-close', action='store_const', - dest='closure_behaviour', const='close', default='auto', + autoclose = CommandArgument( + '--auto-close', + action='store_const', + dest='closure_behaviour', + const='close', + default='auto', help='Always close the browser after tests complete.') func = autoclose(func) - rerun = CommandArgument('--rerun-failures', action='store_true', + rerun = CommandArgument( + '--rerun-failures', + action='store_true', help='Run only the tests that failed during the last test run.') func = rerun(func) - autorun = CommandArgument('--no-autorun', action='store_true', + autorun = CommandArgument( + '--no-autorun', + action='store_true', help='Do not starting running tests automatically.') func = autorun(func) repeat = CommandArgument('--repeat', type=int, default=0, - help='Repeat the test the given number of times.') + help='Repeat the test the given number of times.') func = repeat(func) - runUntilFailure = CommandArgument("--run-until-failure", action='store_true', - help='Run tests repeatedly and stops on the first time a test fails. ' \ - 'Default cap is 30 runs, which can be overwritten ' \ - 'with the --repeat parameter.') + runUntilFailure = CommandArgument( + "--run-until-failure", + action='store_true', + help='Run tests repeatedly and stops on the first time a test fails. ' + 'Default cap is 30 runs, which can be overwritten ' + 'with the --repeat parameter.') func = runUntilFailure(func) slow = CommandArgument('--slow', action='store_true', - help='Delay execution between tests.') + help='Delay execution between tests.') func = slow(func) - end_at = CommandArgument('--end-at', type=str, + end_at = CommandArgument( + '--end-at', + type=str, help='Stop running the test sequence at this test.') func = end_at(func) - start_at = CommandArgument('--start-at', type=str, + start_at = CommandArgument( + '--start-at', + type=str, help='Start running the test sequence at this test.') func = start_at(func) - chunk_dir = CommandArgument('--chunk-by-dir', type=int, + chunk_dir = CommandArgument( + '--chunk-by-dir', + type=int, help='Group tests together in chunks by this many top directories.') func = chunk_dir(func) - chunk_total = CommandArgument('--total-chunks', type=int, + chunk_total = CommandArgument( + '--total-chunks', + type=int, help='Total number of chunks to split tests into.') func = chunk_total(func) - this_chunk = CommandArgument('--this-chunk', type=int, + this_chunk = CommandArgument( + '--this-chunk', + type=int, help='If running tests by chunks, the number of the chunk to run.') func = this_chunk(func) - debug_on_failure = CommandArgument('--debug-on-failure', action='store_true', - help='Breaks execution and enters the JS debugger on a test failure. ' \ - 'Should be used together with --jsdebugger.') + debug_on_failure = CommandArgument( + '--debug-on-failure', + action='store_true', + help='Breaks execution and enters the JS debugger on a test failure. ' + 'Should be used together with --jsdebugger.') func = debug_on_failure(func) setpref = CommandArgument('--setpref', default=[], action='append', - metavar='PREF=VALUE', dest='extraPrefs', - help='defines an extra user preference') + metavar='PREF=VALUE', dest='extraPrefs', + help='defines an extra user preference') func = setpref(func) - jsdebugger = CommandArgument('--jsdebugger', action='store_true', + jsdebugger = CommandArgument( + '--jsdebugger', + action='store_true', help='Start the browser JS debugger before running the test. Implies --no-autorun.') func = jsdebugger(func) - e10s = CommandArgument('--e10s', action='store_true', + e10s = CommandArgument( + '--e10s', + action='store_true', help='Run tests with electrolysis preferences and test filtering enabled.') func = e10s(func) - strict_content_sandbox = CommandArgument('--strict-content-sandbox', action='store_true', + strict_content_sandbox = CommandArgument( + '--strict-content-sandbox', + action='store_true', help='Run tests with a more strict content sandbox (Windows only).') func = strict_content_sandbox(func) - this_chunk = CommandArgument('--nested_oop', action='store_true', + this_chunk = CommandArgument( + '--nested_oop', + action='store_true', help='Run tests with nested oop preferences and test filtering enabled.') func = this_chunk(func) dmd = CommandArgument('--dmd', action='store_true', - help='Run tests with DMD active.') + help='Run tests with DMD active.') func = dmd(func) - dumpAboutMemory = CommandArgument('--dump-about-memory-after-test', action='store_true', + dumpAboutMemory = CommandArgument( + '--dump-about-memory-after-test', + action='store_true', help='Dump an about:memory log after every test.') func = dumpAboutMemory(func) dumpDMD = CommandArgument('--dump-dmd-after-test', action='store_true', - help='Dump a DMD log after every test.') + help='Dump a DMD log after every test.') func = dumpDMD(func) - dumpOutputDirectory = CommandArgument('--dump-output-directory', action='store', + dumpOutputDirectory = CommandArgument( + '--dump-output-directory', + action='store', help='Specifies the directory in which to place dumped memory reports.') func = dumpOutputDirectory(func) - path = CommandArgument('test_paths', default=None, nargs='*', + path = CommandArgument( + 'test_paths', + default=None, + nargs='*', metavar='TEST', - help='Test to run. Can be specified as a single file, a ' \ - 'directory, or omitted. If omitted, the entire test suite is ' \ - 'executed.') + help='Test to run. Can be specified as a single file, a ' + 'directory, or omitted. If omitted, the entire test suite is ' + 'executed.') func = path(func) - install_extension = CommandArgument('--install-extension', - help='Install given extension before running selected tests. ' \ - 'Parameter is a path to xpi file.') + install_extension = CommandArgument( + '--install-extension', + help='Install given extension before running selected tests. ' + 'Parameter is a path to xpi file.') func = install_extension(func) - quiet = CommandArgument('--quiet', default=False, action='store_true', + quiet = CommandArgument( + '--quiet', + default=False, + action='store_true', help='Do not print test log lines unless a failure occurs.') func = quiet(func) - setenv = CommandArgument('--setenv', default=[], action='append', - metavar='NAME=VALUE', dest='environment', - help="Sets the given variable in the application's environment") + setenv = CommandArgument( + '--setenv', + default=[], + action='append', + metavar='NAME=VALUE', + dest='environment', + help="Sets the given variable in the application's environment") func = setenv(func) - runbydir = CommandArgument('--run-by-dir', default=False, - action='store_true', - dest='runByDir', + runbydir = CommandArgument( + '--run-by-dir', + default=False, + action='store_true', + dest='runByDir', help='Run each directory in a single browser instance with a fresh profile.') func = runbydir(func) - bisect_chunk = CommandArgument('--bisect-chunk', type=str, - dest='bisectChunk', + bisect_chunk = CommandArgument( + '--bisect-chunk', + type=str, + dest='bisectChunk', help='Specify the failing test name to find the previous tests that may be causing the failure.') func = bisect_chunk(func) - test_media = CommandArgument('--use-test-media-devices', default=False, - action='store_true', - dest='useTestMediaDevices', + test_media = CommandArgument( + '--use-test-media-devices', + default=False, + action='store_true', + dest='useTestMediaDevices', help='Use test media device drivers for media testing.') func = test_media(func) - app_override = CommandArgument('--app-override', default=None, action='store', - help="Override the default binary used to run tests with the path you provide, e.g. " \ - " --app-override /usr/bin/firefox . " \ - "If you have run ./mach package beforehand, you can specify 'dist' to " \ - "run tests against the distribution bundle's binary."); + app_override = CommandArgument( + '--app-override', + default=None, + action='store', + help="Override the default binary used to run tests with the path you provide, e.g. " + " --app-override /usr/bin/firefox . " + "If you have run ./mach package beforehand, you can specify 'dist' to " + "run tests against the distribution bundle's binary.") func = app_override(func) - timeout = CommandArgument('--timeout', default=None, - help='The per-test timeout time in seconds (default: 60 seconds)'); + timeout = CommandArgument( + '--timeout', + default=None, + help='The per-test timeout time in seconds (default: 60 seconds)') func = timeout(func) return func + def B2GCommand(func): """Decorator that adds shared command arguments to b2g mochitest commands.""" - busybox = CommandArgument('--busybox', default=None, + busybox = CommandArgument( + '--busybox', + default=None, help='Path to busybox binary to install on device') func = busybox(func) logdir = CommandArgument('--logdir', default=None, - help='directory to store log files') + help='directory to store log files') func = logdir(func) profile = CommandArgument('--profile', default=None, - help='for desktop testing, the path to the \ + help='for desktop testing, the path to the \ gaia profile to use') func = profile(func) geckopath = CommandArgument('--gecko-path', default=None, - help='the path to a gecko distribution that should \ + help='the path to a gecko distribution that should \ be installed on the emulator prior to test') func = geckopath(func) - nowindow = CommandArgument('--no-window', action='store_true', default=False, + nowindow = CommandArgument( + '--no-window', + action='store_true', + default=False, help='Pass --no-window to the emulator') func = nowindow(func) sdcard = CommandArgument('--sdcard', default="10MB", - help='Define size of sdcard: 1MB, 50MB...etc') + help='Define size of sdcard: 1MB, 50MB...etc') func = sdcard(func) - marionette = CommandArgument('--marionette', default=None, + marionette = CommandArgument( + '--marionette', + default=None, help='host:port to use when connecting to Marionette') func = marionette(func) - chunk_total = CommandArgument('--total-chunks', type=int, + chunk_total = CommandArgument( + '--total-chunks', + type=int, help='Total number of chunks to split tests into.') func = chunk_total(func) - this_chunk = CommandArgument('--this-chunk', type=int, + this_chunk = CommandArgument( + '--this-chunk', + type=int, help='If running tests by chunks, the number of the chunk to run.') func = this_chunk(func) - path = CommandArgument('test_paths', default=None, nargs='*', + path = CommandArgument( + 'test_paths', + default=None, + nargs='*', metavar='TEST', - help='Test to run. Can be specified as a single file, a ' \ - 'directory, or omitted. If omitted, the entire test suite is ' \ - 'executed.') + help='Test to run. Can be specified as a single file, a ' + 'directory, or omitted. If omitted, the entire test suite is ' + 'executed.') func = path(func) repeat = CommandArgument('--repeat', type=int, default=0, - help='Repeat the test the given number of times.') + help='Repeat the test the given number of times.') func = repeat(func) - runUntilFailure = CommandArgument("--run-until-failure", action='store_true', - help='Run tests repeatedly and stops on the first time a test fails. ' \ - 'Default cap is 30 runs, which can be overwritten ' \ - 'with the --repeat parameter.') + runUntilFailure = CommandArgument( + "--run-until-failure", + action='store_true', + help='Run tests repeatedly and stops on the first time a test fails. ' + 'Default cap is 30 runs, which can be overwritten ' + 'with the --repeat parameter.') func = runUntilFailure(func) return func @@ -648,34 +812,48 @@ def B2GCommand(func): _st_parser = argparse.ArgumentParser() structured.commandline.add_logging_group(_st_parser) + @CommandProvider class MachCommands(MachCommandBase): - @Command('mochitest-plain', category='testing', - conditions=[conditions.is_firefox_or_mulet], + + @Command( + 'mochitest-plain', + category='testing', + conditions=[ + conditions.is_firefox_or_mulet], description='Run a plain mochitest (integration test, plain web page).', parser=_st_parser) @MochitestCommand def run_mochitest_plain(self, test_paths, **kwargs): return self.run_mochitest(test_paths, 'plain', **kwargs) - @Command('mochitest-chrome', category='testing', - conditions=[conditions.is_firefox], + @Command( + 'mochitest-chrome', + category='testing', + conditions=[ + conditions.is_firefox], description='Run a chrome mochitest (integration test with some XUL).', parser=_st_parser) @MochitestCommand def run_mochitest_chrome(self, test_paths, **kwargs): return self.run_mochitest(test_paths, 'chrome', **kwargs) - @Command('mochitest-browser', category='testing', - conditions=[conditions.is_firefox], + @Command( + 'mochitest-browser', + category='testing', + conditions=[ + conditions.is_firefox], description='Run a mochitest with browser chrome (integration test with a standard browser).', parser=_st_parser) @MochitestCommand def run_mochitest_browser(self, test_paths, **kwargs): return self.run_mochitest(test_paths, 'browser', **kwargs) - @Command('mochitest-devtools', category='testing', - conditions=[conditions.is_firefox], + @Command( + 'mochitest-devtools', + category='testing', + conditions=[ + conditions.is_firefox], description='Run a devtools mochitest with browser chrome (integration test with a standard browser with the devtools frame).', parser=_st_parser) @MochitestCommand @@ -683,21 +861,24 @@ class MachCommands(MachCommandBase): return self.run_mochitest(test_paths, 'devtools', **kwargs) @Command('jetpack-package', category='testing', - conditions=[conditions.is_firefox], - description='Run a jetpack package test.') + conditions=[conditions.is_firefox], + description='Run a jetpack package test.') @MochitestCommand def run_mochitest_jetpack_package(self, test_paths, **kwargs): return self.run_mochitest(test_paths, 'jetpack-package', **kwargs) @Command('jetpack-addon', category='testing', - conditions=[conditions.is_firefox], - description='Run a jetpack addon test.') + conditions=[conditions.is_firefox], + description='Run a jetpack addon test.') @MochitestCommand def run_mochitest_jetpack_addon(self, test_paths, **kwargs): return self.run_mochitest(test_paths, 'jetpack-addon', **kwargs) - @Command('mochitest-metro', category='testing', - conditions=[conditions.is_firefox], + @Command( + 'mochitest-metro', + category='testing', + conditions=[ + conditions.is_firefox], description='Run a mochitest with metro browser chrome (tests for Windows touch interface).', parser=_st_parser) @MochitestCommand @@ -705,23 +886,29 @@ class MachCommands(MachCommandBase): return self.run_mochitest(test_paths, 'metro', **kwargs) @Command('mochitest-a11y', category='testing', - conditions=[conditions.is_firefox], - description='Run an a11y mochitest (accessibility tests).', - parser=_st_parser) + conditions=[conditions.is_firefox], + description='Run an a11y mochitest (accessibility tests).', + parser=_st_parser) @MochitestCommand def run_mochitest_a11y(self, test_paths, **kwargs): return self.run_mochitest(test_paths, 'a11y', **kwargs) - @Command('webapprt-test-chrome', category='testing', - conditions=[conditions.is_firefox], + @Command( + 'webapprt-test-chrome', + category='testing', + conditions=[ + conditions.is_firefox], description='Run a webapprt chrome mochitest (Web App Runtime with the browser chrome).', parser=_st_parser) @MochitestCommand def run_mochitest_webapprt_chrome(self, test_paths, **kwargs): return self.run_mochitest(test_paths, 'webapprt-chrome', **kwargs) - @Command('webapprt-test-content', category='testing', - conditions=[conditions.is_firefox], + @Command( + 'webapprt-test-content', + category='testing', + conditions=[ + conditions.is_firefox], description='Run a webapprt content mochitest (Content rendering of the Web App Runtime).', parser=_st_parser) @MochitestCommand @@ -729,14 +916,14 @@ class MachCommands(MachCommandBase): return self.run_mochitest(test_paths, 'webapprt-content', **kwargs) @Command('mochitest', category='testing', - conditions=[conditions.is_firefox], - description='Run any flavor of mochitest (integration test).', - parser=_st_parser) + conditions=[conditions.is_firefox], + description='Run any flavor of mochitest (integration test).', + parser=_st_parser) @MochitestCommand @CommandArgument('-f', '--flavor', choices=FLAVORS.keys(), - help='Only run tests of this flavor.') + help='Only run tests of this flavor.') def run_mochitest_general(self, test_paths, flavor=None, test_objects=None, - **kwargs): + **kwargs): self._preruntest() from mozbuild.testing import TestResolver @@ -746,7 +933,7 @@ class MachCommands(MachCommandBase): else: resolver = self._spawn(TestResolver) tests = list(resolver.resolve_tests(paths=test_paths, - cwd=self._mach_context.cwd)) + cwd=self._mach_context.cwd)) # Our current approach is to group the tests by suite and then perform # an invocation for each suite. Ideally, this would be done @@ -773,8 +960,11 @@ class MachCommands(MachCommandBase): mochitest = self._spawn(MochitestRunner) overall = None for suite, tests in sorted(suites.items()): - result = mochitest.run_desktop_test(self._mach_context, - test_paths=[test['file_relpath'] for test in tests], suite=suite, + result = mochitest.run_desktop_test( + self._mach_context, + test_paths=[ + test['file_relpath'] for test in tests], + suite=suite, **kwargs) if result: overall = result @@ -794,8 +984,11 @@ class MachCommands(MachCommandBase): mochitest = self._spawn(MochitestRunner) - return mochitest.run_desktop_test(self._mach_context, - test_paths=test_paths, suite=flavor, **kwargs) + return mochitest.run_desktop_test( + self._mach_context, + test_paths=test_paths, + suite=flavor, + **kwargs) # TODO For now b2g commands will only work with the emulator, @@ -810,27 +1003,39 @@ def is_emulator(cls): @CommandProvider class B2GCommands(MachCommandBase): + """So far these are only mochitest plain. They are implemented separately because their command lines are completely different. """ + def __init__(self, context): MachCommandBase.__init__(self, context) for attr in ('b2g_home', 'xre_path', 'device_name', 'get_build_var'): setattr(self, attr, getattr(context, attr, None)) - @Command('mochitest-remote', category='testing', + @Command( + 'mochitest-remote', + category='testing', description='Run a remote mochitest (integration test for fennec/android).', - conditions=[conditions.is_b2g, is_emulator]) + conditions=[ + conditions.is_b2g, + is_emulator]) @B2GCommand def run_mochitest_remote(self, test_paths, **kwargs): if self.get_build_var: - host_webapps_dir = os.path.join(self.get_build_var('TARGET_OUT_DATA'), - 'local', 'webapps') - if not os.path.isdir(os.path.join(host_webapps_dir, - 'test-container.gaiamobile.org')): - print(ENG_BUILD_REQUIRED % ('mochitest-remote', host_webapps_dir)) + host_webapps_dir = os.path.join( + self.get_build_var('TARGET_OUT_DATA'), + 'local', + 'webapps') + if not os.path.isdir( + os.path.join( + host_webapps_dir, + 'test-container.gaiamobile.org')): + print( + ENG_BUILD_REQUIRED % + ('mochitest-remote', host_webapps_dir)) return 1 from mozbuild.controller.building import BuildDriver @@ -847,22 +1052,29 @@ class B2GCommands(MachCommandBase): driver.install_tests(remove=False) mochitest = self._spawn(MochitestRunner) - return mochitest.run_b2g_test(b2g_home=self.b2g_home, - xre_path=self.xre_path, test_paths=test_paths, **kwargs) + return mochitest.run_b2g_test( + b2g_home=self.b2g_home, + xre_path=self.xre_path, + test_paths=test_paths, + **kwargs) @Command('mochitest-chrome-remote', category='testing', - description='Run a remote mochitest-chrome.', - conditions=[conditions.is_b2g, is_emulator]) + description='Run a remote mochitest-chrome.', + conditions=[conditions.is_b2g, is_emulator]) @B2GCommand def run_mochitest_chrome_remote(self, test_paths, **kwargs): return self.run_mochitest_remote(test_paths, chrome=True, **kwargs) - @Command('mochitest-b2g-desktop', category='testing', - conditions=[conditions.is_b2g_desktop], + @Command( + 'mochitest-b2g-desktop', + category='testing', + conditions=[ + conditions.is_b2g_desktop], description='Run a b2g desktop mochitest (same as mochitest-plain but for b2g desktop).') @B2GCommand def run_mochitest_b2g_desktop(self, test_paths, **kwargs): - kwargs['profile'] = kwargs.get('profile') or os.environ.get('GAIA_PROFILE') + kwargs['profile'] = kwargs.get( + 'profile') or os.environ.get('GAIA_PROFILE') if not kwargs['profile'] or not os.path.isdir(kwargs['profile']): print(GAIA_PROFILE_NOT_FOUND % 'mochitest-b2g-desktop') return 1 @@ -886,31 +1098,52 @@ class B2GCommands(MachCommandBase): @CommandProvider class AndroidCommands(MachCommandBase): + @Command('robocop', category='testing', - conditions=[conditions.is_android], - description='Run a Robocop test.') - @CommandArgument('test_path', default=None, nargs='?', + conditions=[conditions.is_android], + description='Run a Robocop test.') + @CommandArgument( + 'test_path', + default=None, + nargs='?', metavar='TEST', - help='Test to run. Can be specified as a Robocop test name (like "testLoad"), ' \ - 'or omitted. If omitted, the entire test suite is executed.') + help='Test to run. Can be specified as a Robocop test name (like "testLoad"), ' + 'or omitted. If omitted, the entire test suite is executed.') def run_robocop(self, test_path): self.tests_dir = os.path.join(self.topobjdir, '_tests') - self.mochitest_dir = os.path.join(self.tests_dir, 'testing', 'mochitest') + self.mochitest_dir = os.path.join( + self.tests_dir, + 'testing', + 'mochitest') import imp path = os.path.join(self.mochitest_dir, 'runtestsremote.py') with open(path, 'r') as fh: imp.load_module('runtestsremote', fh, path, - ('.py', 'r', imp.PY_SOURCE)) + ('.py', 'r', imp.PY_SOURCE)) import runtestsremote args = [ - '--xre-path=' + os.environ.get('MOZ_HOST_BIN'), + '--xre-path=' + + os.environ.get('MOZ_HOST_BIN'), '--dm_trans=adb', '--deviceIP=', '--console-level=INFO', - '--app=' + self.substs['ANDROID_PACKAGE_NAME'], - '--robocop-apk=' + os.path.join(self.topobjdir, 'build', 'mobile', 'robocop', 'robocop-debug.apk'), - '--robocop-ini=' + os.path.join(self.topobjdir, 'build', 'mobile', 'robocop', 'robocop.ini'), + '--app=' + + self.substs['ANDROID_PACKAGE_NAME'], + '--robocop-apk=' + + os.path.join( + self.topobjdir, + 'build', + 'mobile', + 'robocop', + 'robocop-debug.apk'), + '--robocop-ini=' + + os.path.join( + self.topobjdir, + 'build', + 'mobile', + 'robocop', + 'robocop.ini'), '--log-mach=-', ] diff --git a/testing/mochitest/mochitest_options.py b/testing/mochitest/mochitest_options.py index c60ca2a1540..845a24fb115 100644 --- a/testing/mochitest/mochitest_options.py +++ b/testing/mochitest/mochitest_options.py @@ -23,7 +23,9 @@ __all__ = ["MochitestOptions", "B2GOptions"] VMWARE_RECORDING_HELPER_BASENAME = "vmwarerecordinghelper" + class MochitestOptions(optparse.OptionParser): + """Usage instructions for runtests.py. All arguments are optional. If --chrome is specified, chrome tests will be run instead of web content tests. @@ -35,76 +37,76 @@ class MochitestOptions(optparse.OptionParser): LEVEL_STRING = ", ".join(LOG_LEVELS) mochitest_options = [ [["--close-when-done"], - { "action": "store_true", + {"action": "store_true", "dest": "closeWhenDone", "default": False, "help": "close the application when tests are done running", - }], + }], [["--appname"], - { "action": "store", + {"action": "store", "type": "string", "dest": "app", "default": None, "help": "absolute path to application, overriding default", - }], + }], [["--utility-path"], - { "action": "store", + {"action": "store", "type": "string", "dest": "utilityPath", "default": build_obj.bindir if build_obj is not None else None, "help": "absolute path to directory containing utility programs (xpcshell, ssltunnel, certutil)", - }], + }], [["--certificate-path"], - { "action": "store", + {"action": "store", "type": "string", "dest": "certPath", "help": "absolute path to directory containing certificate store to use testing profile", "default": os.path.join(build_obj.topsrcdir, 'build', 'pgo', 'certs') if build_obj is not None else None, - }], + }], [["--autorun"], - { "action": "store_true", + {"action": "store_true", "dest": "autorun", "help": "start running tests when the application starts", "default": False, - }], + }], [["--timeout"], - { "type": "int", + {"type": "int", "dest": "timeout", "help": "per-test timeout in seconds", "default": None, - }], + }], [["--total-chunks"], - { "type": "int", + {"type": "int", "dest": "totalChunks", "help": "how many chunks to split the tests up into", "default": None, - }], + }], [["--this-chunk"], - { "type": "int", + {"type": "int", "dest": "thisChunk", "help": "which chunk to run", "default": None, - }], + }], [["--chunk-by-dir"], - { "type": "int", + {"type": "int", "dest": "chunkByDir", "help": "group tests together in the same chunk that are in the same top chunkByDir directories", "default": 0, - }], + }], [["--run-by-dir"], - { "action": "store_true", + {"action": "store_true", "dest": "runByDir", "help": "Run each directory in a single browser instance with a fresh profile", "default": False, - }], + }], [["--shuffle"], - { "dest": "shuffle", + {"dest": "shuffle", "action": "store_true", "help": "randomize test order", "default": False, - }], + }], [["--console-level"], - { "action": "store", + {"action": "store", "type": "choice", "dest": "consoleLevel", "choices": LOG_LEVELS, @@ -112,370 +114,370 @@ class MochitestOptions(optparse.OptionParser): "help": "one of %s to determine the level of console " "logging" % LEVEL_STRING, "default": None, - }], + }], [["--chrome"], - { "action": "store_true", + {"action": "store_true", "dest": "chrome", "help": "run chrome Mochitests", "default": False, - }], + }], [["--ipcplugins"], - { "action": "store_true", + {"action": "store_true", "dest": "ipcplugins", "help": "run ipcplugins Mochitests", "default": False, - }], + }], [["--test-path"], - { "action": "store", + {"action": "store", "type": "string", "dest": "testPath", "help": "start in the given directory's tests", "default": "", - }], + }], [["--bisect-chunk"], - { "action": "store", + {"action": "store", "type": "string", "dest": "bisectChunk", "help": "Specify the failing test name to find the previous tests that may be causing the failure.", "default": None, - }], + }], [["--start-at"], - { "action": "store", + {"action": "store", "type": "string", "dest": "startAt", "help": "skip over tests until reaching the given test", "default": "", - }], + }], [["--end-at"], - { "action": "store", + {"action": "store", "type": "string", "dest": "endAt", "help": "don't run any tests after the given one", "default": "", - }], + }], [["--browser-chrome"], - { "action": "store_true", + {"action": "store_true", "dest": "browserChrome", "help": "run browser chrome Mochitests", "default": False, - }], + }], [["--subsuite"], - { "action": "store", + {"action": "store", "dest": "subsuite", "help": "subsuite of tests to run", "default": None, - }], + }], [["--jetpack-package"], - { "action": "store_true", + {"action": "store_true", "dest": "jetpackPackage", "help": "run jetpack package tests", "default": False, - }], + }], [["--jetpack-addon"], - { "action": "store_true", + {"action": "store_true", "dest": "jetpackAddon", "help": "run jetpack addon tests", "default": False, - }], + }], [["--webapprt-content"], - { "action": "store_true", + {"action": "store_true", "dest": "webapprtContent", "help": "run WebappRT content tests", "default": False, - }], + }], [["--webapprt-chrome"], - { "action": "store_true", + {"action": "store_true", "dest": "webapprtChrome", "help": "run WebappRT chrome tests", "default": False, - }], + }], [["--a11y"], - { "action": "store_true", + {"action": "store_true", "dest": "a11y", "help": "run accessibility Mochitests", "default": False, - }], + }], [["--setenv"], - { "action": "append", + {"action": "append", "type": "string", "dest": "environment", "metavar": "NAME=VALUE", "help": "sets the given variable in the application's " - "environment", + "environment", "default": [], - }], + }], [["--exclude-extension"], - { "action": "append", + {"action": "append", "type": "string", "dest": "extensionsToExclude", "help": "excludes the given extension from being installed " - "in the test profile", + "in the test profile", "default": [], - }], + }], [["--browser-arg"], - { "action": "append", + {"action": "append", "type": "string", "dest": "browserArgs", "metavar": "ARG", "help": "provides an argument to the test application", "default": [], - }], + }], [["--leak-threshold"], - { "action": "store", + {"action": "store", "type": "int", "dest": "defaultLeakThreshold", "metavar": "THRESHOLD", "help": "fail if the number of bytes leaked in default " - "processes through refcounted objects (or bytes " - "in classes with MOZ_COUNT_CTOR and MOZ_COUNT_DTOR) " - "is greater than the given number", + "processes through refcounted objects (or bytes " + "in classes with MOZ_COUNT_CTOR and MOZ_COUNT_DTOR) " + "is greater than the given number", "default": 0, - }], + }], [["--fatal-assertions"], - { "action": "store_true", + {"action": "store_true", "dest": "fatalAssertions", "help": "abort testing whenever an assertion is hit " - "(requires a debug build to be effective)", + "(requires a debug build to be effective)", "default": False, - }], + }], [["--extra-profile-file"], - { "action": "append", + {"action": "append", "dest": "extraProfileFiles", "help": "copy specified files/dirs to testing profile", "default": [], - }], + }], [["--install-extension"], - { "action": "append", + {"action": "append", "dest": "extensionsToInstall", "help": "install the specified extension in the testing profile." - "The extension file's name should be .xpi where is" - "the extension's id as indicated in its install.rdf." - "An optional path can be specified too.", + "The extension file's name should be .xpi where is" + "the extension's id as indicated in its install.rdf." + "An optional path can be specified too.", "default": [], - }], + }], [["--profile-path"], - { "action": "store", + {"action": "store", "type": "string", "dest": "profilePath", "help": "Directory where the profile will be stored." - "This directory will be deleted after the tests are finished", + "This directory will be deleted after the tests are finished", "default": None, - }], + }], [["--testing-modules-dir"], - { "action": "store", + {"action": "store", "type": "string", "dest": "testingModulesDir", "help": "Directory where testing-only JS modules are located.", "default": None, - }], + }], [["--use-vmware-recording"], - { "action": "store_true", + {"action": "store_true", "dest": "vmwareRecording", "help": "enables recording while the application is running " - "inside a VMware Workstation 7.0 or later VM", + "inside a VMware Workstation 7.0 or later VM", "default": False, - }], + }], [["--repeat"], - { "action": "store", + {"action": "store", "type": "int", "dest": "repeat", "metavar": "REPEAT", "help": "repeats the test or set of tests the given number of times, ie: repeat: 1 will run the test twice.", "default": 0, - }], + }], [["--run-until-failure"], - { "action": "store_true", + {"action": "store_true", "dest": "runUntilFailure", "help": "Run tests repeatedly and stops on the first time a test fails. " - "Default cap is 30 runs, which can be overwritten with the --repeat parameter.", + "Default cap is 30 runs, which can be overwritten with the --repeat parameter.", "default": False, - }], + }], [["--run-only-tests"], - { "action": "store", + {"action": "store", "type": "string", "dest": "runOnlyTests", "help": "JSON list of tests that we only want to run. [DEPRECATED- please use --test-manifest]", "default": None, - }], + }], [["--test-manifest"], - { "action": "store", + {"action": "store", "type": "string", "dest": "testManifest", "help": "JSON list of tests to specify 'runtests'. Old format for mobile specific tests", "default": None, - }], + }], [["--manifest"], - { "action": "store", + {"action": "store", "type": "string", "dest": "manifestFile", "help": ".ini format of tests to run.", "default": None, - }], + }], [["--testrun-manifest-file"], - { "action": "store", + {"action": "store", "type": "string", "dest": "testRunManifestFile", "help": "Overrides the default filename of the tests.json manifest file that is created from the manifest and used by the test runners to run the tests. Only useful when running multiple test runs simulatenously on the same machine.", "default": 'tests.json', - }], + }], [["--failure-file"], - { "action": "store", + {"action": "store", "type": "string", "dest": "failureFile", "help": "Filename of the output file where we can store a .json list of failures to be run in the future with --run-only-tests.", "default": None, - }], + }], [["--run-slower"], - { "action": "store_true", + {"action": "store_true", "dest": "runSlower", "help": "Delay execution between test files.", "default": False, - }], + }], [["--metro-immersive"], - { "action": "store_true", + {"action": "store_true", "dest": "immersiveMode", "help": "launches tests in immersive browser", "default": False, - }], + }], [["--httpd-path"], - { "action": "store", + {"action": "store", "type": "string", "dest": "httpdPath", "default": None, "help": "path to the httpd.js file", - }], + }], [["--setpref"], - { "action": "append", + {"action": "append", "type": "string", "default": [], "dest": "extraPrefs", "metavar": "PREF=VALUE", "help": "defines an extra user preference", - }], + }], [["--jsdebugger"], - { "action": "store_true", + {"action": "store_true", "default": False, "dest": "jsdebugger", "help": "open the browser debugger", - }], + }], [["--debug-on-failure"], - { "action": "store_true", + {"action": "store_true", "default": False, "dest": "debugOnFailure", "help": "breaks execution and enters the JS debugger on a test failure. Should be used together with --jsdebugger." - }], + }], [["--e10s"], - { "action": "store_true", + {"action": "store_true", "default": False, "dest": "e10s", "help": "Run tests with electrolysis preferences and test filtering enabled.", - }], + }], [["--strict-content-sandbox"], - { "action": "store_true", + {"action": "store_true", "default": False, "dest": "strictContentSandbox", "help": "Run tests with a more strict content sandbox (Windows only).", - }], + }], [["--nested_oop"], - { "action": "store_true", + {"action": "store_true", "default": False, "dest": "nested_oop", "help": "Run tests with nested_oop preferences and test filtering enabled.", - }], + }], [["--dmd-path"], - { "action": "store", - "default": None, - "dest": "dmdPath", - "help": "Specifies the path to the directory containing the shared library for DMD.", - }], + {"action": "store", + "default": None, + "dest": "dmdPath", + "help": "Specifies the path to the directory containing the shared library for DMD.", + }], [["--dump-output-directory"], - { "action": "store", - "default": None, - "dest": "dumpOutputDirectory", - "help": "Specifies the directory in which to place dumped memory reports.", - }], + {"action": "store", + "default": None, + "dest": "dumpOutputDirectory", + "help": "Specifies the directory in which to place dumped memory reports.", + }], [["--dump-about-memory-after-test"], - { "action": "store_true", - "default": False, - "dest": "dumpAboutMemoryAfterTest", - "help": "Produce an about:memory dump after each test in the directory specified " - "by --dump-output-directory." - }], + {"action": "store_true", + "default": False, + "dest": "dumpAboutMemoryAfterTest", + "help": "Produce an about:memory dump after each test in the directory specified " + "by --dump-output-directory." + }], [["--dump-dmd-after-test"], - { "action": "store_true", - "default": False, - "dest": "dumpDMDAfterTest", - "help": "Produce a DMD dump after each test in the directory specified " - "by --dump-output-directory." - }], + {"action": "store_true", + "default": False, + "dest": "dumpDMDAfterTest", + "help": "Produce a DMD dump after each test in the directory specified " + "by --dump-output-directory." + }], [["--slowscript"], - { "action": "store_true", - "default": False, - "dest": "slowscript", - "help": "Do not set the JS_DISABLE_SLOW_SCRIPT_SIGNALS env variable; " - "when not set, recoverable but misleading SIGSEGV instances " - "may occur in Ion/Odin JIT code." - }], + {"action": "store_true", + "default": False, + "dest": "slowscript", + "help": "Do not set the JS_DISABLE_SLOW_SCRIPT_SIGNALS env variable; " + "when not set, recoverable but misleading SIGSEGV instances " + "may occur in Ion/Odin JIT code." + }], [["--screenshot-on-fail"], - { "action": "store_true", - "default": False, - "dest": "screenshotOnFail", - "help": "Take screenshots on all test failures. Set $MOZ_UPLOAD_DIR to a directory for storing the screenshots." - }], + {"action": "store_true", + "default": False, + "dest": "screenshotOnFail", + "help": "Take screenshots on all test failures. Set $MOZ_UPLOAD_DIR to a directory for storing the screenshots." + }], [["--quiet"], - { "action": "store_true", - "default": False, - "dest": "quiet", - "help": "Do not print test log lines unless a failure occurs." - }], + {"action": "store_true", + "default": False, + "dest": "quiet", + "help": "Do not print test log lines unless a failure occurs." + }], [["--pidfile"], - { "action": "store", + {"action": "store", "type": "string", "dest": "pidFile", "help": "name of the pidfile to generate", "default": "", - }], + }], [["--use-test-media-devices"], - { "action": "store_true", + {"action": "store_true", "default": False, "dest": "useTestMediaDevices", "help": "Use test media device drivers for media testing.", - }], + }], [["--gmp-path"], - { "action": "store", + {"action": "store", "default": None, "dest": "gmp_path", "help": "Path to fake GMP plugin. Will be deduced from the binary if not passed.", - }], + }], [["--xre-path"], - { "action": "store", - "type": "string", + {"action": "store", + "type": "string", "dest": "xrePath", "default": None, # individual scripts will set a sane default "help": "absolute path to directory containing XRE (probably xulrunner)", - }], + }], [["--symbols-path"], - { "action": "store", - "type": "string", + {"action": "store", + "type": "string", "dest": "symbolsPath", "default": None, "help": "absolute path to directory containing breakpad symbols, or the URL of a zip file containing symbols", - }], + }], [["--debugger"], - { "action": "store", + {"action": "store", "dest": "debugger", "help": "use the given debugger to launch the application", - }], + }], [["--debugger-args"], - { "action": "store", + {"action": "store", "dest": "debuggerArgs", "help": "pass the given args to the debugger _before_ the application on the command line", - }], + }], [["--debugger-interactive"], - { "action": "store_true", + {"action": "store_true", "dest": "debuggerInteractive", "help": "prevents the test harness from redirecting stdout and stderr for interactive debuggers", - }], + }], ] def __init__(self, **kwargs): @@ -492,18 +494,22 @@ class MochitestOptions(optparse.OptionParser): def verifyOptions(self, options, mochitest): """ verify correct options and cleanup paths """ - mozinfo.update({"e10s": options.e10s}) # for test manifest parsing. - mozinfo.update({"strictContentSandbox": options.strictContentSandbox}) # for test manifest parsing. - mozinfo.update({"nested_oop": options.nested_oop}) # for test manifest parsing. + mozinfo.update({"e10s": options.e10s}) # for test manifest parsing. + # for test manifest parsing. + mozinfo.update({"strictContentSandbox": options.strictContentSandbox}) + # for test manifest parsing. + mozinfo.update({"nested_oop": options.nested_oop}) if options.app is None: if build_obj is not None: options.app = build_obj.get_binary_path() else: - self.error("could not find the application path, --appname must be specified") + self.error( + "could not find the application path, --appname must be specified") if options.totalChunks is not None and options.thisChunk is None: - self.error("thisChunk must be specified when totalChunks is specified") + self.error( + "thisChunk must be specified when totalChunks is specified") if options.totalChunks: if not 1 <= options.thisChunk <= options.totalChunks: @@ -515,12 +521,16 @@ class MochitestOptions(optparse.OptionParser): if options.app != self.defaults['app']: options.xrePath = os.path.dirname(options.app) if mozinfo.isMac: - options.xrePath = os.path.join(os.path.dirname(options.xrePath), "Resources") + options.xrePath = os.path.join( + os.path.dirname( + options.xrePath), + "Resources") elif build_obj is not None: # otherwise default to dist/bin options.xrePath = build_obj.bindir else: - self.error("could not find xre directory, --xre-path must be specified") + self.error( + "could not find xre directory, --xre-path must be specified") # allow relative paths options.xrePath = mochitest.getFullPath(options.xrePath) @@ -543,7 +553,9 @@ class MochitestOptions(optparse.OptionParser): if options.certPath: options.certPath = mochitest.getFullPath(options.certPath) - if options.symbolsPath and len(urlparse(options.symbolsPath).scheme) < 2: + if options.symbolsPath and len( + urlparse( + options.symbolsPath).scheme) < 2: options.symbolsPath = mochitest.getFullPath(options.symbolsPath) # Set server information on the options object @@ -551,14 +563,16 @@ class MochitestOptions(optparse.OptionParser): options.httpPort = DEFAULT_PORTS['http'] options.sslPort = DEFAULT_PORTS['https'] # options.webSocketPort = DEFAULT_PORTS['ws'] - options.webSocketPort = str(9988) # <- http://hg.mozilla.org/mozilla-central/file/b871dfb2186f/build/automation.py.in#l30 + # <- http://hg.mozilla.org/mozilla-central/file/b871dfb2186f/build/automation.py.in#l30 + options.webSocketPort = str(9988) # The default websocket port is incorrect in mozprofile; it is # set to the SSL proxy setting. See: # see https://bugzilla.mozilla.org/show_bug.cgi?id=916517 if options.vmwareRecording: if not mozinfo.isWin: - self.error("use-vmware-recording is only supported on Windows.") + self.error( + "use-vmware-recording is only supported on Windows.") mochitest.vmwareHelperPath = os.path.join( options.utilityPath, VMWARE_RECORDING_HELPER_BASENAME + ".dll") if not os.path.exists(mochitest.vmwareHelperPath): @@ -566,20 +580,29 @@ class MochitestOptions(optparse.OptionParser): mochitest.vmwareHelperPath) if options.testManifest and options.runOnlyTests: - self.error("Please use --test-manifest only and not --run-only-tests") + self.error( + "Please use --test-manifest only and not --run-only-tests") if options.runOnlyTests: - if not os.path.exists(os.path.abspath(os.path.join(here, options.runOnlyTests))): - self.error("unable to find --run-only-tests file '%s'" % options.runOnlyTests) + if not os.path.exists( + os.path.abspath( + os.path.join( + here, + options.runOnlyTests))): + self.error( + "unable to find --run-only-tests file '%s'" % + options.runOnlyTests) options.runOnly = True options.testManifest = options.runOnlyTests options.runOnlyTests = None if options.manifestFile and options.testManifest: - self.error("Unable to support both --manifest and --test-manifest/--run-only-tests at the same time") + self.error( + "Unable to support both --manifest and --test-manifest/--run-only-tests at the same time") if options.webapprtContent and options.webapprtChrome: - self.error("Only one of --webapprt-content and --webapprt-chrome may be given.") + self.error( + "Only one of --webapprt-content and --webapprt-chrome may be given.") if options.jsdebugger: options.extraPrefs += [ @@ -591,7 +614,8 @@ class MochitestOptions(optparse.OptionParser): options.autorun = False if options.debugOnFailure and not options.jsdebugger: - self.error("--debug-on-failure should be used together with --jsdebugger.") + self.error( + "--debug-on-failure should be used together with --jsdebugger.") # Try to guess the testing modules directory. # This somewhat grotesque hack allows the buildbot machines to find the @@ -608,16 +632,20 @@ class MochitestOptions(optparse.OptionParser): # Even if buildbot is updated, we still want this, as the path we pass in # to the app must be absolute and have proper slashes. if options.testingModulesDir is not None: - options.testingModulesDir = os.path.normpath(options.testingModulesDir) + options.testingModulesDir = os.path.normpath( + options.testingModulesDir) if not os.path.isabs(options.testingModulesDir): - options.testingModulesDir = os.path.abspath(options.testingModulesDir) + options.testingModulesDir = os.path.abspath( + options.testingModulesDir) if not os.path.isdir(options.testingModulesDir): self.error('--testing-modules-dir not a directory: %s' % - options.testingModulesDir) + options.testingModulesDir) - options.testingModulesDir = options.testingModulesDir.replace('\\', '/') + options.testingModulesDir = options.testingModulesDir.replace( + '\\', + '/') if options.testingModulesDir[-1] != '/': options.testingModulesDir += '/' @@ -644,25 +672,30 @@ class MochitestOptions(optparse.OptionParser): if options.useTestMediaDevices: if not mozinfo.isLinux: - self.error('--use-test-media-devices is only supported on Linux currently') + self.error( + '--use-test-media-devices is only supported on Linux currently') for f in ['/usr/bin/gst-launch-0.10', '/usr/bin/pactl']: if not os.path.isfile(f): - self.error('Missing binary %s required for --use-test-media-devices') + self.error( + 'Missing binary %s required for --use-test-media-devices') if options.nested_oop: - if not options.e10s: - options.e10s = True + if not options.e10s: + options.e10s = True options.leakThresholds = { "default": options.defaultLeakThreshold, - "tab": 25000, # See dependencies of bug 1051230. - "geckomediaplugin": 20000, # GMP rarely gets a log, but when it does, it leaks a little. + "tab": 25000, # See dependencies of bug 1051230. + # GMP rarely gets a log, but when it does, it leaks a little. + "geckomediaplugin": 20000, } - # Bug 1065098 - The geckomediaplugin process fails to produce a leak log for some reason. + # Bug 1065098 - The geckomediaplugin process fails to produce a leak + # log for some reason. options.ignoreMissingLeaks = ["geckomediaplugin"] - # Bug 1091917 - We exit early in tab processes on Windows, so we don't get leak logs yet. + # Bug 1091917 - We exit early in tab processes on Windows, so we don't + # get leak logs yet. if mozinfo.isWin: options.ignoreMissingLeaks.append("tab") @@ -676,140 +709,140 @@ class MochitestOptions(optparse.OptionParser): class B2GOptions(MochitestOptions): b2g_options = [ [["--b2gpath"], - { "action": "store", + {"action": "store", "type": "string", "dest": "b2gPath", "help": "path to B2G repo or qemu dir", "default": None, - }], + }], [["--desktop"], - { "action": "store_true", + {"action": "store_true", "dest": "desktop", "help": "Run the tests on a B2G desktop build", "default": False, - }], + }], [["--marionette"], - { "action": "store", + {"action": "store", "type": "string", "dest": "marionette", "help": "host:port to use when connecting to Marionette", "default": None, - }], + }], [["--emulator"], - { "action": "store", + {"action": "store", "type": "string", "dest": "emulator", "help": "Architecture of emulator to use: x86 or arm", "default": None, - }], + }], [["--wifi"], - { "action": "store", + {"action": "store", "type": "string", "dest": "wifi", "help": "Devine wifi configuration for on device mochitest", "default": False, - }], + }], [["--sdcard"], - { "action": "store", + {"action": "store", "type": "string", "dest": "sdcard", "help": "Define size of sdcard: 1MB, 50MB...etc", "default": "10MB", - }], + }], [["--no-window"], - { "action": "store_true", + {"action": "store_true", "dest": "noWindow", "help": "Pass --no-window to the emulator", "default": False, - }], + }], [["--adbpath"], - { "action": "store", + {"action": "store", "type": "string", "dest": "adbPath", "help": "path to adb", "default": "adb", - }], + }], [["--deviceIP"], - { "action": "store", + {"action": "store", "type": "string", "dest": "deviceIP", "help": "ip address of remote device to test", "default": None, - }], + }], [["--devicePort"], - { "action": "store", + {"action": "store", "type": "string", "dest": "devicePort", "help": "port of remote device to test", "default": 20701, - }], + }], [["--remote-logfile"], - { "action": "store", + {"action": "store", "type": "string", "dest": "remoteLogFile", "help": "Name of log file on the device relative to the device root. \ PLEASE ONLY USE A FILENAME.", - "default" : None, - }], + "default": None, + }], [["--remote-webserver"], - { "action": "store", + {"action": "store", "type": "string", "dest": "remoteWebServer", "help": "ip address where the remote web server is hosted at", "default": None, - }], + }], [["--http-port"], - { "action": "store", + {"action": "store", "type": "string", "dest": "httpPort", "help": "ip address where the remote web server is hosted at", "default": None, - }], + }], [["--ssl-port"], - { "action": "store", + {"action": "store", "type": "string", "dest": "sslPort", "help": "ip address where the remote web server is hosted at", "default": None, - }], + }], [["--gecko-path"], - { "action": "store", + {"action": "store", "type": "string", "dest": "geckoPath", "help": "the path to a gecko distribution that should \ be installed on the emulator prior to test", "default": None, - }], + }], [["--profile"], - { "action": "store", + {"action": "store", "type": "string", "dest": "profile", "help": "for desktop testing, the path to the \ gaia profile to use", "default": None, - }], + }], [["--logdir"], - { "action": "store", + {"action": "store", "type": "string", "dest": "logdir", "help": "directory to store log files", "default": None, - }], + }], [['--busybox'], - { "action": 'store', + {"action": 'store', "type": 'string', "dest": 'busybox', "help": "Path to busybox binary to install on device", "default": None, - }], + }], [['--profile-data-dir'], - { "action": 'store', + {"action": 'store', "type": 'string', "dest": 'profile_data_dir', "help": "Path to a directory containing preference and other \ data to be installed into the profile", "default": os.path.join(here, 'profile_data'), - }], + }], ] def __init__(self): @@ -831,15 +864,17 @@ class B2GOptions(MochitestOptions): self.set_defaults(**defaults) def verifyRemoteOptions(self, options): - if options.remoteWebServer == None: + if options.remoteWebServer is None: if os.name != "nt": options.remoteWebServer = moznetwork.get_ip() else: - self.error("You must specify a --remote-webserver=") + self.error( + "You must specify a --remote-webserver=") options.webServer = options.remoteWebServer if options.geckoPath and not options.emulator: - self.error("You must specify --emulator if you specify --gecko-path") + self.error( + "You must specify --emulator if you specify --gecko-path") if options.logdir and not options.emulator: self.error("You must specify --emulator if you specify --logdir") @@ -884,4 +919,4 @@ class B2GOptions(MochitestOptions): def elf_arm(self, filename): data = open(filename, 'rb').read(20) - return data[:4] == "\x7fELF" and ord(data[18]) == 40 # EM_ARM + return data[:4] == "\x7fELF" and ord(data[18]) == 40 # EM_ARM diff --git a/testing/mochitest/runtests.py b/testing/mochitest/runtests.py index 2b9798e61c1..6827d0c2fb1 100644 --- a/testing/mochitest/runtests.py +++ b/testing/mochitest/runtests.py @@ -10,7 +10,7 @@ from __future__ import with_statement import os import sys SCRIPT_DIR = os.path.abspath(os.path.realpath(os.path.dirname(__file__))) -sys.path.insert(0, SCRIPT_DIR); +sys.path.insert(0, SCRIPT_DIR) from urlparse import urlparse import ctypes @@ -72,8 +72,11 @@ NSPR_LOG_MODULES = "" # LOG HANDLING # #################### -### output processing +# output processing + + class MochitestFormatter(TbplFormatter): + """ The purpose of this class is to maintain compatibility with legacy users. Mozharness' summary parser expects the count prefix, and others expect python @@ -94,13 +97,17 @@ class MochitestFormatter(TbplFormatter): if 'js_source' in data or log_level == 'ERROR': data.pop('js_source', None) - output = '%d %s %s' % (MochitestFormatter.log_num, log_level, output) + output = '%d %s %s' % ( + MochitestFormatter.log_num, log_level, output) MochitestFormatter.log_num += 1 return output -### output processing +# output processing + + class MessageLogger(object): + """File-like object for logging messages (structured logs)""" BUFFERING_THRESHOLD = 100 # This is a delimiter used by the JS side to avoid logs interleaving @@ -113,7 +120,6 @@ class MessageLogger(object): 'chrome://mochitests/content/browser/', 'chrome://mochitests/content/chrome/'] - def __init__(self, logger, buffering=True): self.logger = logger self.buffering = buffering @@ -128,17 +134,18 @@ class MessageLogger(object): def valid_message(self, obj): """True if the given object is a valid structured message (only does a superficial validation)""" - return isinstance(obj, dict) and 'action' in obj and obj['action'] in MessageLogger.VALID_ACTIONS + return isinstance(obj, dict) and 'action' in obj and obj[ + 'action'] in MessageLogger.VALID_ACTIONS def _fix_test_name(self, message): - """Normalize a logged test path to match the relative path from the sourcedir. - """ - if 'test' in message: - test = message['test'] - for prefix in MessageLogger.TEST_PATH_PREFIXES: - if test.startswith(prefix): - message['test'] = test[len(prefix):] - break + """Normalize a logged test path to match the relative path from the sourcedir. + """ + if 'test' in message: + test = message['test'] + for prefix in MessageLogger.TEST_PATH_PREFIXES: + if test.startswith(prefix): + message['test'] = test[len(prefix):] + break def parse_line(self, line): """Takes a given line of input (structured or not) and returns a list of structured messages""" @@ -151,9 +158,17 @@ class MessageLogger(object): try: message = json.loads(fragment) if not self.valid_message(message): - message = dict(action='log', level='info', message=fragment, unstructured=True) + message = dict( + action='log', + level='info', + message=fragment, + unstructured=True) except ValueError: - message = dict(action='log', level='info', message=fragment, unstructured=True) + message = dict( + action='log', + level='info', + message=fragment, + unstructured=True) self._fix_test_name(message) messages.append(message) @@ -179,19 +194,20 @@ class MessageLogger(object): # Error detection also supports "raw" errors (in log messages) because some tests # manually dump 'TEST-UNEXPECTED-FAIL'. - if ('expected' in message or - (message['action'] == 'log' and message['message'].startswith('TEST-UNEXPECTED'))): + if ('expected' in message or (message['action'] == 'log' and message[ + 'message'].startswith('TEST-UNEXPECTED'))): # Saving errors/failures to be shown at the end of the test run self.errors.append(message) self.restore_buffering = self.restore_buffering or self.buffering self.buffering = False if self.buffered_messages: - snipped = len(self.buffered_messages) - self.BUFFERING_THRESHOLD + snipped = len( + self.buffered_messages) - self.BUFFERING_THRESHOLD if snipped > 0: - self.logger.info("" - .format(snipped)) + self.logger.info( + "" .format(snipped)) # Dumping previously buffered messages self.dump_buffered(limit=True) @@ -226,7 +242,8 @@ class MessageLogger(object): def dump_buffered(self, limit=False): if limit: - dumped_messages = self.buffered_messages[-self.BUFFERING_THRESHOLD:] + dumped_messages = self.buffered_messages[- + self.BUFFERING_THRESHOLD:] else: dumped_messages = self.buffered_messages @@ -244,577 +261,667 @@ class MessageLogger(object): # PROCESS HANDLING # #################### + def call(*args, **kwargs): - """front-end function to mozprocess.ProcessHandler""" - # TODO: upstream -> mozprocess - # https://bugzilla.mozilla.org/show_bug.cgi?id=791383 - process = mozprocess.ProcessHandler(*args, **kwargs) - process.run() - return process.wait() + """front-end function to mozprocess.ProcessHandler""" + # TODO: upstream -> mozprocess + # https://bugzilla.mozilla.org/show_bug.cgi?id=791383 + process = mozprocess.ProcessHandler(*args, **kwargs) + process.run() + return process.wait() + def killPid(pid, log): - # see also https://bugzilla.mozilla.org/show_bug.cgi?id=911249#c58 - try: - os.kill(pid, getattr(signal, "SIGKILL", signal.SIGTERM)) - except Exception, e: - log.info("Failed to kill process %d: %s" % (pid, str(e))) + # see also https://bugzilla.mozilla.org/show_bug.cgi?id=911249#c58 + try: + os.kill(pid, getattr(signal, "SIGKILL", signal.SIGTERM)) + except Exception as e: + log.info("Failed to kill process %d: %s" % (pid, str(e))) if mozinfo.isWin: - import ctypes.wintypes + import ctypes.wintypes - def isPidAlive(pid): - STILL_ACTIVE = 259 - PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 - pHandle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) - if not pHandle: - return False - pExitCode = ctypes.wintypes.DWORD() - ctypes.windll.kernel32.GetExitCodeProcess(pHandle, ctypes.byref(pExitCode)) - ctypes.windll.kernel32.CloseHandle(pHandle) - return pExitCode.value == STILL_ACTIVE + def isPidAlive(pid): + STILL_ACTIVE = 259 + PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 + pHandle = ctypes.windll.kernel32.OpenProcess( + PROCESS_QUERY_LIMITED_INFORMATION, + 0, + pid) + if not pHandle: + return False + pExitCode = ctypes.wintypes.DWORD() + ctypes.windll.kernel32.GetExitCodeProcess( + pHandle, + ctypes.byref(pExitCode)) + ctypes.windll.kernel32.CloseHandle(pHandle) + return pExitCode.value == STILL_ACTIVE else: - import errno + import errno - def isPidAlive(pid): - try: - # kill(pid, 0) checks for a valid PID without actually sending a signal - # The method throws OSError if the PID is invalid, which we catch below. - os.kill(pid, 0) + def isPidAlive(pid): + try: + # kill(pid, 0) checks for a valid PID without actually sending a signal + # The method throws OSError if the PID is invalid, which we catch + # below. + os.kill(pid, 0) - # Wait on it to see if it's a zombie. This can throw OSError.ECHILD if - # the process terminates before we get to this point. - wpid, wstatus = os.waitpid(pid, os.WNOHANG) - return wpid == 0 - except OSError, err: - # Catch the errors we might expect from os.kill/os.waitpid, - # and re-raise any others - if err.errno == errno.ESRCH or err.errno == errno.ECHILD: - return False - raise + # Wait on it to see if it's a zombie. This can throw OSError.ECHILD if + # the process terminates before we get to this point. + wpid, wstatus = os.waitpid(pid, os.WNOHANG) + return wpid == 0 + except OSError as err: + # Catch the errors we might expect from os.kill/os.waitpid, + # and re-raise any others + if err.errno == errno.ESRCH or err.errno == errno.ECHILD: + return False + raise # TODO: ^ upstream isPidAlive to mozprocess ####################### # HTTP SERVER SUPPORT # ####################### + class MochitestServer(object): - "Web server used to serve Mochitests, for closer fidelity to the real web." - def __init__(self, options, logger): - if isinstance(options, optparse.Values): - options = vars(options) - self._log = logger - self._closeWhenDone = options['closeWhenDone'] - self._utilityPath = options['utilityPath'] - self._xrePath = options['xrePath'] - self._profileDir = options['profilePath'] - self.webServer = options['webServer'] - self.httpPort = options['httpPort'] - self.shutdownURL = "http://%(server)s:%(port)s/server/shutdown" % { "server" : self.webServer, "port" : self.httpPort } - self.testPrefix = "'webapprt_'" if options.get('webapprtContent') else "undefined" + "Web server used to serve Mochitests, for closer fidelity to the real web." - if options.get('httpdPath'): - self._httpdPath = options['httpdPath'] - else: - self._httpdPath = SCRIPT_DIR - self._httpdPath = os.path.abspath(self._httpdPath) + def __init__(self, options, logger): + if isinstance(options, optparse.Values): + options = vars(options) + self._log = logger + self._closeWhenDone = options['closeWhenDone'] + self._utilityPath = options['utilityPath'] + self._xrePath = options['xrePath'] + self._profileDir = options['profilePath'] + self.webServer = options['webServer'] + self.httpPort = options['httpPort'] + self.shutdownURL = "http://%(server)s:%(port)s/server/shutdown" % { + "server": self.webServer, + "port": self.httpPort} + self.testPrefix = "'webapprt_'" if options.get( + 'webapprtContent') else "undefined" - def start(self): - "Run the Mochitest server, returning the process ID of the server." + if options.get('httpdPath'): + self._httpdPath = options['httpdPath'] + else: + self._httpdPath = SCRIPT_DIR + self._httpdPath = os.path.abspath(self._httpdPath) - # get testing environment - env = environment(xrePath=self._xrePath) - env["XPCOM_DEBUG_BREAK"] = "warn" - env["LD_LIBRARY_PATH"] = self._xrePath + def start(self): + "Run the Mochitest server, returning the process ID of the server." - # When running with an ASan build, our xpcshell server will also be ASan-enabled, - # thus consuming too much resources when running together with the browser on - # the test slaves. Try to limit the amount of resources by disabling certain - # features. - env["ASAN_OPTIONS"] = "quarantine_size=1:redzone=32:malloc_context_size=5" + # get testing environment + env = environment(xrePath=self._xrePath) + env["XPCOM_DEBUG_BREAK"] = "warn" + env["LD_LIBRARY_PATH"] = self._xrePath - if mozinfo.isWin: - env["PATH"] = env["PATH"] + ";" + str(self._xrePath) + # When running with an ASan build, our xpcshell server will also be ASan-enabled, + # thus consuming too much resources when running together with the browser on + # the test slaves. Try to limit the amount of resources by disabling certain + # features. + env["ASAN_OPTIONS"] = "quarantine_size=1:redzone=32:malloc_context_size=5" - args = ["-g", self._xrePath, - "-v", "170", - "-f", os.path.join(self._httpdPath, "httpd.js"), - "-e", """const _PROFILE_PATH = '%(profile)s'; const _SERVER_PORT = '%(port)s'; const _SERVER_ADDR = '%(server)s'; const _TEST_PREFIX = %(testPrefix)s; const _DISPLAY_RESULTS = %(displayResults)s;""" % - {"profile" : self._profileDir.replace('\\', '\\\\'), "port" : self.httpPort, "server" : self.webServer, - "testPrefix" : self.testPrefix, "displayResults" : str(not self._closeWhenDone).lower() }, - "-f", os.path.join(SCRIPT_DIR, "server.js")] + if mozinfo.isWin: + env["PATH"] = env["PATH"] + ";" + str(self._xrePath) - xpcshell = os.path.join(self._utilityPath, - "xpcshell" + mozinfo.info['bin_suffix']) - command = [xpcshell] + args - self._process = mozprocess.ProcessHandler(command, cwd=SCRIPT_DIR, env=env) - self._process.run() - self._log.info("%s : launching %s" % (self.__class__.__name__, command)) - pid = self._process.pid - self._log.info("runtests.py | Server pid: %d" % pid) + args = [ + "-g", + self._xrePath, + "-v", + "170", + "-f", + os.path.join( + self._httpdPath, + "httpd.js"), + "-e", + """const _PROFILE_PATH = '%(profile)s'; const _SERVER_PORT = '%(port)s'; const _SERVER_ADDR = '%(server)s'; const _TEST_PREFIX = %(testPrefix)s; const _DISPLAY_RESULTS = %(displayResults)s;""" % { + "profile": self._profileDir.replace( + '\\', + '\\\\'), + "port": self.httpPort, + "server": self.webServer, + "testPrefix": self.testPrefix, + "displayResults": str( + not self._closeWhenDone).lower()}, + "-f", + os.path.join( + SCRIPT_DIR, + "server.js")] - def ensureReady(self, timeout): - assert timeout >= 0 + xpcshell = os.path.join(self._utilityPath, + "xpcshell" + mozinfo.info['bin_suffix']) + command = [xpcshell] + args + self._process = mozprocess.ProcessHandler( + command, + cwd=SCRIPT_DIR, + env=env) + self._process.run() + self._log.info( + "%s : launching %s" % + (self.__class__.__name__, command)) + pid = self._process.pid + self._log.info("runtests.py | Server pid: %d" % pid) - aliveFile = os.path.join(self._profileDir, "server_alive.txt") - i = 0 - while i < timeout: - if os.path.exists(aliveFile): - break - time.sleep(1) - i += 1 - else: - self._log.error("TEST-UNEXPECTED-FAIL | runtests.py | Timed out while waiting for server startup.") - self.stop() - sys.exit(1) + def ensureReady(self, timeout): + assert timeout >= 0 - def stop(self): - try: - with urllib2.urlopen(self.shutdownURL) as c: - c.read() + aliveFile = os.path.join(self._profileDir, "server_alive.txt") + i = 0 + while i < timeout: + if os.path.exists(aliveFile): + break + time.sleep(1) + i += 1 + else: + self._log.error( + "TEST-UNEXPECTED-FAIL | runtests.py | Timed out while waiting for server startup.") + self.stop() + sys.exit(1) + + def stop(self): + try: + with urllib2.urlopen(self.shutdownURL) as c: + c.read() + + # TODO: need ProcessHandler.poll() + # https://bugzilla.mozilla.org/show_bug.cgi?id=912285 + # rtncode = self._process.poll() + rtncode = self._process.proc.poll() + if rtncode is None: + # TODO: need ProcessHandler.terminate() and/or .send_signal() + # https://bugzilla.mozilla.org/show_bug.cgi?id=912285 + # self._process.terminate() + self._process.proc.terminate() + except: + self._process.kill() - # TODO: need ProcessHandler.poll() - # https://bugzilla.mozilla.org/show_bug.cgi?id=912285 - # rtncode = self._process.poll() - rtncode = self._process.proc.poll() - if rtncode is None: - # TODO: need ProcessHandler.terminate() and/or .send_signal() - # https://bugzilla.mozilla.org/show_bug.cgi?id=912285 - # self._process.terminate() - self._process.proc.terminate() - except: - self._process.kill() class WebSocketServer(object): - "Class which encapsulates the mod_pywebsocket server" - def __init__(self, options, scriptdir, logger, debuggerInfo=None): - self.port = options.webSocketPort - self.debuggerInfo = debuggerInfo - self._log = logger - self._scriptdir = scriptdir + "Class which encapsulates the mod_pywebsocket server" + def __init__(self, options, scriptdir, logger, debuggerInfo=None): + self.port = options.webSocketPort + self.debuggerInfo = debuggerInfo + self._log = logger + self._scriptdir = scriptdir - def start(self): - # Invoke pywebsocket through a wrapper which adds special SIGINT handling. - # - # If we're in an interactive debugger, the wrapper causes the server to - # ignore SIGINT so the server doesn't capture a ctrl+c meant for the - # debugger. - # - # If we're not in an interactive debugger, the wrapper causes the server to - # die silently upon receiving a SIGINT. - scriptPath = 'pywebsocket_wrapper.py' - script = os.path.join(self._scriptdir, scriptPath) + def start(self): + # Invoke pywebsocket through a wrapper which adds special SIGINT handling. + # + # If we're in an interactive debugger, the wrapper causes the server to + # ignore SIGINT so the server doesn't capture a ctrl+c meant for the + # debugger. + # + # If we're not in an interactive debugger, the wrapper causes the server to + # die silently upon receiving a SIGINT. + scriptPath = 'pywebsocket_wrapper.py' + script = os.path.join(self._scriptdir, scriptPath) - cmd = [sys.executable, script] - if self.debuggerInfo and self.debuggerInfo.interactive: - cmd += ['--interactive'] - cmd += ['-p', str(self.port), '-w', self._scriptdir, '-l', \ - os.path.join(self._scriptdir, "websock.log"), \ - '--log-level=debug', '--allow-handlers-outside-root-dir'] - # start the process - self._process = mozprocess.ProcessHandler(cmd, cwd=SCRIPT_DIR) - self._process.run() - pid = self._process.pid - self._log.info("runtests.py | Websocket server pid: %d" % pid) + cmd = [sys.executable, script] + if self.debuggerInfo and self.debuggerInfo.interactive: + cmd += ['--interactive'] + cmd += ['-p', str(self.port), '-w', self._scriptdir, '-l', + os.path.join(self._scriptdir, "websock.log"), + '--log-level=debug', '--allow-handlers-outside-root-dir'] + # start the process + self._process = mozprocess.ProcessHandler(cmd, cwd=SCRIPT_DIR) + self._process.run() + pid = self._process.pid + self._log.info("runtests.py | Websocket server pid: %d" % pid) + + def stop(self): + self._process.kill() - def stop(self): - self._process.kill() class MochitestUtilsMixin(object): - """ - Class containing some utility functions common to both local and remote - mochitest runners - """ - # TODO Utility classes are a code smell. This class is temporary - # and should be removed when desktop mochitests are refactored - # on top of mozbase. Each of the functions in here should - # probably live somewhere in mozbase - - oldcwd = os.getcwd() - jarDir = 'mochijar' - - # Path to the test script on the server - TEST_PATH = "tests" - NESTED_OOP_TEST_PATH = "nested_oop" - CHROME_PATH = "redirect.html" - urlOpts = [] - log = None - - def __init__(self, logger_options): - self.update_mozinfo() - self.server = None - self.wsserver = None - self.sslTunnel = None - self._locations = None - - if self.log is None: - commandline.log_formatters["tbpl"] = (MochitestFormatter, - "Mochitest specific tbpl formatter") - self.log = commandline.setup_logging("mochitest", - logger_options, - { - "tbpl": sys.stdout - }) - MochitestUtilsMixin.log = self.log - setAutomationLog(self.log) - - self.message_logger = MessageLogger(logger=self.log) - - def update_mozinfo(self): - """walk up directories to find mozinfo.json update the info""" - # TODO: This should go in a more generic place, e.g. mozinfo - - path = SCRIPT_DIR - dirs = set() - while path != os.path.expanduser('~'): - if path in dirs: - break - dirs.add(path) - path = os.path.split(path)[0] - - mozinfo.find_and_update_from_json(*dirs) - - def getFullPath(self, path): - " Get an absolute path relative to self.oldcwd." - return os.path.normpath(os.path.join(self.oldcwd, os.path.expanduser(path))) - - def getLogFilePath(self, logFile): - """ return the log file path relative to the device we are testing on, in most cases - it will be the full path on the local system """ - return self.getFullPath(logFile) - - @property - def locations(self): - if self._locations is not None: - return self._locations - locations_file = os.path.join(SCRIPT_DIR, 'server-locations.txt') - self._locations = ServerLocations(locations_file) - return self._locations - - def buildURLOptions(self, options, env): - """ Add test control options from the command line to the url - - URL parameters to test URL: - - autorun -- kick off tests automatically - closeWhenDone -- closes the browser after the tests - hideResultsTable -- hides the table of individual test results - logFile -- logs test run to an absolute path - totalChunks -- how many chunks to split tests into - thisChunk -- which chunk to run - startAt -- name of test to start at - endAt -- name of test to end at - timeout -- per-test timeout in seconds - repeat -- How many times to repeat the test, ie: repeat=1 will run the test twice. + Class containing some utility functions common to both local and remote + mochitest runners """ - if not hasattr(options, 'logFile'): - options.logFile = "" - if not hasattr(options, 'fileLevel'): - options.fileLevel = 'INFO' + # TODO Utility classes are a code smell. This class is temporary + # and should be removed when desktop mochitests are refactored + # on top of mozbase. Each of the functions in here should + # probably live somewhere in mozbase - # allow relative paths for logFile - if options.logFile: - options.logFile = self.getLogFilePath(options.logFile) + oldcwd = os.getcwd() + jarDir = 'mochijar' - # Note that all tests under options.subsuite need to be browser chrome tests. - if options.browserChrome or options.chrome or options.subsuite or \ - options.a11y or options.webapprtChrome or options.jetpackPackage or \ - options.jetpackAddon: - self.makeTestConfig(options) - else: - if options.autorun: - self.urlOpts.append("autorun=1") - if options.timeout: - self.urlOpts.append("timeout=%d" % options.timeout) - if options.closeWhenDone: - self.urlOpts.append("closeWhenDone=1") - if options.webapprtContent: - self.urlOpts.append("testRoot=webapprtContent") - if options.logFile: - self.urlOpts.append("logFile=" + encodeURIComponent(options.logFile)) - self.urlOpts.append("fileLevel=" + encodeURIComponent(options.fileLevel)) - if options.consoleLevel: - self.urlOpts.append("consoleLevel=" + encodeURIComponent(options.consoleLevel)) - if options.totalChunks: - self.urlOpts.append("totalChunks=%d" % options.totalChunks) - self.urlOpts.append("thisChunk=%d" % options.thisChunk) - if options.chunkByDir: - self.urlOpts.append("chunkByDir=%d" % options.chunkByDir) - if options.startAt: - self.urlOpts.append("startAt=%s" % options.startAt) - if options.endAt: - self.urlOpts.append("endAt=%s" % options.endAt) - if options.shuffle: - self.urlOpts.append("shuffle=1") - if "MOZ_HIDE_RESULTS_TABLE" in env and env["MOZ_HIDE_RESULTS_TABLE"] == "1": - self.urlOpts.append("hideResultsTable=1") - if options.runUntilFailure: - self.urlOpts.append("runUntilFailure=1") - if options.repeat: - self.urlOpts.append("repeat=%d" % options.repeat) - if os.path.isfile(os.path.join(self.oldcwd, os.path.dirname(__file__), self.TEST_PATH, options.testPath)) and options.repeat > 0: - self.urlOpts.append("testname=%s" % ("/").join([self.TEST_PATH, options.testPath])) - if options.testManifest: - self.urlOpts.append("testManifest=%s" % options.testManifest) - if hasattr(options, 'runOnly') and options.runOnly: - self.urlOpts.append("runOnly=true") + # Path to the test script on the server + TEST_PATH = "tests" + NESTED_OOP_TEST_PATH = "nested_oop" + CHROME_PATH = "redirect.html" + urlOpts = [] + log = None + + def __init__(self, logger_options): + self.update_mozinfo() + self.server = None + self.wsserver = None + self.sslTunnel = None + self._locations = None + + if self.log is None: + commandline.log_formatters["tbpl"] = ( + MochitestFormatter, + "Mochitest specific tbpl formatter") + self.log = commandline.setup_logging("mochitest", + logger_options, + { + "tbpl": sys.stdout + }) + MochitestUtilsMixin.log = self.log + setAutomationLog(self.log) + + self.message_logger = MessageLogger(logger=self.log) + + def update_mozinfo(self): + """walk up directories to find mozinfo.json update the info""" + # TODO: This should go in a more generic place, e.g. mozinfo + + path = SCRIPT_DIR + dirs = set() + while path != os.path.expanduser('~'): + if path in dirs: + break + dirs.add(path) + path = os.path.split(path)[0] + + mozinfo.find_and_update_from_json(*dirs) + + def getFullPath(self, path): + " Get an absolute path relative to self.oldcwd." + return os.path.normpath( + os.path.join( + self.oldcwd, + os.path.expanduser(path))) + + def getLogFilePath(self, logFile): + """ return the log file path relative to the device we are testing on, in most cases + it will be the full path on the local system + """ + return self.getFullPath(logFile) + + @property + def locations(self): + if self._locations is not None: + return self._locations + locations_file = os.path.join(SCRIPT_DIR, 'server-locations.txt') + self._locations = ServerLocations(locations_file) + return self._locations + + def buildURLOptions(self, options, env): + """ Add test control options from the command line to the url + + URL parameters to test URL: + + autorun -- kick off tests automatically + closeWhenDone -- closes the browser after the tests + hideResultsTable -- hides the table of individual test results + logFile -- logs test run to an absolute path + totalChunks -- how many chunks to split tests into + thisChunk -- which chunk to run + startAt -- name of test to start at + endAt -- name of test to end at + timeout -- per-test timeout in seconds + repeat -- How many times to repeat the test, ie: repeat=1 will run the test twice. + """ + + if not hasattr(options, 'logFile'): + options.logFile = "" + if not hasattr(options, 'fileLevel'): + options.fileLevel = 'INFO' + + # allow relative paths for logFile + if options.logFile: + options.logFile = self.getLogFilePath(options.logFile) + + # Note that all tests under options.subsuite need to be browser chrome + # tests. + if options.browserChrome or options.chrome or options.subsuite or \ + options.a11y or options.webapprtChrome or options.jetpackPackage or \ + options.jetpackAddon: + self.makeTestConfig(options) else: - self.urlOpts.append("runOnly=false") - if options.manifestFile: - self.urlOpts.append("manifestFile=%s" % options.manifestFile) - if options.failureFile: - self.urlOpts.append("failureFile=%s" % self.getFullPath(options.failureFile)) - if options.runSlower: - self.urlOpts.append("runSlower=true") - if options.debugOnFailure: - self.urlOpts.append("debugOnFailure=true") - if options.dumpOutputDirectory: - self.urlOpts.append("dumpOutputDirectory=%s" % encodeURIComponent(options.dumpOutputDirectory)) - if options.dumpAboutMemoryAfterTest: - self.urlOpts.append("dumpAboutMemoryAfterTest=true") - if options.dumpDMDAfterTest: - self.urlOpts.append("dumpDMDAfterTest=true") - if options.debugger: - self.urlOpts.append("interactiveDebugger=true") + if options.autorun: + self.urlOpts.append("autorun=1") + if options.timeout: + self.urlOpts.append("timeout=%d" % options.timeout) + if options.closeWhenDone: + self.urlOpts.append("closeWhenDone=1") + if options.webapprtContent: + self.urlOpts.append("testRoot=webapprtContent") + if options.logFile: + self.urlOpts.append( + "logFile=" + + encodeURIComponent( + options.logFile)) + self.urlOpts.append( + "fileLevel=" + + encodeURIComponent( + options.fileLevel)) + if options.consoleLevel: + self.urlOpts.append( + "consoleLevel=" + + encodeURIComponent( + options.consoleLevel)) + if options.totalChunks: + self.urlOpts.append("totalChunks=%d" % options.totalChunks) + self.urlOpts.append("thisChunk=%d" % options.thisChunk) + if options.chunkByDir: + self.urlOpts.append("chunkByDir=%d" % options.chunkByDir) + if options.startAt: + self.urlOpts.append("startAt=%s" % options.startAt) + if options.endAt: + self.urlOpts.append("endAt=%s" % options.endAt) + if options.shuffle: + self.urlOpts.append("shuffle=1") + if "MOZ_HIDE_RESULTS_TABLE" in env and env[ + "MOZ_HIDE_RESULTS_TABLE"] == "1": + self.urlOpts.append("hideResultsTable=1") + if options.runUntilFailure: + self.urlOpts.append("runUntilFailure=1") + if options.repeat: + self.urlOpts.append("repeat=%d" % options.repeat) + if os.path.isfile( + os.path.join( + self.oldcwd, + os.path.dirname(__file__), + self.TEST_PATH, + options.testPath)) and options.repeat > 0: + self.urlOpts.append("testname=%s" % + ("/").join([self.TEST_PATH, options.testPath])) + if options.testManifest: + self.urlOpts.append("testManifest=%s" % options.testManifest) + if hasattr(options, 'runOnly') and options.runOnly: + self.urlOpts.append("runOnly=true") + else: + self.urlOpts.append("runOnly=false") + if options.manifestFile: + self.urlOpts.append("manifestFile=%s" % options.manifestFile) + if options.failureFile: + self.urlOpts.append( + "failureFile=%s" % + self.getFullPath( + options.failureFile)) + if options.runSlower: + self.urlOpts.append("runSlower=true") + if options.debugOnFailure: + self.urlOpts.append("debugOnFailure=true") + if options.dumpOutputDirectory: + self.urlOpts.append( + "dumpOutputDirectory=%s" % + encodeURIComponent( + options.dumpOutputDirectory)) + if options.dumpAboutMemoryAfterTest: + self.urlOpts.append("dumpAboutMemoryAfterTest=true") + if options.dumpDMDAfterTest: + self.urlOpts.append("dumpDMDAfterTest=true") + if options.debugger: + self.urlOpts.append("interactiveDebugger=true") - def getTestFlavor(self, options): - if options.browserChrome: - return "browser-chrome" - elif options.jetpackPackage: - return "jetpack-package" - elif options.jetpackAddon: - return "jetpack-addon" - elif options.chrome: - return "chrome" - elif options.a11y: - return "a11y" - elif options.webapprtChrome: - return "webapprt-chrome" - elif options.webapprtContent: - return "webapprt-content" - else: - return "mochitest" - - # This check can be removed when bug 983867 is fixed. - def isTest(self, options, filename): - allow_js_css = False - if options.browserChrome: - allow_js_css = True - testPattern = re.compile(r"browser_.+\.js") - elif options.jetpackPackage: - allow_js_css = True - testPattern = re.compile(r"test-.+\.js") - elif options.jetpackAddon: - testPattern = re.compile(r".+\.xpi") - elif options.chrome or options.a11y: - testPattern = re.compile(r"(browser|test)_.+\.(xul|html|js|xhtml)") - elif options.webapprtContent: - testPattern = re.compile(r"webapprt_") - elif options.webapprtChrome: - allow_js_css = True - testPattern = re.compile(r"browser_") - else: - testPattern = re.compile(r"test_") - - if not allow_js_css and (".js" in filename or ".css" in filename): - return False - - pathPieces = filename.split("/") - - return (testPattern.match(pathPieces[-1]) and - not re.search(r'\^headers\^$', filename)) - - def getTestPath(self, options): - if options.ipcplugins: - return "dom/plugins/test/mochitest" - else: - return options.testPath - - def setTestRoot(self, options): - if hasattr(self, "testRoot"): - return self.testRoot, self.testRootAbs - else: - if options.browserChrome: - if options.immersiveMode: - self.testRoot = 'metro' + def getTestFlavor(self, options): + if options.browserChrome: + return "browser-chrome" + elif options.jetpackPackage: + return "jetpack-package" + elif options.jetpackAddon: + return "jetpack-addon" + elif options.chrome: + return "chrome" + elif options.a11y: + return "a11y" + elif options.webapprtChrome: + return "webapprt-chrome" + elif options.webapprtContent: + return "webapprt-content" else: - self.testRoot = 'browser' - elif options.jetpackPackage: - self.testRoot = 'jetpack-package' - elif options.jetpackAddon: - self.testRoot = 'jetpack-addon' - elif options.a11y: - self.testRoot = 'a11y' - elif options.webapprtChrome: - self.testRoot = 'webapprtChrome' - elif options.webapprtContent: - self.testRoot = 'webapprtContent' - elif options.chrome: - self.testRoot = 'chrome' - else: - self.testRoot = self.TEST_PATH - self.testRootAbs = os.path.join(SCRIPT_DIR, self.testRoot) + return "mochitest" - def buildTestURL(self, options): - testHost = "http://mochi.test:8888" - testPath = self.getTestPath(options) - testURL = "/".join([testHost, self.TEST_PATH, testPath]) - if os.path.isfile(os.path.join(self.oldcwd, os.path.dirname(__file__), self.TEST_PATH, testPath)) and options.repeat > 0: - testURL = "/".join([testHost, self.TEST_PATH, os.path.dirname(testPath)]) - if options.chrome or options.a11y: - testURL = "/".join([testHost, self.CHROME_PATH]) - elif options.browserChrome or options.jetpackPackage or options.jetpackAddon: - testURL = "about:blank" - if options.nested_oop: - testURL = "/".join([testHost, self.NESTED_OOP_TEST_PATH]) - return testURL + # This check can be removed when bug 983867 is fixed. + def isTest(self, options, filename): + allow_js_css = False + if options.browserChrome: + allow_js_css = True + testPattern = re.compile(r"browser_.+\.js") + elif options.jetpackPackage: + allow_js_css = True + testPattern = re.compile(r"test-.+\.js") + elif options.jetpackAddon: + testPattern = re.compile(r".+\.xpi") + elif options.chrome or options.a11y: + testPattern = re.compile(r"(browser|test)_.+\.(xul|html|js|xhtml)") + elif options.webapprtContent: + testPattern = re.compile(r"webapprt_") + elif options.webapprtChrome: + allow_js_css = True + testPattern = re.compile(r"browser_") + else: + testPattern = re.compile(r"test_") - def buildTestPath(self, options, testsToFilter=None, disabled=True): - """ Build the url path to the specific test harness and test file or directory - Build a manifest of tests to run and write out a json file for the harness to read - testsToFilter option is used to filter/keep the tests provided in the list + if not allow_js_css and (".js" in filename or ".css" in filename): + return False - disabled -- This allows to add all disabled tests on the build side - and then on the run side to only run the enabled ones - """ + pathPieces = filename.split("/") - tests = self.getActiveTests(options, disabled) - paths = [] - for test in tests: - if testsToFilter and (test['path'] not in testsToFilter): - continue - paths.append(test) + return (testPattern.match(pathPieces[-1]) and + not re.search(r'\^headers\^$', filename)) - # Bug 883865 - add this functionality into manifestparser - with open(os.path.join(SCRIPT_DIR, options.testRunManifestFile), 'w') as manifestFile: - manifestFile.write(json.dumps({'tests': paths})) - options.manifestFile = options.testRunManifestFile + def getTestPath(self, options): + if options.ipcplugins: + return "dom/plugins/test/mochitest" + else: + return options.testPath - return self.buildTestURL(options) + def setTestRoot(self, options): + if hasattr(self, "testRoot"): + return self.testRoot, self.testRootAbs + else: + if options.browserChrome: + if options.immersiveMode: + self.testRoot = 'metro' + else: + self.testRoot = 'browser' + elif options.jetpackPackage: + self.testRoot = 'jetpack-package' + elif options.jetpackAddon: + self.testRoot = 'jetpack-addon' + elif options.a11y: + self.testRoot = 'a11y' + elif options.webapprtChrome: + self.testRoot = 'webapprtChrome' + elif options.webapprtContent: + self.testRoot = 'webapprtContent' + elif options.chrome: + self.testRoot = 'chrome' + else: + self.testRoot = self.TEST_PATH + self.testRootAbs = os.path.join(SCRIPT_DIR, self.testRoot) - def startWebSocketServer(self, options, debuggerInfo): - """ Launch the websocket server """ - self.wsserver = WebSocketServer(options, SCRIPT_DIR, self.log, debuggerInfo) - self.wsserver.start() + def buildTestURL(self, options): + testHost = "http://mochi.test:8888" + testPath = self.getTestPath(options) + testURL = "/".join([testHost, self.TEST_PATH, testPath]) + if os.path.isfile( + os.path.join( + self.oldcwd, + os.path.dirname(__file__), + self.TEST_PATH, + testPath)) and options.repeat > 0: + testURL = "/".join([testHost, + self.TEST_PATH, + os.path.dirname(testPath)]) + if options.chrome or options.a11y: + testURL = "/".join([testHost, self.CHROME_PATH]) + elif options.browserChrome or options.jetpackPackage or options.jetpackAddon: + testURL = "about:blank" + if options.nested_oop: + testURL = "/".join([testHost, self.NESTED_OOP_TEST_PATH]) + return testURL - def startWebServer(self, options): - """Create the webserver and start it up""" + def buildTestPath(self, options, testsToFilter=None, disabled=True): + """ Build the url path to the specific test harness and test file or directory + Build a manifest of tests to run and write out a json file for the harness to read + testsToFilter option is used to filter/keep the tests provided in the list - self.server = MochitestServer(options, self.log) - self.server.start() + disabled -- This allows to add all disabled tests on the build side + and then on the run side to only run the enabled ones + """ - if options.pidFile != "": - with open(options.pidFile + ".xpcshell.pid", 'w') as f: - f.write("%s" % self.server._process.pid) + tests = self.getActiveTests(options, disabled) + paths = [] + for test in tests: + if testsToFilter and (test['path'] not in testsToFilter): + continue + paths.append(test) - def startServers(self, options, debuggerInfo, ignoreSSLTunnelExts = False): - # start servers and set ports - # TODO: pass these values, don't set on `self` - self.webServer = options.webServer - self.httpPort = options.httpPort - self.sslPort = options.sslPort - self.webSocketPort = options.webSocketPort + # Bug 883865 - add this functionality into manifestparser + with open(os.path.join(SCRIPT_DIR, options.testRunManifestFile), 'w') as manifestFile: + manifestFile.write(json.dumps({'tests': paths})) + options.manifestFile = options.testRunManifestFile - # httpd-path is specified by standard makefile targets and may be specified - # on the command line to select a particular version of httpd.js. If not - # specified, try to select the one from hostutils.zip, as required in bug 882932. - if not options.httpdPath: - options.httpdPath = os.path.join(options.utilityPath, "components") + return self.buildTestURL(options) - self.startWebServer(options) - self.startWebSocketServer(options, debuggerInfo) + def startWebSocketServer(self, options, debuggerInfo): + """ Launch the websocket server """ + self.wsserver = WebSocketServer( + options, + SCRIPT_DIR, + self.log, + debuggerInfo) + self.wsserver.start() - # start SSL pipe - self.sslTunnel = SSLTunnel(options, logger=self.log, ignoreSSLTunnelExts = ignoreSSLTunnelExts) - self.sslTunnel.buildConfig(self.locations) - self.sslTunnel.start() + def startWebServer(self, options): + """Create the webserver and start it up""" - # If we're lucky, the server has fully started by now, and all paths are - # ready, etc. However, xpcshell cold start times suck, at least for debug - # builds. We'll try to connect to the server for awhile, and if we fail, - # we'll try to kill the server and exit with an error. - if self.server is not None: - self.server.ensureReady(self.SERVER_STARTUP_TIMEOUT) + self.server = MochitestServer(options, self.log) + self.server.start() - def stopServers(self): - """Servers are no longer needed, and perhaps more importantly, anything they - might spew to console might confuse things.""" - if self.server is not None: - try: - self.log.info('Stopping web server') - self.server.stop() - except Exception: - self.log.critical('Exception when stopping web server') + if options.pidFile != "": + with open(options.pidFile + ".xpcshell.pid", 'w') as f: + f.write("%s" % self.server._process.pid) - if self.wsserver is not None: - try: - self.log.info('Stopping web socket server') - self.wsserver.stop() - except Exception: - self.log.critical('Exception when stopping web socket server'); + def startServers(self, options, debuggerInfo, ignoreSSLTunnelExts=False): + # start servers and set ports + # TODO: pass these values, don't set on `self` + self.webServer = options.webServer + self.httpPort = options.httpPort + self.sslPort = options.sslPort + self.webSocketPort = options.webSocketPort - if self.sslTunnel is not None: - try: - self.log.info('Stopping ssltunnel') - self.sslTunnel.stop() - except Exception: - self.log.critical('Exception stopping ssltunnel'); + # httpd-path is specified by standard makefile targets and may be specified + # on the command line to select a particular version of httpd.js. If not + # specified, try to select the one from hostutils.zip, as required in + # bug 882932. + if not options.httpdPath: + options.httpdPath = os.path.join(options.utilityPath, "components") - def copyExtraFilesToProfile(self, options): - "Copy extra files or dirs specified on the command line to the testing profile." - for f in options.extraProfileFiles: - abspath = self.getFullPath(f) - if os.path.isfile(abspath): - shutil.copy2(abspath, options.profilePath) - elif os.path.isdir(abspath): - dest = os.path.join(options.profilePath, os.path.basename(abspath)) - shutil.copytree(abspath, dest) - else: - self.log.warning("runtests.py | Failed to copy %s to profile" % abspath) + self.startWebServer(options) + self.startWebSocketServer(options, debuggerInfo) - def installChromeJar(self, chrome, options): - """ - copy mochijar directory to profile as an extension so we have chrome://mochikit for all harness code - """ - # Write chrome.manifest. - with open(os.path.join(options.profilePath, "extensions", "staged", "mochikit@mozilla.org", "chrome.manifest"), "a") as mfile: - mfile.write(chrome) + # start SSL pipe + self.sslTunnel = SSLTunnel( + options, + logger=self.log, + ignoreSSLTunnelExts=ignoreSSLTunnelExts) + self.sslTunnel.buildConfig(self.locations) + self.sslTunnel.start() - def getChromeTestDir(self, options): - dir = os.path.join(os.path.abspath("."), SCRIPT_DIR) + "/" - if mozinfo.isWin: - dir = "file:///" + dir.replace("\\", "/") - return dir + # If we're lucky, the server has fully started by now, and all paths are + # ready, etc. However, xpcshell cold start times suck, at least for debug + # builds. We'll try to connect to the server for awhile, and if we fail, + # we'll try to kill the server and exit with an error. + if self.server is not None: + self.server.ensureReady(self.SERVER_STARTUP_TIMEOUT) - def writeChromeManifest(self, options): - manifest = os.path.join(options.profilePath, "tests.manifest") - with open(manifest, "w") as manifestFile: - # Register chrome directory. - chrometestDir = self.getChromeTestDir(options) - manifestFile.write("content mochitests %s contentaccessible=yes\n" % chrometestDir) - manifestFile.write("content mochitests-any %s contentaccessible=yes remoteenabled=yes\n" % chrometestDir) - manifestFile.write("content mochitests-content %s contentaccessible=yes remoterequired=yes\n" % chrometestDir) + def stopServers(self): + """Servers are no longer needed, and perhaps more importantly, anything they + might spew to console might confuse things.""" + if self.server is not None: + try: + self.log.info('Stopping web server') + self.server.stop() + except Exception: + self.log.critical('Exception when stopping web server') - if options.testingModulesDir is not None: - manifestFile.write("resource testing-common file:///%s\n" % - options.testingModulesDir) - return manifest + if self.wsserver is not None: + try: + self.log.info('Stopping web socket server') + self.wsserver.stop() + except Exception: + self.log.critical('Exception when stopping web socket server') - def addChromeToProfile(self, options): - "Adds MochiKit chrome tests to the profile." + if self.sslTunnel is not None: + try: + self.log.info('Stopping ssltunnel') + self.sslTunnel.stop() + except Exception: + self.log.critical('Exception stopping ssltunnel') - # Create (empty) chrome directory. - chromedir = os.path.join(options.profilePath, "chrome") - os.mkdir(chromedir) + def copyExtraFilesToProfile(self, options): + "Copy extra files or dirs specified on the command line to the testing profile." + for f in options.extraProfileFiles: + abspath = self.getFullPath(f) + if os.path.isfile(abspath): + shutil.copy2(abspath, options.profilePath) + elif os.path.isdir(abspath): + dest = os.path.join( + options.profilePath, + os.path.basename(abspath)) + shutil.copytree(abspath, dest) + else: + self.log.warning( + "runtests.py | Failed to copy %s to profile" % + abspath) - # Write userChrome.css. - chrome = """ + def installChromeJar(self, chrome, options): + """ + copy mochijar directory to profile as an extension so we have chrome://mochikit for all harness code + """ + # Write chrome.manifest. + with open(os.path.join(options.profilePath, "extensions", "staged", "mochikit@mozilla.org", "chrome.manifest"), "a") as mfile: + mfile.write(chrome) + + def getChromeTestDir(self, options): + dir = os.path.join(os.path.abspath("."), SCRIPT_DIR) + "/" + if mozinfo.isWin: + dir = "file:///" + dir.replace("\\", "/") + return dir + + def writeChromeManifest(self, options): + manifest = os.path.join(options.profilePath, "tests.manifest") + with open(manifest, "w") as manifestFile: + # Register chrome directory. + chrometestDir = self.getChromeTestDir(options) + manifestFile.write( + "content mochitests %s contentaccessible=yes\n" % + chrometestDir) + manifestFile.write( + "content mochitests-any %s contentaccessible=yes remoteenabled=yes\n" % + chrometestDir) + manifestFile.write( + "content mochitests-content %s contentaccessible=yes remoterequired=yes\n" % + chrometestDir) + + if options.testingModulesDir is not None: + manifestFile.write("resource testing-common file:///%s\n" % + options.testingModulesDir) + return manifest + + def addChromeToProfile(self, options): + "Adds MochiKit chrome tests to the profile." + + # Create (empty) chrome directory. + chromedir = os.path.join(options.profilePath, "chrome") + os.mkdir(chromedir) + + # Write userChrome.css. + chrome = """ @namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); /* set default namespace to XUL */ toolbar, toolbarpalette { @@ -824,1409 +931,1597 @@ toolbar#nav-bar { background-image: none !important; } """ - with open(os.path.join(options.profilePath, "userChrome.css"), "a") as chromeFile: - chromeFile.write(chrome) + with open(os.path.join(options.profilePath, "userChrome.css"), "a") as chromeFile: + chromeFile.write(chrome) - manifest = self.writeChromeManifest(options) + manifest = self.writeChromeManifest(options) - # Call installChromeJar(). - if not os.path.isdir(os.path.join(SCRIPT_DIR, self.jarDir)): - self.log.error("TEST-UNEXPECTED-FAIL | invalid setup: missing mochikit extension") - return None + # Call installChromeJar(). + if not os.path.isdir(os.path.join(SCRIPT_DIR, self.jarDir)): + self.log.error( + "TEST-UNEXPECTED-FAIL | invalid setup: missing mochikit extension") + return None - # Support Firefox (browser), B2G (shell), SeaMonkey (navigator), and Webapp - # Runtime (webapp). - chrome = "" - if options.browserChrome or options.chrome or options.a11y or options.webapprtChrome: - chrome += """ + # Support Firefox (browser), B2G (shell), SeaMonkey (navigator), and Webapp + # Runtime (webapp). + chrome = "" + if options.browserChrome or options.chrome or options.a11y or options.webapprtChrome: + chrome += """ overlay chrome://browser/content/browser.xul chrome://mochikit/content/browser-test-overlay.xul overlay chrome://browser/content/shell.xhtml chrome://mochikit/content/browser-test-overlay.xul overlay chrome://navigator/content/navigator.xul chrome://mochikit/content/browser-test-overlay.xul overlay chrome://webapprt/content/webapp.xul chrome://mochikit/content/browser-test-overlay.xul """ - if options.jetpackPackage: - chrome += """ + if options.jetpackPackage: + chrome += """ overlay chrome://browser/content/browser.xul chrome://mochikit/content/jetpack-package-overlay.xul """ - if options.jetpackAddon: - chrome += """ + if options.jetpackAddon: + chrome += """ overlay chrome://browser/content/browser.xul chrome://mochikit/content/jetpack-addon-overlay.xul """ - self.installChromeJar(chrome, options) - return manifest + self.installChromeJar(chrome, options) + return manifest - def getExtensionsToInstall(self, options): - "Return a list of extensions to install in the profile" - extensions = options.extensionsToInstall or [] - appDir = options.app[:options.app.rfind(os.sep)] if options.app else options.utilityPath + def getExtensionsToInstall(self, options): + "Return a list of extensions to install in the profile" + extensions = options.extensionsToInstall or [] + appDir = options.app[ + :options.app.rfind( + os.sep)] if options.app else options.utilityPath - extensionDirs = [ - # Extensions distributed with the test harness. - os.path.normpath(os.path.join(SCRIPT_DIR, "extensions")), - ] - if appDir: - # Extensions distributed with the application. - extensionDirs.append(os.path.join(appDir, "distribution", "extensions")) + extensionDirs = [ + # Extensions distributed with the test harness. + os.path.normpath(os.path.join(SCRIPT_DIR, "extensions")), + ] + if appDir: + # Extensions distributed with the application. + extensionDirs.append( + os.path.join( + appDir, + "distribution", + "extensions")) - for extensionDir in extensionDirs: - if os.path.isdir(extensionDir): - for dirEntry in os.listdir(extensionDir): - if dirEntry not in options.extensionsToExclude: - path = os.path.join(extensionDir, dirEntry) - if os.path.isdir(path) or (os.path.isfile(path) and path.endswith(".xpi")): - extensions.append(path) + for extensionDir in extensionDirs: + if os.path.isdir(extensionDir): + for dirEntry in os.listdir(extensionDir): + if dirEntry not in options.extensionsToExclude: + path = os.path.join(extensionDir, dirEntry) + if os.path.isdir(path) or ( + os.path.isfile(path) and path.endswith(".xpi")): + extensions.append(path) + + # append mochikit + extensions.append(os.path.join(SCRIPT_DIR, self.jarDir)) + return extensions - # append mochikit - extensions.append(os.path.join(SCRIPT_DIR, self.jarDir)) - return extensions class SSLTunnel: - def __init__(self, options, logger, ignoreSSLTunnelExts = False): - self.log = logger - self.process = None - self.utilityPath = options.utilityPath - self.xrePath = options.xrePath - self.certPath = options.certPath - self.sslPort = options.sslPort - self.httpPort = options.httpPort - self.webServer = options.webServer - self.webSocketPort = options.webSocketPort - self.useSSLTunnelExts = not ignoreSSLTunnelExts - self.customCertRE = re.compile("^cert=(?P[0-9a-zA-Z_ ]+)") - self.clientAuthRE = re.compile("^clientauth=(?P[a-z]+)") - self.redirRE = re.compile("^redir=(?P[0-9a-zA-Z_ .]+)") + def __init__(self, options, logger, ignoreSSLTunnelExts=False): + self.log = logger + self.process = None + self.utilityPath = options.utilityPath + self.xrePath = options.xrePath + self.certPath = options.certPath + self.sslPort = options.sslPort + self.httpPort = options.httpPort + self.webServer = options.webServer + self.webSocketPort = options.webSocketPort + self.useSSLTunnelExts = not ignoreSSLTunnelExts - def writeLocation(self, config, loc): - for option in loc.options: - match = self.customCertRE.match(option) - if match: - customcert = match.group("nickname"); - config.write("listen:%s:%s:%s:%s\n" % - (loc.host, loc.port, self.sslPort, customcert)) + self.customCertRE = re.compile("^cert=(?P[0-9a-zA-Z_ ]+)") + self.clientAuthRE = re.compile("^clientauth=(?P[a-z]+)") + self.redirRE = re.compile("^redir=(?P[0-9a-zA-Z_ .]+)") - match = self.clientAuthRE.match(option) - if match: - clientauth = match.group("clientauth"); - config.write("clientauth:%s:%s:%s:%s\n" % - (loc.host, loc.port, self.sslPort, clientauth)) + def writeLocation(self, config, loc): + for option in loc.options: + match = self.customCertRE.match(option) + if match: + customcert = match.group("nickname") + config.write("listen:%s:%s:%s:%s\n" % + (loc.host, loc.port, self.sslPort, customcert)) - match = self.redirRE.match(option) - if match: - redirhost = match.group("redirhost") - config.write("redirhost:%s:%s:%s:%s\n" % - (loc.host, loc.port, self.sslPort, redirhost)) + match = self.clientAuthRE.match(option) + if match: + clientauth = match.group("clientauth") + config.write("clientauth:%s:%s:%s:%s\n" % + (loc.host, loc.port, self.sslPort, clientauth)) - if self.useSSLTunnelExts and option in ('ssl3', 'rc4', 'failHandshake'): - config.write("%s:%s:%s:%s\n" % (option, loc.host, loc.port, self.sslPort)) + match = self.redirRE.match(option) + if match: + redirhost = match.group("redirhost") + config.write("redirhost:%s:%s:%s:%s\n" % + (loc.host, loc.port, self.sslPort, redirhost)) - def buildConfig(self, locations): - """Create the ssltunnel configuration file""" - configFd, self.configFile = tempfile.mkstemp(prefix="ssltunnel", suffix=".cfg") - with os.fdopen(configFd, "w") as config: - config.write("httpproxy:1\n") - config.write("certdbdir:%s\n" % self.certPath) - config.write("forward:127.0.0.1:%s\n" % self.httpPort) - config.write("websocketserver:%s:%s\n" % (self.webServer, self.webSocketPort)) - config.write("listen:*:%s:pgo server certificate\n" % self.sslPort) + if self.useSSLTunnelExts and option in ( + 'ssl3', + 'rc4', + 'failHandshake'): + config.write( + "%s:%s:%s:%s\n" % + (option, loc.host, loc.port, self.sslPort)) - for loc in locations: - if loc.scheme == "https" and "nocert" not in loc.options: - self.writeLocation(config, loc) + def buildConfig(self, locations): + """Create the ssltunnel configuration file""" + configFd, self.configFile = tempfile.mkstemp( + prefix="ssltunnel", suffix=".cfg") + with os.fdopen(configFd, "w") as config: + config.write("httpproxy:1\n") + config.write("certdbdir:%s\n" % self.certPath) + config.write("forward:127.0.0.1:%s\n" % self.httpPort) + config.write( + "websocketserver:%s:%s\n" % + (self.webServer, self.webSocketPort)) + config.write("listen:*:%s:pgo server certificate\n" % self.sslPort) - def start(self): - """ Starts the SSL Tunnel """ + for loc in locations: + if loc.scheme == "https" and "nocert" not in loc.options: + self.writeLocation(config, loc) - # start ssltunnel to provide https:// URLs capability - bin_suffix = mozinfo.info.get('bin_suffix', '') - ssltunnel = os.path.join(self.utilityPath, "ssltunnel" + bin_suffix) - if not os.path.exists(ssltunnel): - self.log.error("INFO | runtests.py | expected to find ssltunnel at %s" % ssltunnel) - exit(1) + def start(self): + """ Starts the SSL Tunnel """ - env = environment(xrePath=self.xrePath) - env["LD_LIBRARY_PATH"] = self.xrePath - self.process = mozprocess.ProcessHandler([ssltunnel, self.configFile], - env=env) - self.process.run() - self.log.info("runtests.py | SSL tunnel pid: %d" % self.process.pid) + # start ssltunnel to provide https:// URLs capability + bin_suffix = mozinfo.info.get('bin_suffix', '') + ssltunnel = os.path.join(self.utilityPath, "ssltunnel" + bin_suffix) + if not os.path.exists(ssltunnel): + self.log.error( + "INFO | runtests.py | expected to find ssltunnel at %s" % + ssltunnel) + exit(1) + + env = environment(xrePath=self.xrePath) + env["LD_LIBRARY_PATH"] = self.xrePath + self.process = mozprocess.ProcessHandler([ssltunnel, self.configFile], + env=env) + self.process.run() + self.log.info("runtests.py | SSL tunnel pid: %d" % self.process.pid) + + def stop(self): + """ Stops the SSL Tunnel and cleans up """ + if self.process is not None: + self.process.kill() + if os.path.exists(self.configFile): + os.remove(self.configFile) - def stop(self): - """ Stops the SSL Tunnel and cleans up """ - if self.process is not None: - self.process.kill() - if os.path.exists(self.configFile): - os.remove(self.configFile) def checkAndConfigureV4l2loopback(device): - ''' - Determine if a given device path is a v4l2loopback device, and if so - toggle a few settings on it via fcntl. Very linux-specific. + ''' + Determine if a given device path is a v4l2loopback device, and if so + toggle a few settings on it via fcntl. Very linux-specific. - Returns (status, device name) where status is a boolean. - ''' - if not mozinfo.isLinux: - return False, '' + Returns (status, device name) where status is a boolean. + ''' + if not mozinfo.isLinux: + return False, '' - libc = ctypes.cdll.LoadLibrary('libc.so.6') - O_RDWR = 2 - # These are from linux/videodev2.h - class v4l2_capability(ctypes.Structure): - _fields_ = [ - ('driver', ctypes.c_char * 16), - ('card', ctypes.c_char * 32), - ('bus_info', ctypes.c_char * 32), - ('version', ctypes.c_uint32), - ('capabilities', ctypes.c_uint32), - ('device_caps', ctypes.c_uint32), - ('reserved', ctypes.c_uint32 * 3) - ] - VIDIOC_QUERYCAP = 0x80685600 + libc = ctypes.cdll.LoadLibrary('libc.so.6') + O_RDWR = 2 + # These are from linux/videodev2.h - fd = libc.open(device, O_RDWR) - if fd < 0: - return False, '' + class v4l2_capability(ctypes.Structure): + _fields_ = [ + ('driver', ctypes.c_char * 16), + ('card', ctypes.c_char * 32), + ('bus_info', ctypes.c_char * 32), + ('version', ctypes.c_uint32), + ('capabilities', ctypes.c_uint32), + ('device_caps', ctypes.c_uint32), + ('reserved', ctypes.c_uint32 * 3) + ] + VIDIOC_QUERYCAP = 0x80685600 - vcap = v4l2_capability() - if libc.ioctl(fd, VIDIOC_QUERYCAP, ctypes.byref(vcap)) != 0: - return False, '' + fd = libc.open(device, O_RDWR) + if fd < 0: + return False, '' - if vcap.driver != 'v4l2 loopback': - return False, '' + vcap = v4l2_capability() + if libc.ioctl(fd, VIDIOC_QUERYCAP, ctypes.byref(vcap)) != 0: + return False, '' - class v4l2_control(ctypes.Structure): - _fields_ = [ - ('id', ctypes.c_uint32), - ('value', ctypes.c_int32) - ] + if vcap.driver != 'v4l2 loopback': + return False, '' - # These are private v4l2 control IDs, see: - # https://github.com/umlaeute/v4l2loopback/blob/fd822cf0faaccdf5f548cddd9a5a3dcebb6d584d/v4l2loopback.c#L131 - KEEP_FORMAT = 0x8000000 - SUSTAIN_FRAMERATE = 0x8000001 - VIDIOC_S_CTRL = 0xc008561c + class v4l2_control(ctypes.Structure): + _fields_ = [ + ('id', ctypes.c_uint32), + ('value', ctypes.c_int32) + ] - control = v4l2_control() - control.id = KEEP_FORMAT - control.value = 1 - libc.ioctl(fd, VIDIOC_S_CTRL, ctypes.byref(control)) + # These are private v4l2 control IDs, see: + # https://github.com/umlaeute/v4l2loopback/blob/fd822cf0faaccdf5f548cddd9a5a3dcebb6d584d/v4l2loopback.c#L131 + KEEP_FORMAT = 0x8000000 + SUSTAIN_FRAMERATE = 0x8000001 + VIDIOC_S_CTRL = 0xc008561c - control.id = SUSTAIN_FRAMERATE - control.value = 1 - libc.ioctl(fd, VIDIOC_S_CTRL, ctypes.byref(control)) - libc.close(fd) + control = v4l2_control() + control.id = KEEP_FORMAT + control.value = 1 + libc.ioctl(fd, VIDIOC_S_CTRL, ctypes.byref(control)) + + control.id = SUSTAIN_FRAMERATE + control.value = 1 + libc.ioctl(fd, VIDIOC_S_CTRL, ctypes.byref(control)) + libc.close(fd) + + return True, vcap.card - return True, vcap.card def findTestMediaDevices(log): - ''' - Find the test media devices configured on this system, and return a dict - containing information about them. The dict will have keys for 'audio' - and 'video', each containing the name of the media device to use. + ''' + Find the test media devices configured on this system, and return a dict + containing information about them. The dict will have keys for 'audio' + and 'video', each containing the name of the media device to use. - If audio and video devices could not be found, return None. + If audio and video devices could not be found, return None. - This method is only currently implemented for Linux. - ''' - if not mozinfo.isLinux: - return None - - info = {} - # Look for a v4l2loopback device. - name = None - device = None - for dev in sorted(glob.glob('/dev/video*')): - result, name_ = checkAndConfigureV4l2loopback(dev) - if result: - name = name_ - device = dev - break - - if not (name and device): - log.error('Couldn\'t find a v4l2loopback video device') - return None - - # Feed it a frame of output so it has something to display - subprocess.check_call(['/usr/bin/gst-launch-0.10', 'videotestsrc', - 'pattern=green', 'num-buffers=1', '!', - 'v4l2sink', 'device=%s' % device]) - info['video'] = name - - # Use pactl to see if the PulseAudio module-sine-source module is loaded. - def sine_source_loaded(): - o = subprocess.check_output(['/usr/bin/pactl', 'list', 'short', 'modules']) - return filter(lambda x: 'module-sine-source' in x, o.splitlines()) - - if not sine_source_loaded(): - # Load module-sine-source - subprocess.check_call(['/usr/bin/pactl', 'load-module', - 'module-sine-source']) - if not sine_source_loaded(): - log.error('Couldn\'t load module-sine-source') - return None - - # Hardcode the name since it's always the same. - info['audio'] = 'Sine source at 440 Hz' - return info - -class KeyValueParseError(Exception): - """error when parsing strings of serialized key-values""" - def __init__(self, msg, errors=()): - self.errors = errors - Exception.__init__(self, msg) - -def parseKeyValue(strings, separator='=', context='key, value: '): - """ - parse string-serialized key-value pairs in the form of - `key = value`. Returns a list of 2-tuples. - Note that whitespace is not stripped. - """ - - # syntax check - missing = [string for string in strings if separator not in string] - if missing: - raise KeyValueParseError("Error: syntax error in %s" % (context, - ','.join(missing)), - errors=missing) - return [string.split(separator, 1) for string in strings] - -class Mochitest(MochitestUtilsMixin): - certdbNew = False - sslTunnel = None - vmwareHelper = None - DEFAULT_TIMEOUT = 60.0 - mediaDevices = None - - # XXX use automation.py for test name to avoid breaking legacy - # TODO: replace this with 'runtests.py' or 'mochitest' or the like - test_name = 'automation.py' - - def __init__(self, logger_options): - super(Mochitest, self).__init__(logger_options) - - # environment function for browserEnv - self.environment = environment - - # Max time in seconds to wait for server startup before tests will fail -- if - # this seems big, it's mostly for debug machines where cold startup - # (particularly after a build) takes forever. - self.SERVER_STARTUP_TIMEOUT = 180 if mozinfo.info.get('debug') else 90 - - # metro browser sub process id - self.browserProcessId = None - - - self.haveDumpedScreen = False - # Create variables to count the number of passes, fails, todos. - self.countpass = 0 - self.countfail = 0 - self.counttodo = 0 - - self.expectedError = {} - self.result = {} - - def extraPrefs(self, extraPrefs): - """interpolate extra preferences from option strings""" - - try: - return dict(parseKeyValue(extraPrefs, context='--setpref=')) - except KeyValueParseError, e: - print str(e) - sys.exit(1) - - def fillCertificateDB(self, options): - # TODO: move -> mozprofile: - # https://bugzilla.mozilla.org/show_bug.cgi?id=746243#c35 - - pwfilePath = os.path.join(options.profilePath, ".crtdbpw") - with open(pwfilePath, "w") as pwfile: - pwfile.write("\n") - - # Pre-create the certification database for the profile - env = self.environment(xrePath=options.xrePath) - env["LD_LIBRARY_PATH"] = options.xrePath - bin_suffix = mozinfo.info.get('bin_suffix', '') - certutil = os.path.join(options.utilityPath, "certutil" + bin_suffix) - pk12util = os.path.join(options.utilityPath, "pk12util" + bin_suffix) - - if self.certdbNew: - # android and b2g use the new DB formats exclusively - certdbPath = "sql:" + options.profilePath - else: - # desktop seems to use the old - certdbPath = options.profilePath - - status = call([certutil, "-N", "-d", certdbPath, "-f", pwfilePath], env=env) - if status: - return status - - # Walk the cert directory and add custom CAs and client certs - files = os.listdir(options.certPath) - for item in files: - root, ext = os.path.splitext(item) - if ext == ".ca": - trustBits = "CT,," - if root.endswith("-object"): - trustBits = "CT,,CT" - call([certutil, "-A", "-i", os.path.join(options.certPath, item), - "-d", certdbPath, "-f", pwfilePath, "-n", root, "-t", trustBits], - env=env) - elif ext == ".client": - call([pk12util, "-i", os.path.join(options.certPath, item), - "-w", pwfilePath, "-d", certdbPath], - env=env) - - os.unlink(pwfilePath) - return 0 - - def buildProfile(self, options): - """ create the profile and add optional chrome bits and files if requested """ - if options.browserChrome and options.timeout: - options.extraPrefs.append("testing.browserTestHarness.timeout=%d" % options.timeout) - options.extraPrefs.append("browser.tabs.remote.autostart=%s" % ('true' if options.e10s else 'false')) - if options.strictContentSandbox: - options.extraPrefs.append("security.sandbox.windows.content.moreStrict=true") - options.extraPrefs.append("dom.ipc.tabs.nested.enabled=%s" % ('true' if options.nested_oop else 'false')) - - # get extensions to install - extensions = self.getExtensionsToInstall(options) - - # web apps - appsPath = os.path.join(SCRIPT_DIR, 'profile_data', 'webapps_mochitest.json') - if os.path.exists(appsPath): - with open(appsPath) as apps_file: - apps = json.load(apps_file) - else: - apps = None - - # preferences - preferences = [ os.path.join(SCRIPT_DIR, 'profile_data', 'prefs_general.js') ] - - # TODO: Let's include those prefs until bug 1072443 is fixed - if mozinfo.info.get('buildapp') == 'mulet': - preferences += [ os.path.join(SCRIPT_DIR, 'profile_data', 'prefs_b2g_unittest.js') ] - - prefs = {} - for path in preferences: - prefs.update(Preferences.read_prefs(path)) - - prefs.update(self.extraPrefs(options.extraPrefs)) - - # interpolate preferences - interpolation = {"server": "%s:%s" % (options.webServer, options.httpPort)} - - # TODO: Remove OOP once bug 1072443 is fixed - if mozinfo.info.get('buildapp') == 'mulet': - interpolation["OOP"] = "false" - - prefs = json.loads(json.dumps(prefs) % interpolation) - for pref in prefs: - prefs[pref] = Preferences.cast(prefs[pref]) - # TODO: make this less hacky - # https://bugzilla.mozilla.org/show_bug.cgi?id=913152 - - # proxy - proxy = {'remote': options.webServer, - 'http': options.httpPort, - 'https': options.sslPort, - # use SSL port for legacy compatibility; see - # - https://bugzilla.mozilla.org/show_bug.cgi?id=688667#c66 - # - https://bugzilla.mozilla.org/show_bug.cgi?id=899221 - # - https://github.com/mozilla/mozbase/commit/43f9510e3d58bfed32790c82a57edac5f928474d - # 'ws': str(self.webSocketPort) - 'ws': options.sslPort - } - - # See if we should use fake media devices. - if options.useTestMediaDevices: - prefs['media.audio_loopback_dev'] = self.mediaDevices['audio'] - prefs['media.video_loopback_dev'] = self.mediaDevices['video'] - - - # create a profile - self.profile = Profile(profile=options.profilePath, - addons=extensions, - locations=self.locations, - preferences=prefs, - apps=apps, - proxy=proxy - ) - - # Fix options.profilePath for legacy consumers. - options.profilePath = self.profile.profile - - manifest = self.addChromeToProfile(options) - self.copyExtraFilesToProfile(options) - - # create certificate database for the profile - # TODO: this should really be upstreamed somewhere, maybe mozprofile - certificateStatus = self.fillCertificateDB(options) - if certificateStatus: - self.log.error("TEST-UNEXPECTED-FAIL | runtests.py | Certificate integration failed") - return None - - return manifest - - def getGMPPluginPath(self, options): - if options.gmp_path: - return options.gmp_path - - gmp_parentdirs = [ - # For local builds, GMP plugins will be under dist/bin. - options.xrePath, - # For packaged builds, GMP plugins will get copied under $profile/plugins. - os.path.join(self.profile.profile, 'plugins'), - ] - - gmp_subdirs = [ - os.path.join('gmp-fake', '1.0'), - os.path.join('gmp-clearkey', '0.1'), - ] - - gmp_paths = [os.path.join(parent, sub) - for parent in gmp_parentdirs - for sub in gmp_subdirs - if os.path.isdir(os.path.join(parent, sub))] - - if not gmp_paths: - # This is fatal for desktop environments. - raise EnvironmentError('Could not find test gmp plugins') - - return os.pathsep.join(gmp_paths) - - def buildBrowserEnv(self, options, debugger=False, env=None): - """build the environment variables for the specific test and operating system""" - if mozinfo.info["asan"]: - lsanPath = SCRIPT_DIR - else: - lsanPath = None - - browserEnv = self.environment(xrePath=options.xrePath, env=env, - debugger=debugger, dmdPath=options.dmdPath, - lsanPath=lsanPath) - - # These variables are necessary for correct application startup; change - # via the commandline at your own risk. - browserEnv["XPCOM_DEBUG_BREAK"] = "stack" - - # When creating child processes on Windows pre-Vista (e.g. Windows XP) we - # don't normally inherit stdout/err handles, because you can only do it by - # inheriting all other inheritable handles as well. - # We need to inherit them for plain mochitests for test logging purposes, so - # we do so on the basis of a specific environment variable. - if self.getTestFlavor(options) == "mochitest": - browserEnv["MOZ_WIN_INHERIT_STD_HANDLES_PRE_VISTA"] = "1" - - # interpolate environment passed with options - try: - browserEnv.update(dict(parseKeyValue(options.environment, context='--setenv'))) - except KeyValueParseError, e: - self.log.error(str(e)) - return None - - browserEnv["XPCOM_MEM_BLOAT_LOG"] = self.leak_report_file - - try: - gmp_path = self.getGMPPluginPath(options) - if gmp_path is not None: - browserEnv["MOZ_GMP_PATH"] = gmp_path - except EnvironmentError: - self.log.error('Could not find path to gmp-fake plugin!') - return None - - if options.fatalAssertions: - browserEnv["XPCOM_DEBUG_BREAK"] = "stack-and-abort" - - # Produce an NSPR log, is setup (see NSPR_LOG_MODULES global at the top of - # this script). - self.nsprLogs = NSPR_LOG_MODULES and "MOZ_UPLOAD_DIR" in os.environ - if self.nsprLogs: - browserEnv["NSPR_LOG_MODULES"] = NSPR_LOG_MODULES - - browserEnv["NSPR_LOG_FILE"] = "%s/nspr.log" % tempfile.gettempdir() - browserEnv["GECKO_SEPARATE_NSPR_LOGS"] = "1" - - if debugger and not options.slowscript: - browserEnv["JS_DISABLE_SLOW_SCRIPT_SIGNALS"] = "1" - - return browserEnv - - def cleanup(self, options): - """ remove temporary files and profile """ - if hasattr(self, 'manifest') and self.manifest is not None: - os.remove(self.manifest) - if hasattr(self, 'profile'): - del self.profile - if options.pidFile != "": - try: - os.remove(options.pidFile) - if os.path.exists(options.pidFile + ".xpcshell.pid"): - os.remove(options.pidFile + ".xpcshell.pid") - except: - self.log.warning("cleaning up pidfile '%s' was unsuccessful from the test harness" % options.pidFile) - options.manifestFile = None - - def dumpScreen(self, utilityPath): - if self.haveDumpedScreen: - self.log.info("Not taking screenshot here: see the one that was previously logged") - return - self.haveDumpedScreen = True - dumpScreen(utilityPath) - - def killAndGetStack(self, processPID, utilityPath, debuggerInfo, dump_screen=False): - """ - Kill the process, preferrably in a way that gets us a stack trace. - Also attempts to obtain a screenshot before killing the process - if specified. - """ - - if dump_screen: - self.dumpScreen(utilityPath) - - if mozinfo.info.get('crashreporter', True) and not debuggerInfo: - if mozinfo.isWin: - # We should have a "crashinject" program in our utility path - crashinject = os.path.normpath(os.path.join(utilityPath, "crashinject.exe")) - if os.path.exists(crashinject): - status = subprocess.Popen([crashinject, str(processPID)]).wait() - printstatus(status, "crashinject") - if status == 0: - return - else: - try: - os.kill(processPID, signal.SIGABRT) - except OSError: - # https://bugzilla.mozilla.org/show_bug.cgi?id=921509 - self.log.info("Can't trigger Breakpad, process no longer exists") - return - self.log.info("Can't trigger Breakpad, just killing process") - killPid(processPID, self.log) - - def checkForZombies(self, processLog, utilityPath, debuggerInfo): - """Look for hung processes""" - - if not os.path.exists(processLog): - self.log.info('Automation Error: PID log not found: %s' % processLog) - # Whilst no hung process was found, the run should still display as a failure - return True - - # scan processLog for zombies - self.log.info('zombiecheck | Reading PID log: %s' % processLog) - processList = [] - pidRE = re.compile(r'launched child process (\d+)$') - with open(processLog) as processLogFD: - for line in processLogFD: - self.log.info(line.rstrip()) - m = pidRE.search(line) - if m: - processList.append(int(m.group(1))) - - # kill zombies - foundZombie = False - for processPID in processList: - self.log.info("zombiecheck | Checking for orphan process with PID: %d" % processPID) - if isPidAlive(processPID): - foundZombie = True - self.log.error("TEST-UNEXPECTED-FAIL | zombiecheck | child process %d still alive after shutdown" % processPID) - self.killAndGetStack(processPID, utilityPath, debuggerInfo, dump_screen=not debuggerInfo) - - return foundZombie - - def startVMwareRecording(self, options): - """ starts recording inside VMware VM using the recording helper dll """ - assert mozinfo.isWin - from ctypes import cdll - self.vmwareHelper = cdll.LoadLibrary(self.vmwareHelperPath) - if self.vmwareHelper is None: - self.log.warning("runtests.py | Failed to load " - "VMware recording helper") - return - self.log.info("runtests.py | Starting VMware recording.") - try: - self.vmwareHelper.StartRecording() - except Exception, e: - self.log.warning("runtests.py | Failed to start " - "VMware recording: (%s)" % str(e)) - self.vmwareHelper = None - - def stopVMwareRecording(self): - """ stops recording inside VMware VM using the recording helper dll """ - try: - assert mozinfo.isWin - if self.vmwareHelper is not None: - self.log.info("runtests.py | Stopping VMware recording.") - self.vmwareHelper.StopRecording() - except Exception, e: - self.log.warning("runtests.py | Failed to stop " - "VMware recording: (%s)" % str(e)) - self.log.exception('Error stopping VMWare recording') - - self.vmwareHelper = None - - def runApp(self, - testUrl, - env, - app, - profile, - extraArgs, - utilityPath, - debuggerInfo=None, - symbolsPath=None, - timeout=-1, - onLaunch=None, - detectShutdownLeaks=False, - screenshotOnFail=False, - testPath=None, - bisectChunk=None, - quiet=False): - """ - Run the app, log the duration it took to execute, return the status code. - Kills the app if it runs for longer than |maxTime| seconds, or outputs nothing for |timeout| seconds. - """ - - # configure the message logger buffering - self.message_logger.buffering = quiet - - # debugger information - interactive = False - debug_args = None - if debuggerInfo: - interactive = debuggerInfo.interactive - debug_args = [debuggerInfo.path] + debuggerInfo.args - - # fix default timeout - if timeout == -1: - timeout = self.DEFAULT_TIMEOUT - - # copy env so we don't munge the caller's environment - env = env.copy() - - # make sure we clean up after ourselves. - try: - # set process log environment variable - tmpfd, processLog = tempfile.mkstemp(suffix='pidlog') - os.close(tmpfd) - env["MOZ_PROCESS_LOG"] = processLog - - if interactive: - # If an interactive debugger is attached, - # don't use timeouts, and don't capture ctrl-c. - timeout = None - signal.signal(signal.SIGINT, lambda sigid, frame: None) - - # build command line - cmd = os.path.abspath(app) - args = list(extraArgs) - # TODO: mozrunner should use -foreground at least for mac - # https://bugzilla.mozilla.org/show_bug.cgi?id=916512 - args.append('-foreground') - if testUrl: - if debuggerInfo and debuggerInfo.requiresEscapedArgs: - testUrl = testUrl.replace("&", "\\&") - args.append(testUrl) - - if detectShutdownLeaks: - shutdownLeaks = ShutdownLeaks(self.log) - else: - shutdownLeaks = None - - if mozinfo.info["asan"] and (mozinfo.isLinux or mozinfo.isMac): - lsanLeaks = LSANLeaks(self.log) - else: - lsanLeaks = None - - # create an instance to process the output - outputHandler = self.OutputHandler(harness=self, - utilityPath=utilityPath, - symbolsPath=symbolsPath, - dump_screen_on_timeout=not debuggerInfo, - dump_screen_on_fail=screenshotOnFail, - shutdownLeaks=shutdownLeaks, - lsanLeaks=lsanLeaks, - bisectChunk=bisectChunk - ) - - def timeoutHandler(): - browserProcessId = outputHandler.browserProcessId - self.handleTimeout(timeout, proc, utilityPath, debuggerInfo, browserProcessId, testPath) - kp_kwargs = {'kill_on_timeout': False, - 'cwd': SCRIPT_DIR, - 'onTimeout': [timeoutHandler]} - kp_kwargs['processOutputLine'] = [outputHandler] - - # create mozrunner instance and start the system under test process - self.lastTestSeen = self.test_name - startTime = datetime.now() - - # b2g desktop requires Runner even though appname is b2g - if mozinfo.info.get('appname') == 'b2g' and mozinfo.info.get('toolkit') != 'gonk': - runner_cls = mozrunner.Runner - else: - runner_cls = mozrunner.runners.get(mozinfo.info.get('appname', 'firefox'), - mozrunner.Runner) - runner = runner_cls(profile=self.profile, - binary=cmd, - cmdargs=args, - env=env, - process_class=mozprocess.ProcessHandlerMixin, - process_args=kp_kwargs) - - # start the runner - runner.start(debug_args=debug_args, - interactive=interactive, - outputTimeout=timeout) - proc = runner.process_handler - self.log.info("runtests.py | Application pid: %d" % proc.pid) - - if onLaunch is not None: - # Allow callers to specify an onLaunch callback to be fired after the - # app is launched. - # We call onLaunch for b2g desktop mochitests so that we can - # run a Marionette script after gecko has completed startup. - onLaunch() - - # wait until app is finished - # XXX copy functionality from - # https://github.com/mozilla/mozbase/blob/master/mozrunner/mozrunner/runner.py#L61 - # until bug 913970 is fixed regarding mozrunner `wait` not returning status - # see https://bugzilla.mozilla.org/show_bug.cgi?id=913970 - status = proc.wait() - printstatus(status, "Main app process") - runner.process_handler = None - - # finalize output handler - outputHandler.finish() - - # record post-test information - if status: - self.message_logger.dump_buffered() - self.log.error("TEST-UNEXPECTED-FAIL | %s | application terminated with exit code %s" % (self.lastTestSeen, status)) - else: - self.lastTestSeen = 'Main app process exited normally' - - self.log.info("runtests.py | Application ran for: %s" % str(datetime.now() - startTime)) - - # Do a final check for zombie child processes. - zombieProcesses = self.checkForZombies(processLog, utilityPath, debuggerInfo) - - # check for crashes - minidump_path = os.path.join(self.profile.profile, "minidumps") - crash_count = mozcrash.log_crashes(self.log, minidump_path, symbolsPath, - test=self.lastTestSeen) - - if crash_count or zombieProcesses: - status = 1 - - finally: - # cleanup - if os.path.exists(processLog): - os.remove(processLog) - - return status - - def initializeLooping(self, options): - """ - This method is used to clear the contents before each run of for loop. - This method is used for --run-by-dir and --bisect-chunk. - """ - self.expectedError.clear() - self.result.clear() - options.manifestFile = None - options.profilePath = None - self.urlOpts = [] - - def getActiveTests(self, options, disabled=True): - """ - This method is used to parse the manifest and return active filtered tests. - """ - self.setTestRoot(options) - manifest = self.getTestManifest(options) - if manifest: - # Python 2.6 doesn't allow unicode keys to be used for keyword - # arguments. This gross hack works around the problem until we - # rid ourselves of 2.6. - info = {} - for k, v in mozinfo.info.items(): - if isinstance(k, unicode): - k = k.encode('ascii') - info[k] = v - - # Bug 883858 - return all tests including disabled tests - testPath = self.getTestPath(options) - testPath = testPath.replace('\\', '/') - if testPath.endswith('.html') or \ - testPath.endswith('.xhtml') or \ - testPath.endswith('.xul') or \ - testPath.endswith('.js'): - # In the case where we have a single file, we don't want to filter based on options such as subsuite. - tests = manifest.active_tests(disabled=disabled, **info) - for test in tests: - if 'disabled' in test: - del test['disabled'] - - else: - filters = [subsuite(options.subsuite)] - tests = manifest.active_tests( - disabled=disabled, filters=filters, **info) - if len(tests) == 0: - tests = manifest.active_tests(disabled=True, **info) - - paths = [] - - for test in tests: - if len(tests) == 1 and 'disabled' in test: - del test['disabled'] - - pathAbs = os.path.abspath(test['path']) - assert pathAbs.startswith(self.testRootAbs) - tp = pathAbs[len(self.testRootAbs):].replace('\\', '/').strip('/') - - # Filter out tests if we are using --test-path - if testPath and not tp.startswith(testPath): - continue - - if not self.isTest(options, tp): - self.log.warning('Warning: %s from manifest %s is not a valid test' % (test['name'], test['manifest'])) - continue - - testob = {'path': tp} - if 'disabled' in test: - testob['disabled'] = test['disabled'] - if 'expected' in test: - testob['expected'] = test['expected'] - paths.append(testob) - - def path_sort(ob1, ob2): - path1 = ob1['path'].split('/') - path2 = ob2['path'].split('/') - return cmp(path1, path2) - - paths.sort(path_sort) - - return paths - - def logPreamble(self, tests): - """Logs a suite_start message and test_start/test_end at the beginning of a run. - """ - self.log.suite_start([t['path'] for t in tests]) - for test in tests: - if 'disabled' in test: - self.log.test_start(test['path']) - self.log.test_end(test['path'], 'SKIP', message=test['disabled']) - - def getTestsToRun(self, options): - """ - This method makes a list of tests that are to be run. Required mainly for --bisect-chunk. - """ - tests = self.getActiveTests(options) - self.logPreamble(tests) - - testsToRun = [] - for test in tests: - if 'disabled' in test: - continue - testsToRun.append(test['path']) - - return testsToRun - - def runMochitests(self, options, onLaunch=None): - "This is a base method for calling other methods in this class for --bisect-chunk." - testsToRun = self.getTestsToRun(options) - - # Making an instance of bisect class for --bisect-chunk option. - bisect = bisection.Bisect(self) - finished = False - status = 0 - bisection_log = 0 - while not finished: - if options.bisectChunk: - testsToRun = bisect.pre_test(options, testsToRun, status) - # To inform that we are in the process of bisection, and to look for bleedthrough - if options.bisectChunk != "default" and not bisection_log: - self.log.info("TEST-UNEXPECTED-FAIL | Bisection | Please ignore repeats and look for 'Bleedthrough' (if any) at the end of the failure list") - bisection_log = 1 - - result = self.doTests(options, onLaunch, testsToRun) - if options.bisectChunk: - status = bisect.post_test(options, self.expectedError, self.result) - else: - status = -1 - - if status == -1: - finished = True - - # We need to print the summary only if options.bisectChunk has a value. - # Also we need to make sure that we do not print the summary in between running tests via --run-by-dir. - if options.bisectChunk and options.bisectChunk in self.result: - bisect.print_summary() - - return result - - def runTests(self, options, onLaunch=None): - """ Prepare, configure, run tests and cleanup """ - - self.setTestRoot(options) - - # Until we have all green, this only runs on bc*/dt*/mochitest-chrome jobs, not webapprt*, jetpack*, or plain - if options.browserChrome: - options.runByDir = True - - if not options.runByDir: - return self.runMochitests(options, onLaunch) - - # code for --run-by-dir - dirs = self.getDirectories(options) - - if options.totalChunks > 1: - chunkSize = int(len(dirs) / options.totalChunks) + 1 - start = chunkSize * (options.thisChunk-1) - end = chunkSize * (options.thisChunk) - dirs = dirs[start:end] - - options.totalChunks = None - options.thisChunk = None - options.chunkByDir = 0 - result = 1 # default value, if no tests are run. - inputTestPath = self.getTestPath(options) - for dir in dirs: - if inputTestPath and not inputTestPath.startswith(dir): - continue - - options.testPath = dir - print "testpath: %s" % options.testPath - - # If we are using --run-by-dir, we should not use the profile path (if) provided - # by the user, since we need to create a new directory for each run. We would face problems - # if we use the directory provided by the user. - result = self.runMochitests(options, onLaunch) - - # Dump the logging buffer - self.message_logger.dump_buffered() - - # printing total number of tests - if options.browserChrome: - print "TEST-INFO | checking window state" - print "Browser Chrome Test Summary" - print "\tPassed: %s" % self.countpass - print "\tFailed: %s" % self.countfail - print "\tTodo: %s" % self.counttodo - print "*** End BrowserChrome Test Results ***" - else: - print "0 INFO TEST-START | Shutdown" - print "1 INFO Passed: %s" % self.countpass - print "2 INFO Failed: %s" % self.countfail - print "3 INFO Todo: %s" % self.counttodo - print "4 INFO SimpleTest FINISHED" - - return result - - def doTests(self, options, onLaunch=None, testsToFilter=None): - # A call to initializeLooping method is required in case of --run-by-dir or --bisect-chunk - # since we need to initialize variables for each loop. - if options.bisectChunk or options.runByDir: - self.initializeLooping(options) - - # get debugger info, a dict of: - # {'path': path to the debugger (string), - # 'interactive': whether the debugger is interactive or not (bool) - # 'args': arguments to the debugger (list) - # TODO: use mozrunner.local.debugger_arguments: - # https://github.com/mozilla/mozbase/blob/master/mozrunner/mozrunner/local.py#L42 - - debuggerInfo = None - if options.debugger: - debuggerInfo = mozdebug.get_debugger_info(options.debugger, - options.debuggerArgs, - options.debuggerInteractive) - - if options.useTestMediaDevices: - devices = findTestMediaDevices(self.log) - if not devices: - self.log.error("Could not find test media devices to use") - return 1 - self.mediaDevices = devices - - # buildProfile sets self.profile . - # This relies on sideeffects and isn't very stateful: - # https://bugzilla.mozilla.org/show_bug.cgi?id=919300 - self.manifest = self.buildProfile(options) - if self.manifest is None: - return 1 - - self.leak_report_file = os.path.join(options.profilePath, "runtests_leaks.log") - - self.browserEnv = self.buildBrowserEnv(options, debuggerInfo is not None) - - # If there are any Mulet-specific tests doing remote network access, - # we will not be aware since we are explicitely allowing this, as for B2G - if mozinfo.info.get('buildapp') == 'mulet' and 'MOZ_DISABLE_NONLOCAL_CONNECTIONS' in self.browserEnv: - del self.browserEnv['MOZ_DISABLE_NONLOCAL_CONNECTIONS'] - - if self.browserEnv is None: - return 1 - - try: - self.startServers(options, debuggerInfo) - - # testsToFilter parameter is used to filter out the test list that is sent to buildTestPath - testURL = self.buildTestPath(options, testsToFilter) - - # read the number of tests here, if we are not going to run any, terminate early - if os.path.exists(os.path.join(SCRIPT_DIR, options.testRunManifestFile)): - with open(os.path.join(SCRIPT_DIR, options.testRunManifestFile)) as fHandle: - tests = json.load(fHandle) - count = 0 - for test in tests['tests']: - count += 1 - if count == 0: - return 1 - - self.buildURLOptions(options, self.browserEnv) - if self.urlOpts: - testURL += "?" + "&".join(self.urlOpts) - - if options.webapprtContent: - options.browserArgs.extend(('-test-mode', testURL)) - testURL = None - - if options.immersiveMode: - options.browserArgs.extend(('-firefoxpath', options.app)) - options.app = self.immersiveHelperPath - - if options.jsdebugger: - options.browserArgs.extend(['-jsdebugger']) - - # Remove the leak detection file so it can't "leak" to the tests run. - # The file is not there if leak logging was not enabled in the application build. - if os.path.exists(self.leak_report_file): - os.remove(self.leak_report_file) - - # then again to actually run mochitest - if options.timeout: - timeout = options.timeout + 30 - elif options.debugger or not options.autorun: - timeout = None - else: - timeout = 330.0 # default JS harness timeout is 300 seconds - - if options.vmwareRecording: - self.startVMwareRecording(options); - - # detect shutdown leaks for m-bc runs - detectShutdownLeaks = mozinfo.info["debug"] and options.browserChrome and not options.webapprtChrome - - self.log.info("runtests.py | Running tests: start.\n") - try: - status = self.runApp(testURL, - self.browserEnv, - options.app, - profile=self.profile, - extraArgs=options.browserArgs, - utilityPath=options.utilityPath, - debuggerInfo=debuggerInfo, - symbolsPath=options.symbolsPath, - timeout=timeout, - onLaunch=onLaunch, - detectShutdownLeaks=detectShutdownLeaks, - screenshotOnFail=options.screenshotOnFail, - testPath=options.testPath, - bisectChunk=options.bisectChunk, - quiet=options.quiet - ) - except KeyboardInterrupt: - self.log.info("runtests.py | Received keyboard interrupt.\n"); - status = -1 - except: - traceback.print_exc() - self.log.error("Automation Error: Received unexpected exception while running application\n") - status = 1 - - finally: - if options.vmwareRecording: - self.stopVMwareRecording(); - self.stopServers() - - processLeakLog(self.leak_report_file, options) - - if self.nsprLogs: - with zipfile.ZipFile("%s/nsprlog.zip" % self.browserEnv["MOZ_UPLOAD_DIR"], "w", zipfile.ZIP_DEFLATED) as logzip: - for logfile in glob.glob("%s/nspr*.log*" % tempfile.gettempdir()): - logzip.write(logfile) - os.remove(logfile) - - self.log.info("runtests.py | Running tests: end.") - - if self.manifest is not None: - self.cleanup(options) - - return status - - def handleTimeout(self, timeout, proc, utilityPath, debuggerInfo, browserProcessId, testPath=None): - """handle process output timeout""" - # TODO: bug 913975 : _processOutput should call self.processOutputLine one more time one timeout (I think) - if testPath: - error_message = "TEST-UNEXPECTED-TIMEOUT | %s | application timed out after %d seconds with no output on %s" % (self.lastTestSeen, int(timeout), testPath) - else: - error_message = "TEST-UNEXPECTED-TIMEOUT | %s | application timed out after %d seconds with no output" % (self.lastTestSeen, int(timeout)) - - self.message_logger.dump_buffered() - self.message_logger.buffering = False - self.log.error(error_message) - - browserProcessId = browserProcessId or proc.pid - self.killAndGetStack(browserProcessId, utilityPath, debuggerInfo, dump_screen=not debuggerInfo) - - - - class OutputHandler(object): - """line output handler for mozrunner""" - def __init__(self, harness, utilityPath, symbolsPath=None, dump_screen_on_timeout=True, dump_screen_on_fail=False, shutdownLeaks=None, lsanLeaks=None, bisectChunk=None): - """ - harness -- harness instance - dump_screen_on_timeout -- whether to dump the screen on timeout - """ - self.harness = harness - self.utilityPath = utilityPath - self.symbolsPath = symbolsPath - self.dump_screen_on_timeout = dump_screen_on_timeout - self.dump_screen_on_fail = dump_screen_on_fail - self.shutdownLeaks = shutdownLeaks - self.lsanLeaks = lsanLeaks - self.bisectChunk = bisectChunk - - # With metro browser runs this script launches the metro test harness which launches the browser. - # The metro test harness hands back the real browser process id via log output which we need to - # pick up on and parse out. This variable tracks the real browser process id if we find it. - self.browserProcessId = None - - self.stackFixerFunction = self.stackFixer() - - def processOutputLine(self, line): - """per line handler of output for mozprocess""" - # Parsing the line (by the structured messages logger). - messages = self.harness.message_logger.parse_line(line) - - for message in messages: - # Passing the message to the handlers - for handler in self.outputHandlers(): - message = handler(message) - - # Processing the message by the logger - self.harness.message_logger.process_message(message) - - __call__ = processOutputLine - - def outputHandlers(self): - """returns ordered list of output handlers""" - handlers = [self.fix_stack, - self.record_last_test, - self.dumpScreenOnTimeout, - self.dumpScreenOnFail, - self.trackShutdownLeaks, - self.trackLSANLeaks, - self.countline, - ] - if self.bisectChunk: - handlers.append(self.record_result) - handlers.append(self.first_error) - - return handlers - - def stackFixer(self): - """ - return stackFixerFunction, if any, to use on the output lines - """ - - if not mozinfo.info.get('debug'): + This method is only currently implemented for Linux. + ''' + if not mozinfo.isLinux: return None - stackFixerFunction = None + info = {} + # Look for a v4l2loopback device. + name = None + device = None + for dev in sorted(glob.glob('/dev/video*')): + result, name_ = checkAndConfigureV4l2loopback(dev) + if result: + name = name_ + device = dev + break - def import_stackFixerModule(module_name): - sys.path.insert(0, self.utilityPath) - module = __import__(module_name, globals(), locals(), []) - sys.path.pop(0) - return module + if not (name and device): + log.error('Couldn\'t find a v4l2loopback video device') + return None - if self.symbolsPath and os.path.exists(self.symbolsPath): - # Run each line through a function in fix_stack_using_bpsyms.py (uses breakpad symbol files). - # This method is preferred for Tinderbox builds, since native symbols may have been stripped. - stackFixerModule = import_stackFixerModule('fix_stack_using_bpsyms') - stackFixerFunction = lambda line: stackFixerModule.fixSymbols(line, self.symbolsPath) + # Feed it a frame of output so it has something to display + subprocess.check_call(['/usr/bin/gst-launch-0.10', 'videotestsrc', + 'pattern=green', 'num-buffers=1', '!', + 'v4l2sink', 'device=%s' % device]) + info['video'] = name - elif mozinfo.isMac: - # Run each line through fix_macosx_stack.py (uses atos). - # This method is preferred for developer machines, so we don't have to run "make buildsymbols". - stackFixerModule = import_stackFixerModule('fix_macosx_stack') - stackFixerFunction = lambda line: stackFixerModule.fixSymbols(line) + # Use pactl to see if the PulseAudio module-sine-source module is loaded. + def sine_source_loaded(): + o = subprocess.check_output( + ['/usr/bin/pactl', 'list', 'short', 'modules']) + return filter(lambda x: 'module-sine-source' in x, o.splitlines()) - elif mozinfo.isLinux: - # Run each line through fix_linux_stack.py (uses addr2line). - # This method is preferred for developer machines, so we don't have to run "make buildsymbols". - stackFixerModule = import_stackFixerModule('fix_linux_stack') - stackFixerFunction = lambda line: stackFixerModule.fixSymbols(line) + if not sine_source_loaded(): + # Load module-sine-source + subprocess.check_call(['/usr/bin/pactl', 'load-module', + 'module-sine-source']) + if not sine_source_loaded(): + log.error('Couldn\'t load module-sine-source') + return None - return stackFixerFunction + # Hardcode the name since it's always the same. + info['audio'] = 'Sine source at 440 Hz' + return info - def finish(self): - if self.shutdownLeaks: - self.shutdownLeaks.process() - if self.lsanLeaks: - self.lsanLeaks.process() +class KeyValueParseError(Exception): - # output message handlers: - # these take a message and return a message + """error when parsing strings of serialized key-values""" - def record_result(self, message): - if message['action'] == 'test_start': #by default make the result key equal to pass. - key = message['test'].split('/')[-1].strip() - self.harness.result[key] = "PASS" - elif message['action'] == 'test_status': - if 'expected' in message: - key = message['test'].split('/')[-1].strip() - self.harness.result[key] = "FAIL" - elif message['status'] == 'FAIL': - key = message['test'].split('/')[-1].strip() - self.harness.result[key] = "TODO" - return message + def __init__(self, msg, errors=()): + self.errors = errors + Exception.__init__(self, msg) - def first_error(self, message): - if message['action'] == 'test_status' and 'expected' in message and message['status'] == 'FAIL': - key = message['test'].split('/')[-1].strip() - if key not in self.harness.expectedError: - self.harness.expectedError[key] = message.get('message', message['subtest']).strip() - return message - def countline(self, message): - if message['action'] != 'log': - return message - line = message['message'] - val = 0 - try: - val = int(line.split(':')[-1].strip()) - except ValueError: - return message - - if "Passed:" in line: - self.harness.countpass += val - elif "Failed:" in line: - self.harness.countfail += val - elif "Todo:" in line: - self.harness.counttodo += val - return message - - def fix_stack(self, message): - if message['action'] == 'log' and self.stackFixerFunction: - message['message'] = self.stackFixerFunction(message['message'].encode('utf-8', 'replace')) - return message - - def record_last_test(self, message): - """record last test on harness""" - if message['action'] == 'test_start': - self.harness.lastTestSeen = message['test'] - return message - - def dumpScreenOnTimeout(self, message): - if (not self.dump_screen_on_fail - and self.dump_screen_on_timeout - and message['action'] == 'test_status' and 'expected' in message - and "Test timed out" in message['subtest']): - self.harness.dumpScreen(self.utilityPath) - return message - - def dumpScreenOnFail(self, message): - if self.dump_screen_on_fail and 'expected' in message and message['status'] == 'FAIL': - self.harness.dumpScreen(self.utilityPath) - return message - - def trackLSANLeaks(self, message): - if self.lsanLeaks and message['action'] == 'log': - self.lsanLeaks.log(message['message']) - return message - - def trackShutdownLeaks(self, message): - if self.shutdownLeaks: - self.shutdownLeaks.log(message) - return message - - def makeTestConfig(self, options): - "Creates a test configuration file for customizing test execution." - options.logFile = options.logFile.replace("\\", "\\\\") - options.testPath = options.testPath.replace("\\", "\\\\") - - if "MOZ_HIDE_RESULTS_TABLE" in os.environ and os.environ["MOZ_HIDE_RESULTS_TABLE"] == "1": - options.hideResultsTable = True - - d = dict((k, v) for k, v in options.__dict__.items() if - (not k.startswith('log_') or - not any([k.endswith(fmt) for fmt in commandline.log_formatters.keys()]))) - d['testRoot'] = self.testRoot - content = json.dumps(d) - - with open(os.path.join(options.profilePath, "testConfig.js"), "w") as config: - config.write(content) - - def getTestManifest(self, options): - if isinstance(options.manifestFile, TestManifest): - manifest = options.manifestFile - elif options.manifestFile and os.path.isfile(options.manifestFile): - manifestFileAbs = os.path.abspath(options.manifestFile) - assert manifestFileAbs.startswith(SCRIPT_DIR) - manifest = TestManifest([options.manifestFile], strict=False) - elif options.manifestFile and os.path.isfile(os.path.join(SCRIPT_DIR, options.manifestFile)): - manifestFileAbs = os.path.abspath(os.path.join(SCRIPT_DIR, options.manifestFile)) - assert manifestFileAbs.startswith(SCRIPT_DIR) - manifest = TestManifest([manifestFileAbs], strict=False) - else: - masterName = self.getTestFlavor(options) + '.ini' - masterPath = os.path.join(SCRIPT_DIR, self.testRoot, masterName) - - if os.path.exists(masterPath): - manifest = TestManifest([masterPath], strict=False) - else: - self._log.warning('TestManifest masterPath %s does not exist' % masterPath) - - return manifest - - def getDirectories(self, options): +def parseKeyValue(strings, separator='=', context='key, value: '): """ - Make the list of directories by parsing manifests + parse string-serialized key-value pairs in the form of + `key = value`. Returns a list of 2-tuples. + Note that whitespace is not stripped. """ - tests = self.getActiveTests(options, False) - dirlist = [] - for test in tests: - rootdir = '/'.join(test['path'].split('/')[:-1]) - if rootdir not in dirlist: - dirlist.append(rootdir) + # syntax check + missing = [string for string in strings if separator not in string] + if missing: + raise KeyValueParseError( + "Error: syntax error in %s" % + (context, ','.join(missing)), errors=missing) + return [string.split(separator, 1) for string in strings] + + +class Mochitest(MochitestUtilsMixin): + certdbNew = False + sslTunnel = None + vmwareHelper = None + DEFAULT_TIMEOUT = 60.0 + mediaDevices = None + + # XXX use automation.py for test name to avoid breaking legacy + # TODO: replace this with 'runtests.py' or 'mochitest' or the like + test_name = 'automation.py' + + def __init__(self, logger_options): + super(Mochitest, self).__init__(logger_options) + + # environment function for browserEnv + self.environment = environment + + # Max time in seconds to wait for server startup before tests will fail -- if + # this seems big, it's mostly for debug machines where cold startup + # (particularly after a build) takes forever. + self.SERVER_STARTUP_TIMEOUT = 180 if mozinfo.info.get('debug') else 90 + + # metro browser sub process id + self.browserProcessId = None + + self.haveDumpedScreen = False + # Create variables to count the number of passes, fails, todos. + self.countpass = 0 + self.countfail = 0 + self.counttodo = 0 + + self.expectedError = {} + self.result = {} + + def extraPrefs(self, extraPrefs): + """interpolate extra preferences from option strings""" + + try: + return dict(parseKeyValue(extraPrefs, context='--setpref=')) + except KeyValueParseError as e: + print str(e) + sys.exit(1) + + def fillCertificateDB(self, options): + # TODO: move -> mozprofile: + # https://bugzilla.mozilla.org/show_bug.cgi?id=746243#c35 + + pwfilePath = os.path.join(options.profilePath, ".crtdbpw") + with open(pwfilePath, "w") as pwfile: + pwfile.write("\n") + + # Pre-create the certification database for the profile + env = self.environment(xrePath=options.xrePath) + env["LD_LIBRARY_PATH"] = options.xrePath + bin_suffix = mozinfo.info.get('bin_suffix', '') + certutil = os.path.join(options.utilityPath, "certutil" + bin_suffix) + pk12util = os.path.join(options.utilityPath, "pk12util" + bin_suffix) + + if self.certdbNew: + # android and b2g use the new DB formats exclusively + certdbPath = "sql:" + options.profilePath + else: + # desktop seems to use the old + certdbPath = options.profilePath + + status = call( + [certutil, "-N", "-d", certdbPath, "-f", pwfilePath], env=env) + if status: + return status + + # Walk the cert directory and add custom CAs and client certs + files = os.listdir(options.certPath) + for item in files: + root, ext = os.path.splitext(item) + if ext == ".ca": + trustBits = "CT,," + if root.endswith("-object"): + trustBits = "CT,,CT" + call([certutil, + "-A", + "-i", + os.path.join(options.certPath, + item), + "-d", + certdbPath, + "-f", + pwfilePath, + "-n", + root, + "-t", + trustBits], + env=env) + elif ext == ".client": + call([pk12util, "-i", os.path.join(options.certPath, item), + "-w", pwfilePath, "-d", certdbPath], + env=env) + + os.unlink(pwfilePath) + return 0 + + def buildProfile(self, options): + """ create the profile and add optional chrome bits and files if requested """ + if options.browserChrome and options.timeout: + options.extraPrefs.append( + "testing.browserTestHarness.timeout=%d" % + options.timeout) + options.extraPrefs.append( + "browser.tabs.remote.autostart=%s" % + ('true' if options.e10s else 'false')) + if options.strictContentSandbox: + options.extraPrefs.append( + "security.sandbox.windows.content.moreStrict=true") + options.extraPrefs.append( + "dom.ipc.tabs.nested.enabled=%s" % + ('true' if options.nested_oop else 'false')) + + # get extensions to install + extensions = self.getExtensionsToInstall(options) + + # web apps + appsPath = os.path.join( + SCRIPT_DIR, + 'profile_data', + 'webapps_mochitest.json') + if os.path.exists(appsPath): + with open(appsPath) as apps_file: + apps = json.load(apps_file) + else: + apps = None + + # preferences + preferences = [ + os.path.join( + SCRIPT_DIR, + 'profile_data', + 'prefs_general.js')] + + # TODO: Let's include those prefs until bug 1072443 is fixed + if mozinfo.info.get('buildapp') == 'mulet': + preferences += [os.path.join(SCRIPT_DIR, + 'profile_data', + 'prefs_b2g_unittest.js')] + + prefs = {} + for path in preferences: + prefs.update(Preferences.read_prefs(path)) + + prefs.update(self.extraPrefs(options.extraPrefs)) + + # interpolate preferences + interpolation = { + "server": "%s:%s" % + (options.webServer, options.httpPort)} + + # TODO: Remove OOP once bug 1072443 is fixed + if mozinfo.info.get('buildapp') == 'mulet': + interpolation["OOP"] = "false" + + prefs = json.loads(json.dumps(prefs) % interpolation) + for pref in prefs: + prefs[pref] = Preferences.cast(prefs[pref]) + # TODO: make this less hacky + # https://bugzilla.mozilla.org/show_bug.cgi?id=913152 + + # proxy + proxy = {'remote': options.webServer, + 'http': options.httpPort, + 'https': options.sslPort, + # use SSL port for legacy compatibility; see + # - https://bugzilla.mozilla.org/show_bug.cgi?id=688667#c66 + # - https://bugzilla.mozilla.org/show_bug.cgi?id=899221 + # - https://github.com/mozilla/mozbase/commit/43f9510e3d58bfed32790c82a57edac5f928474d + # 'ws': str(self.webSocketPort) + 'ws': options.sslPort + } + + # See if we should use fake media devices. + if options.useTestMediaDevices: + prefs['media.audio_loopback_dev'] = self.mediaDevices['audio'] + prefs['media.video_loopback_dev'] = self.mediaDevices['video'] + + # create a profile + self.profile = Profile(profile=options.profilePath, + addons=extensions, + locations=self.locations, + preferences=prefs, + apps=apps, + proxy=proxy + ) + + # Fix options.profilePath for legacy consumers. + options.profilePath = self.profile.profile + + manifest = self.addChromeToProfile(options) + self.copyExtraFilesToProfile(options) + + # create certificate database for the profile + # TODO: this should really be upstreamed somewhere, maybe mozprofile + certificateStatus = self.fillCertificateDB(options) + if certificateStatus: + self.log.error( + "TEST-UNEXPECTED-FAIL | runtests.py | Certificate integration failed") + return None + + return manifest + + def getGMPPluginPath(self, options): + if options.gmp_path: + return options.gmp_path + + gmp_parentdirs = [ + # For local builds, GMP plugins will be under dist/bin. + options.xrePath, + # For packaged builds, GMP plugins will get copied under + # $profile/plugins. + os.path.join(self.profile.profile, 'plugins'), + ] + + gmp_subdirs = [ + os.path.join('gmp-fake', '1.0'), + os.path.join('gmp-clearkey', '0.1'), + ] + + gmp_paths = [os.path.join(parent, sub) + for parent in gmp_parentdirs + for sub in gmp_subdirs + if os.path.isdir(os.path.join(parent, sub))] + + if not gmp_paths: + # This is fatal for desktop environments. + raise EnvironmentError('Could not find test gmp plugins') + + return os.pathsep.join(gmp_paths) + + def buildBrowserEnv(self, options, debugger=False, env=None): + """build the environment variables for the specific test and operating system""" + if mozinfo.info["asan"]: + lsanPath = SCRIPT_DIR + else: + lsanPath = None + + browserEnv = self.environment( + xrePath=options.xrePath, + env=env, + debugger=debugger, + dmdPath=options.dmdPath, + lsanPath=lsanPath) + + # These variables are necessary for correct application startup; change + # via the commandline at your own risk. + browserEnv["XPCOM_DEBUG_BREAK"] = "stack" + + # When creating child processes on Windows pre-Vista (e.g. Windows XP) we + # don't normally inherit stdout/err handles, because you can only do it by + # inheriting all other inheritable handles as well. + # We need to inherit them for plain mochitests for test logging purposes, so + # we do so on the basis of a specific environment variable. + if self.getTestFlavor(options) == "mochitest": + browserEnv["MOZ_WIN_INHERIT_STD_HANDLES_PRE_VISTA"] = "1" + + # interpolate environment passed with options + try: + browserEnv.update( + dict( + parseKeyValue( + options.environment, + context='--setenv'))) + except KeyValueParseError as e: + self.log.error(str(e)) + return None + + browserEnv["XPCOM_MEM_BLOAT_LOG"] = self.leak_report_file + + try: + gmp_path = self.getGMPPluginPath(options) + if gmp_path is not None: + browserEnv["MOZ_GMP_PATH"] = gmp_path + except EnvironmentError: + self.log.error('Could not find path to gmp-fake plugin!') + return None + + if options.fatalAssertions: + browserEnv["XPCOM_DEBUG_BREAK"] = "stack-and-abort" + + # Produce an NSPR log, is setup (see NSPR_LOG_MODULES global at the top of + # this script). + self.nsprLogs = NSPR_LOG_MODULES and "MOZ_UPLOAD_DIR" in os.environ + if self.nsprLogs: + browserEnv["NSPR_LOG_MODULES"] = NSPR_LOG_MODULES + + browserEnv["NSPR_LOG_FILE"] = "%s/nspr.log" % tempfile.gettempdir() + browserEnv["GECKO_SEPARATE_NSPR_LOGS"] = "1" + + if debugger and not options.slowscript: + browserEnv["JS_DISABLE_SLOW_SCRIPT_SIGNALS"] = "1" + + return browserEnv + + def cleanup(self, options): + """ remove temporary files and profile """ + if hasattr(self, 'manifest') and self.manifest is not None: + os.remove(self.manifest) + if hasattr(self, 'profile'): + del self.profile + if options.pidFile != "": + try: + os.remove(options.pidFile) + if os.path.exists(options.pidFile + ".xpcshell.pid"): + os.remove(options.pidFile + ".xpcshell.pid") + except: + self.log.warning( + "cleaning up pidfile '%s' was unsuccessful from the test harness" % + options.pidFile) + options.manifestFile = None + + def dumpScreen(self, utilityPath): + if self.haveDumpedScreen: + self.log.info( + "Not taking screenshot here: see the one that was previously logged") + return + self.haveDumpedScreen = True + dumpScreen(utilityPath) + + def killAndGetStack( + self, + processPID, + utilityPath, + debuggerInfo, + dump_screen=False): + """ + Kill the process, preferrably in a way that gets us a stack trace. + Also attempts to obtain a screenshot before killing the process + if specified. + """ + + if dump_screen: + self.dumpScreen(utilityPath) + + if mozinfo.info.get('crashreporter', True) and not debuggerInfo: + if mozinfo.isWin: + # We should have a "crashinject" program in our utility path + crashinject = os.path.normpath( + os.path.join( + utilityPath, + "crashinject.exe")) + if os.path.exists(crashinject): + status = subprocess.Popen( + [crashinject, str(processPID)]).wait() + printstatus(status, "crashinject") + if status == 0: + return + else: + try: + os.kill(processPID, signal.SIGABRT) + except OSError: + # https://bugzilla.mozilla.org/show_bug.cgi?id=921509 + self.log.info( + "Can't trigger Breakpad, process no longer exists") + return + self.log.info("Can't trigger Breakpad, just killing process") + killPid(processPID, self.log) + + def checkForZombies(self, processLog, utilityPath, debuggerInfo): + """Look for hung processes""" + + if not os.path.exists(processLog): + self.log.info( + 'Automation Error: PID log not found: %s' % + processLog) + # Whilst no hung process was found, the run should still display as + # a failure + return True + + # scan processLog for zombies + self.log.info('zombiecheck | Reading PID log: %s' % processLog) + processList = [] + pidRE = re.compile(r'launched child process (\d+)$') + with open(processLog) as processLogFD: + for line in processLogFD: + self.log.info(line.rstrip()) + m = pidRE.search(line) + if m: + processList.append(int(m.group(1))) + + # kill zombies + foundZombie = False + for processPID in processList: + self.log.info( + "zombiecheck | Checking for orphan process with PID: %d" % + processPID) + if isPidAlive(processPID): + foundZombie = True + self.log.error( + "TEST-UNEXPECTED-FAIL | zombiecheck | child process %d still alive after shutdown" % + processPID) + self.killAndGetStack( + processPID, + utilityPath, + debuggerInfo, + dump_screen=not debuggerInfo) + + return foundZombie + + def startVMwareRecording(self, options): + """ starts recording inside VMware VM using the recording helper dll """ + assert mozinfo.isWin + from ctypes import cdll + self.vmwareHelper = cdll.LoadLibrary(self.vmwareHelperPath) + if self.vmwareHelper is None: + self.log.warning("runtests.py | Failed to load " + "VMware recording helper") + return + self.log.info("runtests.py | Starting VMware recording.") + try: + self.vmwareHelper.StartRecording() + except Exception as e: + self.log.warning("runtests.py | Failed to start " + "VMware recording: (%s)" % str(e)) + self.vmwareHelper = None + + def stopVMwareRecording(self): + """ stops recording inside VMware VM using the recording helper dll """ + try: + assert mozinfo.isWin + if self.vmwareHelper is not None: + self.log.info("runtests.py | Stopping VMware recording.") + self.vmwareHelper.StopRecording() + except Exception as e: + self.log.warning("runtests.py | Failed to stop " + "VMware recording: (%s)" % str(e)) + self.log.exception('Error stopping VMWare recording') + + self.vmwareHelper = None + + def runApp(self, + testUrl, + env, + app, + profile, + extraArgs, + utilityPath, + debuggerInfo=None, + symbolsPath=None, + timeout=-1, + onLaunch=None, + detectShutdownLeaks=False, + screenshotOnFail=False, + testPath=None, + bisectChunk=None, + quiet=False): + """ + Run the app, log the duration it took to execute, return the status code. + Kills the app if it runs for longer than |maxTime| seconds, or outputs nothing for |timeout| seconds. + """ + + # configure the message logger buffering + self.message_logger.buffering = quiet + + # debugger information + interactive = False + debug_args = None + if debuggerInfo: + interactive = debuggerInfo.interactive + debug_args = [debuggerInfo.path] + debuggerInfo.args + + # fix default timeout + if timeout == -1: + timeout = self.DEFAULT_TIMEOUT + + # copy env so we don't munge the caller's environment + env = env.copy() + + # make sure we clean up after ourselves. + try: + # set process log environment variable + tmpfd, processLog = tempfile.mkstemp(suffix='pidlog') + os.close(tmpfd) + env["MOZ_PROCESS_LOG"] = processLog + + if interactive: + # If an interactive debugger is attached, + # don't use timeouts, and don't capture ctrl-c. + timeout = None + signal.signal(signal.SIGINT, lambda sigid, frame: None) + + # build command line + cmd = os.path.abspath(app) + args = list(extraArgs) + # TODO: mozrunner should use -foreground at least for mac + # https://bugzilla.mozilla.org/show_bug.cgi?id=916512 + args.append('-foreground') + if testUrl: + if debuggerInfo and debuggerInfo.requiresEscapedArgs: + testUrl = testUrl.replace("&", "\\&") + args.append(testUrl) + + if detectShutdownLeaks: + shutdownLeaks = ShutdownLeaks(self.log) + else: + shutdownLeaks = None + + if mozinfo.info["asan"] and (mozinfo.isLinux or mozinfo.isMac): + lsanLeaks = LSANLeaks(self.log) + else: + lsanLeaks = None + + # create an instance to process the output + outputHandler = self.OutputHandler( + harness=self, + utilityPath=utilityPath, + symbolsPath=symbolsPath, + dump_screen_on_timeout=not debuggerInfo, + dump_screen_on_fail=screenshotOnFail, + shutdownLeaks=shutdownLeaks, + lsanLeaks=lsanLeaks, + bisectChunk=bisectChunk) + + def timeoutHandler(): + browserProcessId = outputHandler.browserProcessId + self.handleTimeout( + timeout, + proc, + utilityPath, + debuggerInfo, + browserProcessId, + testPath) + kp_kwargs = {'kill_on_timeout': False, + 'cwd': SCRIPT_DIR, + 'onTimeout': [timeoutHandler]} + kp_kwargs['processOutputLine'] = [outputHandler] + + # create mozrunner instance and start the system under test process + self.lastTestSeen = self.test_name + startTime = datetime.now() + + # b2g desktop requires Runner even though appname is b2g + if mozinfo.info.get('appname') == 'b2g' and mozinfo.info.get( + 'toolkit') != 'gonk': + runner_cls = mozrunner.Runner + else: + runner_cls = mozrunner.runners.get( + mozinfo.info.get( + 'appname', + 'firefox'), + mozrunner.Runner) + runner = runner_cls(profile=self.profile, + binary=cmd, + cmdargs=args, + env=env, + process_class=mozprocess.ProcessHandlerMixin, + process_args=kp_kwargs) + + # start the runner + runner.start(debug_args=debug_args, + interactive=interactive, + outputTimeout=timeout) + proc = runner.process_handler + self.log.info("runtests.py | Application pid: %d" % proc.pid) + + if onLaunch is not None: + # Allow callers to specify an onLaunch callback to be fired after the + # app is launched. + # We call onLaunch for b2g desktop mochitests so that we can + # run a Marionette script after gecko has completed startup. + onLaunch() + + # wait until app is finished + # XXX copy functionality from + # https://github.com/mozilla/mozbase/blob/master/mozrunner/mozrunner/runner.py#L61 + # until bug 913970 is fixed regarding mozrunner `wait` not returning status + # see https://bugzilla.mozilla.org/show_bug.cgi?id=913970 + status = proc.wait() + printstatus(status, "Main app process") + runner.process_handler = None + + # finalize output handler + outputHandler.finish() + + # record post-test information + if status: + self.message_logger.dump_buffered() + self.log.error( + "TEST-UNEXPECTED-FAIL | %s | application terminated with exit code %s" % + (self.lastTestSeen, status)) + else: + self.lastTestSeen = 'Main app process exited normally' + + self.log.info( + "runtests.py | Application ran for: %s" % str( + datetime.now() - startTime)) + + # Do a final check for zombie child processes. + zombieProcesses = self.checkForZombies( + processLog, + utilityPath, + debuggerInfo) + + # check for crashes + minidump_path = os.path.join(self.profile.profile, "minidumps") + crash_count = mozcrash.log_crashes( + self.log, + minidump_path, + symbolsPath, + test=self.lastTestSeen) + + if crash_count or zombieProcesses: + status = 1 + + finally: + # cleanup + if os.path.exists(processLog): + os.remove(processLog) + + return status + + def initializeLooping(self, options): + """ + This method is used to clear the contents before each run of for loop. + This method is used for --run-by-dir and --bisect-chunk. + """ + self.expectedError.clear() + self.result.clear() + options.manifestFile = None + options.profilePath = None + self.urlOpts = [] + + def getActiveTests(self, options, disabled=True): + """ + This method is used to parse the manifest and return active filtered tests. + """ + self.setTestRoot(options) + manifest = self.getTestManifest(options) + if manifest: + # Python 2.6 doesn't allow unicode keys to be used for keyword + # arguments. This gross hack works around the problem until we + # rid ourselves of 2.6. + info = {} + for k, v in mozinfo.info.items(): + if isinstance(k, unicode): + k = k.encode('ascii') + info[k] = v + + # Bug 883858 - return all tests including disabled tests + testPath = self.getTestPath(options) + testPath = testPath.replace('\\', '/') + if testPath.endswith('.html') or \ + testPath.endswith('.xhtml') or \ + testPath.endswith('.xul') or \ + testPath.endswith('.js'): + # In the case where we have a single file, we don't want to + # filter based on options such as subsuite. + tests = manifest.active_tests(disabled=disabled, **info) + for test in tests: + if 'disabled' in test: + del test['disabled'] + + else: + filters = [subsuite(options.subsuite)] + tests = manifest.active_tests( + disabled=disabled, filters=filters, **info) + if len(tests) == 0: + tests = manifest.active_tests(disabled=True, **info) + + paths = [] + + for test in tests: + if len(tests) == 1 and 'disabled' in test: + del test['disabled'] + + pathAbs = os.path.abspath(test['path']) + assert pathAbs.startswith(self.testRootAbs) + tp = pathAbs[len(self.testRootAbs):].replace('\\', '/').strip('/') + + # Filter out tests if we are using --test-path + if testPath and not tp.startswith(testPath): + continue + + if not self.isTest(options, tp): + self.log.warning( + 'Warning: %s from manifest %s is not a valid test' % + (test['name'], test['manifest'])) + continue + + testob = {'path': tp} + if 'disabled' in test: + testob['disabled'] = test['disabled'] + if 'expected' in test: + testob['expected'] = test['expected'] + paths.append(testob) + + def path_sort(ob1, ob2): + path1 = ob1['path'].split('/') + path2 = ob2['path'].split('/') + return cmp(path1, path2) + + paths.sort(path_sort) + + return paths + + def logPreamble(self, tests): + """Logs a suite_start message and test_start/test_end at the beginning of a run. + """ + self.log.suite_start([t['path'] for t in tests]) + for test in tests: + if 'disabled' in test: + self.log.test_start(test['path']) + self.log.test_end( + test['path'], + 'SKIP', + message=test['disabled']) + + def getTestsToRun(self, options): + """ + This method makes a list of tests that are to be run. Required mainly for --bisect-chunk. + """ + tests = self.getActiveTests(options) + self.logPreamble(tests) + + testsToRun = [] + for test in tests: + if 'disabled' in test: + continue + testsToRun.append(test['path']) + + return testsToRun + + def runMochitests(self, options, onLaunch=None): + "This is a base method for calling other methods in this class for --bisect-chunk." + testsToRun = self.getTestsToRun(options) + + # Making an instance of bisect class for --bisect-chunk option. + bisect = bisection.Bisect(self) + finished = False + status = 0 + bisection_log = 0 + while not finished: + if options.bisectChunk: + testsToRun = bisect.pre_test(options, testsToRun, status) + # To inform that we are in the process of bisection, and to + # look for bleedthrough + if options.bisectChunk != "default" and not bisection_log: + self.log.info( + "TEST-UNEXPECTED-FAIL | Bisection | Please ignore repeats and look for 'Bleedthrough' (if any) at the end of the failure list") + bisection_log = 1 + + result = self.doTests(options, onLaunch, testsToRun) + if options.bisectChunk: + status = bisect.post_test( + options, + self.expectedError, + self.result) + else: + status = -1 + + if status == -1: + finished = True + + # We need to print the summary only if options.bisectChunk has a value. + # Also we need to make sure that we do not print the summary in between + # running tests via --run-by-dir. + if options.bisectChunk and options.bisectChunk in self.result: + bisect.print_summary() + + return result + + def runTests(self, options, onLaunch=None): + """ Prepare, configure, run tests and cleanup """ + + self.setTestRoot(options) + + # Until we have all green, this only runs on bc*/dt*/mochitest-chrome + # jobs, not webapprt*, jetpack*, or plain + if options.browserChrome: + options.runByDir = True + + if not options.runByDir: + return self.runMochitests(options, onLaunch) + + # code for --run-by-dir + dirs = self.getDirectories(options) + + if options.totalChunks > 1: + chunkSize = int(len(dirs) / options.totalChunks) + 1 + start = chunkSize * (options.thisChunk - 1) + end = chunkSize * (options.thisChunk) + dirs = dirs[start:end] + + options.totalChunks = None + options.thisChunk = None + options.chunkByDir = 0 + result = 1 # default value, if no tests are run. + inputTestPath = self.getTestPath(options) + for dir in dirs: + if inputTestPath and not inputTestPath.startswith(dir): + continue + + options.testPath = dir + print "testpath: %s" % options.testPath + + # If we are using --run-by-dir, we should not use the profile path (if) provided + # by the user, since we need to create a new directory for each run. We would face problems + # if we use the directory provided by the user. + result = self.runMochitests(options, onLaunch) + + # Dump the logging buffer + self.message_logger.dump_buffered() + + # printing total number of tests + if options.browserChrome: + print "TEST-INFO | checking window state" + print "Browser Chrome Test Summary" + print "\tPassed: %s" % self.countpass + print "\tFailed: %s" % self.countfail + print "\tTodo: %s" % self.counttodo + print "*** End BrowserChrome Test Results ***" + else: + print "0 INFO TEST-START | Shutdown" + print "1 INFO Passed: %s" % self.countpass + print "2 INFO Failed: %s" % self.countfail + print "3 INFO Todo: %s" % self.counttodo + print "4 INFO SimpleTest FINISHED" + + return result + + def doTests(self, options, onLaunch=None, testsToFilter=None): + # A call to initializeLooping method is required in case of --run-by-dir or --bisect-chunk + # since we need to initialize variables for each loop. + if options.bisectChunk or options.runByDir: + self.initializeLooping(options) + + # get debugger info, a dict of: + # {'path': path to the debugger (string), + # 'interactive': whether the debugger is interactive or not (bool) + # 'args': arguments to the debugger (list) + # TODO: use mozrunner.local.debugger_arguments: + # https://github.com/mozilla/mozbase/blob/master/mozrunner/mozrunner/local.py#L42 + + debuggerInfo = None + if options.debugger: + debuggerInfo = mozdebug.get_debugger_info( + options.debugger, + options.debuggerArgs, + options.debuggerInteractive) + + if options.useTestMediaDevices: + devices = findTestMediaDevices(self.log) + if not devices: + self.log.error("Could not find test media devices to use") + return 1 + self.mediaDevices = devices + + # buildProfile sets self.profile . + # This relies on sideeffects and isn't very stateful: + # https://bugzilla.mozilla.org/show_bug.cgi?id=919300 + self.manifest = self.buildProfile(options) + if self.manifest is None: + return 1 + + self.leak_report_file = os.path.join( + options.profilePath, + "runtests_leaks.log") + + self.browserEnv = self.buildBrowserEnv( + options, + debuggerInfo is not None) + + # If there are any Mulet-specific tests doing remote network access, + # we will not be aware since we are explicitely allowing this, as for + # B2G + if mozinfo.info.get( + 'buildapp') == 'mulet' and 'MOZ_DISABLE_NONLOCAL_CONNECTIONS' in self.browserEnv: + del self.browserEnv['MOZ_DISABLE_NONLOCAL_CONNECTIONS'] + + if self.browserEnv is None: + return 1 + + try: + self.startServers(options, debuggerInfo) + + # testsToFilter parameter is used to filter out the test list that + # is sent to buildTestPath + testURL = self.buildTestPath(options, testsToFilter) + + # read the number of tests here, if we are not going to run any, + # terminate early + if os.path.exists( + os.path.join( + SCRIPT_DIR, + options.testRunManifestFile)): + with open(os.path.join(SCRIPT_DIR, options.testRunManifestFile)) as fHandle: + tests = json.load(fHandle) + count = 0 + for test in tests['tests']: + count += 1 + if count == 0: + return 1 + + self.buildURLOptions(options, self.browserEnv) + if self.urlOpts: + testURL += "?" + "&".join(self.urlOpts) + + if options.webapprtContent: + options.browserArgs.extend(('-test-mode', testURL)) + testURL = None + + if options.immersiveMode: + options.browserArgs.extend(('-firefoxpath', options.app)) + options.app = self.immersiveHelperPath + + if options.jsdebugger: + options.browserArgs.extend(['-jsdebugger']) + + # Remove the leak detection file so it can't "leak" to the tests run. + # The file is not there if leak logging was not enabled in the + # application build. + if os.path.exists(self.leak_report_file): + os.remove(self.leak_report_file) + + # then again to actually run mochitest + if options.timeout: + timeout = options.timeout + 30 + elif options.debugger or not options.autorun: + timeout = None + else: + timeout = 330.0 # default JS harness timeout is 300 seconds + + if options.vmwareRecording: + self.startVMwareRecording(options) + + # detect shutdown leaks for m-bc runs + detectShutdownLeaks = mozinfo.info[ + "debug"] and options.browserChrome and not options.webapprtChrome + + self.log.info("runtests.py | Running tests: start.\n") + try: + status = self.runApp(testURL, + self.browserEnv, + options.app, + profile=self.profile, + extraArgs=options.browserArgs, + utilityPath=options.utilityPath, + debuggerInfo=debuggerInfo, + symbolsPath=options.symbolsPath, + timeout=timeout, + onLaunch=onLaunch, + detectShutdownLeaks=detectShutdownLeaks, + screenshotOnFail=options.screenshotOnFail, + testPath=options.testPath, + bisectChunk=options.bisectChunk, + quiet=options.quiet + ) + except KeyboardInterrupt: + self.log.info("runtests.py | Received keyboard interrupt.\n") + status = -1 + except: + traceback.print_exc() + self.log.error( + "Automation Error: Received unexpected exception while running application\n") + status = 1 + + finally: + if options.vmwareRecording: + self.stopVMwareRecording() + self.stopServers() + + processLeakLog(self.leak_report_file, options) + + if self.nsprLogs: + with zipfile.ZipFile("%s/nsprlog.zip" % self.browserEnv["MOZ_UPLOAD_DIR"], "w", zipfile.ZIP_DEFLATED) as logzip: + for logfile in glob.glob( + "%s/nspr*.log*" % + tempfile.gettempdir()): + logzip.write(logfile) + os.remove(logfile) + + self.log.info("runtests.py | Running tests: end.") + + if self.manifest is not None: + self.cleanup(options) + + return status + + def handleTimeout( + self, + timeout, + proc, + utilityPath, + debuggerInfo, + browserProcessId, + testPath=None): + """handle process output timeout""" + # TODO: bug 913975 : _processOutput should call self.processOutputLine + # one more time one timeout (I think) + if testPath: + error_message = "TEST-UNEXPECTED-TIMEOUT | %s | application timed out after %d seconds with no output on %s" % ( + self.lastTestSeen, int(timeout), testPath) + else: + error_message = "TEST-UNEXPECTED-TIMEOUT | %s | application timed out after %d seconds with no output" % ( + self.lastTestSeen, int(timeout)) + + self.message_logger.dump_buffered() + self.message_logger.buffering = False + self.log.error(error_message) + + browserProcessId = browserProcessId or proc.pid + self.killAndGetStack( + browserProcessId, + utilityPath, + debuggerInfo, + dump_screen=not debuggerInfo) + + class OutputHandler(object): + + """line output handler for mozrunner""" + + def __init__( + self, + harness, + utilityPath, + symbolsPath=None, + dump_screen_on_timeout=True, + dump_screen_on_fail=False, + shutdownLeaks=None, + lsanLeaks=None, + bisectChunk=None): + """ + harness -- harness instance + dump_screen_on_timeout -- whether to dump the screen on timeout + """ + self.harness = harness + self.utilityPath = utilityPath + self.symbolsPath = symbolsPath + self.dump_screen_on_timeout = dump_screen_on_timeout + self.dump_screen_on_fail = dump_screen_on_fail + self.shutdownLeaks = shutdownLeaks + self.lsanLeaks = lsanLeaks + self.bisectChunk = bisectChunk + + # With metro browser runs this script launches the metro test harness which launches the browser. + # The metro test harness hands back the real browser process id via log output which we need to + # pick up on and parse out. This variable tracks the real browser + # process id if we find it. + self.browserProcessId = None + + self.stackFixerFunction = self.stackFixer() + + def processOutputLine(self, line): + """per line handler of output for mozprocess""" + # Parsing the line (by the structured messages logger). + messages = self.harness.message_logger.parse_line(line) + + for message in messages: + # Passing the message to the handlers + for handler in self.outputHandlers(): + message = handler(message) + + # Processing the message by the logger + self.harness.message_logger.process_message(message) + + __call__ = processOutputLine + + def outputHandlers(self): + """returns ordered list of output handlers""" + handlers = [self.fix_stack, + self.record_last_test, + self.dumpScreenOnTimeout, + self.dumpScreenOnFail, + self.trackShutdownLeaks, + self.trackLSANLeaks, + self.countline, + ] + if self.bisectChunk: + handlers.append(self.record_result) + handlers.append(self.first_error) + + return handlers + + def stackFixer(self): + """ + return stackFixerFunction, if any, to use on the output lines + """ + + if not mozinfo.info.get('debug'): + return None + + stackFixerFunction = None + + def import_stackFixerModule(module_name): + sys.path.insert(0, self.utilityPath) + module = __import__(module_name, globals(), locals(), []) + sys.path.pop(0) + return module + + if self.symbolsPath and os.path.exists(self.symbolsPath): + # Run each line through a function in fix_stack_using_bpsyms.py (uses breakpad symbol files). + # This method is preferred for Tinderbox builds, since native + # symbols may have been stripped. + stackFixerModule = import_stackFixerModule( + 'fix_stack_using_bpsyms') + stackFixerFunction = lambda line: stackFixerModule.fixSymbols( + line, + self.symbolsPath) + + elif mozinfo.isMac: + # Run each line through fix_macosx_stack.py (uses atos). + # This method is preferred for developer machines, so we don't + # have to run "make buildsymbols". + stackFixerModule = import_stackFixerModule('fix_macosx_stack') + stackFixerFunction = lambda line: stackFixerModule.fixSymbols( + line) + + elif mozinfo.isLinux: + # Run each line through fix_linux_stack.py (uses addr2line). + # This method is preferred for developer machines, so we don't + # have to run "make buildsymbols". + stackFixerModule = import_stackFixerModule('fix_linux_stack') + stackFixerFunction = lambda line: stackFixerModule.fixSymbols( + line) + + return stackFixerFunction + + def finish(self): + if self.shutdownLeaks: + self.shutdownLeaks.process() + + if self.lsanLeaks: + self.lsanLeaks.process() + + # output message handlers: + # these take a message and return a message + + def record_result(self, message): + # by default make the result key equal to pass. + if message['action'] == 'test_start': + key = message['test'].split('/')[-1].strip() + self.harness.result[key] = "PASS" + elif message['action'] == 'test_status': + if 'expected' in message: + key = message['test'].split('/')[-1].strip() + self.harness.result[key] = "FAIL" + elif message['status'] == 'FAIL': + key = message['test'].split('/')[-1].strip() + self.harness.result[key] = "TODO" + return message + + def first_error(self, message): + if message['action'] == 'test_status' and 'expected' in message and message[ + 'status'] == 'FAIL': + key = message['test'].split('/')[-1].strip() + if key not in self.harness.expectedError: + self.harness.expectedError[key] = message.get( + 'message', + message['subtest']).strip() + return message + + def countline(self, message): + if message['action'] != 'log': + return message + line = message['message'] + val = 0 + try: + val = int(line.split(':')[-1].strip()) + except ValueError: + return message + + if "Passed:" in line: + self.harness.countpass += val + elif "Failed:" in line: + self.harness.countfail += val + elif "Todo:" in line: + self.harness.counttodo += val + return message + + def fix_stack(self, message): + if message['action'] == 'log' and self.stackFixerFunction: + message['message'] = self.stackFixerFunction( + message['message'].encode( + 'utf-8', + 'replace')) + return message + + def record_last_test(self, message): + """record last test on harness""" + if message['action'] == 'test_start': + self.harness.lastTestSeen = message['test'] + return message + + def dumpScreenOnTimeout(self, message): + if (not self.dump_screen_on_fail + and self.dump_screen_on_timeout + and message['action'] == 'test_status' and 'expected' in message + and "Test timed out" in message['subtest']): + self.harness.dumpScreen(self.utilityPath) + return message + + def dumpScreenOnFail(self, message): + if self.dump_screen_on_fail and 'expected' in message and message[ + 'status'] == 'FAIL': + self.harness.dumpScreen(self.utilityPath) + return message + + def trackLSANLeaks(self, message): + if self.lsanLeaks and message['action'] == 'log': + self.lsanLeaks.log(message['message']) + return message + + def trackShutdownLeaks(self, message): + if self.shutdownLeaks: + self.shutdownLeaks.log(message) + return message + + def makeTestConfig(self, options): + "Creates a test configuration file for customizing test execution." + options.logFile = options.logFile.replace("\\", "\\\\") + options.testPath = options.testPath.replace("\\", "\\\\") + + if "MOZ_HIDE_RESULTS_TABLE" in os.environ and os.environ[ + "MOZ_HIDE_RESULTS_TABLE"] == "1": + options.hideResultsTable = True + + d = dict((k, v) for k, v in options.__dict__.items() if (not k.startswith( + 'log_') or not any([k.endswith(fmt) for fmt in commandline.log_formatters.keys()]))) + d['testRoot'] = self.testRoot + content = json.dumps(d) + + with open(os.path.join(options.profilePath, "testConfig.js"), "w") as config: + config.write(content) + + def getTestManifest(self, options): + if isinstance(options.manifestFile, TestManifest): + manifest = options.manifestFile + elif options.manifestFile and os.path.isfile(options.manifestFile): + manifestFileAbs = os.path.abspath(options.manifestFile) + assert manifestFileAbs.startswith(SCRIPT_DIR) + manifest = TestManifest([options.manifestFile], strict=False) + elif options.manifestFile and os.path.isfile(os.path.join(SCRIPT_DIR, options.manifestFile)): + manifestFileAbs = os.path.abspath( + os.path.join( + SCRIPT_DIR, + options.manifestFile)) + assert manifestFileAbs.startswith(SCRIPT_DIR) + manifest = TestManifest([manifestFileAbs], strict=False) + else: + masterName = self.getTestFlavor(options) + '.ini' + masterPath = os.path.join(SCRIPT_DIR, self.testRoot, masterName) + + if os.path.exists(masterPath): + manifest = TestManifest([masterPath], strict=False) + else: + self._log.warning( + 'TestManifest masterPath %s does not exist' % + masterPath) + + return manifest + + def getDirectories(self, options): + """ + Make the list of directories by parsing manifests + """ + tests = self.getActiveTests(options, False) + dirlist = [] + + for test in tests: + rootdir = '/'.join(test['path'].split('/')[:-1]) + if rootdir not in dirlist: + dirlist.append(rootdir) + + return dirlist - return dirlist def main(): - # parse command line options - parser = MochitestOptions() - commandline.add_logging_group(parser) - options, args = parser.parse_args() - if options is None: - # parsing error - sys.exit(1) - logger_options = {key: value for key, value in vars(options).iteritems() if key.startswith('log')} - mochitest = Mochitest(logger_options) - options = parser.verifyOptions(options, mochitest) + # parse command line options + parser = MochitestOptions() + commandline.add_logging_group(parser) + options, args = parser.parse_args() + if options is None: + # parsing error + sys.exit(1) + logger_options = { + key: value for key, + value in vars(options).iteritems() if key.startswith('log')} + mochitest = Mochitest(logger_options) + options = parser.verifyOptions(options, mochitest) - options.utilityPath = mochitest.getFullPath(options.utilityPath) - options.certPath = mochitest.getFullPath(options.certPath) - if options.symbolsPath and len(urlparse(options.symbolsPath).scheme) < 2: - options.symbolsPath = mochitest.getFullPath(options.symbolsPath) + options.utilityPath = mochitest.getFullPath(options.utilityPath) + options.certPath = mochitest.getFullPath(options.certPath) + if options.symbolsPath and len(urlparse(options.symbolsPath).scheme) < 2: + options.symbolsPath = mochitest.getFullPath(options.symbolsPath) - return_code = mochitest.runTests(options) - mochitest.message_logger.finish() + return_code = mochitest.runTests(options) + mochitest.message_logger.finish() - sys.exit(return_code) + sys.exit(return_code) if __name__ == "__main__": - main() + main() diff --git a/testing/mochitest/runtestsb2g.py b/testing/mochitest/runtestsb2g.py index d3e504a7a3f..d50a472d18d 100644 --- a/testing/mochitest/runtestsb2g.py +++ b/testing/mochitest/runtestsb2g.py @@ -23,14 +23,15 @@ from mozprofile import Profile, Preferences from mozlog import structured import mozinfo + class B2GMochitest(MochitestUtilsMixin): marionette = None def __init__(self, marionette_args, - logger_options, - out_of_process=True, - profile_data_dir=None, - locations=os.path.join(here, 'server-locations.txt')): + logger_options, + out_of_process=True, + profile_data_dir=None, + locations=os.path.join(here, 'server-locations.txt')): super(B2GMochitest, self).__init__(logger_options) self.marionette_args = marionette_args self.out_of_process = out_of_process @@ -43,10 +44,14 @@ class B2GMochitest(MochitestUtilsMixin): self.remote_chrome_test_dir = None if profile_data_dir: - self.preferences = [os.path.join(profile_data_dir, f) - for f in os.listdir(profile_data_dir) if f.startswith('pref')] - self.webapps = [os.path.join(profile_data_dir, f) - for f in os.listdir(profile_data_dir) if f.startswith('webapp')] + self.preferences = [ + os.path.join( + profile_data_dir, + f) for f in os.listdir(profile_data_dir) if f.startswith('pref')] + self.webapps = [ + os.path.join( + profile_data_dir, + f) for f in os.listdir(profile_data_dir) if f.startswith('webapp')] # mozinfo is populated by the parent class if mozinfo.info['debug']: @@ -68,7 +73,12 @@ class B2GMochitest(MochitestUtilsMixin): def buildTestPath(self, options, testsToFilter=None): if options.manifestFile != 'tests.json': - super(B2GMochitest, self).buildTestPath(options, testsToFilter, disabled=False) + super( + B2GMochitest, + self).buildTestPath( + options, + testsToFilter, + disabled=False) return self.buildTestURL(options) def build_profile(self, options): @@ -85,8 +95,11 @@ class B2GMochitest(MochitestUtilsMixin): prefs[thispref[0]] = thispref[1] # interpolate the preferences - interpolation = { "server": "%s:%s" % (options.webServer, options.httpPort), - "OOP": "true" if self.out_of_process else "false" } + interpolation = { + "server": "%s:%s" % + (options.webServer, + options.httpPort), + "OOP": "true" if self.out_of_process else "false"} prefs = json.loads(json.dumps(prefs) % interpolation) for pref in prefs: prefs[pref] = Preferences.cast(prefs[pref]) @@ -138,7 +151,8 @@ class B2GMochitest(MochitestUtilsMixin): if message['action'] == 'test_start': self.runner.last_test = message['test'] - # The logging will be handled by on_output, so we set the stream to None + # The logging will be handled by on_output, so we set the stream to + # None process_args = {'processOutputLine': on_output, 'stream': None} self.marionette_args['process_args'] = process_args @@ -150,23 +164,29 @@ class B2GMochitest(MochitestUtilsMixin): self.remote_log = posixpath.join(self.app_ctx.remote_test_root, 'log', 'mochitest.log') - if not self.app_ctx.dm.dirExists(posixpath.dirname(self.remote_log)): + if not self.app_ctx.dm.dirExists( + posixpath.dirname( + self.remote_log)): self.app_ctx.dm.mkDirs(self.remote_log) if options.chrome: # Update chrome manifest file in profile with correct path. self.writeChromeManifest(options) - self.leak_report_file = posixpath.join(self.app_ctx.remote_test_root, - 'log', 'runtests_leaks.log') + self.leak_report_file = posixpath.join( + self.app_ctx.remote_test_root, + 'log', + 'runtests_leaks.log') # We don't want to copy the host env onto the device, so pass in an # empty env. self.browserEnv = self.buildBrowserEnv(options, env={}) # B2G emulator debug tests still make external connections, so don't - # pass MOZ_DISABLE_NONLOCAL_CONNECTIONS to them for now (bug 1039019). - if mozinfo.info['debug'] and 'MOZ_DISABLE_NONLOCAL_CONNECTIONS' in self.browserEnv: + # pass MOZ_DISABLE_NONLOCAL_CONNECTIONS to them for now (bug + # 1039019). + if mozinfo.info[ + 'debug'] and 'MOZ_DISABLE_NONLOCAL_CONNECTIONS' in self.browserEnv: del self.browserEnv['MOZ_DISABLE_NONLOCAL_CONNECTIONS'] self.runner.env.update(self.browserEnv) @@ -176,7 +196,6 @@ class B2GMochitest(MochitestUtilsMixin): self.test_script_args.append(options.wifi) self.test_script_args.append(options.chrome) - self.runner.start(outputTimeout=timeout) self.marionette.wait_for_port() @@ -185,7 +204,8 @@ class B2GMochitest(MochitestUtilsMixin): # Disable offline status management (bug 777145), otherwise the network # will be 'offline' when the mochitests start. Presumably, the network - # won't be offline on a real device, so we only do this for emulators. + # won't be offline on a real device, so we only do this for + # emulators. self.marionette.execute_script(""" Components.utils.import("resource://gre/modules/Services.jsm"); Services.io.manageOfflineStatus = false; @@ -198,16 +218,20 @@ class B2GMochitest(MochitestUtilsMixin): local = super(B2GMochitest, self).getChromeTestDir(options) local = os.path.join(local, "chrome") remote = self.remote_chrome_test_dir - self.log.info("pushing %s to %s on device..." % (local, remote)) + self.log.info( + "pushing %s to %s on device..." % + (local, remote)) self.app_ctx.dm.pushDir(local, remote) if os.path.isfile(self.test_script): with open(self.test_script, 'r') as script: - self.marionette.execute_script(script.read(), - script_args=self.test_script_args) + self.marionette.execute_script( + script.read(), + script_args=self.test_script_args) else: - self.marionette.execute_script(self.test_script, - script_args=self.test_script_args) + self.marionette.execute_script( + self.test_script, + script_args=self.test_script_args) status = self.runner.wait() if status is None: @@ -215,16 +239,19 @@ class B2GMochitest(MochitestUtilsMixin): status = 124 local_leak_file = tempfile.NamedTemporaryFile() - self.app_ctx.dm.getFile(self.leak_report_file, local_leak_file.name) + self.app_ctx.dm.getFile( + self.leak_report_file, + local_leak_file.name) self.app_ctx.dm.removeFile(self.leak_report_file) processLeakLog(local_leak_file.name, options) except KeyboardInterrupt: - self.log.info("runtests.py | Received keyboard interrupt.\n"); + self.log.info("runtests.py | Received keyboard interrupt.\n") status = -1 except: traceback.print_exc() - self.log.error("Automation Error: Received unexpected exception while running application\n") + self.log.error( + "Automation Error: Received unexpected exception while running application\n") if hasattr(self, 'runner'): self.runner.check_for_crashes() status = 1 @@ -249,7 +276,9 @@ class B2GMochitest(MochitestUtilsMixin): # is defined; the correct directory will be returned later, over- # writing the dummy. if hasattr(self, 'app_ctx'): - self.remote_chrome_test_dir = posixpath.join(self.app_ctx.remote_test_root, 'chrome'); + self.remote_chrome_test_dir = posixpath.join( + self.app_ctx.remote_test_root, + 'chrome') return self.remote_chrome_test_dir return 'dummy-chrome-test-dir' @@ -257,9 +286,20 @@ class B2GMochitest(MochitestUtilsMixin): class B2GDeviceMochitest(B2GMochitest, Mochitest): remote_log = None - def __init__(self, marionette_args, logger_options, profile_data_dir, - local_binary_dir, remote_test_root=None, remote_log_file=None): - B2GMochitest.__init__(self, marionette_args, logger_options, out_of_process=True, profile_data_dir=profile_data_dir) + def __init__( + self, + marionette_args, + logger_options, + profile_data_dir, + local_binary_dir, + remote_test_root=None, + remote_log_file=None): + B2GMochitest.__init__( + self, + marionette_args, + logger_options, + out_of_process=True, + profile_data_dir=profile_data_dir) self.local_log = None self.local_binary_dir = local_binary_dir @@ -314,7 +354,12 @@ class B2GDeviceMochitest(B2GMochitest, Mochitest): class B2GDesktopMochitest(B2GMochitest, Mochitest): def __init__(self, marionette_args, logger_options, profile_data_dir): - B2GMochitest.__init__(self, marionette_args, logger_options, out_of_process=False, profile_data_dir=profile_data_dir) + B2GMochitest.__init__( + self, + marionette_args, + logger_options, + out_of_process=False, + profile_data_dir=profile_data_dir) Mochitest.__init__(self, logger_options) self.certdbNew = True @@ -347,7 +392,10 @@ class B2GDesktopMochitest(B2GMochitest, Mochitest): self.setup_common_options(options) # Copy the extensions to the B2G bundles dir. - extensionDir = os.path.join(options.profilePath, 'extensions', 'staged') + extensionDir = os.path.join( + options.profilePath, + 'extensions', + 'staged') bundlesDir = os.path.join(os.path.dirname(options.app), 'distribution', 'bundles') @@ -378,15 +426,19 @@ def run_remote_mochitests(parser, options): marionette_args['port'] = int(port) options = parser.verifyRemoteOptions(options) - if (options == None): + if (options is None): print "ERROR: Invalid options specified, use --help for a list of valid options" sys.exit(1) - mochitest = B2GDeviceMochitest(marionette_args, options, options.profile_data_dir, - options.xrePath, remote_log_file=options.remoteLogFile) + mochitest = B2GDeviceMochitest( + marionette_args, + options, + options.profile_data_dir, + options.xrePath, + remote_log_file=options.remoteLogFile) options = parser.verifyOptions(options, mochitest) - if (options == None): + if (options is None): sys.exit(1) retVal = 1 @@ -407,6 +459,7 @@ def run_remote_mochitests(parser, options): sys.exit(retVal) + def run_desktop_mochitests(parser, options): # create our Marionette instance marionette_args = {} @@ -420,9 +473,12 @@ def run_desktop_mochitests(parser, options): if os.path.isfile("%s-bin" % options.app): options.app = "%s-bin" % options.app - mochitest = B2GDesktopMochitest(marionette_args, options, options.profile_data_dir) + mochitest = B2GDesktopMochitest( + marionette_args, + options, + options.profile_data_dir) options = MochitestOptions.verifyOptions(parser, options, mochitest) - if options == None: + if options is None: sys.exit(1) if options.desktop and not options.profile: @@ -435,6 +491,7 @@ def run_desktop_mochitests(parser, options): sys.exit(retVal) + def main(): parser = B2GOptions() structured.commandline.add_logging_group(parser) diff --git a/testing/mochitest/runtestsremote.py b/testing/mochitest/runtestsremote.py index 2c8c4584ec6..927b77c7f92 100644 --- a/testing/mochitest/runtestsremote.py +++ b/testing/mochitest/runtestsremote.py @@ -13,7 +13,10 @@ import sys import tempfile import traceback -sys.path.insert(0, os.path.abspath(os.path.realpath(os.path.dirname(__file__)))) +sys.path.insert( + 0, os.path.abspath( + os.path.realpath( + os.path.dirname(__file__)))) from automation import Automation from remoteautomation import RemoteAutomation, fennecLogcatFilters @@ -29,6 +32,7 @@ import moznetwork SCRIPT_DIR = os.path.abspath(os.path.realpath(os.path.dirname(__file__))) + class RemoteOptions(MochitestOptions): def __init__(self, automation, **kwargs): @@ -36,84 +40,117 @@ class RemoteOptions(MochitestOptions): self._automation = automation or Automation() MochitestOptions.__init__(self) - self.add_option("--remote-app-path", action="store", - type = "string", dest = "remoteAppPath", - help = "Path to remote executable relative to device root using only forward slashes. Either this or app must be specified but not both") + self.add_option( + "--remote-app-path", + action="store", + type="string", + dest="remoteAppPath", + help="Path to remote executable relative to device root using only forward slashes. Either this or app must be specified but not both") defaults["remoteAppPath"] = None self.add_option("--deviceIP", action="store", - type = "string", dest = "deviceIP", - help = "ip address of remote device to test") + type="string", dest="deviceIP", + help="ip address of remote device to test") defaults["deviceIP"] = None self.add_option("--deviceSerial", action="store", - type = "string", dest = "deviceSerial", - help = "ip address of remote device to test") + type="string", dest="deviceSerial", + help="ip address of remote device to test") defaults["deviceSerial"] = None - self.add_option("--dm_trans", action="store", - type = "string", dest = "dm_trans", - help = "the transport to use to communicate with device: [adb|sut]; default=sut") + self.add_option( + "--dm_trans", + action="store", + type="string", + dest="dm_trans", + help="the transport to use to communicate with device: [adb|sut]; default=sut") defaults["dm_trans"] = "sut" self.add_option("--devicePort", action="store", - type = "string", dest = "devicePort", - help = "port of remote device to test") + type="string", dest="devicePort", + help="port of remote device to test") defaults["devicePort"] = 20701 - self.add_option("--remote-product-name", action="store", - type = "string", dest = "remoteProductName", - help = "The executable's name of remote product to test - either fennec or firefox, defaults to fennec") + self.add_option( + "--remote-product-name", + action="store", + type="string", + dest="remoteProductName", + help="The executable's name of remote product to test - either fennec or firefox, defaults to fennec") defaults["remoteProductName"] = "fennec" - self.add_option("--remote-logfile", action="store", - type = "string", dest = "remoteLogFile", - help = "Name of log file on the device relative to the device root. PLEASE ONLY USE A FILENAME.") + self.add_option( + "--remote-logfile", + action="store", + type="string", + dest="remoteLogFile", + help="Name of log file on the device relative to the device root. PLEASE ONLY USE A FILENAME.") defaults["remoteLogFile"] = None - self.add_option("--remote-webserver", action = "store", - type = "string", dest = "remoteWebServer", - help = "ip address where the remote web server is hosted at") + self.add_option( + "--remote-webserver", + action="store", + type="string", + dest="remoteWebServer", + help="ip address where the remote web server is hosted at") defaults["remoteWebServer"] = None - self.add_option("--http-port", action = "store", - type = "string", dest = "httpPort", - help = "http port of the remote web server") + self.add_option("--http-port", action="store", + type="string", dest="httpPort", + help="http port of the remote web server") defaults["httpPort"] = automation.DEFAULT_HTTP_PORT - self.add_option("--ssl-port", action = "store", - type = "string", dest = "sslPort", - help = "ssl port of the remote web server") + self.add_option("--ssl-port", action="store", + type="string", dest="sslPort", + help="ssl port of the remote web server") defaults["sslPort"] = automation.DEFAULT_SSL_PORT - self.add_option("--robocop-ini", action = "store", - type = "string", dest = "robocopIni", - help = "name of the .ini file containing the list of tests to run") + self.add_option( + "--robocop-ini", + action="store", + type="string", + dest="robocopIni", + help="name of the .ini file containing the list of tests to run") defaults["robocopIni"] = "" - self.add_option("--robocop", action = "store", - type = "string", dest = "robocop", - help = "name of the .ini file containing the list of tests to run. [DEPRECATED- please use --robocop-ini") + self.add_option( + "--robocop", + action="store", + type="string", + dest="robocop", + help="name of the .ini file containing the list of tests to run. [DEPRECATED- please use --robocop-ini") defaults["robocop"] = "" - self.add_option("--robocop-apk", action = "store", - type = "string", dest = "robocopApk", - help = "name of the Robocop APK to use for ADB test running") + self.add_option( + "--robocop-apk", + action="store", + type="string", + dest="robocopApk", + help="name of the Robocop APK to use for ADB test running") defaults["robocopApk"] = "" - self.add_option("--robocop-path", action = "store", - type = "string", dest = "robocopPath", - help = "Path to the folder where robocop.apk is located at. Primarily used for ADB test running. [DEPRECATED- please use --robocop-apk]") + self.add_option( + "--robocop-path", + action="store", + type="string", + dest="robocopPath", + help="Path to the folder where robocop.apk is located at. Primarily used for ADB test running. [DEPRECATED- please use --robocop-apk]") defaults["robocopPath"] = "" - self.add_option("--robocop-ids", action = "store", - type = "string", dest = "robocopIds", - help = "name of the file containing the view ID map (fennec_ids.txt)") + self.add_option( + "--robocop-ids", + action="store", + type="string", + dest="robocopIds", + help="name of the file containing the view ID map (fennec_ids.txt)") defaults["robocopIds"] = "" - self.add_option("--remoteTestRoot", action = "store", - type = "string", dest = "remoteTestRoot", - help = "remote directory to use as test root (eg. /mnt/sdcard/tests or /data/local/tests)") + self.add_option( + "--remoteTestRoot", + action="store", + type="string", + dest="remoteTestRoot", + help="remote directory to use as test root (eg. /mnt/sdcard/tests or /data/local/tests)") defaults["remoteTestRoot"] = None defaults["logFile"] = "mochitest.log" @@ -131,38 +168,43 @@ class RemoteOptions(MochitestOptions): if not options.remoteTestRoot: options.remoteTestRoot = automation._devicemanager.deviceRoot - if options.remoteWebServer == None: + if options.remoteWebServer is None: if os.name != "nt": options.remoteWebServer = moznetwork.get_ip() else: - options_logger.error("you must specify a --remote-webserver=") + options_logger.error( + "you must specify a --remote-webserver=") return None options.webServer = options.remoteWebServer - if (options.dm_trans == 'sut' and options.deviceIP == None): - options_logger.error("If --dm_trans = sut, you must provide a device IP") + if (options.dm_trans == 'sut' and options.deviceIP is None): + options_logger.error( + "If --dm_trans = sut, you must provide a device IP") return None - if (options.remoteLogFile == None): - options.remoteLogFile = options.remoteTestRoot + '/logs/mochitest.log' + if (options.remoteLogFile is None): + options.remoteLogFile = options.remoteTestRoot + \ + '/logs/mochitest.log' if (options.remoteLogFile.count('/') < 1): - options.remoteLogFile = options.remoteTestRoot + '/' + options.remoteLogFile + options.remoteLogFile = options.remoteTestRoot + \ + '/' + options.remoteLogFile # remoteAppPath or app must be specified to find the product to launch if (options.remoteAppPath and options.app): - options_logger.error("You cannot specify both the remoteAppPath and the app setting") + options_logger.error( + "You cannot specify both the remoteAppPath and the app setting") return None elif (options.remoteAppPath): options.app = options.remoteTestRoot + "/" + options.remoteAppPath - elif (options.app == None): + elif (options.app is None): # Neither remoteAppPath nor app are set -- error options_logger.error("You must specify either appPath or app") return None # Only reset the xrePath if it wasn't provided - if (options.xrePath == None): + if (options.xrePath is None): options.xrePath = options.utilityPath if (options.pidFile != ""): @@ -173,38 +215,49 @@ class RemoteOptions(MochitestOptions): # Robocop specific deprecated options. if options.robocop: if options.robocopIni: - options_logger.error("can not use deprecated --robocop and replacement --robocop-ini together") + options_logger.error( + "can not use deprecated --robocop and replacement --robocop-ini together") return None options.robocopIni = options.robocop del options.robocop if options.robocopPath: if options.robocopApk: - options_logger.error("can not use deprecated --robocop-path and replacement --robocop-apk together") + options_logger.error( + "can not use deprecated --robocop-path and replacement --robocop-apk together") return None - options.robocopApk = os.path.join(options.robocopPath, 'robocop.apk') + options.robocopApk = os.path.join( + options.robocopPath, + 'robocop.apk') del options.robocopPath # Robocop specific options if options.robocopIni != "": if not os.path.exists(options.robocopIni): - options_logger.error("Unable to find specified robocop .ini manifest '%s'" % options.robocopIni) + options_logger.error( + "Unable to find specified robocop .ini manifest '%s'" % + options.robocopIni) return None options.robocopIni = os.path.abspath(options.robocopIni) if options.robocopApk != "": if not os.path.exists(options.robocopApk): - options_logger.error("Unable to find robocop APK '%s'" % options.robocopApk) + options_logger.error( + "Unable to find robocop APK '%s'" % + options.robocopApk) return None options.robocopApk = os.path.abspath(options.robocopApk) if options.robocopIds != "": if not os.path.exists(options.robocopIds): - options_logger.error("Unable to find specified robocop IDs file '%s'" % options.robocopIds) + options_logger.error( + "Unable to find specified robocop IDs file '%s'" % + options.robocopIds) return None options.robocopIds = os.path.abspath(options.robocopIds) - # allow us to keep original application around for cleanup while running robocop via 'am' + # allow us to keep original application around for cleanup while + # running robocop via 'am' options.remoteappname = options.app return options @@ -226,6 +279,7 @@ class RemoteOptions(MochitestOptions): return options + class MochiRemote(Mochitest): _automation = None @@ -247,20 +301,24 @@ class MochiRemote(Mochitest): self._automation.deleteTombstones() self.certdbNew = True self.remoteNSPR = os.path.join(options.remoteTestRoot, "nspr") - self._dm.removeDir(self.remoteNSPR); - self._dm.mkDir(self.remoteNSPR); - self.remoteChromeTestDir = os.path.join(options.remoteTestRoot, "chrome") - self._dm.removeDir(self.remoteChromeTestDir); - self._dm.mkDir(self.remoteChromeTestDir); + self._dm.removeDir(self.remoteNSPR) + self._dm.mkDir(self.remoteNSPR) + self.remoteChromeTestDir = os.path.join( + options.remoteTestRoot, + "chrome") + self._dm.removeDir(self.remoteChromeTestDir) + self._dm.mkDir(self.remoteChromeTestDir) def cleanup(self, options): if self._dm.fileExists(self.remoteLog): self._dm.getFile(self.remoteLog, self.localLog) self._dm.removeFile(self.remoteLog) else: - self.log.warning("Unable to retrieve log file (%s) from remote device" % self.remoteLog) + self.log.warning( + "Unable to retrieve log file (%s) from remote device" % + self.remoteLog) self._dm.removeDir(self.remoteProfile) - self._dm.removeDir(self.remoteChromeTestDir); + self._dm.removeDir(self.remoteChromeTestDir) # Don't leave an old robotium.config hanging around; the # profile it references was just deleted! deviceRoot = self._dm.getDeviceRoot() @@ -270,7 +328,7 @@ class MochiRemote(Mochitest): self._dm.getDirectory(self.remoteNSPR, blobberUploadDir) Mochitest.cleanup(self, options) - def findPath(self, paths, filename = None): + def findPath(self, paths, filename=None): for path in paths: p = path if filename: @@ -286,7 +344,7 @@ class MochiRemote(Mochitest): localAutomation.IS_MAC = False localAutomation.UNIXISH = False hostos = sys.platform - if (hostos == 'mac' or hostos == 'darwin'): + if (hostos == 'mac' or hostos == 'darwin'): localAutomation.IS_MAC = True elif (hostos == 'linux' or hostos == 'linux2'): localAutomation.IS_LINUX = True @@ -315,8 +373,10 @@ class MochiRemote(Mochitest): os.path.join('..', self._automation._product) ] options.xrePath = self.findPath(paths) - if options.xrePath == None: - self.log.error("unable to find xulrunner path for %s, please specify with --xre-path" % os.name) + if options.xrePath is None: + self.log.error( + "unable to find xulrunner path for %s, please specify with --xre-path" % + os.name) sys.exit(1) xpcshell = "xpcshell" @@ -329,15 +389,17 @@ class MochiRemote(Mochitest): paths = [options.xrePath] options.utilityPath = self.findPath(paths, xpcshell) - if options.utilityPath == None: - self.log.error("unable to find utility path for %s, please specify with --utility-path" % os.name) + if options.utilityPath is None: + self.log.error( + "unable to find utility path for %s, please specify with --utility-path" % + os.name) sys.exit(1) xpcshell_path = os.path.join(options.utilityPath, xpcshell) if localAutomation.elf_arm(xpcshell_path): self.log.error('xpcshell at %s is an ARM binary; please use ' - 'the --utility-path argument to specify the path ' - 'to a desktop version.' % xpcshell_path) + 'the --utility-path argument to specify the path ' + 'to a desktop version.' % xpcshell_path) sys.exit(1) if self.localProfile: @@ -356,7 +418,11 @@ class MochiRemote(Mochitest): """ Create the servers on the host and start them up """ restoreRemotePaths = self.switchToLocalPaths(options) # ignoreSSLTunnelExts is a workaround for bug 1109310 - Mochitest.startServers(self, options, debuggerInfo, ignoreSSLTunnelExts = True) + Mochitest.startServers( + self, + options, + debuggerInfo, + ignoreSSLTunnelExts=True) restoreRemotePaths() def buildProfile(self, options): @@ -368,15 +434,31 @@ class MochiRemote(Mochitest): # we do not need this for robotium based tests, lets save a LOT of time if options.robocopIni: shutil.rmtree(os.path.join(options.profilePath, 'webapps')) - shutil.rmtree(os.path.join(options.profilePath, 'extensions', 'staged', 'mochikit@mozilla.org')) - shutil.rmtree(os.path.join(options.profilePath, 'extensions', 'staged', 'worker-test@mozilla.org')) - shutil.rmtree(os.path.join(options.profilePath, 'extensions', 'staged', 'workerbootstrap-test@mozilla.org')) + shutil.rmtree( + os.path.join( + options.profilePath, + 'extensions', + 'staged', + 'mochikit@mozilla.org')) + shutil.rmtree( + os.path.join( + options.profilePath, + 'extensions', + 'staged', + 'worker-test@mozilla.org')) + shutil.rmtree( + os.path.join( + options.profilePath, + 'extensions', + 'staged', + 'workerbootstrap-test@mozilla.org')) os.remove(os.path.join(options.profilePath, 'userChrome.css')) try: self._dm.pushDir(options.profilePath, self.remoteProfile) except devicemanager.DMError: - self.log.error("Automation Error: Unable to copy profile to device.") + self.log.error( + "Automation Error: Unable to copy profile to device.") raise restoreRemotePaths() @@ -392,11 +474,12 @@ class MochiRemote(Mochitest): retVal = Mochitest.buildURLOptions(self, options, env) if not options.robocopIni: - #we really need testConfig.js (for browser chrome) + # we really need testConfig.js (for browser chrome) try: self._dm.pushDir(options.profilePath, self.remoteProfile) except devicemanager.DMError: - self.log.error("Automation Error: Unable to copy profile to device.") + self.log.error( + "Automation Error: Unable to copy profile to device.") raise options.profilePath = self.remoteProfile @@ -416,7 +499,11 @@ class MochiRemote(Mochitest): # robocop tests. return self.buildTestURL(options) else: - return super(MochiRemote, self).buildTestPath(options, testsToFilter) + return super( + MochiRemote, + self).buildTestPath( + options, + testsToFilter) def getChromeTestDir(self, options): local = super(MochiRemote, self).getChromeTestDir(options) @@ -430,7 +517,8 @@ class MochiRemote(Mochitest): def getLogFilePath(self, logFile): return logFile - # In the future we could use LogParser: http://hg.mozilla.org/automation/logparser/ + # In the future we could use LogParser: + # http://hg.mozilla.org/automation/logparser/ def addLogData(self): with open(self.localLog) as currentLog: data = currentLog.readlines() @@ -461,7 +549,8 @@ class MochiRemote(Mochitest): if fail_found: result = 1 if not end_found: - self.log.info("PROCESS-CRASH | Automation Error: Missing end of test marker (process crashed?)") + self.log.info( + "PROCESS-CRASH | Automation Error: Missing end of test marker (process crashed?)") result = 1 return result @@ -494,7 +583,8 @@ class MochiRemote(Mochitest): incr += 1 logFile.append("%s INFO SimpleTest FINISHED" % incr) - # TODO: Consider not printing to stdout because we might be duplicating output + # TODO: Consider not printing to stdout because we might be duplicating + # output print '\n'.join(logFile) with open(self.localLog, 'w') as localLog: localLog.write('\n'.join(logFile)) @@ -506,7 +596,9 @@ class MochiRemote(Mochitest): def printScreenshots(self, screenShotDir): # TODO: This can be re-written after completion of bug 749421 if not self._dm.dirExists(screenShotDir): - self.log.info("SCREENSHOT: No ScreenShots directory available: " + screenShotDir) + self.log.info( + "SCREENSHOT: No ScreenShots directory available: " + + screenShotDir) return printed = 0 @@ -527,8 +619,13 @@ class MochiRemote(Mochitest): def printDeviceInfo(self, printLogcat=False): try: if printLogcat: - logcat = self._dm.getLogcat(filterOutRegexps=fennecLogcatFilters) - self.log.info('\n' + ''.join(logcat).decode('utf-8', 'replace')) + logcat = self._dm.getLogcat( + filterOutRegexps=fennecLogcatFilters) + self.log.info( + '\n' + + ''.join(logcat).decode( + 'utf-8', + 'replace')) self.log.info("Device info: %s" % self._dm.getInfo()) self.log.info("Test root: %s" % self._dm.deviceRoot) except devicemanager.DMError: @@ -543,7 +640,9 @@ class MochiRemote(Mochitest): fHandle.write("profile=%s\n" % (self.remoteProfile)) fHandle.write("logfile=%s\n" % (options.remoteLogFile)) fHandle.write("host=http://mochi.test:8888/tests\n") - fHandle.write("rawhost=http://%s:%s/tests\n" % (options.remoteWebServer, options.httpPort)) + fHandle.write( + "rawhost=http://%s:%s/tests\n" % + (options.remoteWebServer, options.httpPort)) if browserEnv: envstr = "" @@ -551,7 +650,9 @@ class MochiRemote(Mochitest): for key, value in browserEnv.items(): try: value.index(',') - self.log.error("buildRobotiumConfig: browserEnv - Found a ',' in our value, unable to process value. key=%s,value=%s" % (key, value)) + self.log.error( + "buildRobotiumConfig: browserEnv - Found a ',' in our value, unable to process value. key=%s,value=%s" % + (key, value)) self.log.error("browserEnv=%s" % browserEnv) except ValueError: envstr += "%s%s=%s" % (delim, key, value) @@ -561,7 +662,11 @@ class MochiRemote(Mochitest): fHandle.close() self._dm.removeFile(os.path.join(deviceRoot, "robotium.config")) - self._dm.pushFile(fHandle.name, os.path.join(deviceRoot, "robotium.config")) + self._dm.pushFile( + fHandle.name, + os.path.join( + deviceRoot, + "robotium.config")) os.unlink(fHandle.name) def getGMPPluginPath(self, options): @@ -569,10 +674,15 @@ class MochiRemote(Mochitest): return None def buildBrowserEnv(self, options, debugger=False): - browserEnv = Mochitest.buildBrowserEnv(self, options, debugger=debugger) + browserEnv = Mochitest.buildBrowserEnv( + self, + options, + debugger=debugger) # override nsprLogs to avoid processing in Mochitest base class self.nsprLogs = None - browserEnv["NSPR_LOG_FILE"] = os.path.join(self.remoteNSPR, self.nsprLogName) + browserEnv["NSPR_LOG_FILE"] = os.path.join( + self.remoteNSPR, + self.nsprLogName) self.buildRobotiumConfig(options, browserEnv) return browserEnv @@ -593,6 +703,7 @@ class MochiRemote(Mochitest): return self._automation.runApp(*args, **kwargs) + def main(args): message_logger = MessageLogger(logger=None) process_args = {'messageLogger': message_logger} @@ -604,13 +715,23 @@ def main(args): if (options.dm_trans == "adb"): if (options.deviceIP): - dm = droid.DroidADB(options.deviceIP, options.devicePort, deviceRoot=options.remoteTestRoot) + dm = droid.DroidADB( + options.deviceIP, + options.devicePort, + deviceRoot=options.remoteTestRoot) elif (options.deviceSerial): - dm = droid.DroidADB(None, None, deviceSerial=options.deviceSerial, deviceRoot=options.remoteTestRoot) + dm = droid.DroidADB( + None, + None, + deviceSerial=options.deviceSerial, + deviceRoot=options.remoteTestRoot) else: dm = droid.DroidADB(deviceRoot=options.remoteTestRoot) else: - dm = droid.DroidSUT(options.deviceIP, options.devicePort, deviceRoot=options.remoteTestRoot) + dm = droid.DroidSUT( + options.deviceIP, + options.devicePort, + deviceRoot=options.remoteTestRoot) auto.setDeviceManager(dm) options = parser.verifyRemoteOptions(options, auto) @@ -620,23 +741,24 @@ def main(args): message_logger.logger = log mochitest.message_logger = message_logger - if (options == None): - log.error("Invalid options specified, use --help for a list of valid options") + if (options is None): + log.error( + "Invalid options specified, use --help for a list of valid options") return 1 productPieces = options.remoteProductName.split('.') - if (productPieces != None): + if (productPieces is not None): auto.setProduct(productPieces[0]) else: auto.setProduct(options.remoteProductName) auto.setAppName(options.remoteappname) options = parser.verifyOptions(options, mochitest) - if (options == None): + if (options is None): return 1 logParent = os.path.dirname(options.remoteLogFile) - dm.mkDir(logParent); + dm.mkDir(logParent) auto.setRemoteLog(options.remoteLogFile) auto.setServerInfo(options.webServer, options.httpPort, options.sslPort) @@ -645,7 +767,9 @@ def main(args): # Add Android version (SDK level) to mozinfo so that manifest entries # can be conditional on android_version. androidVersion = dm.shellCheckOutput(['getprop', 'ro.build.version.sdk']) - log.info("Android sdk version '%s'; will use this to filter manifests" % str(androidVersion)) + log.info( + "Android sdk version '%s'; will use this to filter manifests" % + str(androidVersion)) mozinfo.info['android_version'] = androidVersion deviceRoot = dm.deviceRoot @@ -677,13 +801,14 @@ def main(args): tests.append(test['name']) if options.totalChunks: - tests_per_chunk = math.ceil(len(tests) / (options.totalChunks * 1.0)) - start = int(round((options.thisChunk-1) * tests_per_chunk)) + tests_per_chunk = math.ceil( + len(tests) / (options.totalChunks * 1.0)) + start = int(round((options.thisChunk - 1) * tests_per_chunk)) end = int(round(options.thisChunk * tests_per_chunk)) if end > len(tests): end = len(tests) my_tests = tests[start:end] - log.info("Running tests %d-%d/%d" % (start+1, end, len(tests))) + log.info("Running tests %d-%d/%d" % (start + 1, end, len(tests))) options.extraPrefs.append('browser.search.suggest.enabled=true') options.extraPrefs.append('browser.search.suggest.prompted=true') @@ -706,7 +831,9 @@ def main(args): continue if 'disabled' in test: - log.info('TEST-INFO | skipping %s | %s' % (test['name'], test['disabled'])) + log.info( + 'TEST-INFO | skipping %s | %s' % + (test['name'], test['disabled'])) continue active_tests.append(test) @@ -714,7 +841,8 @@ def main(args): log.suite_start([t['name'] for t in active_tests]) for test in active_tests: - # When running in a loop, we need to create a fresh profile for each cycle + # When running in a loop, we need to create a fresh profile for + # each cycle if mochitest.localProfile: options.profilePath = mochitest.localProfile os.system("rm -Rf %s" % options.profilePath) @@ -722,34 +850,75 @@ def main(args): mochitest.localProfile = options.profilePath options.app = "am" - options.browserArgs = ["instrument", "-w", "-e", "deviceroot", deviceRoot, "-e", "class"] - options.browserArgs.append("org.mozilla.gecko.tests.%s" % test['name']) - options.browserArgs.append("org.mozilla.roboexample.test/org.mozilla.gecko.FennecInstrumentationTestRunner") + options.browserArgs = [ + "instrument", + "-w", + "-e", + "deviceroot", + deviceRoot, + "-e", + "class"] + options.browserArgs.append( + "org.mozilla.gecko.tests.%s" % + test['name']) + options.browserArgs.append( + "org.mozilla.roboexample.test/org.mozilla.gecko.FennecInstrumentationTestRunner") mochitest.nsprLogName = "nspr-%s.log" % test['name'] - # If the test is for checking the import from bookmarks then make sure there is data to import + # If the test is for checking the import from bookmarks then make + # sure there is data to import if test['name'] == "testImportFromAndroid": - # Get the OS so we can run the insert in the apropriate database and following the correct table schema + # Get the OS so we can run the insert in the apropriate + # database and following the correct table schema osInfo = dm.getInfo("os") devOS = " ".join(osInfo['os']) if ("pandaboard" in devOS): - delete = ['execsu', 'sqlite3', "/data/data/com.android.browser/databases/browser2.db \'delete from bookmarks where _id > 14;\'"] + delete = [ + 'execsu', + 'sqlite3', + "/data/data/com.android.browser/databases/browser2.db \'delete from bookmarks where _id > 14;\'"] else: - delete = ['execsu', 'sqlite3', "/data/data/com.android.browser/databases/browser.db \'delete from bookmarks where _id > 14;\'"] + delete = [ + 'execsu', + 'sqlite3', + "/data/data/com.android.browser/databases/browser.db \'delete from bookmarks where _id > 14;\'"] if (options.dm_trans == "sut"): dm._runCmds([{"cmd": " ".join(delete)}]) # Insert the bookmarks - log.info("Insert bookmarks in the default android browser database") + log.info( + "Insert bookmarks in the default android browser database") for i in range(20): - if ("pandaboard" in devOS): - cmd = ['execsu', 'sqlite3', "/data/data/com.android.browser/databases/browser2.db 'insert or replace into bookmarks(_id,title,url,folder,parent,position) values (" + str(30 + i) + ",\"Bookmark"+ str(i) + "\",\"http://www.bookmark" + str(i) + ".com\",0,1," + str(100 + i) + ");'"] - else: - cmd = ['execsu', 'sqlite3', "/data/data/com.android.browser/databases/browser.db 'insert into bookmarks(title,url,bookmark) values (\"Bookmark"+ str(i) + "\",\"http://www.bookmark" + str(i) + ".com\",1);'"] - if (options.dm_trans == "sut"): - dm._runCmds([{"cmd": " ".join(cmd)}]) + if ("pandaboard" in devOS): + cmd = [ + 'execsu', + 'sqlite3', + "/data/data/com.android.browser/databases/browser2.db 'insert or replace into bookmarks(_id,title,url,folder,parent,position) values (" + + str( + 30 + + i) + + ",\"Bookmark" + + str(i) + + "\",\"http://www.bookmark" + + str(i) + + ".com\",0,1," + + str( + 100 + + i) + + ");'"] + else: + cmd = [ + 'execsu', + 'sqlite3', + "/data/data/com.android.browser/databases/browser.db 'insert into bookmarks(title,url,bookmark) values (\"Bookmark" + + str(i) + + "\",\"http://www.bookmark" + + str(i) + + ".com\",1);'"] + if (options.dm_trans == "sut"): + dm._runCmds([{"cmd": " ".join(cmd)}]) try: screenShotDir = "/mnt/sdcard/Robotium-Screenshots" dm.removeDir(screenShotDir) @@ -761,11 +930,13 @@ def main(args): if result != 0 or log_result != 0: mochitest.printDeviceInfo(printLogcat=True) mochitest.printScreenshots(screenShotDir) - # Ensure earlier failures aren't overwritten by success on this run + # Ensure earlier failures aren't overwritten by success on this + # run if retVal is None or retVal == 0: retVal = result except: - log.error("Automation Error: Exception caught while running tests") + log.error( + "Automation Error: Exception caught while running tests") traceback.print_exc() mochitest.stopServers() try: @@ -779,9 +950,15 @@ def main(args): # Clean-up added bookmarks if test['name'] == "testImportFromAndroid": if ("pandaboard" in devOS): - cmd_del = ['execsu', 'sqlite3', "/data/data/com.android.browser/databases/browser2.db \'delete from bookmarks where _id > 14;\'"] + cmd_del = [ + 'execsu', + 'sqlite3', + "/data/data/com.android.browser/databases/browser2.db \'delete from bookmarks where _id > 14;\'"] else: - cmd_del = ['execsu', 'sqlite3', "/data/data/com.android.browser/databases/browser.db \'delete from bookmarks where _id > 14;\'"] + cmd_del = [ + 'execsu', + 'sqlite3', + "/data/data/com.android.browser/databases/browser.db \'delete from bookmarks where _id > 14;\'"] if (options.dm_trans == "sut"): dm._runCmds([{"cmd": " ".join(cmd_del)}]) if retVal is None: