コード例 #1
0
    def set_active_node_id(self, node_id):
        """Sets the active node by node id.

        The current active node will be disabled first if the new active node
        is different from the current one.

        @param node_id: The node id obtained from cras_utils.get_cras_nodes.
                        Chrome.audio also uses this id to specify input/output
                        nodes.

        @raises AudioExtensionHandlerError if there is no such id.

        """
        if node_id in self._get_active_id():
            logging.debug('Node %s is already active.', node_id)
            return

        logging.debug('Setting active id to %s', node_id)

        self._extension.ExecuteJavaScript('window.__set_active_done = null;')

        self._extension.ExecuteJavaScript("""
                chrome.audio.setActiveDevices(
                    ['%s'],
                    function() {window.__set_active_done = true;});
                """ % (node_id))

        utils.wait_for_value(lambda: (self._extension.EvaluateJavaScript(
            "window.__set_active_done") != None),
                             expected_value=True)
コード例 #2
0
    def set_display_rotation(self,
                             display_id,
                             rotation,
                             delay_before_rotation=0,
                             delay_after_rotation=0):
        """Sets the display rotation for the specified display.

        @param display_id: id of the display to get modes from.
        @param rotation: degree of rotation
        @param delay_before_rotation: time in second for delay before rotation
        @param delay_after_rotation: time in second for delay after rotation
        """
        time.sleep(delay_before_rotation)
        extension = self._resource.get_extension(
            constants.MULTIMEDIA_TEST_EXTENSION)
        extension.ExecuteJavaScript("""
                window.__set_display_rotation_has_error = null;
                chrome.system.display.setDisplayProperties('%(id)s',
                    {"rotation": %(rotation)d}, () => {
                    if (runtime.lastError) {
                        console.error('Failed to set display rotation',
                            runtime.lastError);
                        window.__set_display_rotation_has_error = "failure";
                    } else {
                        window.__set_display_rotation_has_error = "success";
                    }
                });
                """ % {
            'id': display_id,
            'rotation': rotation
        })
        utils.wait_for_value(lambda: (extension.EvaluateJavaScript(
            'window.__set_display_rotation_has_error') != None),
                             expected_value="success")
        time.sleep(delay_after_rotation)
コード例 #3
0
    def wait_for_client_fastboot(self, timeout=30):
        """Wait for the client to come online in fastboot mode

        @param timeout: Time in seconds to wait the client
        @raise ConnectionError: Failed to wait DUT offline.
        """
        utils.wait_for_value(self.is_fastboot_mode, True, timeout_sec=timeout)
コード例 #4
0
    def set_fullscreen(self, is_fullscreen):
        """Sets the current window to full screen.

        @param is_fullscreen: True or False to indicate fullscreen state.
        @return True if success, False otherwise.
        """
        extension = self._resource.get_extension()
        if not extension:
            raise RuntimeError('Autotest extension not found')

        if is_fullscreen:
            window_state = "fullscreen"
        else:
            window_state = "normal"
        extension.ExecuteJavaScript("""
                var __status = 'Running';
                chrome.windows.update(
                        chrome.windows.WINDOW_ID_CURRENT,
                        {state: '%s'},
                        function() { __status = 'Done'; });
                """ % window_state)
        utils.wait_for_value(
            lambda: (extension.EvaluateJavaScript('__status') == 'Done'),
            expected_value=True)
        return self.is_fullscreen_enabled() == is_fullscreen
コード例 #5
0
    def setup_webpage(self, browser, test_url, num_fishes):
        """Open fish tank in a new tab.

        @param browser: The Browser object to run the test with.
        @param test_url: The URL to the aquarium test site.
        @param num_fishes: The number of fishes to run the test with.
        """
        # Create tab and load page. Set the number of fishes when page is fully
        # loaded.
        tab = browser.tabs.New()
        tab.Navigate(test_url)
        tab.Activate()
        self.active_tab = tab
        tab.WaitForDocumentReadyStateToBeComplete()

        # Set the number of fishes when document finishes loading.  Also reset
        # our own FPS counter and start recording FPS and rendering time.
        utils.wait_for_value(
            lambda: tab.EvaluateJavaScript(
                'if (document.readyState === "complete") {'
                '  setSetting(document.getElementById("%s"), %d);'
                '  g_crosFpsCounter.reset();'
                '  true;'
                '} else {'
                '  false;'
                '}' % self.test_settings[num_fishes]
            ),
            expected_value=True,
            timeout_sec=30)

        return tab
