当前位置: 首页>>代码示例>>Python>>正文


Python Marionette.delete_session方法代码示例

本文整理汇总了Python中marionette.Marionette.delete_session方法的典型用法代码示例。如果您正苦于以下问题:Python Marionette.delete_session方法的具体用法?Python Marionette.delete_session怎么用?Python Marionette.delete_session使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在marionette.Marionette的用法示例。


在下文中一共展示了Marionette.delete_session方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
def main(options):
    print "Setting up CertTest app to device"
    dm = None
    if options.adb_path:
        dm = mozdevice.DeviceManagerADB(adbPath=options.adb_path)
    else:
        dm = mozdevice.DeviceManagerADB()
    if dm.dirExists("/data/local/webapps/certtest-app"):
        print "CertTest app is already installed"
        return
    dm.pushFile("certtest_app.zip", "/data/local/certtest_app.zip")
    # forward the marionette port
    print "Forwarding marionette port"
    ret = dm.forward("tcp:2828", "tcp:2828")
    if ret != 0:
        #TODO: right thing here is to keep trying local ports and pass that value in our config
        raise Exception("Can't use localhost:2828 for port forwarding. Is something else using port 2828?")
    # install the app
    print "installing the app"
    f = open("app_install.js", "r")
    script = f.read()
    f.close()
    m = Marionette()
    m.start_session()
    m.set_context("chrome")
    m.set_script_timeout(5000)
    m.execute_async_script(script)
    m.delete_session()
开发者ID:andreastt,项目名称:certtest,代码行数:30,代码来源:device_setup.py

示例2: run_marionette

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
 def run_marionette(self, dir):
     self.logger.info("Starting test run")
     # Start up marionette
     m = Marionette(emulator=True, homedir=dir)
     assert m.start_session()
     for test in self.testlist:
         run_test(test, m)
     m.delete_session()
开发者ID:ctalbert,项目名称:marionette_client,代码行数:10,代码来源:automator.py

示例3: uninstall_app

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
def uninstall_app(app_name, adb_path="adb", script_timeout=5000, marionette=None):
    """
    Uninstalls the given app.

    NOTE: if a marionette session is passed, this function switches to the top-most frame.
    """
    dm = mozdevice.DeviceManagerADB(adbPath=adb_path)
    installed_app_name = app_name.lower()
    installed_app_name = installed_app_name.replace(" ", "-")
    if dm.forward("tcp:2828", "tcp:2828") != 0:
        raise Exception("Can't use localhost:2828 for port forwarding." \
                    "Is something else using port 2828?")

    if not marionette:
        m = Marionette()
        m.start_session()
    else: 
        m = marionette
        m.switch_to_frame()
    uninstall_app = """
    var uninstallWithName = function(name) {
        let apps = window.wrappedJSObject.applications || window.wrappedJSObject.Applications;
        let installedApps = apps.installedApps;
        for (let manifestURL in installedApps) {
          let app = installedApps[manifestURL];
          let origin = null;
          let entryPoints = app.manifest.entry_points;
          if (entryPoints) {
            for (let ep in entryPoints) {
              let currentEntryPoint = entryPoints[ep];
              let appName = currentEntryPoint.name;
              if (name == appName.toLowerCase()) {
                window.wrappedJSObject.navigator.mozApps.mgmt.uninstall(app);
                return true;
              }
            }
          } else {
            let appName = app.manifest.name;
            if (name == appName.toLowerCase()) {
              window.wrappedJSObject.navigator.mozApps.mgmt.uninstall(app);
              return true;
            }
          }
        }
        return false;
      };
    return uninstallWithName("%s");
    """
    m.set_script_timeout(script_timeout)
    m.execute_script(uninstall_app % app_name.lower())
    if not marionette:
        m.delete_session()
开发者ID:cmitchusa,项目名称:fxos-appgen,代码行数:54,代码来源:generator.py

