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


Python Marionette.execute_script方法代码示例

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


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

示例1: set_up_device

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import execute_script [as 别名]
def set_up_device(opt):
    if not opt.wifi_ssid or not opt.wifi_key or not opt.wifi_pass:
        raise ValueError('Missing --wifi options')

    mc = Marionette('localhost', opt.adb_port)
    for i in range(2):
        try:
            mc.start_session()
            break
        except socket.error:
            sh('adb forward tcp:%s tcp:%s' % (opt.adb_port, opt.adb_port))
    if opt.shell:
        from pdb import set_trace
        set_trace()
        return

    # watch out! This is how gaiatest does it.
    mc.__class__ = type('Marionette', (Marionette, MarionetteTouchMixin), {})
    device = GaiaDevice(mc)

    device.restart_b2g()

    apps = GaiaApps(mc)
    data_layer = GaiaData(mc)
    lockscreen = LockScreen(mc)
    mc.setup_touch()

    lockscreen.unlock()
    apps.kill_all()

    data_layer.enable_wifi()
    if opt.wifi_key == 'WPA-PSK':
        pass_key = 'psk'
    elif opt.wifi_key == 'WEP':
        pass_key = 'wep'
    else:
        assert 0, 'unknown key management'
    data = {'ssid': opt.wifi_ssid, 'keyManagement': opt.wifi_key,
            pass_key: opt.wifi_pass}
    data_layer.connect_to_wifi(data)

    mc.switch_to_frame()
    all_apps = set(a['manifest']['name'] for a in get_installed(apps))
    if 'Marketplace Dev' not in all_apps:
        mc.execute_script(
            'navigator.mozApps.install'
            '("https://marketplace-dev.allizom.org/manifest.webapp");')
        wait_for_element_displayed(mc, 'id', 'app-install-install-button')
        yes = mc.find_element('id', 'app-install-install-button')
        mc.tap(yes)
        wait_for_element_displayed(mc, 'id', 'system-banner')

    print 'Pushing payment prefs'
    sh('adb shell stop b2g')
    sh('adb push "%s" /data/local/user.js' % (
        os.path.join(os.path.dirname(__file__), 'payment-prefs.js')))
    sh('adb shell start b2g')

    print 'When your device reboots, Marketplace Dev will be installed'
开发者ID:flodolo,项目名称:webpay,代码行数:61,代码来源:set_up_device.py