コード例 #6
0
    def test_refresh(self, tab):
        """Use keyboard shortcut to test Refresh (F3) key.

        @param tab: current tab.

        @raises error.TestFail if refresh unsuccessful.

        """
        # Set JS variable to initial true value to confirm refresh worked.
        # We are expecting this variable not to exist after the refresh.
        tab.EvaluateJavaScript("not_refreshed=true")
        js = 'not_refreshed == true'
        utils.wait_for_value(lambda: tab.EvaluateJavaScript(js),
                             expected_value=True)

        self._player.blocking_playback_of_default_file(input_type='keyboard',
                                                       filename='keyboard_f3')
        time.sleep(self._WAIT)

        # Verify we are still on the second url.
        self.verify_url(tab, self.URL_2)
        # Check to see not_refresh does not exist (results in exception).
        # If it does, the refresh was not successful.
        try:
            not_refresh = tab.EvaluateJavaScript(js)
            raise error.TestFail("Refresh unsuccesful.")
        except exceptions.EvaluateException:
            logging.info("Refresh successful.")
コード例 #7
0
    def set_resolution(self, display_id, width, height, timeout=3):
        """Sets the resolution of the specified display.

        @param display_id: id of the display to set resolution for.
        @param width: width of the resolution
        @param height: height of the resolution
        @param timeout: maximal time in seconds waiting for the new resolution
                to settle in.
        @raise TimeoutException when the operation is timed out.
        """

        extension = self._resource.get_extension(
                constants.DISPLAY_TEST_EXTENSION)
        extension.ExecuteJavaScript(
                """
                window.__set_resolution_progress = null;
                chrome.system.display.getInfo((info_array) => {
                    var mode;
                    for (var info of info_array) {
                        if (info['id'] == '%(id)s') {
                            for (var m of info['modes']) {
                                if (m['width'] == %(width)d &&
                                    m['height'] == %(height)d) {
                                    mode = m;
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    if (mode === undefined) {
                        console.error('Failed to select the resolution ' +
                            '%(width)dx%(height)d');
                        window.__set_resolution_progress = "mode not found";
                        return;
                    }

                    chrome.system.display.setDisplayProperties('%(id)s',
                        {'displayMode': mode}, () => {
                            if (chrome.runtime.lastError) {
                                window.__set_resolution_progress = "failed: " +
                                    chrome.runtime.lastError.message;
                            } else {
                                window.__set_resolution_progress = "succeeded";
                            }
                        }
                    );
                });
                """
                % {'id': display_id, 'width': width, 'height': height}
        )
        utils.wait_for_value(lambda: (
                extension.EvaluateJavaScript(
                    'window.__set_resolution_progress') != None),
                expected_value=True)
        result = extension.EvaluateJavaScript(
                'window.__set_resolution_progress')
        if result != 'succeeded':
            raise RuntimeError('Failed to set resolution: %r' % result)
コード例 #8
0
    def run_fish_test(self, browser, test_url, num_fishes, perf_log=True):
        """Run the test with the given number of fishes.

        @param browser: The Browser object to run the test with.
        @param test_url: The URL to the aquarium test site.
        @param num_fishes: The number of fishes to run the test with.
        @param perf_log: Report perf data only if it's set to True.
        """
        # Create tab and load page. Set the number of fishes when page is fully
        # loaded.
        tab = browser.tabs.New()
        tab.Navigate(test_url)
        tab.Activate()
        self.active_tab = tab
        tab.WaitForDocumentReadyStateToBeComplete()

        # Set the number of fishes when document finishes loading.  Also reset
        # our own FPS counter and start recording FPS and rendering time.
        utils.wait_for_value(
            lambda: tab.EvaluateJavaScript(
                'if (document.readyState === "complete") {'
                '  setSetting(document.getElementById("%s"), %d);'
                '  g_crosFpsCounter.reset();'
                '  true;'
                '} else {'
                '  false;'
                '}' % self.test_settings[num_fishes]),
            expected_value=True,
            timeout_sec=30)

        if self.kernel_sampler:
            self.kernel_sampler.start_sampling_thread()
        time.sleep(self.test_duration_secs)
        if self.kernel_sampler:
            self.kernel_sampler.stop_sampling_thread()
            self.kernel_sampler.output_flip_stats('flip_stats_%d' % num_fishes)
            self.flip_stats = {}

        if perf_log:
            # Get average FPS and rendering time, then close the tab.
            avg_fps = tab.EvaluateJavaScript('g_crosFpsCounter.getAvgFps();')
            if math.isnan(float(avg_fps)):
                raise error.TestFail('Could not get FPS count.')
            avg_render_time = tab.EvaluateJavaScript(
                'g_crosFpsCounter.getAvgRenderTime();')
            self.perf_keyval['avg_fps_%04d_fishes' % num_fishes] = avg_fps
            self.perf_keyval['avg_render_time_%04d_fishes' % num_fishes] = (
                avg_render_time)
            self.output_perf_value(
                description='avg_fps_%04d_fishes' % num_fishes,
                value=avg_fps,
                units='fps',
                higher_is_better=True)
            logging.info('%d fish(es): Average FPS = %f, '
                         'average render time = %f', num_fishes, avg_fps,
                         avg_render_time)