示例4: dual_driving

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
def dual_driving():
	mm = Marionette(host='localhost', port=2829)
	mm.start_session()
	md = Marionette(host='localhost', port=2828)
	md.start_session()
	md.set_search_timeout(1000) # especially required for webcompat.com JS-driven loading
	ignored_bugs = []
	buglist = []
	for line in open(ignore_file, 'r'):
		if line[0] == '#':
			continue
		ignored_bugs.append(line.strip())
	if start_url:
		print 'Starting from bug search %s' % start_url
		md.navigate(start_url)
		buglist = extract_buglist(md)
	else:
		buglist = extract_buglist_from_file(filename)
	i = 1
	for item in buglist:
		if len(item) <= 1:
			print 'Warning: we expect data format ID    Summary    URL, something is missing'
			continue
				
		if '://' not in item[0]: # assuming this is Bugzilla data from a tab-separated file - in other words a plain bug number
			md.navigate('https://bugzilla.mozilla.org/show_bug.cgi?id=%s' % item[0])
		else: # we've got a bug tracker URL (right?)
			md.navigate(item[0])
		
		if len(item) == 2: # URL is not in the data - let's load the bug first and try to get it from there
			url = get_url_from_bugpage(md)
		else:	
			url = item[2]
		if not url:
			i+=1
			continue
		if i<start_at or url.strip() == '':
			i+=1
			continue
		if '://' not in url:
		    url = 'http://%s' % url
		url = url.strip().rstrip('\r\n')
		location = urlparse.urlparse(url)
		hostname = location.hostname.rstrip('\r\n')
		print str(i) + ' : ' + url
		reset_spoof(mm)
		mm.navigate(url)
		print 'READY to analyze %s, \n%s' % (item[0], item[1])
		options_menu(mm, url, md)
	mm.delete_session()
	md.delete_session()
开发者ID:karlcow,项目名称:marionette_utils,代码行数:53,代码来源:dualdriver.py

示例5: launch_app

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
def launch_app(app_name, adb_path="adb", script_timeout=5000, marionette=None, device_serial=None):
    """
    Launches the given app
    NOTE: if a marionette session is passed, this function switches to the top-most frame.
    """
    dm = mozdevice.DeviceManagerADB(adbPath=adb_path,deviceSerial=device_serial)
    installed_app_name = app_name.lower()
    installed_app_name = installed_app_name.replace(" ", "-")
    dm.forward("tcp:2828", "tcp:2828")

    if not marionette:
        m = Marionette()
        m.start_session()
    else:
        m = marionette
        m.switch_to_frame()
    launch_app = """
    var launchWithName = function(name) {
        let apps = window.wrappedJSObject.applications || window.wrappedJSObject.Applications;
        let installedApps = apps.installedApps;
        for (let manifestURL in installedApps) {
          let app = installedApps[manifestURL];
          let origin = null;
          let entryPoints = app.manifest.entry_points;
          if (entryPoints) {
            for (let ep in entryPoints) {
              let currentEntryPoint = entryPoints[ep];
              let appName = currentEntryPoint.name;
              if (name == appName.toLowerCase()) {
                app.launch();
                return true;
              }
            }
          } else {
            let appName = app.manifest.name;
            if (name == appName.toLowerCase()) {
              app.launch();
              return true;
            }
          }
        }
        return false;
      };
    return launchWithName("%s");
    """
    m.set_script_timeout(script_timeout)
    m.execute_script(launch_app % app_name.lower())
    if not marionette:
        m.delete_session()
开发者ID:lapineige,项目名称:fxos-appgen,代码行数:51,代码来源:generator.py

