Ejemplo n.º 1
0
    def _enable_internet(self, ping_server='google.com'):
        """
        Re-enables the internet connection.

        @param ping_server: The server to ping to check we are online.

        """
        if not self._internet_was_disabled:
            return

        self._internet_was_disabled = False
        logging.debug('Before reconnect: %s', utils.run('ifconfig'))
        for eth in self._NETWORK_INTERFACES:
            utils.run('ifconfig %s up' % eth, ignore_status=True)
        utils.start_service('recover_duts', ignore_status=True)

        # Print ifconfig to help debug DUTs that stay offline.
        logging.debug('After reconnect: %s', utils.run('ifconfig'))

        # We can't return right after reconnecting the network or the server
        # test may not receive the message. So we wait a bit longer for the
        # DUT to be reconnected.
        utils.poll_for_condition(
            lambda: utils.ping(ping_server, tries=3, timeout=10) == 0,
            timeout=120,
            sleep_interval=1,
            exception=error.TestFail('Ping failed after reconnecting network'))
Ejemplo n.º 2
0
    def run_once(self, video):
        """Tests whether video seek works by random seeks forward and backward.

        @param video: Sample video file to be seeked in Chrome.
        """
        with chrome.Chrome(init_network_controller=True) as cr:
            cr.browser.platform.SetHTTPServerDirectories(self.bindir)
            tab = cr.browser.tabs[0]
            tab.Navigate(
                cr.browser.platform.http_server.UrlOf(
                    os.path.join(self.bindir, 'video.html')))
            tab.WaitForDocumentReadyStateToBeComplete()

            tab.EvaluateJavaScript('loadSourceAndRunSeekTest("%s")' % video)

            def get_seek_test_status():
                seek_test_status = tab.EvaluateJavaScript(
                    'getSeekTestStatus()')
                logging.info('Seeking: %s', seek_test_status)
                return seek_test_status

            utils.poll_for_condition(
                lambda: get_seek_test_status() == 'pass',
                exception=error.TestError('Seek test is stuck and timeout'),
                timeout=WAIT_TIMEOUT_S,
                sleep_interval=1)
Ejemplo n.º 3
0
    def run_once(self, codec, is_switchres, video):
        """Tests whether video seek works by random seeks forward and backward.

        @param codec: the codec to be tested, ex. 'vp8', 'vp9', 'h264'.
        @param is_switchres: bool, True if using switch resolution video.
        @param video: Sample video file to be seeked in Chrome.
        """
        if self.is_skipping_test(codec, is_switchres):
            logging.info('Skipping test run on this board.')
            return  # return immediately to pass this test

        with chrome.Chrome(
                extra_browser_args=helper_logger.chrome_vmodule_flag(),
                init_network_controller=True) as cr:
            cr.browser.platform.SetHTTPServerDirectories(self.bindir)
            tab = cr.browser.tabs[0]
            tab.Navigate(
                cr.browser.platform.http_server.UrlOf(
                    os.path.join(self.bindir, 'video.html')))
            tab.WaitForDocumentReadyStateToBeComplete()

            tab.EvaluateJavaScript('loadSourceAndRunSeekTest("%s")' % video)

            def get_seek_test_status():
                seek_test_status = tab.EvaluateJavaScript(
                    'getSeekTestStatus()')
                logging.info('Seeking: %s', seek_test_status)
                return seek_test_status

            utils.poll_for_condition(
                lambda: get_seek_test_status() == 'pass',
                exception=error.TestError('Seek test is stuck and timeout'),
                timeout=WAIT_TIMEOUT_S,
                sleep_interval=1)
Ejemplo n.º 4
0
    def start_new_hangout_session(self, hangout_name):
        """Start a new hangout session.

        @param hangout_name: Name of the hangout session.
        """
        if not self.is_ready_to_start_hangout_session():
            if self.is_in_hangout_session():
                self.end_hangout_session()
            utils.poll_for_condition(
                lambda: self._webview_context.EvaluateJavaScript(
                    "window.hrIsReadyToStartHangoutForTest()"),
                exception=error.TestFail(
                    'Not ready to start hangout session.'),
                timeout=DEFAULT_TIMEOUT,
                sleep_interval=1)

        self._webview_context.ExecuteJavaScript("window.hrStartCallForTest('" +
                                                hangout_name + "')")
        utils.poll_for_condition(
            lambda: self._webview_context.EvaluateJavaScript(
                "window.hrIsInHangoutForTest()"),
            exception=error.TestFail('Not able to start session.'),
            timeout=DEFAULT_TIMEOUT,
            sleep_interval=1)
        logging.info('Started hangout session: %s', hangout_name)