コード例 #9
0
    def get_window_info(self):
        """Gets the current window info from Chrome.system.window API.

        @return a dict for the information of the current window.
        """
        extension = self._resource.get_extension()
        extension.ExecuteJavaScript('window.__window_info = null;')
        extension.ExecuteJavaScript(
                "chrome.windows.getCurrent(function(info) {"
                "window.__window_info = info;})")
        utils.wait_for_value(lambda: (
                extension.EvaluateJavaScript("window.__window_info") != None),
                expected_value=True)
        return extension.EvaluateJavaScript("window.__window_info")
    def get_mute(self):
        """Determines whether audio output is muted.

        @returns Whether audio output is muted.

        """
        self._extension.ExecuteJavaScript('window.__output_muted = null;')
        self._extension.ExecuteJavaScript(
            "chrome.audio.getMute('OUTPUT', function(isMute) {"
            "window.__output_muted = isMute;})")
        utils.wait_for_value(lambda: (self._extension.EvaluateJavaScript(
            "window.__output_muted") != None),
                             expected_value=True)
        return self._extension.EvaluateJavaScript("window.__output_muted")
コード例 #11
0
    def get_display_info(self):
        """Gets the display info from Chrome.system.display API.

        @return array of dict for display info.
        """
        extension = self._resource.get_extension(
                constants.DISPLAY_TEST_EXTENSION)
        extension.ExecuteJavaScript('window.__display_info = null;')
        extension.ExecuteJavaScript(
                "chrome.system.display.getInfo(function(info) {"
                "window.__display_info = info;})")
        utils.wait_for_value(lambda: (
                extension.EvaluateJavaScript("window.__display_info") != None),
                expected_value=True)
        return extension.EvaluateJavaScript("window.__display_info")
コード例 #12
0
def _charge_control_by_ectool(is_charge):
    """execute ectool command.

    Args:
      is_charge: Boolean, True for charging, False for discharging.

    Returns:
      Boolean, True if the command success, False otherwise.
    """
    ec_cmd_discharge = 'ectool chargecontrol discharge'
    ec_cmd_normal = 'ectool chargecontrol normal'
    try:
        if is_charge:
            utils.run(ec_cmd_normal)
        else:
            utils.run(ec_cmd_discharge)
    except error.CmdError as e:
        logging.warning('Unable to use ectool: %s', e)
        return False

    success = utils.wait_for_value(
        lambda: (is_charge != bool(
            re.search(r'Flags.*DISCHARGING',
                      utils.run('ectool battery', ignore_status=True).stdout,
                      re.MULTILINE))),
        expected_value=True,
        timeout_sec=ECTOOL_CHARGECONTROL_TIMEOUT_SECS)
    return success