示例6: install_app

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
def install_app(app_name, app_path, adb_path="adb", script_timeout=5000, marionette=None):
    """
    This installs the given application.

    NOTE: if a marionette session is passed, this function switches to
    'content' context and will be at the top-most frame.
    """
    if is_installed(app_name, adb_path=adb_path):
        raise Exception("%s is already installed" % app_name)
        sys.exit(1)

    app_zip = os.path.basename(app_path)
    dm = mozdevice.DeviceManagerADB(adbPath=adb_path)
    dm.pushFile("%s" % app_path, "/data/local/%s" % app_zip)
    # forward the marionette port
    if dm.forward("tcp:2828", "tcp:2828") != 0:
        raise Exception("Can't use localhost:2828 for port forwarding." \
                        "Is something else using port 2828?")

    # install the app
    install_js = pkg_resources.resource_filename(__name__,
                                                 os.path.sep.join([
                                                   'app_install.js']))
    with open(install_js, "r") as f:
        script = f.read()
    installed_app_name = app_name.lower().replace(" ", "-")
    script = script.replace("YOURAPPID", installed_app_name)
    script = script.replace("YOURAPPZIP", app_zip)

    if not marionette:
        m = Marionette()
        m.start_session()
    else: 
        m = marionette
        m.switch_to_frame()
    m.set_context("chrome")
    m.set_script_timeout(script_timeout)
    m.execute_async_script(script)
    if not marionette:
        m.delete_session()
    else:
        m.set_context("content")
开发者ID:cmitchusa,项目名称:fxos-appgen,代码行数:44,代码来源:generator.py

示例7: install_app

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
def install_app(app_name, app_path, adb_path=None):
    dm = None
    if adb_path:
        dm = mozdevice.DeviceManagerADB(adbPath=adb_path)
    else:
        dm = mozdevice.DeviceManagerADB()

    #TODO: replace with app name
    installed_app_name = app_name.lower()
    installed_app_name = installed_app_name.replace(" ", "-")
    if dm.dirExists("/data/local/webapps/%s" % installed_app_name):
        raise Exception("%s is already installed" % app_name)
        sys.exit(1)
    app_zip = os.path.basename(app_path)
    dm.pushFile("%s" % app_path, "/data/local/%s" % app_zip)
    # forward the marionette port
    ret = dm.forward("tcp:2828", "tcp:2828")
    if ret != 0:
        raise Exception("Can't use localhost:2828 for port forwarding." \
                        "Is something else using port 2828?")

    # install the app
    install_js = pkg_resources.resource_filename(__name__,
                                                 os.path.sep.join([
                                                   'app_install.js']))
    f = open(install_js, "r")
    script = f.read()
    f.close()
    script = script.replace("YOURAPPID", installed_app_name)
    script = script.replace("YOURAPPZIP", app_zip)
    m = Marionette()
    m.start_session()
    m.set_context("chrome")
    m.set_script_timeout(5000)
    m.execute_async_script(script)
    m.delete_session()
开发者ID:soapdog,项目名称:fxos-appgen,代码行数:38,代码来源:generator.py

示例8: GCli

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]

#.........这里部分代码省略.........
            'unlock': {
                'function': self.unlock,
                'help': 'Unlock screen'},
            'volume': {
                'function': self.volume,
                'args': [
                    {'name': 'direction',
                     'choices': ['down', 'up'],
                     'help': 'Direction to change the volume'}],
                'help': 'Change the volume'},
            'wake': {
                'function': self.wake,
                'help': 'Wake from sleep mode'}}

        self.parser = argparse.ArgumentParser()
        self.add_options(self.parser)
        self.add_commands(self.parser)

    def run(self, args=sys.argv[1:]):
        args = self.parser.parse_args()

        host, port = args.address.split(':')
        self.marionette = Marionette(host=host, port=int(port))
        self.marionette.start_session()

        self.apps = gaiatest.GaiaApps(self.marionette)
        self.data_layer = gaiatest.GaiaData(self.marionette)
        self.lock_screen = gaiatest.LockScreen(self.marionette)

        ret = args.func(args)
        if ret is None:
            ret = 0

        self.marionette.delete_session()

        sys.exit(ret)

    def add_options(self, parser):
        parser.add_argument(
            '--address',
            default='localhost:2828',
            help='Address (host:port) of running Gecko instance to connect to '
                 '(default: %(default)s)')

    def add_commands(self, parser):
        subparsers = parser.add_subparsers(
            title='Commands', metavar='<command>')
        for (name, props) in sorted(self.commands.iteritems()):
            subparser = subparsers.add_parser(name, help=props['help'])
            if props.get('args'):
                for arg in props['args']:
                    kwargs = {k: v for k, v in arg.items() if k is not 'name'}
                    subparser.add_argument(arg['name'], **kwargs)
            subparser.set_defaults(func=props['function'])

    def connect_to_wifi(self, args):
        network = {
            'ssid': args.ssid,
            'keyManagement': args.security or 'NONE'}
        if args.security == 'WEP':
            network['wep'] = args.password
        elif args.security == 'WPA-PSK':
            network['psk'] = args.password
        self.data_layer.connect_to_wifi(network)

    def disable_wifi(self, args):
