def _test_javascript_blocked_for_urls(self, policy_value):
        """Verify CrOS enforces the JavaScriptBlockedForUrls policy.

        When JavaScriptBlockedForUrls is undefined, JavaScript execution shall
        be allowed on all pages. When JavaScriptBlockedForUrls contains one or
        more URL patterns, JavaScript execution shall be blocked only on the
        pages whose URL matches any of the listed patterns.

        Note: This test does not use self.navigate_to_url(), because it can
        not depend on methods that evaluate or execute JavaScript.

        @param policy_value: policy value for this case.

        """
        tab = self.cr.browser.tabs.New()
        tab.Activate()
        tab.Navigate(self.TEST_URL)
        time.sleep(1)

        utils.poll_for_condition(
            lambda: tab.url == self.TEST_URL,
            exception=error.TestError('Test page is not ready.'))
        javascript_is_allowed = self._can_execute_javascript(tab)

        if policy_value is not None and (self.WEB_HOST in policy_value
                                         or self.TEST_URL in policy_value):
            # If |WEB_HOST| is in |policy_value|, then JavaScript execution
            # should be blocked. If execution is allowed, raise an error.
            if javascript_is_allowed:
                raise error.TestFail('JavaScript should be blocked.')
        else:
            if not javascript_is_allowed:
                raise error.TestFail('JavaScript should be allowed.')
        tab.Close()
Exemplo n.º 2
0
    def _test_udev_report_atmel(self):
        """Test that atmel trackpad failure can trigger udev crash report."""
        DRIVER_DIR = '/sys/bus/i2c/drivers/atmel_mxt_ts'
        has_atmel_device = False
        if os.path.exists(DRIVER_DIR):
            for filename in os.listdir(DRIVER_DIR):
                if os.path.isdir(os.path.join(DRIVER_DIR, filename)):
                    has_atmel_device = True

        if not has_atmel_device:
            logging.info('No atmel device, skip the test')
            return None

        self._set_consent(True)

        # Use udevadm to trigger a fake udev event representing atmel driver
        # failure. The uevent match rule in 99-crash-reporter.rules is
        # ACTION=="change", SUBSYSTEM=="i2c", DRIVER=="atmel_mxt_ts",
        # ENV{ERROR}=="1" RUN+="/sbin/crash_reporter
        # --udev=SUBSYSTEM=i2c-atmel_mxt_ts:ACTION=change"
        utils.system('udevadm control --property=ERROR=1', ignore_status=True)
        utils.system(
            'udevadm trigger '
            '--action=change '
            '--subsystem-match=i2c '
            '--attr-match=driver=atmel_mxt_ts',
            ignore_status=True)
        utils.system('udevadm control --property=ERROR=0', ignore_status=True)

        utils.poll_for_condition(
            self.CheckAtmelCrashes,
            timeout=60,
            exception=error.TestFail('No valid Atmel crash reports'))
    def _can_execute_javascript(self):
        """
        Determine whether JavaScript is allowed to run on the given page.

        @param tab: browser tab containing JavaScript to run.

        Note: This test does not use self.navigate_to_url(), because it can
        not depend on methods that evaluate or execute JavaScript.

        """
        tab = self.cr.browser.tabs.New()
        tab.Activate()
        tab.Navigate(self.TEST_URL)
        time.sleep(1)

        utils.poll_for_condition(
            lambda: tab.url == self.TEST_URL,
            exception=error.TestError('Test page is not ready.'))

        try:
            utils.poll_for_condition(
                lambda: tab.EvaluateJavaScript('jsAllowed', timeout=2),
                exception=error.TestError('Test page is not ready.'))
            return True
        except (EvaluateException, utils.TimeoutError):
            return False
    def _test_javascript_blocked_for_urls(self, policy_value, policies_json):
        """Verify CrOS enforces the JavaScriptBlockedForUrls policy.

        When JavaScriptBlockedForUrls is undefined, JavaScript execution shall
        be allowed on all pages. When JavaScriptBlockedForUrls contains one or
        more URL patterns, JavaScript execution shall be allowed only on the
        pages whose URL matches any of the listed patterns.

        @param policy_value: policy value expected on chrome://policy page.
        @param policies_json: policy JSON data to send to the fake DM server.

        """
        self.setup_case(self.POLICY_NAME, policy_value, policies_json)
        logging.info('Running _test_javascript_blocked_for_urls(%s, %s)',
                     policy_value, policies_json)

        tab = self.cr.browser.tabs.New()
        tab.Activate()
        tab.Navigate(self.TEST_URL)
        utils.poll_for_condition(
            lambda: tab.url == self.TEST_URL,
            exception=error.TestError('Test page is not ready.'))
        time.sleep(1)

        javascript_is_allowed = self._can_execute_javascript(tab)
        if policy_value is not None and self.URL_HOST in policy_value:
            # If |URL_HOST| is in |policy_value|, then JavaScript execution
            # should be blocked. If execution is allowed, raise an error.
            if javascript_is_allowed:
                raise error.TestFail('JavaScript should be blocked.')
        else:
            if not javascript_is_allowed:
                raise error.TestFail('JavaScript should be allowed.')
        tab.Close()
    def _stop_flash_if_running(self, timeout_sec=10):
        """
        Terminate all Flash processes.

        @param timeout_sec: maximum seconds to wait for processes to die.
        @raises: error.AutoservPidAlreadyDeadError if Flash process is dead.
        @raises: utils.TimeoutError if Flash processes are still running
                 after timeout_sec.

        """
        def kill_flash_process():
            """
            Kill all running flash processes.

            """
            pids = utils.get_process_list('chrome', '--type=ppapi')
            for pid in pids:
                try:
                    utils.nuke_pid(int(pid))
                except error.AutoservPidAlreadyDeadError:
                    pass
            return pids

        # Wait for kill_flash_process to kill all flash processes
        utils.poll_for_condition(lambda: not kill_flash_process(),
                                 timeout=timeout_sec)
