def wait_for_chrome_ready(old_session, host=None, timeout=RESTART_UI_TIMEOUT): """Wait until a new Chrome login prompt is on screen and ready. The standard formula to check whether the prompt has appeared yet is with a pattern like the following: session = get_chrome_session_ident() logout() wait_for_chrome_ready(session) Args: old_session: identifier for the login prompt prior to restarting Chrome. host: If not None, a host object on which to test Chrome state, rather than running commands on the local host. timeout: float number of seconds to wait Raises: TimeoutError: Login prompt didn't get up before timeout """ utils.poll_for_condition( condition=lambda: old_session != get_chrome_session_ident(host), exception=utils.TimeoutError('Timed out waiting for login prompt'), timeout=timeout, sleep_interval=1.0)
def _update_dut(self, host, update_url): """ Update the first DUT normally and save the update engine logs. @param host: the host object for the first DUT. @param update_url: the url to call for updating the DUT. """ logging.info('Updating first DUT with a regular update.') host.reboot() # Sometimes update request is lost if checking right after reboot so # make sure update_engine is ready. self._set_active_p2p_host(self._hosts[0]) utils.poll_for_condition(condition=self._is_update_engine_idle, desc='Waiting for update engine idle') try: updater = autoupdater.ChromiumOSUpdater(update_url, host) updater.update_image() except autoupdater.RootFSUpdateError: logging.exception('Failed to update the first DUT.') raise error.TestFail('Updating the first DUT failed. Error: %s.' % self._get_last_error_string()) finally: logging.info('Saving update engine logs to results dir.') host.get_file(self._UPDATE_ENGINE_LOG, os.path.join(self.resultsdir, 'update_engine.log_first_dut')) host.reboot()
def _test_Arc_cam_status(self, case): """ Test if the Arc Camera has been opened, or not. @param case: bool, value of the VideoCaptureAllowed policy. """ # The Camera can take a few seconds to respond, wait for it. utils.poll_for_condition( lambda: self.did_cam_app_respond(), exception=error.TestFail('Camera APP did not respond.'), timeout=10, sleep_interval=1, desc='Wait for Camera to respond.') # Once the Camera is open, get the status from logcat. cam_device_resp, disabled_resp = self._check_cam_status() if case or case is None: if 'opened successfully' not in cam_device_resp or disabled_resp: raise error.TestFail( 'Camera did not launch when it should have.') else: if ('opened successfully' in cam_device_resp or 'disabled by policy' not in disabled_resp): raise error.TestFail( 'Camera did launch when it should not have.')
def _update_via_p2p(self, host, update_url): """ Update the second DUT via P2P from the first DUT. We perform a non-interactive update and update_engine will check for other devices that have P2P enabled and download from them instead. @param host: The second DUT. @param update_url: the url to call for updating the DUT. """ logging.info('Updating second host via p2p.') host.reboot() self._set_active_p2p_host(self._hosts[1]) utils.poll_for_condition(condition=self._is_update_engine_idle, desc='Waiting for update engine idle') try: # Start a non-interactive update which is required for p2p. updater = autoupdater.ChromiumOSUpdater(update_url, host, interactive=False) updater.update_image() except autoupdater.RootFSUpdateError: logging.exception('Failed to update the second DUT via P2P.') raise error.TestFail('Failed to update the second DUT. Error: %s' % self._get_last_error_string()) finally: logging.info('Saving update engine logs to results dir.') host.get_file(self._UPDATE_ENGINE_LOG, os.path.join(self.resultsdir, 'update_engine.log_second_dut')) # Return the update_engine logs so we can check for p2p entries. return host.run('cat %s' % self._UPDATE_ENGINE_LOG).stdout
def run_once(self): """Body of the test.""" get_assoc_params = lambda conf: xmlrpc_datatypes.AssociationParameters( ssid=self.context.router.get_ssid(instance=0), bgscan_config=conf) get_ping_config = lambda period: ping_runner.PingConfig( self.context.get_wifi_addr(), interval=self.PING_INTERVAL_SECONDS, count=int(period / self.PING_INTERVAL_SECONDS)) self.context.configure(self._config_first_ap) bgscan_config = xmlrpc_datatypes.BgscanConfiguration( short_interval=self.CONFIGURED_BGSCAN_INTERVAL_SECONDS, long_interval=self.CONFIGURED_BGSCAN_INTERVAL_SECONDS, method=xmlrpc_datatypes.BgscanConfiguration.SCAN_METHOD_SIMPLE) self.context.assert_connect_wifi(get_assoc_params(bgscan_config)) logging.info('Pinging router with background scans for %d seconds.', self.BGSCAN_SAMPLE_PERIOD_SECONDS) result_bgscan = self.context.client.ping( get_ping_config(self.BGSCAN_SAMPLE_PERIOD_SECONDS)) logging.info('Ping statistics with bgscan: %r', result_bgscan) # Bring up a second AP, make sure that it shows up in bgscans. self._config_second_ap.ssid = self.context.router.get_ssid() self.context.configure(self._config_second_ap, multi_interface=True) logging.info('Without a ping running, ensure that bgscans succeed.') ap_mac = self.context.router.get_hostapd_mac(ap_num=1) logging.debug('Looking for BSS %s', ap_mac) iw = iw_runner.IwRunner(remote_host=self.context.client.host) utils.poll_for_condition( condition=lambda: self._find_bss_matching_mac_addr(iw, ap_mac), exception=error.TestFail( 'Background scans should detect new BSSes ' 'within an associated ESS.'), timeout=self.BGSCAN_SAMPLE_PERIOD_SECONDS, sleep_interval=1) self.context.router.deconfig_aps(instance=1) self.context.client.shill.disconnect( self.context.router.get_ssid(instance=0)) # Reconfigure AP, so the new bgscan setting can be correctly applied. self.context.configure(self._config_first_ap) # Gather some statistics about ping latencies without scanning going on. self.context.assert_connect_wifi(get_assoc_params(None)) logging.info('Pinging router without background scans for %d seconds.', self.NO_BGSCAN_SAMPLE_PERIOD_SECONDS) result_no_bgscan = self.context.client.ping( get_ping_config(self.NO_BGSCAN_SAMPLE_PERIOD_SECONDS)) logging.info('Ping statistics without bgscan: %r', result_no_bgscan) if result_no_bgscan.max_latency > self.THRESHOLD_BASELINE_LATENCY_MS: raise error.TestFail('RTT latency is too high even without ' 'background scans: %f' % result_no_bgscan.max_latency) if (result_bgscan.max_latency > self.LATENCY_MARGIN_MS + result_no_bgscan.avg_latency): raise error.TestFail( 'Significant difference in rtt due to bgscan: ' '%.1f > %.1f + %d' % (result_bgscan.max_latency, result_no_bgscan.avg_latency, self.LATENCY_MARGIN_MS))
def start_hostapd(self, configuration): """Start a hostapd instance described by conf. @param configuration HostapConfig object. """ # Figure out the correct interface. interface = self.get_wlanif(configuration.frequency, 'managed', configuration.min_streams) phy_name = self.iw_runner.get_interface(interface).phy conf_file = self.HOSTAPD_CONF_FILE_PATTERN % interface log_file = self.HOSTAPD_LOG_FILE_PATTERN % interface stderr_log_file = self.HOSTAPD_STDERR_LOG_FILE_PATTERN % interface control_interface = self.HOSTAPD_CONTROL_INTERFACE_PATTERN % interface hostapd_conf_dict = configuration.generate_dict( interface, control_interface, self.build_unique_ssid(suffix=configuration.ssid_suffix)) logging.debug('hostapd parameters: %r', hostapd_conf_dict) # Generate hostapd.conf. self.router.run( "cat <<EOF >%s\n%s\nEOF\n" % (conf_file, '\n'.join("%s=%s" % kv for kv in hostapd_conf_dict.iteritems()))) # Run hostapd. logging.info('Starting hostapd on %s(%s) channel=%s...', interface, phy_name, configuration.channel) self.router.run('rm %s' % log_file, ignore_status=True) self.router.run('stop wpasupplicant', ignore_status=True) start_command = '%s -dd -t %s > %s 2> %s & echo $!' % ( self.cmd_hostapd, conf_file, log_file, stderr_log_file) pid = int(self.router.run(start_command).stdout.strip()) self.hostapd_instances.append( HostapdInstance(hostapd_conf_dict['ssid'], conf_file, log_file, interface, hostapd_conf_dict.copy(), stderr_log_file, configuration.scenario_name)) # Wait for confirmation that the router came up. logging.info('Waiting for hostapd to startup.') utils.poll_for_condition( condition=lambda: self._has_hostapd_started(log_file, pid), exception=error.TestFail('Timed out while waiting for hostapd ' 'to start.'), timeout=self.STARTUP_TIMEOUT_SECONDS, sleep_interval=self.POLLING_INTERVAL_SECONDS) if configuration.frag_threshold: threshold = self.iw_runner.get_fragmentation_threshold(phy_name) if threshold != configuration.frag_threshold: raise error.TestNAError('Router does not support setting ' 'fragmentation threshold')
def run_once(self): """Body of the test.""" mode_n = hostap_config.HostapConfig.MODE_11N_PURE eap_config = xmlrpc_security_types.WPAEAPConfig( server_ca_cert=site_eap_certs.ca_cert_1, server_cert=site_eap_certs.server_cert_1, server_key=site_eap_certs.server_private_key_1, client_ca_cert=site_eap_certs.ca_cert_1, client_cert=site_eap_certs.client_cert_1, client_key=site_eap_certs.client_private_key_1, # PMKSA caching is only defined for WPA2. wpa_mode=xmlrpc_security_types.WPAConfig.MODE_PURE_WPA2) ap_config0 = hostap_config.HostapConfig(mode=mode_n, frequency=self.AP0_FREQUENCY, security_config=eap_config) self.context.configure(ap_config0) assoc_params = xmlrpc_datatypes.AssociationParameters( ssid=self.context.router.get_ssid(), security_config=eap_config) self.context.assert_connect_wifi(assoc_params) # Add another AP with identical configuration except in 5 Ghz. ap_config1 = hostap_config.HostapConfig( mode=mode_n, ssid=self.context.router.get_ssid(), frequency=self.AP1_FREQUENCY, security_config=eap_config) self.context.configure(ap_config1, multi_interface=True) bssid0 = self.context.router.get_hostapd_mac(0) bssid1 = self.context.router.get_hostapd_mac(1) utils.poll_for_condition( condition=lambda: self.dut_sees_bss(bssid1), exception=error.TestFail( 'Timed out waiting for DUT to see second AP'), timeout=self.TIMEOUT_SECONDS, sleep_interval=1) self.context.client.request_roam(bssid1) if not self.context.client.wait_for_roam( bssid1, timeout_seconds=self.TIMEOUT_SECONDS): raise error.TestFail('Failed to roam to second BSS.') self.context.router.deconfig_aps(instance=1, silent=True) if not self.context.client.wait_for_roam( bssid0, timeout_seconds=self.TIMEOUT_SECONDS): raise error.TestFail('Failed to fall back to first BSS.') pinger = ping_runner.PingRunner(host=self.context.client.host) utils.poll_for_condition(condition=lambda: pinger.simple_ping( self.context.router.get_wifi_ip(0)), exception=error.TestFail( 'Timed out waiting for DUT to be able to' 'ping first BSS after fallback'), timeout=self.TIMEOUT_SECONDS, sleep_interval=1) self.context.router.confirm_pmksa_cache_use(instance=0)
def wait_for_atrus_enumeration(timeout_seconds=30): """ Wait for an Atrus device to enumerate. @param timeout_seconds: Maximum number of seconds to wait. """ device_manager = usb_device_collector.UsbDeviceCollector() utils.poll_for_condition( lambda: len(device_manager.get_devices_by_spec(ATRUS)) >= 1, timeout=timeout_seconds, sleep_interval=1.0, desc='No atrus device enumerated')
def run_once(self, host): """Test body.""" self._router0_conf = hostap_config.HostapConfig( channel=48, mode=hostap_config.HostapConfig.MODE_11A) self._router1_conf = hostap_config.HostapConfig(channel=1) self._client_conf = xmlrpc_datatypes.AssociationParameters() # Configure the inital AP. self.context.configure(self._router0_conf) router_ssid = self.context.router.get_ssid() # Connect to the inital AP. self._client_conf.ssid = router_ssid self.context.assert_connect_wifi(self._client_conf) # Setup a second AP with the same SSID. self._router1_conf.ssid = router_ssid self.context.configure(self._router1_conf, multi_interface=True) # Get BSSIDs of the two APs bssid0 = self.context.router.get_hostapd_mac(0) bssid1 = self.context.router.get_hostapd_mac(1) # Wait for DUT to see the second AP utils.poll_for_condition( condition=lambda: self.dut_sees_bss(bssid1), exception=error.TestFail( 'Timed out waiting for DUT to see second AP'), timeout=self.TIMEOUT_SECONDS, sleep_interval=1) # Check which AP we are currently connected. # This is to include the case that wpa_supplicant # automatically roam to AP2 during the scan. interface = self.context.client.wifi_if current_bssid = self.context.client.iw_runner.get_current_bssid( interface) if current_bssid == bssid0: roam_to_bssid = bssid1 else: roam_to_bssid = bssid0 # Send roam command to shill, # and shill will send dbus roam command to wpa_supplicant self.context.client.request_roam_dbus(roam_to_bssid, interface) # Expect that the DUT will re-connect to the new AP. if not self.context.client.wait_for_roam( roam_to_bssid, timeout_seconds=self.TIMEOUT_SECONDS): raise error.TestFail('Failed to roam.') self.context.router.deconfig()
def cleanup(self): shutil.copy('/var/log/update_engine.log', self.resultsdir) # Turn adapters back on utils.run('ifconfig eth0 up', ignore_status=True) utils.run('ifconfig eth1 up', ignore_status=True) utils.start_service('recover_duts', ignore_status=True) # 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( self._update_server, deadline=5, timeout=5) == 0, timeout=60, sleep_interval=1) logging.info('Online ready to return to server test')
def wait_for_service_states(self, ssid, states, timeout_seconds): """Wait for a service (ssid) to achieve one of a number of states. @param ssid string name of network for whose state we're waiting. @param states tuple states for which to wait. @param timeout_seconds seconds to wait for property to be achieved @return tuple(successful, final_value, duration) where successful is True iff we saw one of |states|, final_value is the final state we saw, and duration is how long we waited to see that value. """ discovery_params = { self.SERVICE_PROPERTY_TYPE: 'wifi', self.SERVICE_PROPERTY_NAME: ssid } start_time = time.time() try: service_object = utils.poll_for_condition( condition=lambda: self.find_matching_service(discovery_params), timeout=timeout_seconds, sleep_interval=self.POLLING_INTERVAL_SECONDS, desc='Find a matching service to the discovery params') return self.wait_for_property_in( service_object, self.SERVICE_PROPERTY_STATE, states, timeout_seconds - (time.time() - start_time)) # poll_for_condition timed out except utils.TimeoutError: logging.error('Timed out waiting for %s states', ssid) return False, 'unknown', timeout_seconds
def scan_for_networks(ssid, capturer, ap_spec): """Returns a list of matching networks after running iw scan. @param ssid: the SSID string to look for in scan. @param capturer: a packet capture device. @param ap_spec: APSpec object corresponding to the AP configuration. @returns a list of the matching networks; if no networks are found at all, returns None. """ # Setup a managed interface to perform scanning on the # packet capture device. freq = ap_spec_module.FREQUENCY_TABLE[ap_spec.channel] wifi_if = capturer.get_wlanif(freq, 'managed') capturer.host.run('%s link set %s up' % (capturer.cmd_ip, wifi_if)) logging.info("Scanning for network ssid: %s", ssid) # We have some APs that need a while to come on-line networks = list() try: networks = utils.poll_for_condition( condition=lambda: capturer.iw_runner.wait_for_scan_result( wifi_if, ssids=[ssid], wait_for_all=True), timeout=300, sleep_interval=35, desc='Timed out getting IWBSSes') except utils.TimeoutError: pass capturer.remove_interface(wifi_if) return networks
def _get_service_connection_id(self, ssid): """Get the connection ID for a service. Polls a service's properties until ConnectionId becomes non-zero, or a timeout occurs. @param ssid: SSID of the service of interest. @raise TestError if a timeout occurs. @return ConnectionId of the current service. """ utils.poll_for_condition( condition=lambda: self._attempt_get_service_id(ssid), exception=error.TestFail('ConnectionId remained zero'), timeout=self.CONNECTION_ID_TIMEOUT_SECS, sleep_interval=1) return self._connection_id
def enable_assistant(autotest_ext): """Enables Google Assistant. @param autotest_ext private autotest extension. @raise error.TestFail if failed to start Assistant service within time. """ if autotest_ext is None: raise error.TestFail('Could not start Assistant service because ' 'autotest extension is not available.') try: autotest_ext.ExecuteJavaScript(''' window.__assistant_ready = 0; chrome.autotestPrivate.setAssistantEnabled(true, 10 * 1000 /* timeout_ms */, () => { if (chrome.runtime.lastError) { window.__assistant_ready = -1; window.__assistant_error_msg = chrome.runtime.lastError.message; } else { window.__assistant_ready = 1; } }); ''') except exceptions.EvaluateException as e: raise error.TestFail('Could not start Assistant "%s".' % e) ready = utils.poll_for_condition( lambda: autotest_ext.EvaluateJavaScript('window.__assistant_ready'), desc='Wait for the assistant running state to return.') if ready == -1: raise error.TestFail( autotest_ext.EvaluateJavaScript('window.__assistant_error_msg'))
def enable_hotword(autotest_ext): """Enables hotword in Google Assistant. @param autotest_ext private autotest extension. @raise error.TestFail if failed to enable hotword feature within time. """ try: autotest_ext.ExecuteJavaScript(''' window.__assistant_hotword_ready = 0; chrome.autotestPrivate.setWhitelistedPref( 'settings.voice_interaction.hotword.enabled', true, function(response) { if (chrome.runtime.lastError) { window.__assistant_hotword_ready = -1; window.__assistant_hotword_error_msg = chrome.runtime.lastError.message; } else { window.__assistant_hotword_ready = 1; } }); ''') except exceptions.EvaluateException as e: raise error.TestFail('Could not enable Hotword "{}".'.format(e)) ready = utils.poll_for_condition( lambda: autotest_ext.EvaluateJavaScript( 'window.__assistant_hotword_ready'), desc='Wait for the hotword pref change event to return".') if ready == -1: raise error.TestFail( autotest_ext.EvaluateJavaScript( 'window.__assistant_hotword_error_msg'))
def wait_for_scan_result(self, interface, bsses=(), ssids=(), timeout_seconds=30, wait_for_all=False): """Returns a list of IWBSS objects for given list of bsses or ssids. This method will scan for a given timeout and return all of the networks that have a matching ssid or bss. If wait_for_all is true and all networks are not found within the given timeout an empty list will be returned. @param interface: which interface to run iw against @param bsses: a list of BSS strings @param ssids: a list of ssid strings @param timeout_seconds: the amount of time to wait in seconds @param wait_for_all: True to wait for all listed bsses or ssids; False to return if any of the networks were found @returns a list of IwBss collections that contain the given bss or ssid; if the scan is empty or returns an error code None is returned. """ logging.info('Performing a scan with a max timeout of %d seconds.', timeout_seconds) # If the in-progress scan takes more than 30 seconds to # complete it will most likely never complete; abort. # See crbug.com/309148 scan_results = list() try: scan_results = utils.poll_for_condition( condition=lambda: self.scan(interface), timeout=timeout_seconds, sleep_interval=5, # to allow in-progress scans to complete desc='Timed out getting IWBSSes that match desired') except utils.TimeoutError as e: pass if not scan_results: # empty list or None return None # get all IWBSSes from the scan that match any of the desired # ssids or bsses passed in matching_iwbsses = filter( lambda iwbss: iwbss.ssid in ssids or iwbss.bss in bsses, scan_results) if wait_for_all: found_bsses = [iwbss.bss for iwbss in matching_iwbsses] found_ssids = [iwbss.ssid for iwbss in matching_iwbsses] # if an expected bss or ssid was not found, and it was required # by the caller that all expected be found, return empty list if any(bss not in found_bsses for bss in bsses) or any(ssid not in found_ssids for ssid in ssids): return list() return list(matching_iwbsses)
def _kill_process_instance(self, process, instance=None, timeout_seconds=10, ignore_timeouts=False): """Kill a process on the router. Kills remote program named |process| (optionally only a specific |instance|). Wait |timeout_seconds| for |process| to die before returning. If |ignore_timeouts| is False, raise a TestError on timeouts. @param process: string name of process to kill. @param instance: string fragment of the command line unique to this instance of the remote process. @param timeout_seconds: float timeout in seconds to wait. @param ignore_timeouts: True iff we should ignore failures to kill processes. @return True iff the specified process has exited. """ if instance is not None: search_arg = '-f "^%s.*%s"' % (process, instance) else: search_arg = process self.host.run('pkill %s' % search_arg, ignore_status=True) # Wait for process to die time.sleep(self.POLLING_INTERVAL_SECONDS) try: utils.poll_for_condition( condition=lambda: self.host.run('pgrep -l %s' % search_arg, ignore_status=True ).exit_status != 0, timeout=timeout_seconds, sleep_interval=self.POLLING_INTERVAL_SECONDS) except utils.TimeoutError: if ignore_timeouts: return False raise error.TestError( 'Timed out waiting for %s%s to die' % (process, '' if instance is None else ' (instance=%s)' % instance)) return True
def _test_timezone(self, expected): """ Verify the Timezone set on the device. This is done by running the UNIX date command (%z) and verifying the timezone matches the expected result. """ def check_timezone(expected): return utils.system_output('date +%z') == expected utils.poll_for_condition( lambda: check_timezone(expected), exception=error.TestFail( 'Time zone was not set! Expected {}'.format(expected)), timeout=5, sleep_interval=1, desc='Polling for timezone change')
def mwifiex_reset(self): """Perform mwifiex reset and wait for the interface to come back up.""" ssid = self.context.router.get_ssid() # Adapter will asynchronously reset. self.context.client.host.run('echo 1 > ' + self.mwifiex_reset_path) # Wait for disconnect. We aren't guaranteed to receive a disconnect # event, but shill will at least notice the adapter went away. self.context.client.wait_for_service_states(ssid, ['idle'], timeout_seconds=20) # Now wait for the reset interface file to come back. utils.poll_for_condition( condition=self.mwifiex_reset_exists, exception=error.TestFail('Failed to reset device %s' % self.context.client.wifi_if), timeout=self._MWIFIEX_RESET_TIMEOUT, sleep_interval=self._MWIFIEX_RESET_INTERVAL)
def _wait_firmware_update_process(host, pid, timeout=_FIRMWARE_UPDATE_TIMEOUT): """Wait `chromeos-firmwareupdate` to finish. @param host Host instance to use for servo and ssh operations. @param pid The process ID of `chromeos-firmwareupdate`. @param timeout Maximum time to wait for firmware updating. """ try: utils.poll_for_condition( lambda: host.run('ps -f -p %s' % pid, timeout=20).exit_status, exception=Exception( "chromeos-firmwareupdate (pid: %s) didn't complete in %s " 'seconds.' % (pid, timeout)), timeout=_FIRMWARE_UPDATE_TIMEOUT, sleep_interval=10, ) except error.AutoservRunError: # We lose the connectivity, so the DUT should be booting up. if not host.wait_up(timeout=host.USB_BOOT_TIMEOUT): raise Exception('DUT failed to boot up after firmware updating.')
def _alt_page_check(self, policy_value): """ Navigates to an invalid webpage, then checks the first item of the suggestion list. @param policy_value: bool or None, the setting of the policy. """ search_box = '#suggestions-list li' tab = self.navigate_to_url('http://localhost:8080/') get_text = "document.querySelector('{}').innerText".format(search_box) def is_page_loaded(): """ Checks to see if page has fully loaded. @returns True if loaded False if not. """ try: tab.EvaluateJavaScript(get_text) return True except exceptions.EvaluateException: return False # Wait for the page to load before checking it. utils.poll_for_condition( lambda: is_page_loaded(), exception=error.TestFail('Page Never loaded!'), timeout=5, sleep_interval=1, desc='Polling for page to load.') list_content = tab.EvaluateJavaScript(get_text) if self.RESULTS_DICT[policy_value] != list_content: raise error.TestFail( 'AlternateErrorPage was not set! Expected the first item in' ' the suggestions-list to be "{}" but received "{}"' .format(self.RESULTS_DICT[policy_value], list_content))
def _check_p2p_still_enabled(self, host): """ Check that updating has not affected P2P status. @param host: The host that we just updated. """ logging.info('Checking that p2p is still enabled after update.') def _is_p2p_enabled(): p2p = host.run('update_engine_client --show_p2p_update', ignore_status=True) if p2p.stderr is not None and 'ENABLED' in p2p.stderr: return True else: return False err = 'P2P was disabled after the first DUT was updated. This is not ' \ 'expected. Something probably went wrong with the update.' utils.poll_for_condition(_is_p2p_enabled, exception=error.TestFail(err))
def video_record_completed(self): """Checks if MediaRecorder has recorded videos. @returns True if videos have been recorded, False otherwise. """ def video_recorded(): """Check the testProgress variable in HTML page.""" # Wait for TEST_PROGRESS appearing on web page. test_progress = self.tab.EvaluateJavaScript(TEST_PROGRESS) return test_progress == 1 try: common_utils.poll_for_condition( video_recorded, timeout=RECORDING_TIMEOUT, exception=error.TestError('Cannot find testProgress.'), sleep_interval=1) except error.TestError: return False else: return True
def is_test_completed(self): """Checks if MediaRecorder test is done. @returns True if test complete, False otherwise. """ def test_done(): """Check the testProgress variable in HTML page.""" # Wait for test completion on web page. test_progress = self.tab.EvaluateJavaScript(TEST_PROGRESS) return test_progress == 1 try: utils.poll_for_condition( test_done, timeout=TIMEOUT, exception=error.TestError('Cannot find testProgress.'), sleep_interval=1) except error.TestError: return False else: return True
def ensure_processes_are_dead_by_name(name, timeout_sec=10): """Terminate all processes specified by name and ensure they're gone. Arguments: name: process name specifier, as understood by pgrep. timeout_sec: maximum number of seconds to wait for processes to die. Raises: error.AutoservPidAlreadyDeadError: no existing process matches name. site_utils.TimeoutError: if processes still exist after timeout_sec. """ def list_and_kill_processes(name): process_list = get_process_list(name) try: for pid in [int(str_pid) for str_pid in process_list]: utils.nuke_pid(pid) except error.AutoservPidAlreadyDeadError: pass return process_list utils.poll_for_condition(lambda: list_and_kill_processes(name) == [], timeout=timeout_sec)
def wait_for_ui_obj(self, name, isRegex=False, remove=False, role=None, timeout=10): """ Waits for the UI object specified. @param name: Parameter to provide to the 'name' attribute. @param isRegex: bool, if the 'name' is a regex. @param remove: bool, if you are waiting for the item to be removed. @param role: Parameter to provide to the 'role' attribute. @param timeout: int, time to wait for the item. @raises error.TestError if the element is not loaded (or removed). """ utils.poll_for_condition(condition=lambda: self.item_present( name=name, isRegex=isRegex, flip=remove, role=role), timeout=timeout, exception=error.TestError( '{} did not load in: {}'.format( name, self.list_screen_items())))
def wait_for_link(self, interface, timeout_seconds=10): """Waits until a link completes on |interface|. @param interface: which interface to run iw against. @param timeout_seconds: the amount of time to wait in seconds. @returns True if link was established before the timeout. """ return utils.poll_for_condition( # gets link results from running dev command, then assumes the # link is completed if 'Not connected' is absent from stdout condition=lambda: 'Not connected' not in self._run( '%s dev %s link' % (self._command_iw, interface)).stdout, timeout=timeout_seconds, sleep_interval=1, desc='Wait until a link completes on |interface|')
def send_text_query(autotest_ext, text_query): """Sends text query to Assistant and returns response. @param autotest_ext private autotest extension. @param text_query text query. @return dictionary containing the information of Assistant query response, mapping from response type to content. """ try: autotest_ext.ExecuteJavaScript(''' window.__assistant_response_ready = 0; chrome.autotestPrivate.sendAssistantTextQuery('%s', 10 * 1000, function(response) { if (chrome.runtime.lastError) { window.__assistant_response_ready = -1; window.__assistant_error_msg = chrome.runtime.lastError.message; } else { window.__assistant_response_ready = 1; window.__query_response = response; } }); ''' % text_query) except exceptions.EvaluateException as e: raise error.TestFail('Could not get Assistant response "%s".' % e) is_ready = utils.poll_for_condition( lambda: autotest_ext.EvaluateJavaScript( 'window.__assistant_response_ready'), desc='Waiting for Assistant response.') if is_ready == -1: raise error.TestFail( autotest_ext.EvaluateJavaScript('window.__assistant_error_msg')) return autotest_ext.EvaluateJavaScript('window.__query_response')
def connect_wifi(self, assoc_params): """ Connect to the WiFi network described by AssociationParameters. @param assoc_params AssociationParameters object. @return serialized AssociationResult object. """ logging.debug('connect_wifi()') # Ouptut should look like: # Using interface 'wlan0' # 0 assoc_result = xmlrpc_datatypes.AssociationResult() network_id = self._add_network(assoc_params.ssid) if assoc_params.is_hidden: self.run_wpa_cli_cmd('set_network %d %s %s' % (network_id, 'scan_ssid', '1')) sec_config = assoc_params.security_config for field, value in sec_config.get_wpa_cli_properties().iteritems(): self.run_wpa_cli_cmd('set_network %d %s %s' % (network_id, field, value)) self.run_wpa_cli_cmd('select_network %d' % network_id) # Wait for an appropriate BSS to appear in scan results. scan_results_pattern = '\t'.join([ '([0-9a-f:]{17})', # BSSID '([0-9]+)', # Frequency '(-[0-9]+)', # Signal level '(.*)', # Encryption types '(.*)' ]) # SSID last_scan_time = -1.0 start_time = time.time() while time.time() - start_time < assoc_params.discovery_timeout: assoc_result.discovery_time = time.time() - start_time if self._is_associating_or_associated(): # Internally, wpa_supplicant writes its scan_results response # to a 4kb buffer. When there are many BSS's, the buffer fills # up, and we'll never see the BSS we care about in some cases. break scan_result = self.run_wpa_cli_cmd('scan_results', check_result=False) found_stations = [] for line in scan_result.stdout.strip().splitlines(): match = re.match(scan_results_pattern, line) if match is None: continue found_stations.append( Station(bssid=match.group(1), frequency=match.group(2), signal=match.group(3), ssid=match.group(5))) logging.debug('Found stations: %r', [station.ssid for station in found_stations]) if [ station for station in found_stations if station.ssid == assoc_params.ssid ]: break if time.time() - last_scan_time > self.SCANNING_INTERVAL_SECONDS: # Sometimes this might fail with a FAIL-BUSY if the previous # scan hasn't finished. scan_result = self.run_wpa_cli_cmd('scan', check_result=False) if scan_result.stdout.strip().endswith('OK'): last_scan_time = time.time() time.sleep(self.POLLING_INTERVAL_SECONDS) else: assoc_result.failure_reason = 'Discovery timed out' return assoc_result.serialize() # Wait on association to finish. start_time = time.time() success = utils.poll_for_condition( condition=lambda: self._is_associated(assoc_params.ssid), timeout=assoc_params.association_timeout, sleep_interval=self.POLLING_INTERVAL_SECONDS, desc='Wait on association to finish') assoc_result.association_time = time.time() - start_time if not success: assoc_result.failure_reason = 'Association timed out' return assoc_result.serialize() # Then wait for ip configuration to finish. start_time = time.time() success = utils.poll_for_condition( condition=lambda: self._is_connected(assoc_params.ssid), timeout=assoc_params.configuration_timeout, sleep_interval=self.POLLING_INTERVAL_SECONDS, desc='Wait for ip configuration to finish') assoc_result.configuration_time = time.time() - start_time if not success: assoc_result.failure_reason = 'DHCP negotiation timed out' return assoc_result.serialize() assoc_result.success = True logging.info('Connected to %s', assoc_params.ssid) return assoc_result.serialize()
def run_once(self, power_on=True): utils.poll_for_condition( lambda: power_status.get_status().on_ac() == power_on, timeout=10, exception=error.TestError('AC power not %d' % power_on))