开发者ID:Mozilla-TWQA,项目名称:gaia,代码行数:70,代码来源:gcli.py

示例9: B2GMixin

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
class B2GMixin(object):
    profileDir = None
    userJS = "/data/local/user.js"
    marionette = None

    def __init__(self, host=None, marionetteHost=None, marionettePort=2828,
                 **kwargs):

        # (allowing marionneteHost to be specified seems a bit
        # counter-intuitive since we normally get it below from the ip
        # address, however we currently need it to be able to connect
        # via adb port forwarding and localhost)
        if marionetteHost:
            self.marionetteHost = marionetteHost
        elif host:
            self.marionetteHost = host
        self.marionettePort = marionettePort

    def cleanup(self):
        if self.profileDir:
            self.restoreProfile()

    def waitForPort(self, timeout):
        """
        Wait for the marionette server to respond.
        Timeout parameter is in seconds
        """
        print "waiting for port"
        starttime = datetime.datetime.now()
        while datetime.datetime.now() - starttime < datetime.timedelta(seconds=timeout):
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                print "trying %s %s" % (self.marionettePort, self.marionetteHost)
                sock.connect((self.marionetteHost, self.marionettePort))
                data = sock.recv(16)
                sock.close()
                if '"from"' in data:
                    return True
            except socket.error:
                pass
            except Exception as e:
                raise DMError("Could not connect to marionette: %s" % e)
            time.sleep(1)
        raise DMError("Could not communicate with Marionette port")

    def setupMarionette(self):
        """
        Start a marionette session.
        If no host is given, then this will get the ip
        of the device, and set up networking if needed.
        """
        if not self.marionetteHost:
            self.setupDHCP()
            self.marionetteHost = self.getIP()
        if not self.marionette:
            self.marionette = Marionette(self.marionetteHost, self.marionettePort)
        if not self.marionette.session:
            self.waitForPort(30)
            self.marionette.start_session()

    def restartB2G(self):
        """
        Restarts the b2g process on the device
        """
        #restart b2g so we start with a clean slate
        if self.marionette and self.marionette.session:
            self.marionette.delete_session()
        self.shellCheckOutput(['stop', 'b2g'])
        # Wait for a bit to make sure B2G has completely shut down.
        tries = 10
        while "b2g" in self.shellCheckOutput(['ps', 'b2g']) and tries > 0:
            tries -= 1
            time.sleep(1)
        if tries == 0:
            raise DMError("Could not kill b2g process")
        self.shellCheckOutput(['start', 'b2g'])

    def setupProfile(self, prefs=None):
        """
        Sets up the user profile on the device,
        The 'prefs' is a string of user_prefs to add to the profile.
        If it is not set, it will default to a standard b2g testing profile.
        """
        if not prefs:
            prefs = """
user_pref("power.screen.timeout", 999999);
user_pref("devtools.debugger.force-local", false);
            """
        #remove previous user.js if there is one
        if not self.profileDir:
            self.profileDir = tempfile.mkdtemp()
        our_userJS = os.path.join(self.profileDir, "user.js")
        if os.path.exists(our_userJS):
            os.remove(our_userJS)
        #copy profile
        try:
            output = self.getFile(self.userJS, our_userJS)
        except subprocess.CalledProcessError:
            pass
        #if we successfully copied the profile, make a backup of the file
#.........这里部分代码省略.........
开发者ID:sinemetu1,项目名称:mozbase,代码行数:103,代码来源:b2gmixin.py