Exemplo n.º 6
0
    def _wait_for_page_ready(self, tab):
        """Wait for JavaScript on page in |tab| to set the pageReady flag.

        @param tab: browser tab with page to load.
        """
        utils.poll_for_condition(
            lambda: tab.EvaluateJavaScript('pageReady'),
            exception=error.TestError('Test page is not ready.'))
    def __wait_for_subprocess(self):
        """Waits for a subprocess that matches self.pattern."""
        def _subprocess_pid(pattern):
            pid = utils.system_output('ps -U chronos -o pid,args | grep %s'
                                      % pattern, ignore_status=True)
            return pid.lstrip().split(' ')[0] if pid else 0

        utils.poll_for_condition(lambda: _subprocess_pid(self.pattern))
        self.pid_bash = _subprocess_pid(self.pattern)
Exemplo n.º 8
0
    def _test_screenshot_apis(self, policy_value):
        """
        Verify DisableScreenshot policy blocks API calls.

        Attempts to capture the screen using all of the methods to capture
        the screen through the APIs. Captures should not happen when
        policy_value is True and should happen in the other cases.

        @param policy_value: policy value for this case

        @raises error.TestFail: In the case where the capture behavior
            does not match the policy value

        """
        tab = self.navigate_to_url('https://google.com')

        current_dir = os.path.dirname(os.path.realpath(__file__))

        for method in self.CAPTURE_CMDS:
            # Set the document.title to the test name
            tab.ExecuteJavaScript('document.title = "%s"' % method)

            # Call the extension's shortcut to trigger the API call
            self.player.blocking_playback(input_type='keyboard',
                                          filepath=os.path.join(
                                              current_dir,
                                              'keyboard_ctrl+shift+y'))

            # desktopCapture opens a prompt window that needs to be OKed
            if method == 'desktopCapture':
                self.player.blocking_playback_of_default_file(
                    input_type='keyboard', filename='keyboard_enter')

            # The document.title is used to pass information to and from
            # the DOM and the extension. The return value of the screenshot
            # API call is set to the document.title.
            try:
                utils.poll_for_condition(lambda: tab.EvaluateJavaScript(
                    'document.title != "%s"' % method),
                                         timeout=POLL_TIMEOUT)
                capture = tab.EvaluateJavaScript('document.title')
            except utils.TimeoutError:
                capture = None

            if capture == 'undefined':
                capture = None

            if policy_value:
                if capture is not None:
                    raise error.TestFail('Screen should not be captured. '
                                         'method = %s, capture = %s' %
                                         (method, capture))
            elif capture is None:
                raise error.TestFail('Screen should be captured. '
                                     'method = %s, capture = %s' %
                                     (method, capture))
    def _can_execute_javascript(self, tab):
        """Determine whether JavaScript is allowed to run on the given page.

        @param tab: browser tab containing JavaScript to run.
        """
        try:
            utils.poll_for_condition(
                lambda: tab.EvaluateJavaScript('jsAllowed', timeout=2),
                exception=error.TestError('Test page is not ready.'))
            return True
        except:
            return False
