def initialize(self): # Make sure these are initiallized to None in case we throw # during self.initialize(). self._chrooted_avahi = None self._peerd = None self._host = None self._zc_listener = None self._chrooted_avahi = chrooted_avahi.ChrootedAvahi() self._chrooted_avahi.start() self.reset_peerd() # Listen on our half of the interface pair for mDNS advertisements. self._host = interface_host.InterfaceHost( self._chrooted_avahi.unchrooted_interface_name) self._zc_listener = zeroconf.ZeroconfDaemon(self._host, self.FAKE_HOST_HOSTNAME) # The queries for hostname/dns_domain are IPCs and therefor relatively # expensive. Do them just once. hostname = self._chrooted_avahi.hostname dns_domain = self._chrooted_avahi.dns_domain if not hostname or not dns_domain: raise error.TestFail('Failed to get hostname/domain from avahi.') self._dns_domain = dns_domain self._hostname = '%s.%s' % (hostname, dns_domain) self._last_cache_refresh_seconds = 0
def cbfs_replace_chips(self, host): """Iterates over known chips in cbfs. For each chip that has an update specified on the command line, copies the firmware (bin, hash) to DUT and updates cbfs in bios.bin. Args: host: host handle to the DUT. """ for chip in self.cbfs_chip_types: chip_name = chip.chip_name logging.info('replacing %s firmware in %s', chip_name, self.BIOS) fw_update = self.req_chip_updates[chip_name] fw_hash = fw_update.compute_hash_bytes() (fd, n) = tempfile.mkstemp() with os.fdopen(fd, 'wb') as f: f.write(fw_hash) try: host.send_file( n, os.path.join(self.cbfs_work_dir, fw_update.cbfs_hash_name)) finally: os.unlink(n) host.send_file( fw_update.fw_file_name, os.path.join(self.cbfs_work_dir, fw_update.cbfs_bin_name)) if not self.faft_client.updater.cbfs_replace_chip( fw_update.fw_name): raise error.TestFail('could not replace %s blobs in cbfs' % fw_update.chip_name)
def run_once(self, username=None, password=None, source="Downloads", file_name='test.dat'): """Copy file to Google Drive in Files application @param username: Real user(Not default autotest user) @param password: Password for the user. @param source: From where to copy file @param file_name: File name """ self.success = False # Used to capture the screenshot if the TC fails with chromedriver.chromedriver(username=username, password=password, disable_default_apps=False, gaia_login=True) as cr_instance: driver = cr_instance.driver self.open_files_application(driver) self.create_file(os.path.join(os.path.join(USER_LOCATION, source), file_name)) self.copy_file(driver, source, GOOGLE_DRIVE, file_name) errors = self.catch_info_or_error_messages(driver) if len(errors): raise error.TestFail("Test failed with the following" " errors. %s", errors) self.success = True
def finalize(self): """ Analyzes the state of the GPU, log history and emits warnings or errors if the state changed since initialize. Also makes a note of the Chrome version for later usage in the perf-dashboard. """ utils.set_dirty_writeback_centisecs(self.dirty_writeback_centisecs) new_gpu_hang = False new_gpu_warning = False if utils.get_cpu_arch() != 'arm': logging.info('Cleanup: Checking for new GPU hangs...') messages = open(self._MESSAGES_FILE, 'r') for line in messages: for hang in self._HANGCHECK: if hang in line: if not line in self.existing_hangs.keys(): logging.info(line) for warn in self._HANGCHECK_WARNING: if warn in line: new_gpu_warning = True logging.warning( 'Saw GPU hang warning during test.') else: logging.warning('Saw GPU hang during test.') new_gpu_hang = True messages.close() if is_sw_rasterizer(): logging.warning('Finished test on SW rasterizer.') raise error.TestFail('Finished test on SW rasterizer.') if self._raise_error_on_hang and new_gpu_hang: raise error.TestError('Detected GPU hang during test.') if new_gpu_hang: raise error.TestWarn('Detected GPU hang during test.') if new_gpu_warning: raise error.TestWarn('Detected GPU warning during test.')
def soft_reset(self): """Initates a PD soft reset sequence @returns True if state transitions match, False otherwise """ snk_reset_states = [ 'SOFT_RESET', 'SNK_DISCOVERY', 'SNK_REQUESTED', 'SNK_TRANSITION', 'SNK_READY' ] src_reset_states = [ 'SOFT_RESET', 'SRC_DISCOVERY', 'SRC_NEGOCIATE', 'SRC_ACCEPTED', 'SRC_POWERED', 'SRC_TRANSITION', 'SRC_READY' ] if self.is_src(): states_list = src_reset_states elif self.is_snk(): states_list = snk_reset_states else: raise error.TestFail('Port Pair not in a connected state') cmd = 'pd %d soft' % self.port return self._reset(cmd, states_list)
def connect_to_network(self, service_list): """Connects to the given network using networkingPrivate API. @param service_list: service list for the network to connect to. """ connect_status = self._chrome_testing.call_test_function( test_utils.LONG_TIMEOUT, 'connectToNetwork', '"' + service_list['GUID'] + '"') if connect_status['error'] == 'connected': return elif connect_status['error'] == 'connecting': for retry in range(3): logging.debug('Just hold on for 10 seconds') time.sleep(10) if connect_status['error'] == 'connected': return if connect_status['status'] == 'chrome-test-call-status-failure': raise error.TestFail( 'Could not connect to %s network. Error returned by ' 'chrome.networkingPrivate.startConnect API: %s' % (service_list['Name'], connect_status['error']))
def _check_scroll_direction(self, filepath, expected): """Playback and raise error if scrolling does not match down value. @param filepath: Gesture file's complete path for playback. @param expected: String, expected direction in which test page scroll should move for the gesture file being played. @raises TestFail if actual scrolling did not match expected. """ is_vertical = expected == 'up' or expected == 'down' is_down_or_right = expected == 'down' or expected == 'right' self._set_default_scroll_position(is_vertical) self._playback(filepath, touch_type='touchscreen') self._wait_for_scroll_position_to_settle(is_vertical) delta = self._get_scroll_position(is_vertical) - self._DEFAULT_SCROLL logging.info('Scroll delta was %d', delta) # Check if movement occured in correct direction. if ((is_down_or_right and delta <= 0) or (not is_down_or_right and delta >= 0)): raise error.TestFail('Page scroll was in wrong direction! ' 'Delta=%d' % delta)
def run_once(self): # Initial policy setup. poldata = policy.build_policy_data() priv = ownership.known_privkey() pub = ownership.known_pubkey() policy.push_policy_and_verify( policy.generate_policy(priv, pub, poldata), self._sm) # Force re-key the device (priv, pub) = ownership.pairgen_as_data() policy.push_policy_and_verify( policy.generate_policy(priv, pub, poldata), self._sm) # Rotate key gracefully. self.username = (''.join(random.sample(string.ascii_lowercase,6)) + "@foo.com") password = ''.join(random.sample(string.ascii_lowercase,6)) self._cryptohome_proxy.remove(self.username) self._cryptohome_proxy.mount(self.username, password, create=True) (new_priv, new_pub) = ownership.pairgen_as_data() self._sm.StartSession(self.username, '') policy.push_policy_and_verify( policy.generate_policy(key=new_priv, pubkey=new_pub, policy=poldata, old_key=priv), self._sm) try: self._sm.StopSession('') except error.TestError as e: logging.error(str(e)) raise error.TestFail('Could not stop session for random user')
def run_once(self, args='', script='runltp', ignore_tests=[]): ignore_tests = ignore_tests + self.site_ignore_tests # In case the user wants to run another test script if script == 'runltp': logfile = os.path.join(self.resultsdir, 'ltp.log') failcmdfile = os.path.join(self.debugdir, 'failcmdfile') skipfile = os.path.join(self.bindir, 'skipfile') args2 = '-q -l %s -C %s -d %s -S %s' % \ (logfile, failcmdfile, self.srcdir, skipfile) args = args + ' ' + args2 ltpbin_dir = os.path.join(self.srcdir, 'bin') cmd = os.path.join(ltpbin_dir, script) + ' ' + args result = utils.run(cmd, ignore_status=True) # look for the first line in result.stdout containing FAIL and, # if found, raise the whole line as a reason of the test failure. for line in result.stdout.split(): if 'FAIL' in line: test_name = line.strip().split(' ')[0] if not test_name in ignore_tests: raise error.TestFail(line)
def CheckForFailures(client, last_message): """Check for any unexpected cr50-update exit codes. This only checks the cr50 update messages that have happened since last_message. If a unexpected exit code is detected it will raise an error> Args: last_message: the last cr50 message from the last update run Returns: the last cr50 message in /var/log/messages Raises: TestFail - If there is a unexpected cr50-update exit code after last_message in /var/log/messages """ messages = client.run(GET_CR50_MESSAGES).stdout.strip() if last_message: messages = messages.rsplit(last_message, 1)[-1] if UPDATE_FAILURE in messages: logging.debug(messages) raise error.TestFail("Detected unexpected exit code during update") return messages.rsplit('\n', 1)[-1]
def _check_for_drag(self, expected): """Playback and check whether tap dragging occurred. Fail if needed. @param expected: True if dragging should happen, else False. @raises: TestFail if actual value does not match expected. """ self._events.clear_previous_events() self._blocking_playback(self._filepaths[self._DRAG_NAME]) self._events.wait_for_events_to_complete() # Find a drag in the reported input events. events_log = self._events.get_events_log() log_search = re.search('mousedown.*\n(mousemove.*\n)+mouseup', events_log, re.MULTILINE) actual_dragging = log_search != None actual_click_count = self._events.get_click_count() actual = actual_dragging and actual_click_count == 1 if actual is not expected: self._events.log_events() raise error.TestFail('Tap dragging movement was %s; expected %s. ' 'Saw %s clicks.' % (actual, expected, actual_click_count))
def _get_path(self, path, allow_missing=False): """Returns the path to an installed Tast-related file or directory. @param path Absolute path in root filesystem, e.g. "/usr/bin/tast". @param allow_missing True if it's okay for the path to be missing. @return: Absolute path within install root, e.g. "/opt/infra-tools/usr/bin/tast", or an empty string if the path wasn't found and allow_missing is True. @raises error.TestFail if the path couldn't be found and allow_missing is False. """ if os.path.exists(path): return path cipd_path = os.path.join(self._CIPD_INSTALL_ROOT, os.path.relpath(path, '/')) if os.path.exists(cipd_path): return cipd_path if allow_missing: return '' raise error.TestFail('Neither %s nor %s exists' % (path, cipd_path))
def _parse_results(self): """Parses results written by the tast command. @raises error.TestFail if one or more tests failed. """ path = os.path.join(self.resultsdir, self._RESULTS_FILENAME) failed = [] with open(path, 'r') as f: for test in json.load(f): if test['errors']: name = test['name'] for err in test['errors']: logging.warning('%s: %s', name, err['reason']) # TODO(derat): Report failures in flaky tests in some other # way. if 'flaky' not in test.get('attr', []): failed.append(name) if failed: msg = '%d failed: ' % len(failed) msg += ' '.join(sorted(failed)[:self._MAX_TEST_NAMES_IN_ERROR]) if len(failed) > self._MAX_TEST_NAMES_IN_ERROR: msg += ' ...' raise error.TestFail(msg)
def execute(self): os.chdir(self.tmpdir) (p1, _) = utils.run_bg('dd if=/dev/hda3 of=/dev/null') time.sleep(60) blah = os.path.join(self.tmpdir, 'blah') dirty_bin = os.path.join(self.srcdir, 'dirty') dirty_op = os.path.join(self.tmpdir, 'dirty') utils.system('echo AA > ' + blah) p2 = subprocess.Popen(dirty_bin + ' ' + blah + ' 1 > ' + dirty_op, shell=True) time.sleep(600) if p2.poll() is None: utils.nuke_subprocess(p1) utils.nuke_subprocess(p2) raise error.TestFail('Writes made no progress') # Commenting out use of utils.run as there is a timeout bug # # try: # utils.run(dirty_bin + ' ' + blah + '1 > ' + dirty_op, 900, False, # None, None) # except Exception: # utils.nuke_subprocess(p1) # raise error.TestFail('Writes made no progress') utils.nuke_subprocess(p1)
def check_section(self): """Check RW_SECTION_[AB] and RW_LEGACY. 1- check RW_SECTION_[AB] exist, non-zero, same size 2- RW_LEGACY exist and > 1MB in size """ # Parse map into dictionary. bios = {} for e in self._TARGET_AREA[TARGET_BIOS]: bios[e['name']] = {'offset': e['offset'], 'size': e['size']} succeed = True # Check RW_SECTION_[AB] sections. if 'RW_SECTION_A' not in bios: succeed = False logging.error('Missing RW_SECTION_A section in FMAP') elif 'RW_SECTION_B' not in bios: succeed = False logging.error('Missing RW_SECTION_B section in FMAP') else: if bios['RW_SECTION_A']['size'] != bios['RW_SECTION_B']['size']: succeed = False logging.error('RW_SECTION_A size != RW_SECTION_B size') if (bios['RW_SECTION_A']['size'] == 0 or bios['RW_SECTION_B']['size'] == 0): succeed = False logging.error('RW_SECTION_A size or RW_SECTION_B size == 0') # Check RW_LEGACY section. if 'RW_LEGACY' not in bios: succeed = False logging.error('Missing RW_LEGACY section in FMAP') else: if bios['RW_LEGACY']['size'] < 1024 * 1024: succeed = False logging.error('RW_LEGACY size is < 1M') if not succeed: raise error.TestFail('SECTION check failed.')
def setup_u2fd(self): """Start u2fd on the host""" self.start_u2fd = not self.u2fd_is_running() if not self.start_u2fd: logging.info('u2fd is already running') return # Login tpm_utils.ClearTPMOwnerRequest(self.host, wait_for_ready=True) # Wait for cryptohome to show the TPM is ready before logging in. if not utils.wait_for_value(self.cryptohome_ready, True, timeout_sec=60): raise error.TestError('Crytpohome did not start') client_at = autotest.Autotest(self.host) client_at.run_test('login_LoginSuccess') # Wait for the owner key to exist before trying to start u2fd. if not utils.wait_for_value(self.owner_key_exists, True, timeout_sec=120): raise error.TestError('Device did not create owner key') self.create_g2f_force = not self.host.path_exists(self.G2FFORCE_PATH) if self.create_g2f_force: logging.info('Creating %s', self.G2FFORCE_PATH) self.host.run('touch %s' % self.G2FFORCE_PATH) # Start u2fd self.host.run('start u2fd') self.host.run('trunks_send --u2f_cert --crt=/tmp/cert0.crt') # Make sure it is still running if not self.u2fd_is_running(): raise error.TestFail('could not start u2fd') logging.info('u2fd is running')
def run_once(self, host, repeat, peripheral_whitelist_dict): """Main function to run autotest. @param host: Host object representing the DUT. @param repeat: Number of times peripheral should be hotplugged. @param peripheral_whitelist_dict: Dictionary of peripherals to test. """ self.client = host factory = remote_facade_factory.RemoteFacadeFactory(host, no_chrome=True) self.cfm_facade = factory.create_cfm_facade() tpm_utils.ClearTPMOwnerRequest(self.client) if self.client.servo: self.client.servo.switch_usbkey('dut') self.client.servo.set('usb_mux_sel3', 'dut_sees_usbkey') time.sleep(_SHORT_TIMEOUT) self._set_hub_power(True) try: self._enroll_device_and_skip_oobe() self._set_peripheral(peripheral_whitelist_dict) on_off_list = [True, False] on_off = itertools.cycle(on_off_list) while repeat: reset_ = on_off.next() self._set_hub_power(reset_) self._peripheral_detection(peripheral_whitelist_dict, reset_) repeat -= 1 except Exception as e: raise error.TestFail(str(e)) tpm_utils.ClearTPMOwnerRequest(self.client)
def _get_section(self, bios, section): """Return start address and size of an fmap section. @param bios: string, bios file name to retrieve fmap from @param section: string, section name to look for @return tuple of ints for start and size of the section. """ # Store temp results in the attributes dictionary; when the expected # section name is found in the 'area_name:' field, the offset and size # of the section would be stored in this dictionary. attributes = {} for line in [x.strip() for x in self.run_cmd('dump_fmap %s' % bios)]: if not line: continue tokens = line.split() if tokens[0] == 'area_name:' and tokens[1] == section: return (int(attributes['area_offset:'], 16), int(attributes['area_size:'], 16)) if len(tokens) > 1: attributes[tokens[0]] = tokens[1] raise error.TestFail('Could not find section %s in the fmap' % section)
def run_once(self): """ Entry point of this test. """ self.job.install_pkg(self.dep, 'dep', self.dep_dir) with service_stopper.ServiceStopper([self.adapter_service]): binary_path = os.path.join(self.dep_dir, 'bin', self.test_binary) test_log_file = os.path.join( self.resultsdir, '%s_%s' % (self.test_name, self.test_log_suffix)) args = [ '--gtest_filter=Camera3StillCaptureTest/' 'Camera3SimpleStillCaptureTest.PerformanceTest/*', '--output_log=%s' % test_log_file ] ret = utils.system(' '.join([binary_path, ' '.join(args)]), timeout=self.timeout, ignore_status=True) self._analyze_log(test_log_file) if ret != 0: msg = 'Failed to execute command: ' + ' '.join( [binary_path, ' '.join(args)]) raise error.TestFail(msg)
def _check_update_engine_log_for_entry(self, entry, raise_error=False, err_str=None, update_engine_log=None): """ Checks for entries in the update_engine log. @param entry: The line to search for. @param raise_error: Fails tests if log doesn't contain entry. @param err_str: The error string to raise if we cannot find entry. @param update_engine_log: Update engine log string you want to search. If None, we will read from the current update engine log. @return Boolean if the update engine log contains the entry. """ if update_engine_log: result = self._run('echo "%s" | grep "%s"' % (update_engine_log, entry), ignore_status=True) else: result = self._run('cat %s | grep "%s"' % (self._UPDATE_ENGINE_LOG, entry), ignore_status=True) if result.exit_status != 0: if raise_error: error_str = 'Did not find expected string in update_engine ' \ 'log: %s' % entry logging.debug(error_str) raise error.TestFail(err_str if err_str else error_str) else: return False return True
def _execute_connect_sequence(self, device): """Execute mulitple connections and track power role This method will disconnect/connect a TypeC PD port and collect the power role statistics of each connection. The time delay for reconnect adds a random delay so that test to increase randomness for dualrole swaps. @param device: PD device object @returns list with number of SNK and SRC connections """ stats = [0, 0] random.seed() # Try N disconnect/connects for attempt in xrange(self.CONNECT_ITERATIONS): try: # Disconnect time from 1 to 2 seconds disc_time = self.PD_DISCONNECT_TIME + random.random() logging.info('Disconnect time = %.2f seconds', disc_time) # Force disconnect/connect device.cc_disconnect_connect(disc_time) # Wait for connection to be reestablished time.sleep(self.PD_DISCONNECT_TIME + self.PD_CONNECT_DELAY) # Check power role and update connection stats if device.is_snk(): stats[self.SNK] += 1 logging.info('Power Role = SNK') elif device.is_src(): stats[self.SRC] += 1 logging.info('Power Role = SRC') except NotImplementedError: raise error.TestFail('TrySRC disconnect requires Plankton') logging.info('SNK = %d: SRC = %d: Total = %d', stats[0], stats[1], self.CONNECT_ITERATIONS) return stats
def run_once(self, host=None, ssid=None, passphrase=None, ping_host=_DEFAULT_PING_HOST, ping_count=_DEFAULT_PING_COUNT, ping_timeout=_DEFAULT_PING_TIMEOUT): """Pings an Internet host with given timeout and count values. @param host: A host object representing the DUT. @param ssid: Ssid to connect to. @param passphrase: A string representing the passphrase to the ssid. @param ping_host: The Internet host to ping. @param ping_count: The number of pings to attempt. The test passes if we get at least one reply. @param ping_timeout: The number of seconds to wait for a reply. @raise TestFail: The test failed. """ if afe_utils.host_in_lab(host): ssid = site_utils.get_wireless_ssid(host.hostname) passphrase = global_config.global_config.get_config_value( 'CLIENT', 'wireless_password', default=None) host.run('am startservice -n com.google.wifisetup/.WifiSetupService ' '-a WifiSetupService.Connect -e ssid %s -e passphrase %s' % (ssid, passphrase)) @retry.retry(error.GenericHostRunError, timeout_min=1.5, delay_sec=3) def ping(): cmd = 'ping -q -c %s -W %s %s' % (ping_count, ping_timeout, ping_host) host.run(cmd) try: ping() except error.GenericHostRunError: raise error.TestFail( 'Failed to ping %s in %d seconds on all %d attempts' % (ping_host, ping_timeout, ping_count))
def compare_avtest_label_detect(self, dc_results): avtest_label = subprocess.check_output(['avtest_label_detect']).strip() logging.debug("avtest_label_detect result\n%s", avtest_label) test_failure = False avtest_detected_labels = set() for line in avtest_label.splitlines(): label = line.split(':')[1].strip() if label in video_VideoCapability.avtest_label_to_capability: cap = video_VideoCapability.avtest_label_to_capability[label] avtest_detected_labels.add(cap) for cap in video_VideoCapability.avtest_label_to_capability.values(): if dc_results[cap] == 'yes' and cap not in avtest_detected_labels: logging.error('Static capability claims %s is available. ' "But avtest_label_detect doesn't detect", cap) test_failure = True if dc_results[cap] == 'no' and cap in avtest_detected_labels: logging.error("Static capability claims %s isn't available. " 'But avtest_label_detect detects', cap) test_failure = True if test_failure: raise error.TestFail("Dynamic capability detection results did not " "match static capability configuration.")
def check_bitrates_in_capture(self, pcap_result, max_mcs_index): """ Check that frames in a packet capture have expected MCS indices. @param pcap_result: RemoteCaptureResult tuple. @param max_mcs_index: int MCS index representing the highest possible bitrate on this device. """ logging.info('Analyzing packet capture...') display_filter = 'udp and ip.src==%s' % self.context.client.wifi_ip frames = tcpdump_analyzer.get_frames(pcap_result.local_pcap_path, display_filter, reject_bad_fcs=False) logging.info('Grouping frames by MCS index') counts = {} for frame in frames: counts[frame.mcs_index] = counts.get(frame.mcs_index, 0) + 1 logging.info('Saw WiFi frames with MCS indices: %r', counts) # Now figure out the index which the device sent the most packets with. dominant_index = None num_packets_sent = -1 for index, num_packets in counts.iteritems(): if num_packets > num_packets_sent: dominant_index = index num_packets_sent = num_packets # We should see that the device sent more frames with the maximal index # than anything else. This checks that the rate controller is fairly # aggressive and using all of the device's capabilities. if dominant_index != max_mcs_index: raise error.TestFail('Failed to use best possible MCS ' 'index %d in a clean RF environment: %r' % (max_mcs_index, counts))
def CheckChipBoardId(client, board_id, flags): """Compare the given board_id and flags to the running board_id and flags Interpret board_id and flags how gsctool would interpret them, then compare those interpreted values to the running board_id and flags. Args: client: the object to run commands on board_id: a hex str, symbolic str, or int value for board_id flags: the int value of flags or None Raises: TestFail if the new board id info does not match """ # Read back the board id and flags new_board_id, _, new_flags = GetChipBoardId(client) expected_board_id = GetIntBoardId(board_id) expected_flags = GetExpectedFlags(flags) if new_board_id != expected_board_id or new_flags != expected_flags: raise error.TestFail('Failed to set board id expected %x:%x, but got ' '%x:%x' % (expected_board_id, expected_flags, new_board_id, new_flags))
def _scrape_text_from_website(self, tab): """ Returns a list of the the text content displayed on the page matching the page_scrape_cmd filter. @param tab: tab containing the website to be parsed. @raises: TestFail if the expected text content was not found on the page. """ parsed_message_string = '' parsed_message_list = [] page_scrape_cmd = 'document.getElementById("main-message").innerText;' try: parsed_message_string = tab.EvaluateJavaScript(page_scrape_cmd) except Exception as err: raise error.TestFail('Unable to find the expected ' 'text content on the test ' 'page: %s\n %r' % (tab.url, err)) logging.info('Parsed message:%s', parsed_message_string) parsed_message_list = [ str(word) for word in parsed_message_string.split('\n') if word ] return parsed_message_list
def run_once(self, wifi_timeout=2, dev=None): '''Check that WiFi interface is available after a resume @param dev: device (eg 'wlan0') to use for wifi tests. autodetected if unset. @param wifi_timeout: number of seconds within which the interface must come up after a suspend/resume cycle. ''' if dev is None: dev = self._get_wifi_dev() if dev is None: raise error.TestError('No wifi device supplied to check for' 'or found on system') random.seed() self._suspend_to_ram() start_time = datetime.datetime.now() deadline = start_time + datetime.timedelta(seconds=wifi_timeout) found_dev = None while (not found_dev) and (deadline > datetime.datetime.now()): found_dev = self._get_wifi_dev() if found_dev == dev: delay = datetime.datetime.now() - start_time logging.info('Found %s about %d ms after resume' % (dev, int(delay.total_seconds() * 1000))) return elif found_dev is not None: logging.error('Found %s on resume, was %s before suspend' % (found_dev, dev)) if found_dev != dev: delay = datetime.datetime.now() - start_time raise error.TestFail('Did not find %s after %d ms' % (dev, int(delay.total_seconds() * 1000)))
def join(self, signal=None, timeout=5.0): """ Kills the remote command and waits until it dies. Takes an optional signal argument to control which signal to send the process to be killed. @param signal Signal string to give to pkill (e.g. SIGNAL_INT). @param timeout float number of seconds to wait for join to finish. """ if signal is None: signal_arg = '' else: # In theory, it should be hard to pass something evil for signal if # we make sure it's an integer before passing it to pkill. signal_arg = '-' + str(int(signal)) # Ignore status because the command may have exited already self._host.run("pkill %s %s" % (signal_arg, self._command_name), ignore_status=True) self._thread.join(timeout) if self._thread.isAlive(): raise error.TestFail('Failed to kill remote command: %s' % self._command_name)
def get_slots_and_suffix(self): """Gets number of slots supported and slot suffixes used. Prerequisite: The DUT is in ADB mode. """ self.num_slots = int(self.dut.run_output('bootctl get-number-slots')) logging.info('Number of slots: %d', self.num_slots) self.suffix_a = self.dut.run_output('bootctl get-suffix 0') self.suffix_b = self.dut.run_output('bootctl get-suffix 1') logging.info('Slot 0 suffix: "%s"', self.suffix_a) logging.info('Slot 1 suffix: "%s"', self.suffix_b) _assert_equal(2, self.num_slots) # We're going to need the size of the boot partitions later. self.boot_a_size = int( self.dut.run_output( 'blockdev --getsize64 /dev/block/by-name/boot%s' % self.suffix_a)) self.boot_b_size = int( self.dut.run_output( 'blockdev --getsize64 /dev/block/by-name/boot%s' % self.suffix_b)) if self.boot_a_size != self.boot_b_size: raise error.TestFail('boot partitions are not the same size') logging.info('boot partition size: %d bytes', self.boot_a_size)
def run_once(self): """ Try to access different resources which are restricted by cgroup. """ logging.info('Starting cgroup testing') err = "" # Run available tests for i in ['memory', 'cpuset']: logging.info("---< 'test_%s' START >---", i) try: if not self.modules.get_pwd(i): raise error.TestFail("module not available/mounted") t_function = getattr(self, "test_%s" % i) t_function() logging.info("---< 'test_%s' PASSED >---", i) except AttributeError: err += "%s, " % i logging.error("test_%s: Test doesn't exist", i) logging.info("---< 'test_%s' FAILED >---", i) except Exception, inst: err += "%s, " % i logging.error("test_%s: %s", i, inst) logging.info("---< 'test_%s' FAILED >---", i)