示例2: uninstall_app

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import execute_script [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

示例3: launch_app

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import execute_script [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

示例4: _StartProcess

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import execute_script [as 别名]
    def _StartProcess(self):
        if not self.isEmulatorInitialized:
            print("Starting Emulator ...")
            self.emulatorProcess = subprocess.Popen(
                [self.emulatorStartScript], cwd=os.path.dirname(self.emulatorStartScript), shell=True)

            # adb shell setprop net.dns1 10.0.2.3

            self._isBootFinished()
            self.monitoringProcessId = self.adb.getPID(self.monitoredProcessName)

            print("Forwarding TCP port %d ..." % self.forwardedPortADB)
            self.adb.command(["forward", "tcp:%d" % self.forwardedPortADB, "tcp:%d" % self.forwardedPortADB])

            self.isEmulatorInitialized = True

        time.sleep(20)

        if self.crashSuccess:
            print("Restarting %s ..." % self.monitoredProcessName)
            self.adb.killProcess(self.monitoredProcessName, True)
            time.sleep(40)
            self.monitoringProcessId = self.adb.getPID(self.monitoredProcessName)
            self.crashSuccess = False
            self.debugLogData = str()
            self.adb.checkCmd(["logcat", "-c"])

        print("Starting Marionette session ...")
        marionette = Marionette('localhost', self.forwardedPortADB)
        print(marionette.status())
        marionette.start_session()
        marionette.set_script_timeout(self.scriptTimeout)
        marionette.switch_to_frame()

        lock = gaia.LockScreen(marionette)
        lock.unlock()

        apps = gaia.GaiaApps(marionette)
        print(apps.runningApps())

        print("Launching Browser application")
        apps.launch(self.appName, switch_to_frame=True)

        print("Navigating to %s ..." % self.publisherURL)
        marionette.execute_script("return window.wrappedJSObject.Browser.navigate('%s')" % self.publisherURL)

        self.isMonitorInitialized = True
开发者ID:KurSh,项目名称:peach,代码行数:49,代码来源:b2g.py

示例5: B2GManager

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

#.........这里部分代码省略.........
                data = sock.recv(16)
                sock.close()
                if '"from"' in data:
                    print "got it"
                    return True
            except:
                import traceback
                print traceback.format_exc()
            time.sleep(1)
        return False

    def get_marionette(self):
        self.marionette = Marionette(self.marionette_host, self.marionette_port)

    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
        print "connect to marionette"
        if not self.wait_for_port(30):
            raise Exception("Could not communicate with Marionette port after restarting B2G")
        self.get_marionette()

    def set_tmpdir(self, tmpdir):
        self.tmpdir = tmpdir

    def setup_profile(self, prefs):
        if not self.tmpdir:
            raise Exception("You must set the tmpdir")
        #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])
        print "opening userjs"
        user_js = open(our_user_js, 'a')
        print "Writing: %s" % prefs
        user_js.write("%s" % prefs)
        print "closing"
        user_js.close()
        self.dm.checkCmd(['push', our_user_js, self.userJS])
        self.restart_b2g()

    def forward_port(self):
        self.dm.checkCmd(['forward',
                          'tcp:%s' % self.marionette_port,
                          'tcp:%s' % self.marionette_port])

    def setup_ethernet(self):
        #TODO: need to add timeout
        tries = 3
        while tries > 0:
            print "on try: %d" % tries
            output = StringIO.StringIO()
            self.dm.shell(['ifconfig', 'eth0'], output)
            print "we get back %s" % output.getvalue()
            if "ip" in output.getvalue():
                return
            output.close()
            try:
                self.dm.checkCmd(['shell', 'netcfg', 'eth0', 'dhcp'], timeout=10)
            except DMError:
                pass
            tries = tries - 1
        raise DMError("Could not set up ethernet connection")

    def restore_profile(self):
        if not self.tmpdir:
            raise Exception("You must set the tmpdir")
        #if we successfully copied the profile, make a backup of the file
        our_user_js = os.path.join(self.tmpdir, "user.js")
        if os.path.exists(our_user_js):
            self.dm.checkCmd(['shell', 'dd', 'if=%s.orig' % self.userJS, 'of=%s' % self.userJS])

    def get_appinfo(self):
        if not self.marionette:
            self.forward_port()
            self.wait_for_port(30)
            self.get_marionette()
        self.marionette.start_session()
        self.marionette.set_context("chrome")
        appinfo = self.marionette.execute_script("""
                                var appInfo = Components.classes["@mozilla.org/xre/app-info;1"]
                                .getService(Components.interfaces.nsIXULAppInfo);
                                return appInfo;
                                """)
        (year, month, day) = (appinfo["appBuildID"][0:4], appinfo["appBuildID"][4:6], appinfo["appBuildID"][6:8])
        appinfo['date'] =  "%s-%s-%s" % (year, month, day)
        return appinfo
开发者ID:malini,项目名称:mozbase,代码行数:104,代码来源:b2g.py

示例6: assert

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import execute_script [as 别名]
 assert(m.start_session())
 assert(m.get_session_capabilities()['javascriptEnabled'] == True)
 assert(m.get_window() == server.TEST_CURRENT_WINDOW)
 assert(m.window == server.TEST_CURRENT_WINDOW)
 assert(m.get_windows() == server.TEST_WINDOW_LIST)
 assert(m.switch_to_window('window2'))
 assert(m.window == 'window2')
 assert(m.close_window('window2'))
 assert(m.set_script_timeout(1000))
 assert(m.set_search_timeout(500))
 assert(m.get_url() == server.TEST_URL)
 assert(m.navigate(server.TEST_URL))
 assert(m.go_back())
 assert(m.go_forward())
 assert(m.refresh())
 assert(m.execute_script(server.TEST_EXECUTE_SCRIPT))
 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())
开发者ID:Kml55,项目名称:marionette_client,代码行数:33,代码来源:test_protocol.py

示例7: B2GDesktopReftest

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import execute_script [as 别名]
class B2GDesktopReftest(RefTest):
    marionette = None

    def __init__(self, marionette_args):
        RefTest.__init__(self)
        self.last_test = os.path.basename(__file__)
        self.marionette_args = marionette_args
        self.profile = None
        self.runner = None
        self.test_script = os.path.join(here, 'b2g_start_script.js')
        self.timeout = None

    def run_marionette_script(self):
        self.marionette = Marionette(**self.marionette_args)
        assert(self.marionette.wait_for_port())
        self.marionette.start_session()
        self.marionette.set_context(self.marionette.CONTEXT_CHROME)

        if os.path.isfile(self.test_script):
            f = open(self.test_script, 'r')
            self.test_script = f.read()
            f.close()
        self.marionette.execute_script(self.test_script)

    def run_tests(self, test_path, options):
        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,
                            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)
            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["b2g.system_startup_url"] = "app://test-container.gaiamobile.org/index.html"
        prefs["b2g.system_manifest_url"] = "app://test-container.gaiamobile.org/manifest.webapp"
        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