Ejemplo n.º 5
0
def DisconnectFromCellularService(bs, flim, service):
    """Attempts to disconnect from the supplied cellular service.

    Args:
        bs:  A basestation object.  Pass None to skip basestation-side checks
        flim:  A flimflam object
        service:  A cellular service object
    """

    flim.DisconnectService(service)  # Waits for flimflam state to go to idle

    if bs:
        verifier = bs.GetAirStateVerifier()
        # This is racy: The modem is free to report itself as
        # disconnected before it actually finishes tearing down its RF
        # connection.
        verifier.AssertDataStatusIn([
            cellular.UeGenericDataStatus.DISCONNECTING,
            cellular.UeGenericDataStatus.REGISTERED,
            cellular.UeGenericDataStatus.NONE,
        ])

        def _ModemIsFullyDisconnected():
            return verifier.IsDataStatusIn([
                cellular.UeGenericDataStatus.REGISTERED,
                cellular.UeGenericDataStatus.NONE,
            ])

        utils.poll_for_condition(
            _ModemIsFullyDisconnected,
            timeout=20,
            exception=cellular_system_error.BadState(
                'modem not disconnected from base station'))
Ejemplo n.º 6
0
def wait_for_android_boot(timeout=None):
    """Sleep until Android has completed booting or timeout occurs."""
    if timeout is None:
        timeout = _WAIT_FOR_ANDROID_BOOT_SECONDS

    def _is_container_started():
        return utils.system('android-sh -c true', ignore_status=True) == 0

    def _is_android_booted():
        output = utils.system_output(
            'android-sh -c "getprop sys.boot_completed"', ignore_status=True)
        return output.strip() == '1'

    logging.info('Waiting for Android to boot completely.')

    start_time = time.time()
    utils.poll_for_condition(condition=_is_container_started,
                             desc='Container has started',
                             timeout=timeout,
                             exception=error.TestFail('Android did not boot!'),
                             sleep_interval=_BOOT_CHECK_INTERVAL_SECONDS)
    with Logcat(_VAR_LOGCAT_BOOT_PATH):
        boot_timeout = timeout - (time.time() - start_time)
        utils.poll_for_condition(
            condition=_is_android_booted,
            desc='Android has booted',
            timeout=boot_timeout,
            exception=error.TestFail('Android did not boot!'),
            sleep_interval=_BOOT_CHECK_INTERVAL_SECONDS)
    logging.info('Android has booted completely.')
Ejemplo n.º 7
0
    def _run_test(self):
        self.test.reset_modem()

        # The modem state should be REGISTERED.
        self.test.check_modem_state(mm1_constants.MM_MODEM_STATE_REGISTERED)

        # Service should appear as 'not-activated'.
        self.test.check_service_activation_state('not-activated')

        # Call 'CompleteActivation' on the service.
        service = self.test.test_env.shill.find_cellular_service_object()
        service.CompleteCellularActivation()

        # Wait for shill to retry the failed activations, except the last retry
        # will succeed.
        # NOTE: Don't check for transitory service activation states while this
        # is happening because shill will reset the modem once the activation
        # succeeds which will cause the existing service to get deleted.
        modem = self.pseudomm.get_modem()
        utils.poll_for_condition(
            lambda: (modem.properties(I_ACTIVATION_TEST)['ActivateCount'] ==
                     self.NUM_ACTIVATE_RETRIES),
            exception=error.TestFail('Shill did not retry failed activation'),
            timeout=10)

        # The modem should reset in 5 seconds. Wait 5 more seconds to make sure
        # a new service gets created.
        time.sleep(10)
        self.test.check_service_activation_state('activated')
    def run_once(self, html):
        """Tests whether Chrome reloads video after reloading the tab.

        @param html: Sample html file to be loaded and reloaded in Chrome.
        """
        with chrome.Chrome() as cr:
            cr.browser.platform.SetHTTPServerDirectories(self.bindir)
            tab = cr.browser.tabs[0]
            tab.Navigate(
                cr.browser.platform.http_server.UrlOf(
                    os.path.join(self.bindir, html)))

            def is_video_at_start():
                """Checks if video is at the start position."""
                return tab.EvaluateJavaScript(
                    '(typeof videoAtStart != "undefined") && videoAtStart')

            # Expect video being loaded and started for the first time.
            utils.poll_for_condition(
                is_video_at_start,
                exception=error.TestError('Video is not started'),
                timeout=WAIT_TIMEOUT_S,
                sleep_interval=1)

            # Reload the tab after playing video for a while.
            tab.EvaluateJavaScript('playAndReload()')

            # Expect video being restarted after reloading the tab.
            utils.poll_for_condition(
                is_video_at_start,
                exception=error.TestError('Video is not restarted'),
                timeout=WAIT_TIMEOUT_S,
                sleep_interval=1)
    def wait_for_scroll_position_to_settle(self, scroll_vertical=True):
        """Wait for page to move and then stop moving.

        @param scroll_vertical: True for Vertical scroll and
                                False for horizontal scroll.

        @raise: TestError if page either does not move or does not stop moving.

        """
        # Wait until page starts moving.
        utils.poll_for_condition(
            lambda: self.get_scroll_position(scroll_vertical
                                             ) != self._DEFAULT_SCROLL,
            exception=error.TestError('No scrolling occurred!'),
            timeout=30)

        # Wait until page has stopped moving.
        self._previous = self._DEFAULT_SCROLL

        def _movement_stopped():
            current = self.get_scroll_position()
            result = current == self._previous
            self._previous = current
            return result

        utils.poll_for_condition(
            lambda: _movement_stopped(),
            sleep_interval=1,
            exception=error.TestError('Page did not stop moving!'),
            timeout=30)
