本文整理汇总了Python中mozrunner.FirefoxRunner.stop方法的典型用法代码示例。如果您正苦于以下问题:Python FirefoxRunner.stop方法的具体用法?Python FirefoxRunner.stop怎么用?Python FirefoxRunner.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mozrunner.FirefoxRunner
的用法示例。
在下文中一共展示了FirefoxRunner.stop方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FirefoxBrowser
# 需要导入模块: from mozrunner import FirefoxRunner [as 别名]
# 或者: from mozrunner.FirefoxRunner import stop [as 别名]
class FirefoxBrowser(Browser):
used_ports = set()
init_timeout = 60
def __init__(self, logger, binary, prefs_root, debug_info=None,
symbols_path=None, stackwalk_binary=None, certutil_binary=None,
ca_certificate_path=None, e10s=False):
Browser.__init__(self, logger)
self.binary = binary
self.prefs_root = prefs_root
self.marionette_port = None
self.runner = None
self.debug_info = debug_info
self.profile = None
self.symbols_path = symbols_path
self.stackwalk_binary = stackwalk_binary
self.ca_certificate_path = ca_certificate_path
self.certutil_binary = certutil_binary
self.e10s = e10s
def start(self):
self.marionette_port = get_free_port(2828, exclude=self.used_ports)
self.used_ports.add(self.marionette_port)
env = os.environ.copy()
env["MOZ_DISABLE_NONLOCAL_CONNECTIONS"] = "1"
locations = ServerLocations(filename=os.path.join(here, "server-locations.txt"))
preferences = self.load_prefs()
self.profile = FirefoxProfile(locations=locations,
preferences=preferences)
self.profile.set_preferences({"marionette.defaultPrefs.enabled": True,
"marionette.defaultPrefs.port": self.marionette_port,
"dom.disable_open_during_load": False,
"network.dns.localDomains": ",".join(hostnames),
"network.proxy.type": 0,
"places.history.enabled": False})
if self.e10s:
self.profile.set_preferences({"browser.tabs.remote.autostart": True})
# Bug 1262954: winxp + e10s, disable hwaccel
if (self.e10s and platform.system() in ("Windows", "Microsoft") and
'5.1' in platform.version()):
self.profile.set_preferences({"layers.acceleration.disabled": True})
if self.ca_certificate_path is not None:
self.setup_ssl()
debug_args, cmd = browser_command(self.binary, [cmd_arg("marionette"), "about:blank"],
self.debug_info)
self.runner = FirefoxRunner(profile=self.profile,
binary=cmd[0],
cmdargs=cmd[1:],
env=env,
process_class=ProcessHandler,
process_args={"processOutputLine": [self.on_output]})
self.logger.debug("Starting Firefox")
self.runner.start(debug_args=debug_args, interactive=self.debug_info and self.debug_info.interactive)
self.logger.debug("Firefox Started")
def load_prefs(self):
prefs_path = os.path.join(self.prefs_root, "prefs_general.js")
if os.path.exists(prefs_path):
preferences = Preferences.read_prefs(prefs_path)
else:
self.logger.warning("Failed to find base prefs file in %s" % prefs_path)
preferences = []
return preferences
def stop(self):
self.logger.debug("Stopping browser")
if self.runner is not None:
try:
self.runner.stop()
except OSError:
# This can happen on Windows if the process is already dead
pass
def pid(self):
if self.runner.process_handler is None:
return None
try:
return self.runner.process_handler.pid
except AttributeError:
return None
def on_output(self, line):
"""Write a line of output from the firefox process to the log"""
self.logger.process_output(self.pid(),
line.decode("utf8", "replace"),
command=" ".join(self.runner.command))
def is_alive(self):
#.........这里部分代码省略.........
示例2: FirefoxBrowser
# 需要导入模块: from mozrunner import FirefoxRunner [as 别名]
# 或者: from mozrunner.FirefoxRunner import stop [as 别名]
#.........这里部分代码省略.........
process_args={"processOutputLine": [self.on_output]})
self.logger.debug("Starting Firefox")
self.runner.start(debug_args=debug_args, interactive=self.debug_info and self.debug_info.interactive)
self.logger.debug("Firefox Started")
def load_prefs(self):
prefs = Preferences()
pref_paths = []
prefs_general = os.path.join(self.prefs_root, 'prefs_general.js')
if os.path.isfile(prefs_general):
# Old preference file used in Firefox 60 and earlier (remove when no longer supported)
pref_paths.append(prefs_general)
profiles = os.path.join(self.prefs_root, 'profiles.json')
if os.path.isfile(profiles):
with open(profiles, 'r') as fh:
for name in json.load(fh)['web-platform-tests']:
pref_paths.append(os.path.join(self.prefs_root, name, 'user.js'))
for path in pref_paths:
if os.path.exists(path):
prefs.add(Preferences.read_prefs(path))
else:
self.logger.warning("Failed to find base prefs file in %s" % path)
# Add any custom preferences
prefs.add(self.extra_prefs, cast=True)
return prefs()
def stop(self, force=False):
if self.runner is not None and self.runner.is_running():
try:
# For Firefox we assume that stopping the runner prompts the
# browser to shut down. This allows the leak log to be written
for clean, stop_f in [(True, lambda: self.runner.wait(self.shutdown_timeout)),
(False, lambda: self.runner.stop(signal.SIGTERM)),
(False, lambda: self.runner.stop(signal.SIGKILL))]:
if not force or not clean:
retcode = stop_f()
if retcode is not None:
self.logger.info("Browser exited with return code %s" % retcode)
break
except OSError:
# This can happen on Windows if the process is already dead
pass
self.logger.debug("stopped")
def process_leaks(self):
self.logger.debug("PROCESS LEAKS %s" % self.leak_report_file)
if self.leak_report_file is None:
return
mozleak.process_leak_log(
self.leak_report_file,
leak_thresholds={
"default": 0,
"tab": 10000, # See dependencies of bug 1051230.
# GMP rarely gets a log, but when it does, it leaks a little.
"geckomediaplugin": 20000,
},
ignore_missing_leaks=["geckomediaplugin"],
log=self.logger,
stack_fixer=self.stack_fixer
示例3: FirefoxBrowser
# 需要导入模块: from mozrunner import FirefoxRunner [as 别名]
# 或者: from mozrunner.FirefoxRunner import stop [as 别名]
class FirefoxBrowser(Browser):
used_ports = set()
def __init__(self, logger, binary, prefs_root, debug_args=None, interactive=None,
symbols_path=None, stackwalk_binary=None):
Browser.__init__(self, logger)
self.binary = binary
self.prefs_root = prefs_root
self.marionette_port = None
self.used_ports.add(self.marionette_port)
self.runner = None
self.debug_args = debug_args
self.interactive = interactive
self.profile = None
self.symbols_path = symbols_path
self.stackwalk_binary = stackwalk_binary
def start(self):
self.marionette_port = get_free_port(2828, exclude=self.used_ports)
env = os.environ.copy()
env["MOZ_CRASHREPORTER"] = "1"
env["MOZ_CRASHREPORTER_SHUTDOWN"] = "1"
env["MOZ_CRASHREPORTER_NO_REPORT"] = "1"
env["MOZ_DISABLE_NONLOCAL_CONNECTIONS"] = "1"
locations = ServerLocations(filename=os.path.join(here, "server-locations.txt"))
preferences = self.load_prefs()
ports = {"http": "8000",
"https": "8443",
"ws": "8888"}
self.profile = FirefoxProfile(locations=locations,
proxy=ports,
preferences=preferences)
self.profile.set_preferences({"marionette.defaultPrefs.enabled": True,
"marionette.defaultPrefs.port": self.marionette_port,
"dom.disable_open_during_load": False})
self.runner = FirefoxRunner(profile=self.profile,
binary=self.binary,
cmdargs=[cmd_arg("marionette"), "about:blank"],
env=env,
process_class=ProcessHandler,
process_args={"processOutputLine": [self.on_output]})
self.logger.debug("Starting Firefox")
self.runner.start(debug_args=self.debug_args, interactive=self.interactive)
self.logger.debug("Firefox Started")
def load_prefs(self):
prefs_path = os.path.join(self.prefs_root, "prefs_general.js")
if os.path.exists(prefs_path):
preferences = Preferences.read_prefs(prefs_path)
else:
self.logger.warning("Failed to find base prefs file in %s" % prefs_path)
preferences = []
return preferences
def stop(self):
self.logger.debug("Stopping browser")
if self.runner is not None:
try:
self.runner.stop()
except OSError:
# This can happen on Windows if the process is already dead
pass
def pid(self):
if self.runner.process_handler is None:
return None
try:
return self.runner.process_handler.pid
except AttributeError:
return None
def on_output(self, line):
"""Write a line of output from the firefox process to the log"""
self.logger.process_output(self.pid(),
line.decode("utf8", "replace"),
command=" ".join(self.runner.command))
def is_alive(self):
if self.runner:
return self.runner.is_running()
return False
def cleanup(self):
self.stop()
def executor_browser(self):
assert self.marionette_port is not None
return ExecutorBrowser, {"marionette_port": self.marionette_port}
def log_crash(self, process, test):
dump_dir = os.path.join(self.profile.profile, "minidumps")
#.........这里部分代码省略.........
示例4: B2GDesktopReftest
# 需要导入模块: from mozrunner import FirefoxRunner [as 别名]
# 或者: from mozrunner.FirefoxRunner import stop [as 别名]
#.........这里部分代码省略.........
self.runner = FirefoxRunner(profile=self.profile,
binary=cmd,
cmdargs=args,
env=env,
process_class=ProcessHandler,
process_args=kp_kwargs,
symbols_path=options.symbolsPath)
status = 0
try:
self.runner.start(outputTimeout=self.timeout)
log.info("%s | Application pid: %d",
os.path.basename(__file__),
self.runner.process_handler.pid)
# kick starts the reftest harness
self.run_marionette_script()
status = self.runner.wait()
finally:
self.runner.check_for_crashes(test_name=self.last_test)
self.runner.cleanup()
if status > 0:
log.testFail("%s | application terminated with exit code %s",
self.last_test, status)
elif status < 0:
log.info("%s | application killed with signal %s",
self.last_test, -status)
log.info("%s | Running tests: end.", os.path.basename(__file__))
return status
def create_profile(self, options, manifests, profile_to_clone=None):
profile = RefTest.createReftestProfile(self, options, manifests,
profile_to_clone=profile_to_clone)
prefs = {}
# Turn off the locale picker screen
prefs["browser.firstrun.show.localepicker"] = False
if not self.build_type == "mulet":
# FIXME: With Mulet we can't set this values since Gaia won't launch
prefs["b2g.system_startup_url"] = \
"app://test-container.gaiamobile.org/index.html"
prefs["b2g.system_manifest_url"] = \
"app://test-container.gaiamobile.org/manifest.webapp"
# Make sure we disable system updates
prefs["app.update.enabled"] = False
prefs["app.update.url"] = ""
prefs["app.update.url.override"] = ""
# Disable webapp updates
prefs["webapps.update.enabled"] = False
# Disable tiles also
prefs["browser.newtabpage.directory.source"] = ""
prefs["browser.newtabpage.directory.ping"] = ""
prefs["dom.ipc.tabs.disabled"] = False
prefs["dom.mozBrowserFramesEnabled"] = True
prefs["font.size.inflation.emPerLine"] = 0
prefs["font.size.inflation.minTwips"] = 0
prefs["network.dns.localDomains"] = "app://test-container.gaiamobile.org"
prefs["reftest.browser.iframe.enabled"] = False
prefs["reftest.remote"] = False
# Set a future policy version to avoid the telemetry prompt.
prefs["toolkit.telemetry.prompted"] = 999
prefs["toolkit.telemetry.notifiedOptOut"] = 999
# Disable periodic updates of service workers
prefs["dom.serviceWorkers.periodic-updates.enabled"] = False
# Set the extra prefs.
profile.set_preferences(prefs)
return profile
def build_command_line(self, app, ignore_window_size=False,
browser_arg=None):
cmd = os.path.abspath(app)
args = ['-marionette']
if browser_arg:
args += [browser_arg]
if not ignore_window_size:
args.extend(['--screen', '800x1000'])
if self.build_type == "mulet":
args += ['-chrome', 'chrome://b2g/content/shell.html']
return cmd, args
def _on_output(self, line):
sys.stdout.write("%s\n" % line)
sys.stdout.flush()
# TODO use structured logging
if "TEST-START" in line and "|" in line:
self.last_test = line.split("|")[1].strip()
def _on_timeout(self):
msg = "%s | application timed out after %s seconds with no output"
log.testFail(msg % (self.last_test, self.timeout))
# kill process to get a stack
self.runner.stop(sig=signal.SIGABRT)
示例5: MuletReftest
# 需要导入模块: from mozrunner import FirefoxRunner [as 别名]
# 或者: from mozrunner.FirefoxRunner import stop [as 别名]
#.........这里部分代码省略.........
browser_arg=options.browser_arg)
self.runner = FirefoxRunner(profile=self.profile,
binary=cmd,
cmdargs=args,
env=env,
process_class=ProcessHandler,
process_args=kp_kwargs,
symbols_path=options.symbolsPath)
status = 0
try:
self.runner.start(outputTimeout=self.timeout)
self.log.info("%s | Application pid: %d" % (
os.path.basename(__file__),
self.runner.process_handler.pid))
# kick starts the reftest harness
self.run_marionette_script()
status = self.runner.wait()
finally:
self.runner.check_for_crashes(test_name=self.last_test)
self.runner.cleanup()
if status > 0:
self.log.testFail("%s | application terminated with exit code %s" % (
self.last_test, status))
elif status < 0:
self.log.info("%s | application killed with signal %s" % (
self.last_test, -status))
self.log.info("%s | Running tests: end." % os.path.basename(__file__))
return status
def create_profile(self, options, manifests, profile_to_clone=None):
profile = RefTest.createReftestProfile(self, options, manifests,
profile_to_clone=profile_to_clone)
prefs = {}
# Turn off the locale picker screen
prefs["browser.firstrun.show.localepicker"] = False
if not self.build_type == "mulet":
# FIXME: With Mulet we can't set this values since Gaia won't launch
prefs["b2g.system_startup_url"] = \
"app://test-container.gaiamobile.org/index.html"
prefs["b2g.system_manifest_url"] = \
"app://test-container.gaiamobile.org/manifest.webapp"
# Make sure we disable system updates
prefs["app.update.enabled"] = False
prefs["app.update.url"] = ""
# Disable webapp updates
prefs["webapps.update.enabled"] = False
# Disable tiles also
prefs["browser.newtabpage.directory.source"] = ""
prefs["browser.newtabpage.directory.ping"] = ""
prefs["dom.ipc.tabs.disabled"] = False
prefs["dom.mozBrowserFramesEnabled"] = True
prefs["font.size.inflation.emPerLine"] = 0
prefs["font.size.inflation.minTwips"] = 0
prefs["network.dns.localDomains"] = "app://test-container.gaiamobile.org"
prefs["reftest.browser.iframe.enabled"] = False
prefs["reftest.remote"] = False
# Set the extra prefs.
profile.set_preferences(prefs)
return profile
def build_command_line(self, app, ignore_window_size=False,
browser_arg=None):
cmd = os.path.abspath(app)
args = ['-marionette']
if browser_arg:
args += [browser_arg]
if not ignore_window_size:
args.extend(['--screen', '800x1000'])
if self.build_type == "mulet":
args += ['-chrome', 'chrome://b2g/content/shell.html']
return cmd, args
def _on_timeout(self):
msg = "%s | application timed out after %s seconds with no output"
self.log.testFail(msg % (self.last_test, self.timeout))
self.log.error("Force-terminating active process(es).");
# kill process to get a stack
self.runner.stop(sig=signal.SIGABRT)
def _unlockScreen(self):
self.marionette.set_context(self.marionette.CONTEXT_CONTENT)
self.marionette.import_script(os.path.abspath(
os.path.join(__file__, os.path.pardir, "gaia_lock_screen.js")))
self.marionette.switch_to_frame()
self.marionette.execute_async_script('GaiaLockScreen.unlock()')
def _wait_for_homescreen(self, timeout):
self.log.info("Waiting for home screen to load")
Wait(self.marionette, timeout).until(expected.element_present(
By.CSS_SELECTOR, '#homescreen[loading-state=false]'))
示例6: B2GDesktopReftest
# 需要导入模块: from mozrunner import FirefoxRunner [as 别名]
# 或者: from mozrunner.FirefoxRunner import stop [as 别名]
#.........这里部分代码省略.........
reftestlist = self.getManifestPath(test_path)
if not reftestlist.startswith('file://'):
reftestlist = 'file://%s' % reftestlist
self.profile = self.create_profile(options, reftestlist,
profile_to_clone=options.profile)
env = self.buildBrowserEnv(options, self.profile.profile)
kp_kwargs = { 'processOutputLine': [self._on_output],
'onTimeout': [self._on_timeout],
'kill_on_timeout': False }
if not options.debugger:
if not options.timeout:
if mozinfo.info['debug']:
options.timeout = 420
else:
options.timeout = 300
self.timeout = options.timeout + 30.0
log.info("%s | Running tests: start.", os.path.basename(__file__))
cmd, args = self.build_command_line(options.app,
ignore_window_size=options.ignoreWindowSize)
self.runner = FirefoxRunner(profile=self.profile,
binary=cmd,
cmdargs=args,
env=env,
process_class=ProcessHandler,
symbols_path=options.symbolsPath,
kp_kwargs=kp_kwargs)
status = 0
try:
self.runner.start(outputTimeout=self.timeout)
log.info("%s | Application pid: %d",
os.path.basename(__file__),
self.runner.process_handler.pid)
# kick starts the reftest harness
self.run_marionette_script()
status = self.runner.wait()
finally:
self.runner.check_for_crashes(test_name=self.last_test)
self.runner.cleanup()
if status > 0:
log.testFail("%s | application terminated with exit code %s",
self.last_test, status)
elif status < 0:
log.info("%s | application killed with signal %s",
self.last_test, -status)
log.info("%s | Running tests: end.", os.path.basename(__file__))
return status
def create_profile(self, options, reftestlist, profile_to_clone=None):
profile = RefTest.createReftestProfile(self, options, reftestlist,
profile_to_clone=profile_to_clone)
prefs = {}
# Turn off the locale picker screen
prefs["browser.firstrun.show.localepicker"] = False
prefs["browser.homescreenURL"] = "app://test-container.gaiamobile.org/index.html"
prefs["browser.manifestURL"] = "app://test-container.gaiamobile.org/manifest.webapp"
prefs["browser.tabs.remote"] = False
prefs["dom.ipc.tabs.disabled"] = False
prefs["dom.mozBrowserFramesEnabled"] = True
prefs["font.size.inflation.emPerLine"] = 0
prefs["font.size.inflation.minTwips"] = 0
prefs["network.dns.localDomains"] = "app://test-container.gaiamobile.org"
prefs["reftest.browser.iframe.enabled"] = False
prefs["reftest.remote"] = False
prefs["reftest.uri"] = "%s" % reftestlist
# Set a future policy version to avoid the telemetry prompt.
prefs["toolkit.telemetry.prompted"] = 999
prefs["toolkit.telemetry.notifiedOptOut"] = 999
# Set the extra prefs.
profile.set_preferences(prefs)
return profile
def build_command_line(self, app, ignore_window_size=False):
cmd = os.path.abspath(app)
args = ['-marionette']
if not ignore_window_size:
args.extend(['--screen', '800x1000'])
return cmd, args
def _on_output(self, line):
print(line)
# TODO use structured logging
if "TEST-START" in line and "|" in line:
self.last_test = line.split("|")[1].strip()
def _on_timeout(self):
msg = "%s | application timed out after %s seconds with no output"
log.testFail(msg % (self.last_test, self.timeout))
# kill process to get a stack
self.runner.stop(sig=signal.SIGABRT)
示例7: sleep
# 需要导入模块: from mozrunner import FirefoxRunner [as 别名]
# 或者: from mozrunner.FirefoxRunner import stop [as 别名]
# Give last two lines of file a chance to write and send log file to fb_logs
sleep(1)
filename = logfile.name
logfile.close()
# Send log file to couchdb
self.log.info("Sending log file to couchdb at '" + self.couchURI + "'")
try:
fb_logs.main(["--log", filename, "--database", self.databasename, "--couch", self.couchURI,
"--changeset", utils.get_changeset(self.appdir), "--section", self.section])
except Exception:
self.log.error("Log file not sent to couchdb at server: '" + self.couchURI + "' and database: '" + self.databasename)
self.log.error(traceback.format_exc())
# Cleanup
mozRunner.stop()
self.log.debug("Exiting - Status successful")
self.cleanup()
# Called from the command line
def cli(argv=sys.argv[1:]):
parser = OptionParser("usage: %prog [options]")
parser.add_option("--appname", dest="binary",
help="Firefox binary path")
parser.add_option("--profile-path", dest="profile",
help="The profile to use when running Firefox")
parser.add_option("-s", "--serverpath", dest="serverpath",
help="The http server containing the Firebug tests")
示例8: FirefoxBrowser
# 需要导入模块: from mozrunner import FirefoxRunner [as 别名]
# 或者: from mozrunner.FirefoxRunner import stop [as 别名]
class FirefoxBrowser(Browser):
used_ports = set()
def __init__(self, logger, binary, prefs_root, debug_args=None, interactive=None,
symbols_path=None, stackwalk_binary=None, certutil_binary=None,
ca_certificate_path=None):
Browser.__init__(self, logger)
self.binary = binary
self.prefs_root = prefs_root
self.marionette_port = None
self.used_ports.add(self.marionette_port)
self.runner = None
self.debug_args = debug_args
self.interactive = interactive
self.profile = None
self.symbols_path = symbols_path
self.stackwalk_binary = stackwalk_binary
self.ca_certificate_path = ca_certificate_path
self.certutil_binary = certutil_binary
def start(self):
self.marionette_port = get_free_port(2828, exclude=self.used_ports)
env = os.environ.copy()
env["MOZ_CRASHREPORTER"] = "1"
env["MOZ_CRASHREPORTER_SHUTDOWN"] = "1"
env["MOZ_CRASHREPORTER_NO_REPORT"] = "1"
env["MOZ_DISABLE_NONLOCAL_CONNECTIONS"] = "1"
locations = ServerLocations(filename=os.path.join(here, "server-locations.txt"))
preferences = self.load_prefs()
ports = {"http": "8000",
"https": "8443",
"ws": "8888"}
self.profile = FirefoxProfile(locations=locations,
proxy=ports,
preferences=preferences)
self.profile.set_preferences({"marionette.defaultPrefs.enabled": True,
"marionette.defaultPrefs.port": self.marionette_port,
"dom.disable_open_during_load": False})
if self.ca_certificate_path is not None:
self.setup_ssl()
self.runner = FirefoxRunner(profile=self.profile,
binary=self.binary,
cmdargs=[cmd_arg("marionette"), "about:blank"],
env=env,
process_class=ProcessHandler,
process_args={"processOutputLine": [self.on_output]})
self.logger.debug("Starting Firefox")
self.runner.start(debug_args=self.debug_args, interactive=self.interactive)
self.logger.debug("Firefox Started")
def load_prefs(self):
prefs_path = os.path.join(self.prefs_root, "prefs_general.js")
if os.path.exists(prefs_path):
preferences = Preferences.read_prefs(prefs_path)
else:
self.logger.warning("Failed to find base prefs file in %s" % prefs_path)
preferences = []
return preferences
def stop(self):
self.logger.debug("Stopping browser")
if self.runner is not None:
try:
self.runner.stop()
except OSError:
# This can happen on Windows if the process is already dead
pass
def pid(self):
if self.runner.process_handler is None:
return None
try:
return self.runner.process_handler.pid
except AttributeError:
return None
def on_output(self, line):
"""Write a line of output from the firefox process to the log"""
self.logger.process_output(self.pid(),
line.decode("utf8", "replace"),
command=" ".join(self.runner.command))
def is_alive(self):
if self.runner:
return self.runner.is_running()
return False
def cleanup(self):
self.stop()
#.........这里部分代码省略.........
示例9: FirefoxBrowser
# 需要导入模块: from mozrunner import FirefoxRunner [as 别名]
# 或者: from mozrunner.FirefoxRunner import stop [as 别名]
#.........这里部分代码省略.........
prefs = Preferences()
pref_paths = []
profiles = os.path.join(self.prefs_root, 'profiles.json')
if os.path.isfile(profiles):
with open(profiles, 'r') as fh:
for name in json.load(fh)['web-platform-tests']:
if self.browser_channel in (None, 'nightly'):
pref_paths.append(os.path.join(self.prefs_root, name, 'user.js'))
elif name != 'unittest-features':
pref_paths.append(os.path.join(self.prefs_root, name, 'user.js'))
else:
# Old preference files used before the creation of profiles.json (remove when no longer supported)
legacy_pref_paths = (
os.path.join(self.prefs_root, 'prefs_general.js'), # Used in Firefox 60 and below
os.path.join(self.prefs_root, 'common', 'user.js'), # Used in Firefox 61
)
for path in legacy_pref_paths:
if os.path.isfile(path):
pref_paths.append(path)
for path in pref_paths:
if os.path.exists(path):
prefs.add(Preferences.read_prefs(path))
else:
self.logger.warning("Failed to find base prefs file in %s" % path)
# Add any custom preferences
prefs.add(self.extra_prefs, cast=True)
return prefs()
def stop(self, force=False):
if self.runner is not None and self.runner.is_running():
try:
# For Firefox we assume that stopping the runner prompts the
# browser to shut down. This allows the leak log to be written
for clean, stop_f in [(True, lambda: self.runner.wait(self.shutdown_timeout)),
(False, lambda: self.runner.stop(signal.SIGTERM)),
(False, lambda: self.runner.stop(signal.SIGKILL))]:
if not force or not clean:
retcode = stop_f()
if retcode is not None:
self.logger.info("Browser exited with return code %s" % retcode)
break
except OSError:
# This can happen on Windows if the process is already dead
pass
self.process_leaks()
self.logger.debug("stopped")
def process_leaks(self):
self.logger.info("PROCESS LEAKS %s" % self.leak_report_file)
if self.lsan_handler:
self.lsan_handler.process()
if self.leak_report_file is not None:
mozleak.process_leak_log(
self.leak_report_file,
leak_thresholds=self.mozleak_thresholds,
ignore_missing_leaks=["gmplugin"],
log=self.logger,
stack_fixer=self.stack_fixer,
scope=self.group_metadata.get("scope"),
allowed=self.mozleak_allowed
)
示例10: TestRunnerManager
# 需要导入模块: from mozrunner import FirefoxRunner [as 别名]
# 或者: from mozrunner.FirefoxRunner import stop [as 别名]
class TestRunnerManager(threading.Thread):
"""Thread that owns a single TestRunner process and any processes required
by the TestRunner (e.g. the Firefox binary)"""
init_lock = threading.Lock()
def __init__(self, server_url, firefox_binary, run_info, tests_queue,
stop_flag, runner_cls=TestharnessTestRunner,
marionette_port=None, process_cls=FirefoxProcess):
self.http_server_url = server_url
self.firefox_binary = firefox_binary
self.tests_queue = tests_queue
self.run_info = run_info
self.stop_flag = stop_flag
self.command_pipe = None
self.firefox_runner = None
self.test_runner_proc = None
self.runner_cls = runner_cls
self.marionette_port = marionette_port
self.process_cls = process_cls
threading.Thread.__init__(self)
#This is started in the actual new thread
self.logger = None
#This may not really be what we want
self.daemon = True
self.setup_fail_count = 0
self.max_setup_fails = 5
self.init_timer = None
def run(self):
self.logger = structuredlog.getOutputLogger("WPT")
self.init()
while True:
commands = {"test_ended":self.test_ended,
"setup_succeeded": self.setup_succeeded,
"setup_failed": self.setup_failed}
has_data = self.command_pipe.poll(1)
if has_data:
command, data = self.command_pipe.recv()
if commands[command](*data) is Stop:
break
else:
if self.stop_flag.is_set():
self.stop_runner(graceful=True)
break
elif not self.test_runner_proc.is_alive():
#This happens when we run out of tests;
#We ask the runner to stop, it shuts itself
#down and then we end up here
#An alternate implementation strategy would be to have the
#runner signal that it is done just before it terminates
self.firefox_runner.stop()
break
def init(self):
#It seems that this lock is helpful to prevent some race that otherwise
#sometimes stops the spawned processes initalising correctly, and
#leaves this thread hung
with self.init_lock:
def init_failed():
self.logger.error("Init failed")
self.setup_failed()
#TODO: make this timeout configurable
self.init_timer = threading.Timer(30, self.setup_failed)
self.init_timer.start()
self.command_pipe, remote_end = Pipe()
self.start_firefox()
self.start_test_runner(remote_end)
def start_firefox(self):
env = os.environ.copy()
env['MOZ_CRASHREPORTER_NO_REPORT'] = '1'
profile = Profile()
profile.set_preferences({"marionette.defaultPrefs.enabled": True,
"marionette.defaultPrefs.port": self.marionette_port,
"dom.disable_open_during_load": False,
"dom.max_script_run_time": 0})
self.firefox_runner = FirefoxRunner(profile,
self.firefox_binary,
cmdargs=["--marionette"],
env=env,
kp_kwargs = {"processOutputLine":[self.on_output]},
process_class=self.process_cls)
self.logger.debug("Starting Firefox")
self.firefox_runner.start()
self.logger.debug("Firefox Started")
def start_test_runner(self, remote_connection):
self.test_runner_proc = Process(target=start_runner,
args=(self.runner_cls,
self.http_server_url,
self.marionette_port,
remote_connection))
self.logger.debug("Starting test runner")
self.test_runner_proc.start()
#.........这里部分代码省略.........
示例11: FirefoxThread
# 需要导入模块: from mozrunner import FirefoxRunner [as 别名]
# 或者: from mozrunner.FirefoxRunner import stop [as 别名]
class FirefoxThread(Thread):
def __init__(self, binary, marionette_port = 2828):
Thread.__init__(self)
self.binary = binary
self.marionette_port = marionette_port
self.logger = FirefoxThreadLogger(None)
self._firefoxRunningEvent = Event()
def run(self):
'''
Starts Firefox thread with Marionette turned on.
'''
self.profile = FirefoxProfile()
self.profile.set_preferences({"marionette.defaultPrefs.enabled" : True,
"marionette.defaultPrefs.port": 2828,
"browser.startup.page": 0,
"browser.startup.homepage": "about:blank",
})
self.runner = FirefoxRunner(profile = self.profile,
binary = self.binary,
kp_kwargs = {'processOutputLine' : [self.logger]})
self.runner.start()
self._firefoxRunningEvent.set()
self.runner.wait()
def stop(self):
'''
Stops Firefox/Nightly. To be called by external thread.
'''
self.runner.stop()
def getPID(self):
'''
This is called by external threads, and blocks until PID is available in FirefoxRunner,
which is shortly after start() has been called.
'''
self._firefoxRunningEvent.wait()
return self.runner.process_handler.proc.pid
def waitForMarionettePortOpenReady(self, timeout):
'''
This method can be run by an external thread. Returns True when the port is open, or False on timeout.
It's active waiting with 1 sec heartbeat, if you know better solution please mail me.
Originally taken from:
https://github.com/mozilla/marionette_client/blob/master/marionette/emulator.py#L246
'''
starttime = datetime.datetime.now()
while datetime.datetime.now() - starttime < datetime.timedelta(seconds=timeout):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', self.marionette_port))
data = sock.recv(16)
sock.close()
if '"from"' in data:
return True
except:
#import traceback
#print traceback.format_exc()
pass
time.sleep(1)
print ''
return False