#.........这里部分代码省略.........
开发者ID:alex-tifrea,项目名称:gecko-dev,代码行数:103,代码来源:b2g_desktop.py

示例8: B2GMixin

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

#.........这里部分代码省略.........
        """
        #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:
            self.getFile(self.userJS, our_userJS)
        except subprocess.CalledProcessError:
            pass
        #if we successfully copied the profile, make a backup of the file
        if os.path.exists(our_userJS):
            self.shellCheckOutput(['dd', 'if=%s' % self.userJS, 'of=%s.orig' % self.userJS])
        with open(our_userJS, 'a') as user_file:
            user_file.write("%s" % prefs)

        self.pushFile(our_userJS, self.userJS)
        self.restartB2G()
        self.setupMarionette()

    def setupDHCP(self, interfaces=['eth0', 'wlan0']):
        """Sets up networking.

        :param interfaces: Network connection types to try. Defaults to eth0 and wlan0.
        """
        all_interfaces = [line.split()[0] for line in \
                          self.shellCheckOutput(['netcfg']).splitlines()[1:]]
        interfaces_to_try = filter(lambda i: i in interfaces, all_interfaces)

        tries = 5
        print "Setting up DHCP..."
        while tries > 0:
            print "attempts left: %d" % tries
            try:
                for interface in interfaces_to_try:
                    self.shellCheckOutput(['netcfg', interface, 'dhcp'],
                                          timeout=10)
                    if self.getIP(interfaces=[interface]):
                        return
            except DMError:
                pass
            time.sleep(1)
            tries -= 1
        raise DMError("Could not set up network connection")

    def restoreProfile(self):
        """
        Restores the original user profile on the device.
        """
        if not self.profileDir:
            raise DMError("There is no profile to restore")
        #if we successfully copied the profile, make a backup of the file
        our_userJS = os.path.join(self.profileDir, "user.js")
        if os.path.exists(our_userJS):
            self.shellCheckOutput(['dd', 'if=%s.orig' % self.userJS, 'of=%s' % self.userJS])
        mozfile.remove(self.profileDir)
        self.profileDir = None

    def getAppInfo(self):
        """
        Returns the appinfo, with an additional "date" key.

        :rtype: dictionary
        """
        if not self.marionette or not self.marionette.session:
            self.setupMarionette()
        self.marionette.set_context("chrome")
        appinfo = self.marionette.execute_script("""
                                var appInfo = Components.classes["@mozilla.org/xre/app-info;1"]
                                .getService(Components.interfaces.nsIXULAppInfo);
                                return appInfo;
                                """)
        (year, month, day) = (appinfo["appBuildID"][0:4], appinfo["appBuildID"][4:6], appinfo["appBuildID"][6:8])
        appinfo['date'] =  "%s-%s-%s" % (year, month, day)
        return appinfo
开发者ID:Nicksol,项目名称:mozbase,代码行数:104,代码来源:b2gmixin.py

示例9: MatsRunner

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import execute_script [as 别名]
class MatsRunner(object):
    def __init__(self, config_file = 'config.ini', url = 'about:blank'):
        self.config_file = config_file
        self.url = url
        
    def start(self):
        '''
        This method starts MATS.
        '''
        
        print 'Using ' + MatsController.__name__ + ' as controller.'
        print 'Loading config from "' + self.config_file + '"...',
        self.config = get_config(self.config_file)   #get_config makes sure that the config makes sense. More details in get_config.py
        self.marionette_port = self.config['Marionette']['port'] 
        print 'OK'
        
        print 'Starting Firefox/Nightly from "' + self.config['Firefox']['binary'] + '" with Marionette on port ' + str(self.marionette_port) + '.'        
        self.FirefoxThread = FirefoxThread(self.config['Firefox']['binary'], self.marionette_port)
        self.FirefoxThread.start()
        
        print 'Creating controller'
        pid = self.FirefoxThread.getPID() # this function blocks until PID is available from FirefoxThread
        self.controller = MatsController(pid)
        
        print 'Starting controller'
        self.controller.start()
        self.controller.wait_for_ready()
        
        print 'Waiting for Marionette port to open (' + str(self.marionette_port) + ')'
        portReady = self.FirefoxThread.waitForMarionettePortOpenReady(self.config['Marionette']['port_timeout'])
        if portReady:
            print 'Marionette port open'
        else:
            print 'Error: timeout, shutting down MATS'
            self.controller.stop()
            self.FirefoxThread.stop()
            return
        
        #TODO: remove line below once https://bugzilla.mozilla.org/show_bug.cgi?id=753273 is fixed
        #sleep(10)
        
        try:
            print 'Starting Marionette'
            self.marionette = Marionette('localhost', self.marionette_port)
            #TODO: move starting session and navigation to separate methods
            print 'Starting session'
            sleep(5) #TODO temporary workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=757078
            self.marionette_session = self.marionette.start_session()
            print 'Navigating to ' + self.url
            print self.marionette.navigate(self.url)
        except Exception as e:
            print 'Error starting Marionette'
            fall(e)
            self.controller.stop()
            self.FirefoxThread.stop()

        print 'MATS up and running. Waiting until Firefox/Nightly stops.'
    
    def wait_for_stop(self):
        self.FirefoxThread.join()
        print 'Stopping controller'
        self.controller.stop()
        self.controller.join()
        print 'MATS runner finishes.'
    
    def stop(self):
        self.FirefoxThread.stop()
        self.FirefoxThread.join()
        print 'Stopping controller'
        self.controller.stop()
        self.controller.join()
        print 'MATS runner finishes.'
    
    def instantiate_a11y(self):
        '''
        runs via marionette script taken from 
        http://dxr.lanedo.com/search.cgi?tree=mozilla-central&string=nsIAccessibleApplication
        to force A11y engine instantiation.
        
        sets context to content after doing it's stuff
        '''
        
        script = \
'''
const nsIAccessibleRetrieval = Components.interfaces.nsIAccessibleRetrieval;
const nsIAccessibleApplication = Components.interfaces.nsIAccessibleApplication;

var gAccRetrieval = Components.classes["@mozilla.org/accessibleRetrieval;1"].
  getService(nsIAccessibleRetrieval);
app = gAccRetrieval.getApplicationAccessible().
    QueryInterface(nsIAccessibleApplication);
    
return (app) ? true : false;
'''
        self.marionette.set_context("chrome")
        notNull = self.marionette.execute_script(script)
        self.marionette.set_context("content")
        return notNull
    
    def is_a11y_instantiated(self):
#.........这里部分代码省略.........
开发者ID:askalski,项目名称:mats,代码行数:103,代码来源:mats_runner.py

示例10: kill

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import execute_script [as 别名]
def kill(origin):
    marionette = Marionette(host='localhost', port=2828)
    marionette.start_session()
    marionette.set_context(marionette.CONTEXT_CONTENT)
    marionette.execute_script("window.wrappedJSObject.WindowManager.kill('%s')" % origin)
开发者ID:bobsilverberg,项目名称:b2gperf,代码行数:7,代码来源:kill.py

示例11: B2GMochitest

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

#.........这里部分代码省略.........
        self.copyExtraFilesToProfile(options)
        return manifest

    def run_tests(self, options):
        """ Prepare, configure, run tests and cleanup """

        manifest = self.build_profile(options)
        self.leak_report_file = os.path.join(options.profilePath, "runtests_leaks.log")

        # configuring the message logger's buffering
        self.message_logger.buffering = options.quiet

        if options.debugger or not options.autorun:
            timeout = None
        else:
            if not options.timeout:
                if mozinfo.info['debug']:
                    options.timeout = 420
                else:
                    options.timeout = 300
            timeout = options.timeout + 30.0

        log.info("runtestsb2g.py | Running tests: start.")
        status = 0
        try:
            def on_output(line):
                messages = self.message_logger.write(line)
                for message in messages:
                    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
            process_args = {'processOutputLine': on_output,
                            'stream': None}
            self.marionette_args['process_args'] = process_args
            self.marionette_args['profile'] = self.profile

            self.marionette = Marionette(**self.marionette_args)
            self.runner = self.marionette.runner
            self.app_ctx = self.runner.app_ctx

            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)):
                self.app_ctx.dm.mkDirs(self.remote_log)

            self.startServers(options, None)
            self.buildURLOptions(options, {'MOZ_HIDE_RESULTS_TABLE': '1'})
            self.test_script_args.append(not options.emulator)
            self.test_script_args.append(options.wifi)


            self.runner.start(outputTimeout=timeout)

            self.marionette.wait_for_port()
            self.marionette.start_session()
            self.marionette.set_context(self.marionette.CONTEXT_CHROME)

            # 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.
            self.marionette.execute_script("""
                Components.utils.import("resource://gre/modules/Services.jsm");
                Services.io.manageOfflineStatus = false;
                Services.io.offline = false;
                """)

            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)
            else:
                self.marionette.execute_script(self.test_script,
                                               script_args=self.test_script_args)
            status = self.runner.wait()

            if status is None:
                # the runner has timed out
                status = 124
        except KeyboardInterrupt:
            log.info("runtests.py | Received keyboard interrupt.\n");
            status = -1
        except:
            traceback.print_exc()
            log.error("Automation Error: Received unexpected exception while running application\n")
            if hasattr(self, 'runner'):
                self.runner.check_for_crashes()
            status = 1

        self.stopServers()

        log.info("runtestsb2g.py | Running tests: end.")

        if manifest is not None:
            self.cleanup(manifest, options)
        return status

    def getGMPPluginPath(self, options):
        # TODO: bug 1043403
        return None
开发者ID:chenhequn,项目名称:gecko,代码行数:104,代码来源:runtestsb2g.py

示例12: uninstall_app

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

    NOTE: if a marionette session is passed, this function switches to the top-most frame.
    """

    def check_uninstall(marionette):
        uninstall = marionette.execute_script("return window.wrappedJSObject.uninstall;")
        return uninstall != 'none'

    def check_click_uninstall(marionette):
        button = marionette.find_element('css selector', 'gaia-confirm .confirm')
        try:
            button.click()
            not_displayed = not button.is_displayed()
        except StaleElementException:
            not_displayed = True
        return not_displayed

    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")

    print 'requesting uninstall of app', app_name
    if not marionette:
        m = Marionette()
        m.start_session()
    else:
        m = marionette
        m.switch_to_frame()

    m.set_context("chrome")
    m.execute_script("""
    Components.utils.import("resource://gre/modules/Services.jsm");
    window.wrappedJSObject.uninstall = 'none';
    Services.obs.addObserver(function observer(subject, topic) {
        Services.obs.removeObserver(observer, topic);
        window.wrappedJSObject.uninstall = 'ask';
        }, "webapps-ask-uninstall", false);
    Services.obs.addObserver(function observer(subject, topic) {
        Services.obs.removeObserver(observer, topic);
        window.wrappedJSObject.uninstall = 'uninstall';
        }, "webapps-uninstall", false);
        """)
    m.set_context("content")

    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)
    result = m.execute_script(uninstall_app % app_name.lower())

    if result:
        m.set_context("chrome")
        Wait(m, 10).until(check_uninstall)
        uninstall = m.execute_script("return window.wrappedJSObject.uninstall;")
        m.set_context("content")
        if uninstall == 'ask':
            m.switch_to_frame()
            Wait(m, 20).until(element_displayed(m.find_element('css selector', 'gaia-confirm .confirm')))
            Wait(m, 20).until(check_click_uninstall)

    if not marionette:
        m.delete_session()
