def TakeScreenshot(self, identifier_mark): """Takes a screen shot from current specified device. Args: identifier_mark: A string to identify the screen shot DebugInfo will take. It will be part of filename of the screen shot. Empty string is acceptable. Returns: Returns True if successfully taking screen shot from device, otherwise returns False. """ self.InitStorage() assert isinstance(identifier_mark, str) shot_path = os.path.join( self.log_dir, ''.join([ self._GeneratePrefixName(), identifier_mark, '_screenshot.png' ])) screenshot_path = os.path.join(os.getenv('ANDROID_HOST_OUT'), 'bin', 'screenshot2') re_success = re.compile(re.escape('Success.'), re.MULTILINE) if re_success.findall( cmd_helper.GetCmdOutput( [screenshot_path, '-s', self.device, shot_path])): logging.info("Successfully took a screen shot to %s" % shot_path) return True logging.error('Failed to take screen shot from device %s' % self.device) return False
def _GetProguardData(self): proguard_output = cmd_helper.GetCmdOutput([self._PROGUARD_PATH, '-injars', self._jar_path, '-dontshrink', '-dontoptimize', '-dontobfuscate', '-dontpreverify', '-dump', ]).split('\n') clazz = None method = None annotation = None has_value = False qualified_method = None for line in proguard_output: m = self._PROGUARD_CLASS_RE.match(line) if m: clazz = m.group(1).replace('/', '.') # Change package delim. annotation = None continue m = self._PROGUARD_METHOD_RE.match(line) if m: method = m.group(1) annotation = None qualified_method = clazz + '#' + method if method.startswith('test') and clazz.endswith('Test'): self._test_methods += [qualified_method] continue if not qualified_method: # Ignore non-method annotations. continue m = self._PROGUARD_ANNOTATION_RE.match(line) if m: annotation = m.group(1).split('/')[-1] # Ignore the annotation package. self._annotation_map[qualified_method].append(annotation) has_value = False continue if annotation: if not has_value: m = self._PROGUARD_ANNOTATION_CONST_RE.match(line) if m: has_value = True else: m = self._PROGUARD_ANNOTATION_VALUE_RE.match(line) if m: value = m.group(1) self._annotation_map[qualified_method].append( annotation + ':' + value) has_value = False logging.info('Storing proguard output to %s', self._pickled_proguard_name) d = {'VERSION': PICKLE_FORMAT_VERSION, 'ANNOTATION_MAP': self._annotation_map, 'TEST_METHODS': self._test_methods} with open(self._pickled_proguard_name, 'w') as f: f.write(pickle.dumps(d))
def GetPackageNameForApk(apk_path): """Returns the package name of the apk file.""" aapt_output = cmd_helper.GetCmdOutput( ['aapt', 'dump', 'badging', apk_path]).split('\n') package_name_re = re.compile(r'package: .*name=\'(\S*)\'') for line in aapt_output: m = package_name_re.match(line) if m: return m.group(1) raise Exception('Failed to determine package name of %s' % apk_path)
def _Initialize(self): proguard_output = cmd_helper.GetCmdOutput([ self._PROGUARD_PATH, '-injars', self._jar_path, '-dontshrink', '-dontoptimize', '-dontobfuscate', '-dontpreverify', '-dump', ]).split('\n') clazz = None method = None annotation = None has_value = False qualified_method = None for line in proguard_output: m = self._PROGUARD_CLASS_RE.match(line) if m: clazz = m.group(1).replace('/', '.') # Change package delim. annotation = None continue m = self._PROGUARD_METHOD_RE.match(line) if m: method = m.group(1) annotation = None qualified_method = clazz + '#' + method if method.startswith('test') and clazz.endswith('Test'): self._test_methods += [qualified_method] continue m = self._PROGUARD_ANNOTATION_RE.match(line) if m: assert qualified_method annotation = m.group(1).split('/')[ -1] # Ignore the annotation package. self._annotation_map[qualified_method].append(annotation) has_value = False continue if annotation: assert qualified_method if not has_value: m = self._PROGUARD_ANNOTATION_CONST_RE.match(line) if m: has_value = True else: m = self._PROGUARD_ANNOTATION_VALUE_RE.match(line) if m: value = m.group(1) self._annotation_map[qualified_method].append( annotation + ':' + value) has_value = False
def GetEmulators(): """Returns a list of emulators. Does not filter by status (e.g. offline). Both devices starting with 'emulator' will be returned in below output: * daemon not running. starting it now on port 5037 * * daemon started successfully * List of devices attached 027c10494100b4d7 device emulator-5554 offline emulator-5558 device """ re_device = re.compile('^emulator-[0-9]+', re.MULTILINE) devices = re_device.findall(cmd_helper.GetCmdOutput(['adb', 'devices'])) return devices
def _KillAllEmulators(): """Kill all running emulators that look like ones we started. There are odd 'sticky' cases where there can be no emulator process running but a device slot is taken. A little bot trouble and and we're out of room forever. """ emulators = android_commands.GetEmulators() if not emulators: return for emu_name in emulators: cmd_helper.GetCmdOutput(['adb', '-s', emu_name, 'emu', 'kill']) logging.info('Emulator killing is async; give a few seconds for all to die.') for i in range(5): if not android_commands.GetEmulators(): return time.sleep(1)
def IsHostPortUsed(host_port): """Checks whether the specified host port is used or not. Uses -n -P to inhibit the conversion of host/port numbers to host/port names. Args: host_port: Port on host we want to check. Returns: True if the port on host is already used, otherwise returns False. """ port_info = '(127\.0\.0\.1)|(localhost)\:%d' % host_port # TODO(jnd): Find a better way to filter the port. re_port = re.compile(port_info, re.MULTILINE) if re_port.findall(cmd_helper.GetCmdOutput(['lsof', '-nPi:%d' % host_port])): return True return False
def IsHostPortUsed(host_port): """Checks whether the specified host port is used or not. Uses -n -P to inhibit the conversion of host/port numbers to host/port names. Args: host_port: Port on host we want to check. Returns: True if the port on host is already used, otherwise returns False. """ port_info = '(\*)|(127\.0\.0\.1)|(localhost):%d' % host_port # TODO(jnd): Find a better way to filter the port. Note that connecting to the # socket and closing it would leave it in the TIME_WAIT state. Setting # SO_LINGER on it and then closing it makes the Python HTTP server crash. re_port = re.compile(port_info, re.MULTILINE) if re_port.search(cmd_helper.GetCmdOutput(['lsof', '-nPi:%d' % host_port])): return True return False
def GetAttachedDevices(): """Returns a list of attached, online android devices. If a preferred device has been set with ANDROID_SERIAL, it will be first in the returned list. Example output: * daemon not running. starting it now on port 5037 * * daemon started successfully * List of devices attached 027c10494100b4d7 device emulator-5554 offline """ re_device = re.compile('^([a-zA-Z0-9_:.-]+)\tdevice$', re.MULTILINE) devices = re_device.findall(cmd_helper.GetCmdOutput(['adb', 'devices'])) preferred_device = os.environ.get('ANDROID_SERIAL') if preferred_device in devices: devices.remove(preferred_device) devices.insert(0, preferred_device) return devices
def GetAVDs(): """Returns a list of AVDs.""" re_avd = re.compile('^[ ]+Name: ([a-zA-Z0-9_:.-]+)', re.MULTILINE) avds = re_avd.findall(cmd_helper.GetCmdOutput(['android', 'list', 'avd'])) return avds