Ejemplo n.º 10
0
    def disable_modem_for_test_setup(self, timeout_seconds=10):
        """
        Disables all cellular modems.

        Use this method only for setting up tests.  Do not use this method to
        test disable functionality because this method repeatedly attempts to
        disable the cellular technology until it succeeds (ignoring all DBus
        errors) since the DisableTechnology() call may fail for various reasons
        (eg. an enable is in progress).

        @param timeout_seconds: Amount of time to wait until the modem is
                disabled.
        @raises ShillProxyError if the modems fail to disable within
                |timeout_seconds|.

        """
        def _disable_cellular_technology(self):
            try:
                self._manager.DisableTechnology(self.TECHNOLOGY_CELLULAR)
                return True
            except dbus.DBusException as e:
                return False

        utils.poll_for_condition(lambda: _disable_cellular_technology(self),
                                 exception=shill_proxy.ShillProxyTimeoutError(
                                     'Failed to disable cellular technology.'),
                                 timeout=timeout_seconds)
        modem = self.find_cellular_device_object()
        self.wait_for_property_in(modem,
                                  self.DEVICE_PROPERTY_POWERED,
                                  [self.VALUE_POWERED_OFF],
                                  timeout_seconds=timeout_seconds)
    def _itesting_machine(self, machine_name, timeout=SHORT_TIMEOUT_SECONDS):
        """
        Get the testing interface of the given interactive state machine.

        @param machine_name: The name of the interactive state machine.
        @return dbus.Interface for the testing interface of
                InteractiveScanningMachine, if found. None otherwise.
        @raises utils.TimeoutError if a valid dbus object can't be found.

        """
        def _get_machine():
            machine = self._bus.get_object(
                mm1_constants.I_MODEM_MANAGER,
                '/'.join([pm_constants.TESTING_PATH, machine_name]))
            if machine:
                i_machine = dbus.Interface(machine, pm_constants.I_TESTING_ISM)
                # Only way to know if this DBus object is valid is to call a
                # method on it.
                try:
                    i_machine.IsWaiting()  # Ignore result.
                    return i_machine
                except dbus.exceptions.DBusException as e:
                    logging.debug(e)
                    return None

        utils.poll_for_condition(_get_machine, timeout=timeout)
        return _get_machine()
    def run_once(self):
        # Make sure Chrome minidumps are written locally.
        minidumps_file = '/mnt/stateful_partition/etc/enable_chromium_minidumps'
        if not os.path.exists(minidumps_file):
            open(minidumps_file, 'w').close()
            pgrep_process = subprocess.Popen(['pgrep', 'session_manager'],
                                             stdout=subprocess.PIPE)
            old_pid = pgrep_process.communicate()[0].strip()
            subprocess.call(['pkill', constants.SESSION_MANAGER])
            utils.poll_for_condition(
                lambda: self._session_manager_ready(old_pid), timeout=20)
        assert os.path.exists(minidumps_file)

        # Enable Chrome testing interface and Login
        deps_dir = os.path.join(self.autodir, 'deps')
        pyautolib_dir = os.path.join(self.cr_source_dir,
                                     'chrome', 'test', 'pyautolib')
        login_cmd = cros_ui.xcommand_as(
            'python %s chromeos_utils.ChromeosUtils.LoginToDefaultAccount '
            '-v --no-http-server' %
                os.path.join(pyautolib_dir, 'chromeos', 'chromeos_utils.py'))
        utils.system(login_cmd)

        # Run pyauto tests in the "CHROMEOS_FLASH" test suite
        chronos_id = pwd.getpwnam('chronos')
        os.chown(os.getcwd(), chronos_id.pw_uid, chronos_id.pw_gid)
        functional_cmd = cros_ui.xcommand_as(
            '%s/chrome_test/test_src/chrome/test/functional/'
            'pyauto_functional.py --suite=CHROMEOS_FLASH -v' % deps_dir)
        utils.system(functional_cmd)