开发者ID:lapineige,项目名称:fxos-appgen,代码行数:94,代码来源:generator.py

示例13: run

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import execute_script [as 别名]
    def run(self, script, address='localhost:2828', symbols=None,
            treeherder='https://treeherder.mozilla.org/', reset=False,
            **kwargs):
        try:
            host, port = address.split(':')
        except ValueError:
            raise ValueError('--address must be in the format host:port')

        # Check that Orangutan is installed
        self.adb_device = ADBDevice(self.device_serial)
        orng_path = posixpath.join('data', 'local', 'orng')
        if not self.adb_device.exists(orng_path):
            raise Exception('Orangutan not found! Please install it according '
                            'to the documentation.')

        self.runner = B2GDeviceRunner(
            serial=self.device_serial,
            process_args={'stream': None},
            symbols_path=symbols,
            logdir=self.temp_dir)

        if reset:
            self.runner.start()
        else:
            self.runner.device.connect()

        port = self.runner.device.setup_port_forwarding(remote_port=port)
        assert self.runner.device.wait_for_port(port), \
            'Timed out waiting for port!'

        marionette = Marionette(host=host, port=port)
        marionette.start_session()

        try:
            marionette.set_context(marionette.CONTEXT_CHROME)
            self.is_debug = marionette.execute_script(
                'return Components.classes["@mozilla.org/xpcom/debug;1"].'
                'getService(Components.interfaces.nsIDebug2).isDebugBuild;')
            marionette.set_context(marionette.CONTEXT_CONTENT)

            if reset:
                gaia_device = GaiaDevice(marionette)
                gaia_device.wait_for_b2g_ready(timeout=120)
                gaia_device.unlock()
                gaia_apps = GaiaApps(marionette)
                gaia_apps.kill_all()

            # TODO: Disable bluetooth, emergency calls, carrier, etc

            # Run Orangutan script
            remote_script = posixpath.join(self.adb_device.test_root,
                                           'orng.script')
            self.adb_device.push(script, remote_script)
            self.start_time = time.time()
            # TODO: Kill remote process on keyboard interrupt
            self.adb_device.shell('%s %s %s' % (orng_path,
                                                self.device_properties['input'],
                                                remote_script))
            self.end_time = time.time()
            self.adb_device.rm(remote_script)
        except (MarionetteException, IOError):
            if self.runner.crashed:
                # Crash has been detected
                pass
            else:
                raise
        self.runner.check_for_crashes(test_name='b2gmonkey')

        # Report results to Treeherder
        required_envs = ['TREEHERDER_KEY', 'TREEHERDER_SECRET']
        if all([os.environ.get(v) for v in required_envs]):
            self.post_to_treeherder(script, treeherder)
        else:
            self._logger.info(
                'Results will not be posted to Treeherder. Please set the '
                'following environment variables to enable Treeherder '
                'reports: %s' % ', '.join([
                    v for v in required_envs if not os.environ.get(v)]))