コード例 #13
0
def connect_bluetooth_module(bt_adapter, target_mac_address,
                             timeout=_CONNECT_TIMEOUT):
    """Controls Cros device to connect to bluetooth module on audio board.

    @param bt_adapter: A BluetoothDevice object to control bluetooth adapter
                       on Cros device.
    @param target_mac_address: The MAC address of bluetooth module to be
                               connected.
    @param timeout: Timeout in seconds to connect bluetooth module.

    @raises: ChameleonBluetoothAudioError if Cros device fails to connect to
             bluetooth module on audio board.

    """
    def _connect_device():
        logging.info('Try to connect to device')
        success = bt_adapter.connect_device(target_mac_address)
        if not success:
            logging.debug('Can not connect device, retry in 1 second.')
            time.sleep(1)
            return False
        logging.debug('Connection established.')
        return True

    # Connects bluetooth module with given MAC address.
    connected = utils.wait_for_value(_connect_device, True, timeout_sec=timeout)
    if not connected:
        raise ChameleonBluetoothAudioError(
                'Failed to let Cros device connect to bluetooth module %s' %
                target_mac_address)
コード例 #14
0
 def _is_screen_locked(self):
     """Return true if login status indicates that screen is locked."""
     login_status = utils.wait_for_value(
         lambda: self.cr.login_status['isScreenLocked'],
         expected_value=True,
         timeout_sec=self.IDLE_ACTION_DELAY)
     return login_status
コード例 #15
0
    def get_audio_info(self):
        """Gets the audio info from Chrome audio API.

        @returns: An array of [outputInfo, inputInfo].
                  outputInfo is an array of output node info dicts. Each dict
                  contains these key-value pairs:
                     string  id
                         The unique identifier of the audio output device.

                     string  name
                         The user-friendly name (e.g. "Bose Amplifier").

                     boolean isActive
                         True if this is the current active device.

                     boolean isMuted
                         True if this is muted.

                     double  volume
                         The output volume ranging from 0.0 to 100.0.

                  inputInfo is an arrya of input node info dicts. Each dict
                  contains these key-value pairs:
                     string  id
                         The unique identifier of the audio input device.

                     string  name
                         The user-friendly name (e.g. "USB Microphone").

                     boolean isActive
                         True if this is the current active device.

                     boolean isMuted
                         True if this is muted.

                     double  gain
                         The input gain ranging from 0.0 to 100.0.

        """
        self._extension.ExecuteJavaScript('window.__audio_info = null;')
        self._extension.ExecuteJavaScript(
            "chrome.audio.getInfo(function(outputInfo, inputInfo) {"
            "window.__audio_info = [outputInfo, inputInfo];})")
        utils.wait_for_value(lambda: (self._extension.EvaluateJavaScript(
            "window.__audio_info") != None),
                             expected_value=True)
        return self._extension.EvaluateJavaScript("window.__audio_info")
コード例 #16
0
def connect_bluetooth_module_full_flow(bt_adapter, target_mac_address,
                             timeout=_SEARCH_TIMEOUT):
    """Controls Cros device to connect to bluetooth module on audio board.

    @param bt_adapter: A BluetoothDevice object to control bluetooth adapter
                       on Cros device.
    @param target_mac_address: The MAC address of bluetooth module to be
                               connected.
    @param timeout: Timeout in seconds to search for bluetooth module.

    @raises: ChameleonBluetoothAudioError if Cros device fails to connect to
             bluetooth module on audio board.

    """
    # Resets bluetooth adapter on Cros device.
    if not bt_adapter.reset_on():
        raise ChameleonBluetoothAudioError(
                'Failed to reset bluetooth adapter on Cros host.'
                ' You should check if controller is available on Cros host'
                ' using bluetoothctl.')

    # Starts discovery mode of bluetooth adapter.
    if not bt_adapter.start_discovery():
        raise ChameleonBluetoothAudioError(
                'Failed to start discovery on bluetooth adapter on Cros host')

    def _find_device():
        """Controls bluetooth adapter to search for bluetooth module.

        @returns: True if there is a bluetooth device with MAC address
                  matches target_mac_address. False otherwise.

        """
        return bt_adapter.has_device(target_mac_address)

    # Searches for bluetooth module with given MAC address.
    found_device = utils.wait_for_value(_find_device, True, timeout_sec=timeout)
    if not bt_adapter.stop_discovery():
        raise ChameleonBluetoothAudioError(
            'Failed to stop discovery on bluetooth adapter on Cros host')

    if not found_device:
        raise ChameleonBluetoothAudioError(
                'Can not find bluetooth module with MAC address %s' %
                target_mac_address)

    pair_legacy_bluetooth_module(bt_adapter, target_mac_address)

    # Disconnects from bluetooth module to clean up the state.
    if not bt_adapter.disconnect_device(target_mac_address):
        raise ChameleonBluetoothAudioError(
                'Failed to let Cros device disconnect from bluetooth module %s' %
                target_mac_address)
    time.sleep(_SLEEP_AFTER_DISCONNECT)

    # Connects to bluetooth module.
    connect_bluetooth_module(bt_adapter, target_mac_address)

    logging.info('Bluetooth module at %s is connected', target_mac_address)