Ejemplo n.º 13
0
    def lock_screen(self, perf_values):
        """Lock the screen.

        @param perf_values: Performance data will be stored inside of this dict.

        @raises: error.TestFail when screen already locked.
        @raises: error.TestFail when screen not locked.

        """
        logging.debug('lock_screen')
        if self.screen_locked:
            raise error.TestFail('Screen already locked')
        signal_listener = session_manager.ScreenIsLockedSignalListener(
                gobject.MainLoop())
        ext = self._chrome.autotest_ext

        start = datetime.now()
        ext.EvaluateJavaScript('chrome.autotestPrivate.lockScreen();')
        signal_listener.wait_for_signals(desc='Screen is locked.',
                                         timeout=self._SCREEN_IS_LOCKED_TIMEOUT)
        perf_values['lock_seconds'] = (datetime.now() - start).total_seconds()

        utils.poll_for_condition(
                lambda: self.screen_locked,
                exception=error.TestFail('Screen not locked'))
    def run_test_on_port(self, chameleon_port, test_mirrored):
        """Run the test on the given Chameleon port.

        @param chameleon_port: a ChameleonPorts object.
        @param test_mirrored: True if mirror mode
        @raise error.TestFail if any display errors
        """
        self.chameleon_port = chameleon_port
        self.screen_test = chameleon_screen_test.ChameleonScreenTest(
            self.host, chameleon_port, self.display_facade, self.outputdir)

        # Get connector type used (HDMI,DP,...)
        self.connector_used = self.display_facade.get_external_connector_name()

        # Set main display mode for the test
        logging.info("Setting Mirrored display mode")
        self.display_facade.set_mirrored(test_mirrored)
        self.logout()
        utils.poll_for_condition(
            self.is_logged_out,
            exception=error.TestFail('User is not logged out'),
            sleep_interval=1)
        logging.info("Restarting the chrome again!")
        self.browser_facade.start_default_chrome(restart=True)
        logging.info("Checking the external display mode and image!")
        self.check_external_display(test_mirrored)
        if self.errors:
            raise error.TestFail('; '.join(set(self.errors)))
    def _check_browser_history(self, case_value):
        """
        Checks the browser history page to verify if history was saved.

        @case_value: case value for this case.

        """
        # Adding the URL below to browser's history.
        self.navigate_to_url("http://www.google.com")

        active_tab = self.navigate_to_url("chrome://history")

        utils.poll_for_condition(
            lambda: self.check_page_readiness(active_tab, PAGE_SCRAPE_CMD),
            exception=error.TestFail('Page is not ready.'),
            timeout=5,
            sleep_interval=1)
        content = active_tab.EvaluateJavaScript(PAGE_SCRAPE_CMD)

        if case_value:
            if "hidden" in content:
                raise error.TestFail("History is not empty and it should be.")
        else:
            if "hidden" not in content:
                raise error.TestFail("History is empty and it should not be.")
    def wait_for_events_to_complete(self, delay_secs=1, timeout=60):
        """Wait until test page stops seeing events for delay_secs seconds.

        @param delay_secs: the polling frequency in seconds.
        @param timeout: the number of seconds to wait for events to complete.
        @raises: error.TestError if no events occurred.
        @raises: error.TestError if events did not stop after timeout seconds.

        """
        self._tmp_previous_event_count = -1

        def _events_stopped_coming():
            most_recent_event_count = self.get_event_count()
            delta = most_recent_event_count - self._tmp_previous_event_count
            self._tmp_previous_event_count = most_recent_event_count
            return most_recent_event_count != 0 and delta == 0

        try:
            utils.poll_for_condition(_events_stopped_coming,
                                     exception=error.TestError(),
                                     sleep_interval=delay_secs,
                                     timeout=timeout)
        except error.TestError:
            if self._tmp_previous_event_count == 0:
                raise error.TestError('No touch event was seen!')
            else:
                self.log_events()
                raise error.TestError('Touch events did not stop!')