Exemplo n.º 10
0
    def wait_for_extension(self):
        """Wait for the extension to install so we can open it."""
        def load_page():
            self.tab = self.navigate_to_url(self.EXTENSION_PAGE, self.tab)
            return self.tab.EvaluateJavaScript(
                "document.querySelector('#cert-enrollment') !== null")

        utils.poll_for_condition(
            load_page,
            timeout=15,
            sleep_interval=1,
            desc='Timed out waiting for extension to install.')
    def _is_flash_running(self):
        """
        Check if a Flash process is running.

        @returns: True if one or more flash processes are running.

        """
        try:
            utils.poll_for_condition(
                lambda: utils.get_process_list('chrome', '--type=ppapi'))
        except utils.TimeoutError:
            return False

        return True
Exemplo n.º 12
0
    def wait_for_active_stream_count(self, expected_count):
        """
        Waits for there to be the expected number of audio streams.

        @param expected_count: Number of audio streams to wait for.

        @raises error.TestError: if there is a timeout before the there is the
        desired number of audio streams.

        """
        utils.poll_for_condition(
            lambda: cras_utils.get_active_stream_count() == expected_count,
            exception=error.TestError(
                'Timeout waiting active stream count to become %d' %
                expected_count))
Exemplo n.º 13
0
Arquivo: api.py Projeto: gimlids/riker
def ensure_running(instances, timeout=600, poll_delay=10):
    if len(instances) == 0:
        return
    log('info', 'Waiting for instances {} to be running'.format(instances), show_header=True)
    def get_status():
        try:
            return aws.conn.get_all_instance_status([inst.id for inst in instances])
        except boto.exception.EC2ResponseError:
            log('info', 'No status yet')
    def is_status_ok(statuses):
        #for s in statuses:
        #    log('info', 'state={}, system_status={}'.format(s.state_name, s.system_status.status))
        return len(statuses) > 0 and \
            all([s.state_name == 'running' and s.system_status.status == 'ok' for s in statuses])
    poll_for_condition(get_status, is_status_ok, timeout, poll_delay)
    [instance.update() for instance in instances]
Exemplo n.º 14
0
Arquivo: api.py Projeto: gimlids/riker
def ensure_complete(image_ids, timeout=1200, poll_delay=10):
    if len(image_ids) == 0:
        return
    log('info', 'Waiting for image {} to be available'.format(image_ids), show_header=True)
    def get_image(image_id):
        def _get_image():
            try:
                return aws.conn.get_image(image_id)
            except boto.exception.EC2ResponseError:
                log('info', 'No state yet')
        return _get_image
    def is_image_available(image):
        #log('info', 'state={}'.format(image.state if image is not None else 'noimage',))
        return image is not None and image.state == 'available'
    for image_id in image_ids:
        poll_for_condition(get_image(image_id), is_image_available, timeout, poll_delay)
    def _screenshot_file_exists(self):
        """
        Return True if screenshot was captured. else returns False.

        @returns boolean indicating if screenshot file was saved or not.

        """
        try:
            utils.poll_for_condition(
                lambda: len(glob.glob(self._SCREENSHOT_FILENAME)) > 0,
                timeout=POLL_TIMEOUT,
                sleep_interval=POLL_FREQUENCY)
        except utils.TimeoutError:
            logging.info('Screenshot file not found.')
            return False

        logging.info('Screenshot file found.')
        return True
Exemplo n.º 16
0
Arquivo: api.py Projeto: ddnn55/riker
def ensure_running(instances, timeout=600, poll_delay=10):
    if len(instances) == 0:
        return
    log('info',
        'Waiting for instances {} to be running'.format(instances),
        show_header=True)

    def get_status():
        try:
            return aws.conn.get_all_instance_status(
                [inst.id for inst in instances])
        except boto.exception.EC2ResponseError:
            log('info', 'No status yet')

    def is_status_ok(statuses):
        #for s in statuses:
        #    log('info', 'state={}, system_status={}'.format(s.state_name, s.system_status.status))
        return len(statuses) > 0 and \
            all([s.state_name == 'running' and s.system_status.status == 'ok' for s in statuses])

    poll_for_condition(get_status, is_status_ok, timeout, poll_delay)
    [instance.update() for instance in instances]