コード例 #17
0
    def run_once(self, run_time_sec=60):
        """
        @param run_time_sec: time to run the test
        """
        if run_time_sec < 30:
            raise error.TestError('Must run for at least 30 seconds')

        with chrome.Chrome(init_network_controller=True) as cr:
            # Start powerd if not started.  Set timeouts for quick idle events.
            run_time_ms = run_time_sec * 1000
            # At the time of writing this test, the video detector gets a status
            # update from Chrome every ten seconds.
            dim_ms = 10000
            off_ms = max(3600000, run_time_ms * 10)
            prefs = {
                'has_ambient_light_sensor': 0,
                'ignore_external_policy': 1,
                'plugged_dim_ms': dim_ms,
                'plugged_off_ms': off_ms,
                'unplugged_dim_ms': dim_ms,
                'unplugged_off_ms': off_ms,
            }
            self._pref_change = power_utils.PowerPrefChanger(prefs)

            keyvals = {}

            # Start with max brightness, so we can easily detect dimming.
            power_utils.BacklightController().set_brightness_to_max()
            backlight = power_utils.Backlight()
            initial_brightness = \
                utils.wait_for_value(backlight.get_max_level)

            # Open a tab to play video.
            cr.browser.platform.SetHTTPServerDirectories(self.bindir)
            tab = cr.browser.tabs[0]
            tab.Navigate(
                cr.browser.platform.http_server.UrlOf(
                    os.path.join(self.bindir, 'fade.html')))
            tab.WaitForDocumentReadyStateToBeComplete()

            # Sleep until the runtime is up.
            time.sleep(run_time_sec)

            # Stop powerd to avoid dimming when the video stops.
            utils.system_output('stop powerd')

            final_brightness = backlight.get_level()

            # Check that the backlight stayed the same.
            if initial_brightness != final_brightness:
                raise error.TestFail(
                    ('Backlight level changed from %d to %d when it should ' + \
                     'have stayed the same.') %
                    (initial_brightness, final_brightness))

            keyvals['initial_brightness'] = initial_brightness
            keyvals['final_brightness'] = final_brightness
            self.write_perf_keyval(keyvals)
    def set_active_node_id(self, node_id):
        """Sets the active node by node id.

        The current active node will be disabled first if the new active node
        is different from the current one.

        @param node_id: Node id obtained from cras_utils.get_cras_nodes.
                        Chrome.audio also uses this id to specify input/output
                        nodes.
                        Note that node id returned by cras_utils.get_cras_nodes
                        is a number, while chrome.audio API expects a string.

        @raises AudioExtensionHandlerError if there is no such id.

        """
        nodes = self.get_audio_devices({})
        target_node = None
        for node in nodes:
            if node['id'] == str(node_id):
                target_node = node
                break

        if not target_node:
            logging.error('Node %s not found.', node_id)
            raise AudioExtensionHandlerError('Node id not found')

        if target_node['isActive']:
            logging.debug('Node %s is already active.', node_id)
            return

        logging.debug('Setting active id to %s', node_id)

        self._extension.ExecuteJavaScript('window.__set_active_done = null;')

        is_input = target_node['streamType'] == 'INPUT'
        stream_type = 'input' if is_input else 'output'
        self._extension.ExecuteJavaScript("""
                chrome.audio.setActiveDevices(
                    {'%s': ['%s']},
                    function() {window.__set_active_done = true;});
                """ % (stream_type, node_id))

        utils.wait_for_value(lambda: (self._extension.EvaluateJavaScript(
            "window.__set_active_done") != None),
                             expected_value=True)