Ejemplo n.º 17
0
def nuke_subprocess(subproc, timeout_hint_seconds=0):
    """
    Attempt to kill the given subprocess via an escalating series of signals.

    Between each attempt, the process is given |timeout_hint_seconds| to clean
    up. So, the function may take up to 3 * |timeout_hint_seconds| time to
    finish.

    @param subproc: The python subprocess to nuke.
    @param timeout_hint_seconds: The time to wait between successive attempts.
    @returns: The result from the subprocess, None if we failed to kill it.

    """
    # check if the subprocess is still alive, first
    if subproc.poll() is not None:
        return subproc.poll()

    signal_queue = [signal.SIGINT, signal.SIGTERM, signal.SIGKILL]
    for sig in signal_queue:
        logging.info('Nuking %s with %s', subproc.pid, sig)
        utils.signal_pid(subproc.pid, sig)
        try:
            utils.poll_for_condition(
                    lambda: subproc.poll() is not None,
                    timeout=timeout_hint_seconds)
            return subproc.poll()
        except utils.TimeoutError:
            pass
    return None
Ejemplo n.º 18
0
    def start(self, wait_for_network=True):
        """Start the container.

        @param wait_for_network: True to wait for network to be up. Default is
                                 set to True.

        @raise ContainerError: If container does not exist, or fails to start.
        """
        cmd = 'sudo lxc-start -P %s -n %s -d' % (self.container_path,
                                                 self.name)
        output = utils.run(cmd).stdout
        if not self.is_running():
            raise error.ContainerError(
                'Container %s failed to start. lxc command output:\n%s' %
                (os.path.join(self.container_path, self.name), output))

        if wait_for_network:
            logging.debug('Wait for network to be up.')
            start_time = time.time()
            utils.poll_for_condition(
                condition=self.is_network_up,
                timeout=constants.NETWORK_INIT_TIMEOUT,
                sleep_interval=constants.NETWORK_INIT_CHECK_INTERVAL)
            logging.debug('Network is up after %.2f seconds.',
                          time.time() - start_time)
    def is_network_connected(self, ssid):
        """
        Return True if the DUT is connected to the Network.

        Returns True if the DUT is connected to the network. Waits for a
        a short time if the DUT is in a connecting state.

        @param ssid: The SSID of the network.

        @returns: True if the DUT is connected to the network/ssid,
                else returns False

        @raises error.TestFail: If the DUT is stuck in the connecting state.

        """
        utils.poll_for_condition(
            lambda: (self._get_network_connection_state(ssid) != 'Connecting'),
            exception=error.TestFail('Device stuck in connecting state'),
            timeout=self.SHORT_TIMEOUT)
        try:
            utils.poll_for_condition(
                lambda:
                (self._get_network_connection_state(ssid) == 'Connected'),
                timeout=self.SHORT_TIMEOUT)
        except utils.TimeoutError:
            pass
        network_connection_state = self._get_network_connection_state(ssid)
        logging.debug("Connection state for SSID-%r is: %r", ssid,
                      network_connection_state)
        return network_connection_state == 'Connected'
Ejemplo n.º 20
0
    def stop(self):
        """Restore the backed-up DNS settings and stop the mock DNS server."""
        try:
            # Follow resolv.conf symlink.
            resolv = os.path.realpath(constants.RESOLV_CONF_FILE)
            # Grab path to the real file, do following work in that directory.
            resolv_dir = os.path.dirname(resolv)
            resolv_bak = os.path.join(resolv_dir, self._resolv_bak_file)
            os.chmod(resolv_dir, self._resolv_dir_mode)
            if os.path.exists(resolv_bak):
                os.rename(resolv_bak, resolv)
            else:
                # This probably means shill restarted during the execution
                # of our test, and has cleaned up the .bak file we created.
                raise error.TestError('Backup file %s no longer exists!  '
                                      'Connection manager probably crashed '
                                      'during the test run.' %
                                      resolv_bak)

            utils.poll_for_condition(
                lambda: self.__attempt_resolve('www.google.com.',
                                               '127.0.0.1',
                                               expected=False),
                utils.TimeoutError('Timed out waiting to revert DNS.  '
                                   'resolv.conf contents are: ' +
                                   utils.read_one_line(resolv)),
                timeout=10)
        finally:
            # Stop the DNS server.
            self._stopper.set()
            self._thread.join()