示例10: assert

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
    assert(m.execute_js_script(server.TEST_EXECUTE_SCRIPT))
    assert(m.execute_js_script(server.TEST_EXECUTE_SCRIPT, server.TEST_EXECUTE_SCRIPT_ARGS))
    assert(m.execute_script(server.TEST_EXECUTE_SCRIPT, server.TEST_EXECUTE_SCRIPT_ARGS))
    assert(m.execute_async_script(server.TEST_EXECUTE_SCRIPT))
    assert(m.execute_async_script(server.TEST_EXECUTE_SCRIPT, server.TEST_EXECUTE_SCRIPT_ARGS))
    assert(str(m.find_element(HTMLElement.CLASS, 'heading')) == server.TEST_FIND_ELEMENT)
    assert([str(x) for x in m.find_elements(HTMLElement.TAG, 'p')] == server.TEST_FIND_ELEMENTS)
    assert(str(m.find_element(HTMLElement.CLASS, 'heading').find_element(HTMLElement.TAG, 'h1')) == server.TEST_FIND_ELEMENT)
    assert([str(x) for x in m.find_element(HTMLElement.ID, 'div1').find_elements(HTMLElement.SELECTOR, '.main')] == \
        server.TEST_FIND_ELEMENTS)
    assert(m.find_element(HTMLElement.ID, 'id1').click())
    assert(m.find_element(HTMLElement.ID, 'id2').text() == server.TEST_GET_TEXT)
    assert(m.find_element(HTMLElement.ID, 'id3').send_keys('Mozilla Firefox'))
    assert(m.find_element(HTMLElement.ID, 'id3').value() == server.TEST_GET_VALUE)
    assert(m.find_element(HTMLElement.ID, 'id3').clear())
    assert(m.find_element(HTMLElement.ID, 'id3').selected())
    assert(m.find_element(HTMLElement.ID, 'id1').equals(m.find_element(HTMLElement.TAG, 'p')))
    assert(m.find_element(HTMLElement.ID, 'id3').enabled())
    assert(m.find_element(HTMLElement.ID, 'id3').displayed())
    assert(m.find_element(HTMLElement.ID, 'id3').get_attribute('value') == server.TEST_GET_VALUE)
    assert(m.delete_session())

    # verify a session is started automatically for us if needed
    assert(m.switch_to_frame('frame1'))
    assert(m.switch_to_frame(1))
    assert(m.switch_to_frame(m.find_element(HTMLElement.ID, 'frameid')))
    assert(m.switch_to_frame())
    assert(m.get_window() == server.TEST_CURRENT_WINDOW)
    assert(m.set_context(m.CONTEXT_CHROME))
    assert(m.delete_session())
开发者ID:Kml55,项目名称:marionette_client,代码行数:32,代码来源:test_protocol.py