コード例 #19
0
    def ccd_open_from_ap(self):
        """Start the open process and press the power button."""
        self._ccd_open_last_len = 0

        self._ccd_open_stdout = StringIO.StringIO()

        ccd_open_cmd = utils.sh_escape('gsctool -a -o')
        full_ssh_cmd = '%s "%s"' % (self.host.ssh_command(options='-tt'),
                                    ccd_open_cmd)
        # Start running the Cr50 Open process in the background.
        self._ccd_open_job = utils.BgJob(full_ssh_cmd,
                                         nickname='ccd_open',
                                         stdout_tee=self._ccd_open_stdout,
                                         stderr_tee=utils.TEE_TO_LOGS)

        if self._ccd_open_job == None:
            raise error.TestFail('could not start ccd open')

        try:
            # Wait for the first gsctool power button prompt before starting the
            # open process.
            logging.info(self._get_ccd_open_output())
            # Cr50 starts out by requesting 5 quick presses then 4 longer
            # power button presses. Run the quick presses without looking at the
            # command output, because getting the output can take some time. For
            # the presses that require a 1 minute wait check the output between
            # presses, so we can catch errors
            #
            # run quick presses for 30 seconds. It may take a couple of seconds
            # for open to start. 10 seconds should be enough. 30 is just used
            # because it will definitely be enough, and this process takes 300
            # seconds, so doing quick presses for 30 seconds won't matter.
            end_time = time.time() + 30
            while time.time() < end_time:
                self.servo.power_short_press()
                logging.info('short int power button press')
                time.sleep(self.PP_SHORT_INTERVAL)
            # Poll the output and press the power button for the longer presses.
            utils.wait_for_value(self._check_open_and_press_power_button,
                                 expected_value=True,
                                 timeout_sec=self.cr50.PP_LONG)
        except Exception, e:
            logging.info(e)
            raise
    def set_mute(self, mute):
        """Mutes the audio output using chrome.audio API.

        @param mute: True to mute. False otherwise.

        """
        is_muted_string = 'true' if mute else 'false'

        self._extension.ExecuteJavaScript('window.__set_mute_done = null;')

        self._extension.ExecuteJavaScript("""
                chrome.audio.setMute(
                    'OUTPUT', %s,
                    function() {window.__set_mute_done = true;});
                """ % (is_muted_string))

        utils.wait_for_value(lambda: (self._extension.EvaluateJavaScript(
            "window.__set_mute_done") != None),
                             expected_value=True)
コード例 #21
0
    def wait_external_display_connected(self, display):
        """Waits for the specified external display to be connected.

        @param display: The display name as a string, like 'HDMI1', or
                        False if no external display is expected.
        @return: True if display is connected; False otherwise.
        """
        result = utils.wait_for_value(self.get_external_connector_name,
                                      expected_value=display)
        return result == display
コード例 #22
0
    def wait_for_file(self, name, timeout=120):
        """Wait until a file is created.

           @param name: File name.
           @param timeout: Timeout waiting for the file.
           @raises error.TestFail: Raised in case of timeout.

        """
        if not utils.wait_for_value(lambda: os.path.isfile(name),
                                    expected_value=True,
                                    timeout_sec=timeout):
            raise error.TestFail('Timeout waiting for %r' % name)
コード例 #23
0
    def _check_api_available(self):
        """Checks chrome.audio is available.

        @raises: AudioExtensionHandlerError if extension is not available.

        """
        success = utils.wait_for_value(
            lambda:
            (self._extension.EvaluateJavaScript("chrome.audio") != None),
            expected_value=True)
        if not success:
            raise AudioExtensionHandlerError('chrome.audio is not available.')
コード例 #24
0
    def set_active_volume(self, volume):
        """Sets the active audio output volume using chrome.audio API.

        This method also unmutes the node.

        @param volume: Volume to set (0~100).

        """
        output_id, _ = self._get_active_id()
        logging.debug('output_id: %s', output_id)

        self._extension.ExecuteJavaScript('window.__set_volume_done = null;')

        self._extension.ExecuteJavaScript("""
                chrome.audio.setProperties(
                    '%s',
                    {isMuted: false, volume: %s},
                    function() {window.__set_volume_done = true;});
                """ % (output_id, volume))

        utils.wait_for_value(lambda: (self._extension.EvaluateJavaScript(
            "window.__set_volume_done") != None),
                             expected_value=True)