Ejemplo n.º 21
0
def wait_for_adb_ready(timeout=_WAIT_FOR_ADB_READY):
    """Wait for the ADB client to connect to the ARC container.

    @param timeout: Timeout in seconds.
    """
    # When partial boot is enabled, although adbd is started at login screen,
    # we still need /data to be mounted to set up key-based authentication.
    # /data should be mounted once the user has logged in.
    if is_partial_boot_enabled():
        _wait_for_data_mounted()

    setup_adb_host()
    if is_adb_connected():
        return

    # Push keys for adb.
    pubkey_path = os.environ[_ADB_VENDOR_KEYS] + '.pub'
    with open(pubkey_path, 'r') as f:
        _write_android_file(_ANDROID_ADB_KEYS_PATH, f.read())
    _android_shell('restorecon ' + pipes.quote(_ANDROID_ADB_KEYS_PATH))

    # This starts adbd.
    _android_shell('setprop sys.usb.config mtp,adb')

    # Kill existing adb server to ensure that a full reconnect is performed.
    utils.system('adb kill-server', ignore_status=True)

    exception = error.TestFail('adb is not ready in %d seconds.' % timeout)
    utils.poll_for_condition(adb_connect, exception, timeout)
Ejemplo n.º 22
0
    def test_unlock_sim_pin_lock(self):
        """
        Test successfully unlocking the SIM after it has been pin-locked.

        """
        # First, pin-lock the SIM.
        self._pin_lock_sim()

        retries_left = self._get_retries_left()
        self.device.EnterPin(self.current_pin)

        if self._is_sim_pin_locked():
            raise error.TestFail('Failed to unlock a pin-locked SIM with '
                                 'correct pin.')
        if not self._is_sim_lock_enabled():
            raise error.TestFail('SIM lock got disabled when attemping to'
                                 'unlock a pin-locked SIM.')
        if self._get_retries_left() != retries_left:
            raise error.TestFail('Unexpected change in number of retries left '
                                 'after a successful unlock of pin-locked SIM. '
                                 'retries before:%d, after:%d' %
                                 (retries_left, self._get_retries_left()))
        # The shill service reappears after the SIM is unlocked.
        # We need a fresh handle on the service.
        utils.poll_for_condition(
                lambda: self.test_env.shill.get_service_for_device(self.device))
        self.service = self.test_env.shill.get_service_for_device(self.device)
        self.test_env.shill.wait_for_property_in(self.service,
                                                 'state',
                                                 ['online'],
                                                 DEFAULT_OPERATION_TIMEOUT)
Ejemplo n.º 23
0
    def RunCryptohomeTest(self):
        """Test Cryptohome."""
        logging.info('RunCryptohomeTest: Starting chrome and logging in.')
        is_arc_available = utils.is_arc_available()
        arc_mode = arc_common.ARC_MODE_ENABLED if is_arc_available else None
        with chrome.Chrome(arc_mode=arc_mode, num_tries=1) as cr:
            # Check that the cryptohome is mounted.
            # is_vault_mounted throws an exception if it fails.
            logging.info('Checking mounted cryptohome.')
            cryptohome.is_vault_mounted(user=cr.username, allow_fail=False)
            # Navigate to about:blank.
            tab = cr.browser.tabs[0]
            tab.Navigate('about:blank')

            # Evaluate some javascript.
            logging.info('Evaluating JavaScript.')
            if tab.EvaluateJavaScript('2+2') != 4:
                raise TestFail('EvaluateJavaScript failed')

            # ARC test.
            if is_arc_available:
                arc.wait_for_adb_ready()
                logging.info('Android booted successfully.')
                arc.wait_for_android_process('org.chromium.arc.intent_helper')
                if not arc.is_package_installed('android'):
                    raise TestFail(
                        '"android" system package was not listed by '
                        'Package Manager.')

        if is_arc_available:
            utils.poll_for_condition(
                lambda: not arc.is_android_container_alive(),
                timeout=15,
                desc='Android container still running '
                'after Chrome shutdown.')
Ejemplo n.º 24
0
def check_ui_property(chrome_networking_test_context,
                      network_guid,
                      property_name,
                      expected_value,
                      expansion_level=1,
                      timeout=LONG_TIMEOUT):
    """
    Polls until the given network property has the expected value.

    @param chrome_networking_test_context: Instance of
            chrome_networking_test_context.ChromeNetworkingTestContext.
    @param network_guid: GUID of the network.
    @param property_name: Property to check.
    @param expected_value: Value the property is expected to obtain.
    @param expansion_level: Path expansion depth.
    @param timeout: Timeout interval in which the property should reach the
            expected value.

    @raises error.TestFail, if the check doesn't pass within |timeout|.

    """
    def _compare_props():
        network = call_test_function_check_success(
            chrome_networking_test_context, 'getNetworkInfo',
            ('"' + network_guid + '"', ))
        value = get_ui_property(network, property_name, expansion_level)
        return value == expected_value

    utils.poll_for_condition(
        _compare_props,
        error.TestFail('Property "' + property_name + '" on network "' +
                       network_guid + '" never obtained value "' +
                       expected_value + '"'), timeout)
