def main(argv): parser = optparse.OptionParser() parser.set_usage("usage: %prog [options] target") AddInstallAPKOption(parser) options, args = parser.parse_args(argv) if len(args) > 1 and options.apk: parser.error("Appending the apk as argument can't be used with --apk.") elif len(args) > 2: parser.error("Too many arguments.") constants.SetBuildType(options.build_type) ValidateInstallAPKOption(parser, options, args) devices = device_utils.DeviceUtils.HealthyDevices() if options.device: devices = [d for d in devices if d == options.device] if not devices: raise device_errors.DeviceUnreachableError(options.device) elif not devices: raise device_errors.NoDevicesError() device_utils.DeviceUtils.parallel(devices).Install( options.apk, reinstall=options.keep_data)
def InitShell(self, device=None): ''' Runs adb as root, and installs the apk as needed. |device| is the target device to run on, if multiple devices are connected. Returns 0 on success or a non-zero exit code on a terminal failure. ''' try: devices = device_utils.DeviceUtils.HealthyDevices() if device: self.device = next((d for d in devices if d == device), None) if not self.device: raise device_errors.DeviceUnreachableError(device) elif devices: self.device = devices[0] else: raise device_errors.NoDevicesError() logging.getLogger().debug('Using device: %s', self.device) # Clean the logs on the device to avoid displaying prior activity. subprocess.check_call(self._CreateADBCommand(['logcat', '-c'])) self.device.EnableRoot() self.device.Install(self.paths.apk_path) except base_error.BaseError as e: # Report 'device not found' as infra failures. See http://crbug.com/493900 print 'Exception in AndroidShell.InitShell:\n%s' % str(e) if e.is_infra_error or 'error: device not found' in str(e): return constants.INFRA_EXIT_CODE return constants.ERROR_EXIT_CODE return 0
def main(argv): parser = optparse.OptionParser(usage='Usage: %prog [options] device_port ' 'host_port [device_port_2 host_port_2] ...', description=__doc__) parser.add_option('-v', '--verbose', dest='verbose_count', default=0, action='count', help='Verbose level (multiple times for more)') parser.add_option('--device', help='Serial number of device we should use.') parser.add_option('--blacklist-file', help='Device blacklist JSON file.') parser.add_option('--debug', action='store_const', const='Debug', dest='build_type', default='Release', help='Use Debug build of host tools instead of Release.') options, args = parser.parse_args(argv) run_tests_helper.SetLogLevel(options.verbose_count) if len(args) < 2 or not len(args) % 2: parser.error('Need even number of port pairs') sys.exit(1) try: port_pairs = map(int, args[1:]) port_pairs = zip(port_pairs[::2], port_pairs[1::2]) except ValueError: parser.error('Bad port number') sys.exit(1) if options.blacklist_file: blacklist = device_blacklist.Blacklist(options.blacklist_file) else: blacklist = None devices = device_utils.DeviceUtils.HealthyDevices(blacklist) if options.device: device = next((d for d in devices if d == options.device), None) if not device: raise device_errors.DeviceUnreachableError(options.device) elif devices: device = devices[0] logging.info('No device specified. Defaulting to %s', devices[0]) else: raise device_errors.NoDevicesError() constants.SetBuildType(options.build_type) try: forwarder.Forwarder.Map(port_pairs, device) while True: time.sleep(60) except KeyboardInterrupt: sys.exit(0) finally: forwarder.Forwarder.UnmapAllDevicePorts(device)
def _GetAttachedDevices(blacklist_file, test_device): """Get all attached devices. Args: test_device: Name of a specific device to use. Returns: A list of attached devices. """ if not blacklist_file: # TODO(jbudorick): Remove this once bots pass the blacklist file. blacklist_file = device_blacklist.BLACKLIST_JSON logging.warning('Using default device blacklist %s', device_blacklist.BLACKLIST_JSON) blacklist = device_blacklist.Blacklist(blacklist_file) attached_devices = device_utils.DeviceUtils.HealthyDevices(blacklist) if test_device: test_device = [d for d in attached_devices if d == test_device] if not test_device: raise device_errors.DeviceUnreachableError( 'Did not find device %s among attached device. Attached devices: %s' % (test_device, ', '.join(attached_devices))) return test_device else: if not attached_devices: raise device_errors.NoDevicesError() return sorted(attached_devices)
def __str__(self): """Returns the device serial.""" s = self.old_interface.GetDevice() if not s: s = self.old_interface.Adb().GetSerialNumber() if s == 'unknown': raise device_errors.NoDevicesError() return s
def GlobalSetUp(self): os.putenv('TEST_HTTP_PORT', str(ANDROID_TEST_HTTP_PORT)) os.putenv('TEST_HTTPS_PORT', str(ANDROID_TEST_HTTPS_PORT)) devices = device_utils.DeviceUtils.HealthyDevices() if not devices: raise device_errors.NoDevicesError() elif len(devices) > 1: logging.warning('Multiple devices attached. Using %s.' % devices[0]) self._device = devices[0] forwarder.Forwarder.Map( [(ANDROID_TEST_HTTP_PORT, ANDROID_TEST_HTTP_PORT), (ANDROID_TEST_HTTPS_PORT, ANDROID_TEST_HTTPS_PORT)], self._device)
def main(): # Parse options. parser = optparse.OptionParser(description=__doc__, usage='screenshot.py [options] [filename]') parser.add_option('-d', '--device', metavar='ANDROID_DEVICE', help='Serial ' 'number of Android device to use.', default=None) parser.add_option('-f', '--file', help='Save result to file instead of ' 'generating a timestamped file name.', metavar='FILE') parser.add_option('-v', '--verbose', help='Verbose logging.', action='store_true') video_options = optparse.OptionGroup(parser, 'Video capture') video_options.add_option('--video', help='Enable video capturing. Requires ' 'Android KitKat or later', action='store_true') video_options.add_option('-b', '--bitrate', help='Bitrate in megabits/s, ' 'from 0.1 to 100 mbps, %default mbps by default.', default=4, type='float') video_options.add_option('-r', '--rotate', help='Rotate video by 90 degrees.', default=False, action='store_true') video_options.add_option('-s', '--size', metavar='WIDTHxHEIGHT', help='Frame size to use instead of the device ' 'screen size.', default=None) parser.add_option_group(video_options) (options, args) = parser.parse_args() if len(args) > 1: parser.error('Too many positional arguments.') host_file = args[0] if args else options.file if options.verbose: logging.getLogger().setLevel(logging.DEBUG) devices = device_utils.DeviceUtils.HealthyDevices() if options.device: device = next((d for d in devices if d == options.device), None) if not device: raise device_errors.DeviceUnreachableError(options.device) else: if len(devices) > 1: parser.error('Multiple devices are attached. ' 'Please specify device serial number with --device.') elif len(devices) == 1: device = devices[0] else: raise device_errors.NoDevicesError() if options.video: _CaptureVideo(device, host_file, options) else: _CaptureScreenshot(device, host_file) return 0
def main(): parser = argparse.ArgumentParser( description="Script to do semi-automated upgrade testing.") parser.add_argument('-v', '--verbose', action='count', help='Print verbose log information.') parser.add_argument('--blacklist-file', help='Device blacklist JSON file.') command_parsers = parser.add_subparsers(dest='command') subparser = command_parsers.add_parser('create_app_data') subparser.add_argument('--old-apk', required=True, help='Path to apk to update from.') subparser.add_argument('--app-data', required=True, help='Path to where the app data backup should be ' 'saved to.') subparser.add_argument('--package-name', help='Chrome apk package name.') subparser = command_parsers.add_parser('test_update') subparser.add_argument('--old-apk', required=True, help='Path to apk to update from.') subparser.add_argument('--new-apk', required=True, help='Path to apk to update to.') subparser.add_argument('--app-data', required=True, help='Path to where the app data backup is saved.') subparser.add_argument('--package-name', help='Chrome apk package name.') args = parser.parse_args() run_tests_helper.SetLogLevel(args.verbose) if args.blacklist_file: blacklist = device_blacklist.Blacklist(args.blacklist_file) else: blacklist = None devices = device_utils.DeviceUtils.HealthyDevices(blacklist) if not devices: raise device_errors.NoDevicesError() device = devices[0] logging.info('Using device %s for testing.' % str(device)) package_name = (args.package_name if args.package_name else apk_helper.GetPackageName(args.old_apk)) if args.command == 'create_app_data': CreateAppData(device, args.old_apk, args.app_data, package_name) elif args.command == 'test_update': TestUpdate( device, args.old_apk, args.new_apk, args.app_data, package_name) else: raise Exception('Unknown test command: %s' % args.command)
def _GetAttachedDevices(test_device=None): """Get all attached devices. Args: test_device: Name of a specific device to use. Returns: A list of attached devices. """ attached_devices = device_utils.DeviceUtils.HealthyDevices() if test_device: test_device = [d for d in attached_devices if d == test_device] if not test_device: raise device_errors.DeviceUnreachableError( 'Did not find device %s among attached device. Attached devices: %s' % (test_device, ', '.join(attached_devices))) return test_device else: if not attached_devices: raise device_errors.NoDevicesError() return sorted(attached_devices)
def InitShell(self, origin='localhost', device=None): """ Runs adb as root, starts an origin server, and installs the apk as needed. |origin| is the origin for mojo: URLs; if its value is 'localhost', a local http server will be set up to serve files from the build directory. |device| is the target device to run on, if multiple devices are connected. Returns 0 on success or a non-zero exit code on a terminal failure. """ try: devices = device_utils.DeviceUtils.HealthyDevices() if device: self.device = next((d for d in devices if d == device), None) if not self.device: raise device_errors.DeviceUnreachableError(device) elif devices: self.device = devices[0] else: raise device_errors.NoDevicesError() logging.getLogger().debug("Using device: %s", self.device) # Clean the logs on the device to avoid displaying prior activity. subprocess.check_call(self._CreateADBCommand(['logcat', '-c'])) self.device.EnableRoot() self.device.Install(self.paths.apk_path) except base_error.BaseError as e: # Report "device not found" as infra failures. See http://crbug.com/493900 print "Exception in AndroidShell.InitShell:\n%s" % str(e) if e.is_infra_error or "error: device not found" in str(e): return constants.INFRA_EXIT_CODE return constants.ERROR_EXIT_CODE if origin is 'localhost': origin = self._StartHttpServerForDirectory(self.paths.build_dir) if origin: self.shell_args.append("--origin=" + origin) return 0
def main(argv): option_parser = optparse.OptionParser() option_parser.add_option('-l', '--low', help='Simulate Activity#onLowMemory()', action='store_true') option_parser.add_option( '-t', '--trim', help=('Simulate Activity#onTrimMemory(...) with ' + ', '.join(ACTION_TRIM.keys())), type='string') option_parser.add_option('-b', '--browser', default=DEFAULT_BROWSER, help=('Which browser to use. One of ' + ', '.join(constants.PACKAGE_INFO.keys()) + ' [default: %default]'), type='string') (options, args) = option_parser.parse_args(argv) if len(args) > 1: print 'Unknown argument: ', args[1:] option_parser.print_help() sys.exit(1) if options.low and options.trim: option_parser.error('options --low and --trim are mutually exclusive') if not options.low and not options.trim: option_parser.print_help() sys.exit(1) action = None if options.low: action = ACTION_LOW elif options.trim in ACTION_TRIM.keys(): action = ACTION_TRIM[options.trim] if action is None: option_parser.print_help() sys.exit(1) if not options.browser in constants.PACKAGE_INFO.keys(): option_parser.error('Unknown browser option ' + options.browser) package_info = constants.PACKAGE_INFO[options.browser] package = package_info.package activity = package_info.activity devices = device_utils.DeviceUtils.HealthyDevices() if not devices: raise device_errors.NoDevicesError() elif len(devices) > 1: logging.warning('Multiple devices attached. Using %s.', str(devices[0])) device = devices[0] try: device.EnableRoot() except device_errors.CommandFailedError as e: # Try to change the flags and start the activity anyway. # TODO(jbudorick) Handle this exception appropriately after interface # conversions are finished. logging.error(str(e)) flags = flag_changer.FlagChanger(device, package_info.cmdline_file) if ENABLE_TEST_INTENTS_FLAG not in flags.Get(): flags.AddFlags([ENABLE_TEST_INTENTS_FLAG]) device.StartActivity( intent.Intent(package=package, activity=activity, action=action))
def main(): parser = argparse.ArgumentParser() apk_group = parser.add_mutually_exclusive_group(required=True) apk_group.add_argument('--apk', dest='apk_name', help='DEPRECATED The name of the apk containing the' ' application (with the .apk extension).') apk_group.add_argument('apk_path', nargs='?', help='The path to the APK to install.') # TODO(jbudorick): Remove once no clients pass --apk_package parser.add_argument('--apk_package', help='DEPRECATED unused') parser.add_argument('--split', action='append', dest='splits', help='A glob matching the apk splits. ' 'Can be specified multiple times.') parser.add_argument('--keep_data', action='store_true', default=False, help='Keep the package data when installing ' 'the application.') parser.add_argument('--debug', action='store_const', const='Debug', dest='build_type', default=os.environ.get('BUILDTYPE', 'Debug'), help='If set, run test suites under out/Debug. ' 'Default is env var BUILDTYPE or Debug') parser.add_argument('--release', action='store_const', const='Release', dest='build_type', help='If set, run test suites under out/Release. ' 'Default is env var BUILDTYPE or Debug.') parser.add_argument('-d', '--device', dest='device', help='Target device for apk to install on.') parser.add_argument('-v', '--verbose', action='count', help='Enable verbose logging.') args = parser.parse_args() run_tests_helper.SetLogLevel(args.verbose) constants.SetBuildType(args.build_type) apk = args.apk_path or args.apk_name if not apk.endswith('.apk'): apk += '.apk' if not os.path.exists(apk): apk = os.path.join(constants.GetOutDirectory(), 'apks', apk) if not os.path.exists(apk): parser.error('%s not found.' % apk) if args.splits: splits = [] base_apk_package = apk_helper.ApkHelper(apk).GetPackageName() for split_glob in args.splits: apks = [f for f in glob.glob(split_glob) if f.endswith('.apk')] if not apks: logging.warning('No apks matched for %s.' % split_glob) for f in apks: helper = apk_helper.ApkHelper(f) if (helper.GetPackageName() == base_apk_package and helper.GetSplitName()): splits.append(f) devices = device_utils.DeviceUtils.HealthyDevices() if args.device: devices = [d for d in devices if d == args.device] if not devices: raise device_errors.DeviceUnreachableError(args.device) elif not devices: raise device_errors.NoDevicesError() def blacklisting_install(device): try: if args.splits: device.InstallSplitApk(apk, splits, reinstall=args.keep_data) else: device.Install(apk, reinstall=args.keep_data) except device_errors.CommandFailedError: logging.exception('Failed to install %s', args.apk_name) device_blacklist.ExtendBlacklist([str(device)]) logging.warning('Blacklisting %s', str(device)) except device_errors.CommandTimeoutError: logging.exception('Timed out while installing %s', args.apk_name) device_blacklist.ExtendBlacklist([str(device)]) logging.warning('Blacklisting %s', str(device)) device_utils.DeviceUtils.parallel(devices).pMap(blacklisting_install)
def main(): logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') parser = argparse.ArgumentParser() parser.add_argument('apk_path', help='The path to the APK to install.') parser.add_argument('--split', action='append', dest='splits', help='A glob matching the apk splits. ' 'Can be specified multiple times.') parser.add_argument('--lib-dir', help='Path to native libraries directory.') parser.add_argument('-d', '--device', dest='device', help='Target device for apk to install on.') parser.add_argument('--uninstall', action='store_true', default=False, help='Remove the app and all side-loaded files.') args = parser.parse_args() constants.SetBuildType('Debug') if args.device: # Retries are annoying when commands fail for legitimate reasons. Might want # to enable them if this is ever used on bots though. device = device_utils.DeviceUtils(args.device, default_retries=0) else: devices = device_utils.DeviceUtils.HealthyDevices(default_retries=0) if not devices: raise device_errors.NoDevicesError() elif len(devices) > 1: raise Exception('More than one device available.\n' 'Use --device=SERIAL to select a device.') device = devices[0] apk_package = apk_helper.ApkHelper(args.apk_path).GetPackageName() device_incremental_dir = '/data/local/tmp/incremental-app-%s' % apk_package if args.uninstall: logging.info('Uninstalling .apk') device.Uninstall(apk_package) logging.info('Removing side-loaded files') device.RunShellCommand(['rm', '-rf', device_incremental_dir], check_return=True) return # Install .apk(s) if any of them have changed. logging.info('Installing .apk') if args.splits: splits = [] for split_glob in args.splits: splits.extend((f for f in glob.glob(split_glob))) device.InstallSplitApk(args.apk_path, splits, reinstall=True) else: device.Install(args.apk_path, reinstall=True) # Push .so files to the device (if they have changed). if args.lib_dir: logging.info('Pushing libraries') device_lib_dir = posixpath.join(device_incremental_dir, 'lib') device.PushChangedFiles([(args.lib_dir, device_lib_dir)], delete_device_stale=True)