Exemplo n.º 17
0
Arquivo: api.py Projeto: ddnn55/riker
def ensure_complete(image_ids, timeout=1200, poll_delay=10):
    if len(image_ids) == 0:
        return
    log('info',
        'Waiting for image {} to be available'.format(image_ids),
        show_header=True)

    def get_image(image_id):
        def _get_image():
            try:
                return aws.conn.get_image(image_id)
            except boto.exception.EC2ResponseError:
                log('info', 'No state yet')

        return _get_image

    def is_image_available(image):
        #log('info', 'state={}'.format(image.state if image is not None else 'noimage',))
        return image is not None and image.state == 'available'

    for image_id in image_ids:
        poll_for_condition(get_image(image_id), is_image_available, timeout,
                           poll_delay)
Exemplo n.º 18
0
    def call_api(self, button_id, field_id=None):
        """
        Call the API by clicking a button and checking its output fields.

        @param button_id: ID of the button element.
        @param field_id: Text field output is printed to (if any).

        @returns: Output of the call, if any.
        @raises error.TestFail: If the API call fails.

        """
        error_id = button_id + '-error'
        self.click_button(button_id)

        # Wait for the API to return 'OK' and raise an error if it doesn't.
        utils.poll_for_condition(
            lambda: 'OK' in self.field_value(error_id),
            timeout=5,
            exception=error.TestFail('API error: %s' %
                                     self.field_value(error_id)))

        if field_id:
            field = self.field_value(field_id)
            return field
Exemplo n.º 19
0
 def _wait_for_page_ready(self, tab):
     utils.poll_for_condition(
         lambda: tab.EvaluateJavaScript('pageReady'),
         exception=error.TestError('Test page is not ready.'))
    def run_once(self):
        with chrome.Chrome() as cr:
            test_processes = []
            test_processes.append(
                    _TestProcess('while :; do :; done ; # tst00','bash.*tst00'))
            # Create a test command that ignores SIGTERM.
            test_processes.append(
                    _TestProcess('trap 15; while :; do :; done ; # tst01',
                                 'bash.*tst01'))

            for test in test_processes:
                if not test.run_me_as_chronos():
                    raise error.TestFail(
                            'Did not start: bash %s' % test.command)

            session_manager = self.__get_session_manager_pid()
            if not session_manager:
                raise error.TestError('Could not find session manager pid')

            if not self.__has_chronos_processes(session_manager):
                raise error.TestFail(
                        'Expected to find processes owned by chronos that were '
                        'not started by the session manager while logged in.')

            cpids = self.__get_chronos_pids()

            # Sanity checks: make sure test jobs are in the list and still
            # running.
            for test in test_processes:
                if cpids.count(test.pid_bash) != 1:
                    raise error.TestFail('Job missing (%s - %s)' %
                                         (test.pid_bash, test.command))
                if self.__is_process_dead(test.pid_bash):
                    raise error.TestFail('Job prematurely dead (%s - %s)' %
                                         (test.pid_bash, test.command))

        logging.info('Logged out, searching for processes that should be dead.')

        # Wait until we have a new session manager.  At that point, all
        # old processes should be dead.
        old_session_manager = session_manager
        utils.poll_for_condition(
                lambda: old_session_manager != self.__get_session_manager_pid())
        session_manager = self.__get_session_manager_pid()

        # Make sure all pre-logout chronos processes are now dead.
        old_pid_count = 0
        for p in cpids:
            if not self.__is_process_dead(p):
                old_pid_count += 1
                proc_args = utils.system_output('ps -p %s -o args=' % p,
                                                ignore_status=True)
                logging.info('Found pre-logout chronos process pid=%s (%s) '
                             'still alive.', p, proc_args)
                # If p is something we started, kill it.
                for test in test_processes:
                    if (p == test.pid_su or p == test.pid_bash):
                        utils.signal_pid(p, signal.SIGKILL)

        if old_pid_count > 0:
            raise error.TestFail('Found %s chronos processes that survived '
                                 'logout.' % old_pid_count)