Ejemplo n.º 25
0
    def Test(self):
        """Test that the Enable and Disable technology functions work.

       The expectation is that by using enable technology shill
       will change the power state of the device by requesting that
       the modem manager modem be either Enabled or Disabled.  The
       state tracked by shill should not change until *after* the
       modem state has changed.  Thus after Enabling or Disabling the
       technology, we wait until the shill device state changes,
       and then assert that the modem state has also changed, without
       having to wait again.

       Raises:
         error.TestFail - if the shill device or the modem manager
           modem is not in the expected state
    """
        device = self.test_env.shill.find_cellular_device_object()

        for i in range(2):
            # Enable technology, ensure that device and modem are enabled.
            self.test_env.shill.manager.EnableTechnology('cellular')
            utils.poll_for_condition(
                lambda: self.CompareDevicePowerState(device, True),
                error.TestFail('Device Failed to enter state Powered=True'))
            if not self.CompareModemPowerState(self.test_env.modem, True):
                raise error.TestFail('Modem Failed to enter state Enabled')

            # Disable technology, ensure that device and modem are disabled.
            self.test_env.shill.manager.DisableTechnology('cellular')
            utils.poll_for_condition(
                lambda: self.CompareDevicePowerState(device, False),
                error.TestFail('Device Failed to enter state Powered=False'))
            if not self.CompareModemPowerState(self.test_env.modem, False):
                raise error.TestFail('Modem Failed to enter state Disabled')
Ejemplo n.º 26
0
    def run_once(self):
        # Make sure Chrome minidumps are written locally.
        minidumps_file = "/mnt/stateful_partition/etc/enable_chromium_minidumps"
        if not os.path.exists(minidumps_file):
            open(minidumps_file, "w").close()
            pgrep_process = subprocess.Popen(["pgrep", "session_manager"], stdout=subprocess.PIPE)
            old_pid = pgrep_process.communicate()[0].strip()
            subprocess.call(["pkill", constants.SESSION_MANAGER])
            utils.poll_for_condition(lambda: self._session_manager_ready(old_pid), timeout=20)
        assert os.path.exists(minidumps_file)

        # Enable chrome testing interface and Login
        deps_dir = os.path.join(self.autodir, "deps")
        pyautolib_dir = os.path.join(self.cr_source_dir, "chrome", "test", "pyautolib")
        login_cmd = cros_ui.xcommand_as(
            "python %s chromeos_utils.ChromeosUtils.LoginToDefaultAccount "
            "-v --no-http-server" % os.path.join(pyautolib_dir, "chromeos", "chromeos_utils.py")
        )
        utils.system(login_cmd)

        # Run pyauto tests in the "FULL" suite
        functional_cmd = cros_ui.xcommand_as(
            "%s/chrome_test/test_src/chrome/test/functional/" "pyauto_functional.py --suite=FULL -v" % deps_dir
        )
        utils.system(functional_cmd)
Ejemplo n.º 27
0
def do_dircrypto_migration(user, password, timeout=600):
    """Start dircrypto migration for the user.

    @param user: The user to migrate.
    @param password: The password used to mount the users vault
    @param timeout: How long in seconds to wait for the migration to finish
    before failing.
    """
    unmount_vault(user)
    args = [
            CRYPTOHOME_CMD,
            '--action=mount_ex',
            '--to_migrate_from_ecryptfs',
            '--user=%s' % user,
            '--password=%s' % password]
    logging.info(__run_cmd(' '.join(args)))
    if not __get_mount_info(temporary_mount_path(user), allow_fail=True):
        raise ChromiumOSError('Failed to mount home for migration')
    args = [CRYPTOHOME_CMD, '--action=migrate_to_dircrypto', '--user=%s' % user]
    logging.info(__run_cmd(' '.join(args)))
    utils.poll_for_condition(
        lambda: not __get_mount_info(
                temporary_mount_path(user), allow_fail=True),
        timeout=timeout,
        exception=error.TestError(
                'Timeout waiting for dircrypto migration to finish'))
Ejemplo n.º 28
0
    def wait_for_signal(self, signal_name):
        """Waits for the reception of a signal.

        Args:
            signal_name: The name of the signal to wait for.

        Returns:
            The content of the signal.
        """
        if signal_name not in self.__signal_content:
            return None

        def check_signal_content():
            context = self.main_loop.get_context()
            while context.iteration(False):
                pass
            return self.__signal_content[signal_name] is not None

        logging.debug('Waiting for D-Bus signal "%s"', signal_name)
        utils.poll_for_condition(condition=check_signal_content,
                                 desc='%s signal' % signal_name,
                                 timeout=self.signal_timeout_in_seconds)
        content = self.__signal_content[signal_name]
        logging.debug('Received D-Bus signal "%s(%s)"', signal_name, content)
        self.__signal_content[signal_name] = None
        return content