示例11: GCli

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
class GCli(object):

    def __init__(self):
        self.commands = {
            'connectwifi': {
                'function': self.connect_to_wifi,
                'args': [
                    {'name': 'ssid',
                     'help': 'SSID of the network to connect to'},
                    {'name': '--security',
                     'choices': ['WPA-PSK', 'WEP'],
                     'help': 'Security model of the network'},
                    {'name': '--password',
                     'help': 'Password to access the network'}],
                'help': 'Connect to a WiFi network'},
            'disablewifi': {
                'function': self.disable_wifi,
                'help': 'Disable WiFi'},
            'enablewifi': {
                'function': self.enable_wifi,
                'help': 'Enable WiFi'},
            'forgetallwifi': {
                'function': self.forget_all_wifi_networks,
                'help': 'Forget all WiFi networks'},
            'getknownwifi': {
                'function': self.known_wifi_networks,
                'help': 'Show known WiFi networks'},
            'getsetting': {
                'function': self.get_setting,
                'args': [{
                    'name': 'name',
                    'help': 'Name of the setting to retrieve'}],
                'help': 'Show the current value of a setting'},
            'killapps': {
                'function': self.kill_all_apps,
                'help': 'Kill all running apps'},
            'launchapp': {
                'function': self.launch_app,
                'args': [
                    {'name': 'name',
                     'nargs': argparse.REMAINDER,
                     'help': 'Name of app to launch'}],
                'help': 'Launch an application'},
            'lock': {
                'function': self.lock,
                'help': 'Lock screen'},
            'setsetting': {
                'function': self.set_setting,
                'args': [
                    {'name': 'name',
                     'help': 'Name of setting to change'},
                    {'name': 'value',
                     'help': 'New value for setting'}],
                'help': 'Change the value of a setting'},
            'unlock': {
                'function': self.unlock,
                'help': 'Unlock screen'}}

        self.parser = argparse.ArgumentParser()
        self.add_options(self.parser)
        self.add_commands(self.parser)

    def run(self, args=sys.argv[1:]):
        args = self.parser.parse_args()

        host, port = args.address.split(':')
        self.marionette = Marionette(host=host, port=int(port))
        self.marionette.start_session()

        self.apps = gaiatest.GaiaApps(self.marionette)
        self.data_layer = gaiatest.GaiaData(self.marionette)
        self.lock_screen = gaiatest.LockScreen(self.marionette)

        ret = args.func(args)
        if ret is None:
            ret = 0

        self.marionette.delete_session()

        sys.exit(ret)

    def add_options(self, parser):
        parser.add_argument(
            '--address',
            default='localhost:2828',
            help='Address (host:port) of running Gecko instance to connect to '
                 '(default: %(default)s)')

    def add_commands(self, parser):
        subparsers = parser.add_subparsers(title='Commands', metavar='<command>')
        for (name, props) in sorted(self.commands.iteritems()):
            subparser = subparsers.add_parser(name, help=props['help'])
            if props.get('args'):
                for arg in props['args']:
                    kwargs = {k: v for k, v in arg.items() if k is not 'name'}
                    subparser.add_argument(arg['name'], **kwargs)
            subparser.set_defaults(func=props['function'])

    def connect_to_wifi(self, args):
        network = {
#.........这里部分代码省略.........
开发者ID:AaronMT,项目名称:gaia,代码行数:103,代码来源:gcli.py

示例12: B2GMixin

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
class B2GMixin(object):
    profileDir = None
    userJS = "/data/local/user.js"
    marionette = None

    def __init__(self, host=None, marionetteHost=None, marionettePort=2828,
                 **kwargs):

        # (allowing marionneteHost to be specified seems a bit
        # counter-intuitive since we normally get it below from the ip
        # address, however we currently need it to be able to connect
        # via adb port forwarding and localhost)
        if marionetteHost:
            self.marionetteHost = marionetteHost
        elif host:
            self.marionetteHost = host
        self.marionettePort = marionettePort

    def cleanup(self):
        """
        If a user profile was setup on the device, restore it to the original.
        """
        if self.profileDir:
            self.restoreProfile()

    def waitForPort(self, timeout):
        """Waits for the marionette server to respond, until the timeout specified.

	:param timeout: Timeout parameter in seconds.
        """
        print "waiting for port"
        starttime = datetime.datetime.now()
        while datetime.datetime.now() - starttime < datetime.timedelta(seconds=timeout):
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                print "trying %s %s" % (self.marionettePort, self.marionetteHost)
                sock.connect((self.marionetteHost, self.marionettePort))
                data = sock.recv(16)
                sock.close()
                if '"from"' in data:
                    return True
            except socket.error:
                pass
            except Exception as e:
                raise DMError("Could not connect to marionette: %s" % e)
            time.sleep(1)
        raise DMError("Could not communicate with Marionette port")

    def setupMarionette(self, scriptTimeout=60000):
        """
        Starts a marionette session.
        If no host was given at init, the ip of the device will be retrieved
        and networking will be established.
        """
        if not self.marionetteHost:
            self.setupDHCP()
            self.marionetteHost = self.getIP()
        if not self.marionette:
            self.marionette = Marionette(self.marionetteHost, self.marionettePort)
        if not self.marionette.session:
            self.waitForPort(30)
            self.marionette.start_session()

        self.marionette.set_script_timeout(scriptTimeout)

    def restartB2G(self):
        """
        Restarts the b2g process on the device.
        """
        #restart b2g so we start with a clean slate
        if self.marionette and self.marionette.session:
            self.marionette.delete_session()
        self.shellCheckOutput(['stop', 'b2g'])
        # Wait for a bit to make sure B2G has completely shut down.
        tries = 10
        while "b2g" in self.shellCheckOutput(['ps', 'b2g']) and tries > 0:
            tries -= 1
            time.sleep(1)
        if tries == 0:
            raise DMError("Could not kill b2g process")
        self.shellCheckOutput(['start', 'b2g'])

    def setupProfile(self, prefs=None):
        """Sets up the user profile on the device.

        :param prefs: String of user_prefs to add to the profile. Defaults to a standard b2g testing profile.
        """
        # currently we have no custom prefs to set (when bug 800138 is fixed,
        # we will probably want to enable marionette on an external ip by
        # default)
        if not prefs:
            prefs = ""

        #remove previous user.js if there is one
        if not self.profileDir:
            self.profileDir = tempfile.mkdtemp()
        our_userJS = os.path.join(self.profileDir, "user.js")
        mozfile.remove(our_userJS)
        #copy profile
        try:
#.........这里部分代码省略.........
开发者ID:Nicksol,项目名称:mozbase,代码行数:103,代码来源:b2gmixin.py

示例13: dual_driving

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
def dual_driving():
	try:
		print('Will connect to mobile..')
		mm = Marionette(host='localhost', port=2829)
		mm.start_session()
		if disable_ua_overrides_by_default:
			set_mozilla_pref(mm, 'general.useragent.site_specific_overrides', False)
			set_mozilla_pref(mm, 'general.useragent.updates.enabled', False)
			
		print('Will connect to desktop...')
		md = Marionette(host='localhost', port=2828)
		md.start_session()
		md.set_search_timeout(1000) # especially required for webcompat.com JS-driven loading
		ignored_bugs = []
		buglist = []
		device_map = get_device_map()

		for line in open(ignore_file, 'r'):
			if line[0] == '#':
				continue
			ignored_bugs.append(line.strip())
		if start_url:
			print 'Starting from bug search %s' % start_url
			md.navigate(start_url)
			buglist = extract_buglist(md)
		else:
			buglist = extract_buglist_from_file(filename)
		i = 1
		#print(len(buglist))
		for item in buglist:
			if len(item) <= 1:
				print 'Warning: we expect data format ID    Summary    URL, something is missing'
				continue
			if i<start_at:
				i+=1
				continue
			buglink = ''
			if '://' not in item[0]: # assuming this is Bugzilla data from a tab-separated file - in other words a plain bug number
				# TODO: will we ever process lists of webcompat.com "plain numbers"??
				buglink = 'https://bugzilla.mozilla.org/show_bug.cgi?id=%s' % item[0]
			else: # we've got a bug tracker URL (right?)
				buglink = item[0]
			# users who have bugzilla's "load next bug in search" don't need an extra navigate() call
			if buglink not in md.get_url():
				print('Item %s, Loading bug %s'%(i,item[0]))
				md.navigate(item[0])

			if len(item) == 2: # URL is not in the data - let's load the bug first and try to get it from there
				url = get_url_from_bugpage(md)
			else:
				url = item[2]
			if not url:
				i+=1
				continue
			if url.strip() == '':
				i+=1
				continue
			if '://' not in url:
			    url = 'http://%s' % url
			url = url.strip().rstrip('\r\n')
			location = urlparse.urlparse(url)
			hostname = location.hostname.rstrip('\r\n')
			print str(i) + ' : ' + url
			reset_spoof(mm)
			try:
				mm.navigate(url)
				try_to_launch_url_in_android(device_map, url)
				print 'READY to analyze %s, \n%s' % (item[0], item[1])
			except:
				print('could not load %s, try again by pressing u\n\n' % url)
			options_menu(mm, url, md, device_map)
		mm.delete_session()
		md.delete_session()
	except Exception as err:
		print err
		try:
			mm.delete_session()
		except:
			pass
		try:
			md.delete_session()
		except:
			pass
开发者ID:hallvors,项目名称:marionette_utils,代码行数:85,代码来源:dualdriver.py

示例14: B2GRunner

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
class B2GRunner(object):
    remote_profile_dir = None

    def __init__(self, dm, url, tmpdir, marionette_host=None, marionette_port=None):
        self.dm = dm
        self.url = url
        self.tmpdir = tmpdir
        self.userJS = "/data/local/user.js"
        self.marionette_host = marionette_host or 'localhost'
        self.marionette_port = marionette_port or 2828
        self.marionette = None

    def wait_for_port(self, timeout):
        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(('localhost', self.marionette_port))
                data = sock.recv(16)
                sock.close()
                if '"from"' in data:
                    return True
            except:
                import traceback
                print traceback.format_exc()
            time.sleep(1)
        return False

    def restart_b2g(self):
        #restart b2g so we start with a clean slate
        self.dm.checkCmd(['shell', 'stop', 'b2g'])
        # Wait for a bit to make sure B2G has completely shut down.
        time.sleep(10)
        self.dm.checkCmd(['shell', 'start', 'b2g'])
        
        #wait for marionette port to come up
        if not self.wait_for_port(30000):
            raise Exception("Could not communicate with Marionette port after restarting B2G")
        self.marionette = Marionette(self.marionette_host, self.marionette_port)
    
    def setup_profile(self):
        #remove previous user.js if there is one
        our_user_js = os.path.join(self.tmpdir, "user.js")
        if os.path.exists(our_user_js):
            os.remove(our_user_js)
        #copy profile
        try:
            self.dm.checkCmd(["pull", self.userJS, our_user_js])
        except subprocess.CalledProcessError:
            pass
        #if we successfully copied the profile, make a backup of the file
        if os.path.exists(our_user_js): 
            self.dm.checkCmd(['shell', 'dd', 'if=%s' % self.userJS, 'of=%s.orig' % self.userJS])
        user_js = open(our_user_js, 'a')
        user_js.write("""
user_pref("power.screen.timeout", 999999);
        """)
        user_js.close()
        self.dm.checkCmd(['push', our_user_js, self.userJS])
        self.restart_b2g()

    def start(self):
        #forward the marionette port
        self.dm.checkCmd(['forward',
                          'tcp:%s' % self.marionette_port,
                          'tcp:%s' % self.marionette_port])

        print "Setting up profile"
        self.setup_profile()
        #enable ethernet connection
        print "Running netcfg, it may take some time."
        self.dm.checkCmd(['shell', 'netcfg', 'eth0', 'dhcp'])
        #launch app
        session = self.marionette.start_session()
        if 'b2g' not in session:
            raise Exception("bad session value %s returned by start_session" % session)

        # start the tests by navigating to the mochitest url
        self.marionette.execute_script("window.location.href='%s';" % self.url)

    def stop(self):
        self.marionette.delete_session()
开发者ID:bgirard,项目名称:eideticker,代码行数:84,代码来源:runner.py

示例15: Marionette

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import delete_session [as 别名]
                      help='host:port of running Gecko instance to connect to')
    parser.add_option('--homedir', dest='homedir', action='store',
                      help='home directory of emulator files')
    options, tests = parser.parse_args()

    if not tests:
        parser.print_usage()
        parser.exit()

    if options.address:
        host, port = options.address.split(':')
        if options.emulator:
            m = Marionette(host=host, port=int(port),
                           connectToRunningEmulator=True,
                           homedir=options.homedir)
        else:
            m = Marionette(host=host, port=int(port))
    elif options.emulator:
        m = Marionette(emulator=True,
                       homedir=options.homedir)
    else:
        raise Exception("must specify --address or --emulator")

    assert(m.start_session())

    for test in tests:
        run_test(test, m)

    m.delete_session()

开发者ID:ctalbert,项目名称:marionette_client,代码行数:31,代码来源:runtests.py


注:本文中的marionette.Marionette.delete_session方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。