开发者ID:JJTC-PX,项目名称:b2gmonkey,代码行数:80,代码来源:b2gmonkey.py

示例14: Marionette

# 需要导入模块: from marionette import Marionette [as 别名]
# 或者: from marionette.Marionette import execute_script [as 别名]
#!/usr/bin/python2.7
#
# Script to work around Marionette bug 879816 (cannot click the modal 'ok' button
# following clicking something else).
#
from marionette import Marionette
marionette = Marionette(host='localhost', port=2828)
marionette.start_session()
marionette.switch_to_frame()
marionette.execute_script("document.getElementById('modal-dialog-prompt-ok').click();")

开发者ID:villenavg,项目名称:OWD_TEST_TOOLKIT,代码行数:12,代码来源:click_modal_ok_btn.py

示例15: ftu

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

#.........这里部分代码省略.........
      puk_input = client.find_element('css selector', '#puk-input')
      puk_input.send_keys(sim_puk)

      # switch to app://communications.gaiamobile.org/ftu/index.html#data_3g
      next = client.find_element('css selector', '#unlock-sim-button')
      next.tap()
      time.sleep(short_time)

    # app://communications.gaiamobile.org/ftu/index.html#data_3g
    file_name = 'data_3g'
    screenshot_entry = {
      "id" : file_name,
      "script" : app,
      "gaia" : gaia_hash,
      "hg" : hg_hash,
      "changed" : False,
      "path" : screenshot_path}
    test_flags = {
      "sim": True,
      "no-sim": False}
    if check_flags(test_flags, device_flags):
      screenshot_entry.update(test_flags)
      if take_screenshot(locale, screenshot_path, client, file_name):
        screenshot_entry['changed'] = True
      log_displayed_l10n_strings(client, db, app, app_categ, screenshot_entry, '#activation-screen')


      # switch to app://communications.gaiamobile.org/ftu/index.html#wifi
      next = client.find_element('css selector', '#forward')
      next.tap()
      time.sleep(long_time)

      # enable overlay "scanningNetworks" spinner screen (loading-overlay)
      client.execute_script("window.wrappedJSObject.utils.overlay.show('scanningNetworks', 'spinner');")
      time.sleep(middle_time)
    
    # overlay "scanningNetworks" spinner screen
    file_name = 'wifi-loading_overlay-scanning_networks'
    screenshot_entry = {
      "id" : file_name,
      "script" : app,
      "gaia" : gaia_hash,
      "hg" : hg_hash,
      "changed" : False,
      "path" : screenshot_path}
    test_flags = {}
    if check_flags(test_flags, device_flags):
      screenshot_entry.update(test_flags)
      if take_screenshot(locale, screenshot_path, client, file_name):
        screenshot_entry['changed'] = True
      log_displayed_l10n_strings(client, db, app, app_categ, screenshot_entry, '#loading-overlay')


      # disable overlay "scanningNetworks" spinner screen
      client.execute_script("window.wrappedJSObject.utils.overlay.hide('scanningNetworks', 'spinner');")
      time.sleep(middle_time)

    # app://communications.gaiamobile.org/ftu/index.html#wifi
    file_name = 'wifi'
    screenshot_entry = {
      "id" : file_name,
      "script" : app,
      "gaia" : gaia_hash,
      "hg" : hg_hash,
      "changed" : False,
      "path" : screenshot_path}
开发者ID:TheoChevalier,项目名称:b2g-screenshots,代码行数:70,代码来源:ftu.py


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