コード例 #25
0
    def set_mute(self, mute):
        """Mutes the active audio output using chrome.audio API.

        @param mute: True to mute. False otherwise.

        """
        output_id, _ = self._get_active_id()
        logging.debug('output_id: %s', output_id)

        is_muted_string = 'true' if mute else 'false'

        self._extension.ExecuteJavaScript('window.__set_mute_done = null;')

        self._extension.ExecuteJavaScript("""
                chrome.audio.setProperties(
                    '%s',
                    {isMuted: %s},
                    function() {window.__set_mute_done = true;});
                """ % (output_id, is_muted_string))

        utils.wait_for_value(lambda: (self._extension.EvaluateJavaScript(
            "window.__set_mute_done") != None),
                             expected_value=True)
コード例 #26
0
    def wait_for_stable_ccd_state(self, state, timeout, raise_error):
        """Wait up to timeout seconds for CCD to be 'on' or 'off'

        Verify ccd is off or on and remains in that state for 3 seconds.

        Args:
            state: a string either 'on' or 'off'.
            timeout: time in seconds to wait
            raise_error: Raise TestFail if the value is state is not reached.

        Raises:
            TestFail if ccd never reaches the specified state
        """
        wait_for_enable = state == 'on'
        logging.info("Wait until ccd is %s",
                     'on' if wait_for_enable else 'off')
        enabled = utils.wait_for_value(self.ccd_is_enabled,
                                       wait_for_enable,
                                       timeout_sec=timeout)
        if enabled != wait_for_enable:
            error_msg = ("timed out before detecting ccd '%s'" %
                         ('on' if wait_for_enable else 'off'))
            if raise_error:
                raise error.TestFail(error_msg)
            logging.warning(error_msg)
        else:
            # Make sure the state doesn't change.
            enabled = utils.wait_for_value(self.ccd_is_enabled,
                                           not enabled,
                                           timeout_sec=self.SHORT_WAIT)
            if enabled != wait_for_enable:
                error_msg = ("CCD switched %r after briefly being %r" %
                             ('on' if enabled else 'off', state))
                if raise_error:
                    raise error.TestFail(error_msg)
                logging.info(error_msg)
        logging.info("ccd is %r", 'on' if enabled else 'off')
コード例 #27
0
    def wait_for_attestation_prepared(self, timeout=120):
        """Wait until attestation is prepared, i.e.
           AttestationPrepareForEnrollment init stage is done.

           @param timeout: Timeout waiting for attestation to be
                           prepared.
           @raises error.TestFail: Raised in case of timeout.

        """
        if not utils.wait_for_value(is_attestation_prepared,
                                    expected_value=True,
                                    timeout_sec=timeout):
            logging.debug('tpm_more_status: %r',
                          cryptohome.get_tpm_more_status())
            raise error.TestFail('Timeout waiting for attestation_prepared')
コード例 #28
0
    def _is_screen_locked(self):
        """Return true if login status indicates that screen is locked."""
        def _get_screen_locked():
            """Return isScreenLocked property, if defined."""
            login_status = self.cr.login_status
            if (isinstance(login_status, dict)
                    and 'isScreenLocked' in login_status):
                return self.cr.login_status['isScreenLocked']
            else:
                logging.debug('login_status: %s', login_status)
                return None

        return utils.wait_for_value(_get_screen_locked,
                                    expected_value=True,
                                    timeout_sec=self.IDLE_ACTION_DELAY)
コード例 #29
0
def wait_output_connected(output):
    """Wait for output to connect.

    @param output: The output name as a string.

    @return: True if output is connected; False otherwise.
    """
    def _is_connected(output):
        """Helper function."""
        outputs = get_display_output_state()
        if output not in outputs:
            return False
        return outputs[output]

    return utils.wait_for_value(lambda: _is_connected(output),
                                expected_value=True)
コード例 #30
0
    def _wait_for_login_status(self, attribute, value, timeout):
        """Return when attribute has value, or its current value on timeout.

        Login_status is a dictionary of attributes that describe the login
        status of the current session. It contains values for the following
        attributes: isLoggedIn, isRegularUser, isOwner, isKiosk, isGuest,
        isScreenLocked, userImage, email, and displayEmail.

        @param attribute: String attribute key to be measured.
        @param value: Boolean attribute value expected.
        @param timeout: integer seconds till timeout.
        @returns dict of login status.

        """
        attribute_value = utils.wait_for_value(
            lambda: self.cr.login_status[attribute],
            expected_value=value,
            timeout_sec=timeout)
        return attribute_value