Ejemplo n.º 29
0
    def wait_for_condition_on_expression_result(self, expression, condition,
                                                timeout):
        """
        Blocks until |condition| returns True when applied to the result of the
        JavaScript expression |expression|.

        @param expression: JavaScript expression to evaluate.
        @param condition: A function that accepts a single argument and returns
                a boolean.
        @param timeout: The timeout interval length, in seconds, after which
                this method will raise an error.
        @raises error.TestFail, if the conditions is not met within the given
                timeout interval.

        """
        extension = self.network_test_extension

        def _evaluate_expr():
            return extension.EvaluateJavaScript(expression)

        utils.poll_for_condition(
            lambda: condition(_evaluate_expr()),
            error.TestFail('Timed out waiting for condition on expression: ' +
                           expression), timeout)
        return _evaluate_expr()
Ejemplo n.º 30
0
    def _WaitForRealModemManagersToDie(self):
        """
        Wait for real modem managers to quit. Die otherwise.

        Sometimes service stopper does not kill ModemManager process, if it is
        launched by something other than upstart. We want to ensure that the
        process is dead before continuing.

        This method can block for up to a minute. Sometimes, ModemManager can
        take up to a 10 seconds to die after service stopper has stopped it. We
        wait for it to clean up before concluding that the process is here to
        stay.

        @raises: PseudoModemManagerContextException if a modem manager process
                does not quit in a reasonable amount of time.
        """
        def _IsProcessRunning(process):
            try:
                utils.run('pgrep -x %s' % process)
                return True
            except error.CmdError:
                return False

        for manager in self.REAL_MANAGER_PROCESSES:
            try:
                utils.poll_for_condition(
                        lambda:not _IsProcessRunning(manager),
                        timeout=self.WAIT_FOR_HARDWARE_TIMEOUT_SECONDS)
            except utils.TimeoutError:
                err_msg = ('%s is still running. '
                           'It may interfere with pseudomodem.' %
                           manager)
                logging.error(err_msg)
                raise PseudoModemManagerContextException(err_msg)
Ejemplo n.º 31
0
    def _disable_internet(self, ping_server='google.com'):
        """Disable the internet connection"""
        self._internet_was_disabled = True
        try:
            logging.debug('Before disconnect: %s', utils.run('ifconfig'))
            # DUTs in the lab have a service called recover_duts that is used to
            # check that the DUT is online and if it is not it will bring it
            # back online. We will need to stop this service for the length
            # of this test.
            utils.stop_service('recover_duts', ignore_status=True)
            for eth in self._NETWORK_INTERFACES:
                result = utils.run('ifconfig %s down' % eth,
                                   ignore_status=True)
                logging.debug(result)

            # Print ifconfig to help debug DUTs that stay online.
            logging.debug('After disconnect: %s', utils.run('ifconfig'))

            # Make sure we are offline
            utils.poll_for_condition(
                lambda: utils.ping(ping_server, deadline=5, timeout=5) != 0,
                timeout=60,
                sleep_interval=1,
                desc='Ping failure while offline.')
        except (error.CmdError, utils.TimeoutError):
            logging.exception('Failed to disconnect one or more interfaces.')
            logging.debug(utils.run('ifconfig', ignore_status=True))
            raise error.TestFail('Disabling the internet connection failed.')
    def run_once(self):
        """Runs the integration test."""
        # Create the browser instance.
        camera_path = os.path.join(os.path.dirname(__file__),
                                   'src/camera/build/camera')
        browser = chrome.Chrome(extension_paths=[camera_path],
                                is_component=False)

        # Start the Camera app.
        extension = browser.get_extension(camera_path)
        extension.ExecuteJavaScript('camera.bg.createForTesting();')

        # Wait until the Camera app acquires the stream.
        js_is_capturing = (
            'camera.bg.appWindow && '
            'camera.bg.appWindow.contentWindow.camera && '
            'camera.bg.appWindow.contentWindow.camera.Camera && '
            'camera.bg.appWindow.contentWindow.camera.Camera.getInstance().'
            'cameraView.capturing')

        # Verify if the camera initializes correctly in up to 30 seconds.
        utils.poll_for_condition(
            condition=lambda: extension.EvaluateJavaScript(js_is_capturing),
            exception=error.TestError('Camera initialization timed out.'),
            sleep_interval=1,
            timeout=30)