def main():
  parser = argparse.ArgumentParser(
      'Run an adb shell command on selected devices')
  parser.add_argument('cmd', help='Adb shell command to run.', nargs="+")
  logging_common.AddLoggingArguments(parser)
  script_common.AddDeviceArguments(parser)
  script_common.AddEnvironmentArguments(parser)
  parser.add_argument('--as-root', action='store_true', help='Run as root.')
  parser.add_argument('--json-output', help='File to dump json output to.')
  args = parser.parse_args()

  logging_common.InitializeLogging(args)
  script_common.InitializeEnvironment(args)

  devices = script_common.GetDevices(args.devices, args.denylist_file)
  p_out = (device_utils.DeviceUtils.parallel(devices).RunShellCommand(
      args.cmd, large_output=True, as_root=args.as_root,
      check_return=True).pGet(None))

  data = {}
  for device, output in zip(devices, p_out):
    for line in output:
      print '%s: %s' % (device, line)
    data[str(device)] = output

  if args.json_output:
    with open(args.json_output, 'w') as f:
      json.dump(data, f)

  return 0
Example #2
0
def main():
  # Parse options.
  parser = argparse.ArgumentParser(description=__doc__)
  logging_common.AddLoggingArguments(parser)
  script_common.AddDeviceArguments(parser)
  parser.add_argument(
      '-f',
      '--file',
      metavar='FILE',
      help='Save result to file instead of generating a '
      'timestamped file name.')
  parser.add_argument(
      'host_file',
      nargs='?',
      help='File to which the screenshot will be saved.')

  args = parser.parse_args()
  host_file = args.host_file or args.file
  logging_common.InitializeLogging(args)

  devices = script_common.GetDevices(args.devices, args.blacklist_file)

  def screenshot(device):
    f = None
    if host_file:
      root, ext = os.path.splitext(host_file)
      f = '%s_%s%s' % (root, str(device), ext)
    f = device.TakeScreenshot(f)
    print 'Screenshot for device %s written to %s' % (str(device),
                                                      os.path.abspath(f))

  device_utils.DeviceUtils.parallel(devices).pMap(screenshot)
  return 0
Example #3
0
def main(raw_args):
    parser = argparse.ArgumentParser(
        description="Use your keyboard as your phone's keyboard.")
    logging_common.AddLoggingArguments(parser)
    script_common.AddDeviceArguments(parser)
    args = parser.parse_args(raw_args)

    logging_common.InitializeLogging(args)

    devices = script_common.GetDevices(args.devices, None)
    if len(devices) > 1:
        raise MultipleDevicesError(devices)

    def next_char():
        while True:
            yield sys.stdin.read(1)

    try:
        fd = sys.stdin.fileno()

        # See man 3 termios for more info on what this is doing.
        old_attrs = termios.tcgetattr(fd)
        new_attrs = copy.deepcopy(old_attrs)
        new_attrs[tty.LFLAG] = new_attrs[tty.LFLAG] & ~(termios.ICANON)
        new_attrs[tty.CC][tty.VMIN] = 1
        new_attrs[tty.CC][tty.VTIME] = 0
        termios.tcsetattr(fd, termios.TCSAFLUSH, new_attrs)

        Keyboard(devices[0], next_char())
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, old_attrs)
    return 0
Example #4
0
def main(raw_args):
  parser = argparse.ArgumentParser()
  parser.add_argument('--debug', action='store_true',
                      help='Get additional debugging mode')
  parser.add_argument(
      '--output-directory',
      help='the path to the build output directory, such as out/Debug')
  parser.add_argument('--report-path',
                      default='report.html', help='Report path')
  parser.add_argument('--adb-path',
                      help='Absolute path to the adb binary to use.')

  script_common.AddDeviceArguments(parser)
  logging_common.AddLoggingArguments(parser)

  args = parser.parse_args(raw_args)
  logging_common.InitializeLogging(args)
  devil_chromium.Initialize(adb_path=args.adb_path)

  devices = script_common.GetDevices(args.devices, args.blacklist_file)
  device = devices[0]

  if len(devices) > 1:
    raise device_errors.MultipleDevicesError(devices)

  with tempfile_ext.NamedTemporaryDirectory(
      prefix='tmp_simpleperf') as tmp_dir:
    runner = SimplePerfRunner(
        device, args, tmp_dir,
        StackAddressInterpreter(args, tmp_dir))
    runner.Run()
Example #5
0
def main(raw_args):
  parser = argparse.ArgumentParser(
      description="Use your keyboard as your phone's keyboard.")
  script_common.AddDeviceArguments(parser)
  parser.add_argument('-v', '--verbose', action='count', help='print more')
  args = parser.parse_args(raw_args)

  run_tests_helper.SetLogLevel(args.verbose)

  devices = script_common.GetDevices(args.devices, None)
  if len(devices) > 1:
    raise MultipleDevicesError(devices)

  def next_char():
    while True:
      yield sys.stdin.read(1)

  try:
    fd = sys.stdin.fileno()

    # See man 3 termios for more info on what this is doing.
    old_attrs = termios.tcgetattr(fd)
    new_attrs = copy.deepcopy(old_attrs)
    new_attrs[tty.LFLAG] = new_attrs[tty.LFLAG] & ~(termios.ICANON)
    new_attrs[tty.CC][tty.VMIN] = 1
    new_attrs[tty.CC][tty.VTIME] = 0
    termios.tcsetattr(fd, termios.TCSAFLUSH, new_attrs)

    Keyboard(devices[0], next_char())
  finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, old_attrs)
  return 0
Example #6
0
def main(raw_args):
  parser = argparse.ArgumentParser()
  subparsers = parser.add_subparsers()

  def add_common_arguments(p):
    script_common.AddDeviceArguments(p)
    p.add_argument(
        '--adb-path', help='Path to the adb binary.')
    p.add_argument(
        '-v', '--verbose', action='count', default=0,
        help='Print more information.')
    p.add_argument('command', nargs='*')

  @contextlib.contextmanager
  def remove_system_app(device, args):
    RemoveSystemApps(device, args.packages)
    yield

  remove_parser = subparsers.add_parser('remove')
  remove_parser.add_argument(
      '--package', dest='packages', nargs='*', required=True,
      help='The system package(s) to remove.')
  add_common_arguments(remove_parser)
  remove_parser.set_defaults(func=remove_system_app)

  @contextlib.contextmanager
  def replace_system_app(device, args):
    with ReplaceSystemApp(device, args.package, args.replace_with):
      yield

  replace_parser = subparsers.add_parser('replace')
  replace_parser.add_argument(
      '--package', required=True,
      help='The system package to replace.')
  replace_parser.add_argument(
      '--replace-with', metavar='APK', required=True,
      help='The APK with which the existing system app should be replaced.')
  add_common_arguments(replace_parser)
  replace_parser.set_defaults(func=replace_system_app)

  args = parser.parse_args(raw_args)

  run_tests_helper.SetLogLevel(args.verbose)

  devil_dynamic_config = devil_env.EmptyConfig()
  if args.adb_path:
    devil_dynamic_config['dependencies'].update(
        devil_env.LocalConfigItem(
            'adb', devil_env.GetPlatform(), args.adb_path))

  devil_env.config.Initialize(configs=[devil_dynamic_config])

  devices = script_common.GetDevices(args.devices, args.blacklist_file)
  parallel_devices = parallelizer.SyncParallelizer(
      [args.func(d, args) for d in devices])
  with parallel_devices:
    if args.command:
      return cmd_helper.Call(args.command)
    return 0
def ProvisionDevices(devices,
                     blacklist_file,
                     adb_key_files=None,
                     disable_location=False,
                     disable_mock_location=False,
                     disable_network=False,
                     disable_system_chrome=False,
                     emulators=False,
                     enable_java_debug=False,
                     max_battery_temp=None,
                     min_battery_level=None,
                     output_device_blacklist=None,
                     reboot_timeout=None,
                     remove_system_webview=False,
                     wipe=True):
    blacklist = (device_blacklist.Blacklist(blacklist_file)
                 if blacklist_file else None)
    devices = script_common.GetDevices(devices, blacklist)
    devices = [d for d in devices if not emulators or d.adb.is_emulator]
    parallel_devices = device_utils.DeviceUtils.parallel(devices)

    steps = []
    if wipe:
        steps += [ProvisionStep(lambda d: Wipe(d, adb_key_files), reboot=True)]
    steps += [
        ProvisionStep(lambda d: SetProperties(
            d, enable_java_debug, disable_location, disable_mock_location),
                      reboot=not emulators)
    ]

    if disable_network:
        steps.append(ProvisionStep(DisableNetwork))

    if disable_system_chrome:
        steps.append(ProvisionStep(DisableSystemChrome))

    if max_battery_temp:
        steps.append(
            ProvisionStep(lambda d: WaitForTemperature(d, max_battery_temp)))

    if min_battery_level:
        steps.append(
            ProvisionStep(lambda d: WaitForCharge(d, min_battery_level)))

    if remove_system_webview:
        steps.append(ProvisionStep(RemoveSystemWebView))

    steps.append(ProvisionStep(SetDate))
    steps.append(ProvisionStep(CheckExternalStorage))

    parallel_devices.pMap(ProvisionDevice, steps, blacklist, reboot_timeout)

    blacklisted_devices = blacklist.Read() if blacklist else []
    if output_device_blacklist:
        with open(output_device_blacklist, 'w') as f:
            json.dump(blacklisted_devices, f)
    if all(d in blacklisted_devices for d in devices):
        raise device_errors.NoDevicesError
    return 0
Example #8
0
def main():
  # Parse options.
  parser = argparse.ArgumentParser(description=__doc__)
  parser.add_argument('-d', '--device', dest='devices', action='append',
                      help='Serial number of Android device to use.')
  parser.add_argument('--blacklist-file', help='Device blacklist JSON file.')
  parser.add_argument('-f', '--file', metavar='FILE',
                      help='Save result to file instead of generating a '
                           'timestamped file name.')
  parser.add_argument('-v', '--verbose', action='store_true',
                      help='Verbose logging.')
  parser.add_argument('-b', '--bitrate', default=4, type=float,
                      help='Bitrate in megabits/s, from 0.1 to 100 mbps, '
                           '%default mbps by default.')
  parser.add_argument('-r', '--rotate', action='store_true',
                      help='Rotate video by 90 degrees.')
  parser.add_argument('-s', '--size', metavar='WIDTHxHEIGHT',
                      help='Frame size to use instead of the device '
                           'screen size.')
  parser.add_argument('host_file', nargs='?',
                      help='File to which the video capture will be written.')

  args = parser.parse_args()

  host_file = args.host_file or args.file

  if args.verbose:
    logging.getLogger().setLevel(logging.DEBUG)

  size = (tuple(int(i) for i in args.size.split('x'))
          if args.size
          else None)

  def record_video(device, stop_recording):
    recorder = VideoRecorder(
        device, megabits_per_second=args.bitrate, size=size, rotate=args.rotate)
    with recorder:
      stop_recording.wait()

    f = None
    if host_file:
      root, ext = os.path.splitext(host_file)
      f = '%s_%s%s' % (root, str(device), ext)
    f = recorder.Pull(f)
    print 'Video written to %s' % os.path.abspath(f)

  parallel_devices = device_utils.DeviceUtils.parallel(
      script_common.GetDevices(args.devices, args.blacklist_file),
      async=True)
  stop_recording = threading.Event()
  running_recording = parallel_devices.pMap(record_video, stop_recording)
  print 'Recording. Press Enter to stop.',
  sys.stdout.flush()
  raw_input()
  stop_recording.set()

  running_recording.pGet(None)
  return 0
Example #9
0
def main(raw_args):
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    def add_common_arguments(p):
        script_common.AddDeviceArguments(p)
        script_common.AddEnvironmentArguments(p)
        p.add_argument('-v',
                       '--verbose',
                       action='count',
                       default=0,
                       help='Print more information.')
        p.add_argument('command', nargs='*')

    @contextlib.contextmanager
    def remove_system_app(device, args):
        RemoveSystemApps(device, args.packages)
        yield

    remove_parser = subparsers.add_parser('remove')
    remove_parser.add_argument('--package',
                               dest='packages',
                               nargs='*',
                               required=True,
                               help='The system package(s) to remove.')
    add_common_arguments(remove_parser)
    remove_parser.set_defaults(func=remove_system_app)

    @contextlib.contextmanager
    def replace_system_app(device, args):
        with ReplaceSystemApp(device, args.package, args.replace_with):
            yield

    replace_parser = subparsers.add_parser('replace')
    replace_parser.add_argument('--package',
                                required=True,
                                help='The system package to replace.')
    replace_parser.add_argument(
        '--replace-with',
        metavar='APK',
        required=True,
        help='The APK with which the existing system app should be replaced.')
    add_common_arguments(replace_parser)
    replace_parser.set_defaults(func=replace_system_app)

    args = parser.parse_args(raw_args)

    run_tests_helper.SetLogLevel(args.verbose)
    script_common.InitializeEnvironment(args)

    devices = script_common.GetDevices(args.devices, args.denylist_file)
    parallel_devices = parallelizer.SyncParallelizer(
        [args.func(d, args) for d in devices])
    with parallel_devices:
        if args.command:
            return cmd_helper.Call(args.command)
        return 0
Example #10
0
 def testNoSpecs(self):
     devices = [
         device_utils.DeviceUtils('123'),
         device_utils.DeviceUtils('456'),
     ]
     with mock.patch(
             'devil.android.device_utils.DeviceUtils.HealthyDevices',
             return_value=devices):
         self.assertEquals(devices, script_common.GetDevices(None, None))
Example #11
0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('build_path', help='Path to android build.')
  parser.add_argument(
      '-w', '--wipe', action='store_true', help='If set, wipes user data')
  logging_common.AddLoggingArguments(parser)
  script_common.AddDeviceArguments(parser)
  args = parser.parse_args()
  logging_common.InitializeLogging(args)

  if args.blacklist_file:
    blacklist = device_blacklist.Blacklist(args.blacklist_file).Read()
    if blacklist:
      logger.critical('Device(s) in blacklist, not flashing devices:')
      for key in blacklist:
        logger.critical('  %s', key)
      return exit_codes.INFRA

  flashed_devices = []
  failed_devices = []

  def flash(device):
    try:
      device.FlashDevice(args.build_path, wipe=args.wipe)
      flashed_devices.append(device)
    except Exception:  # pylint: disable=broad-except
      logger.exception('Device %s failed to flash.', str(device))
      failed_devices.append(device)

  devices = []
  try:
    adb_devices = script_common.GetDevices(args.devices, args.blacklist_file)
    devices += [fastboot_utils.FastbootUtils(device=d) for d in adb_devices]
  except device_errors.NoDevicesError:
    # Don't bail out if we're not looking for any particular device and there's
    # at least one sitting in fastboot mode. Note that if we ARE looking for a
    # particular device, and it's in fastboot mode, this will still fail.
    fastboot_devices = fastboot.Fastboot.Devices()
    if args.devices or not fastboot_devices:
      raise
    devices += [
        fastboot_utils.FastbootUtils(fastbooter=d) for d in fastboot_devices
    ]

  parallel_devices = parallelizer.SyncParallelizer(devices)
  parallel_devices.pMap(flash)

  if flashed_devices:
    logger.info('The following devices were flashed:')
    logger.info('  %s', ' '.join(str(d) for d in flashed_devices))
  if failed_devices:
    logger.critical('The following devices failed to flash:')
    logger.critical('  %s', ' '.join(str(d) for d in failed_devices))
    return exit_codes.INFRA
  return 0
Example #12
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--arch',
        choices=list(set(_SUPPORTED_ARCH_DICT.values())),
        default=None,
        type=str,
        help=('Architecture to for CTS tests. Will auto-determine based on '
              'the device ro.product.cpu.abi property.'))
    parser.add_argument('--platform',
                        choices=['L', 'M', 'N', 'O'],
                        required=False,
                        default=None,
                        help='Android platform version for CTS tests. '
                        'Will auto-determine based on SDK level by default.')
    parser.add_argument(
        '--skip-expected-failures',
        action='store_true',
        help='Option to skip all tests that are expected to fail.')
    parser.add_argument('--apk-dir',
                        help='Directory to extract CTS APKs to. '
                        'Will use temp directory by default.')
    parser.add_argument(
        '--test-launcher-summary-output',
        '--json-results-file',
        '--write-full-results-to',
        '--isolated-script-test-output',
        dest='json_results_file',
        type=os.path.realpath,
        help='If set, will dump results in JSON form to the specified file. '
        'Note that this will also trigger saving per-test logcats to '
        'logdog.')
    script_common.AddDeviceArguments(parser)

    args, test_runner_args = parser.parse_known_args()
    devil_chromium.Initialize()

    devices = script_common.GetDevices(args.devices, args.blacklist_file)
    device = devices[0]
    if len(devices) > 1:
        logging.warning(
            'Only single device supported, using 1st of %d devices: %s',
            len(devices), device.serial)
    test_runner_args.extend(['-d', device.serial])

    if args.platform is None:
        args.platform = DeterminePlatform(device)
        if args.platform is None:
            raise Exception('Could not auto-determine device platform, '
                            'please specifiy --platform')

    arch = args.arch if args.arch else DetermineArch(device)

    return RunAllCTSTests(args, arch, test_runner_args)
Example #13
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('build_path', help='Path to android build.')
    parser.add_argument('-d',
                        '--device',
                        dest='devices',
                        action='append',
                        help='Device(s) to flash.')
    parser.add_argument('-v',
                        '--verbose',
                        default=0,
                        action='count',
                        help='Verbose level (multiple times for more)')
    parser.add_argument('-w',
                        '--wipe',
                        action='store_true',
                        help='If set, wipes user data')
    parser.add_argument('--blacklist-file', help='Device blacklist file.')
    args = parser.parse_args()
    run_tests_helper.SetLogLevel(args.verbose)

    if args.blacklist_file:
        blacklist = device_blacklist.Blacklist(args.blacklist_file).Read()
        if blacklist:
            logging.critical('Device(s) in blacklist, not flashing devices:')
            for key in blacklist:
                logging.critical('  %s', key)
            return exit_codes.INFRA

    flashed_devices = []
    failed_devices = []

    def flash(device):
        fastboot = fastboot_utils.FastbootUtils(device)
        try:
            fastboot.FlashDevice(args.build_path, wipe=args.wipe)
            flashed_devices.append(device)
        except Exception:  # pylint: disable=broad-except
            logging.exception('Device %s failed to flash.', str(device))
            failed_devices.append(device)

    devices = script_common.GetDevices(args.devices, args.blacklist_file)
    device_utils.DeviceUtils.parallel(devices).pMap(flash)

    if flashed_devices:
        logging.info('The following devices were flashed:')
        logging.info('  %s', ' '.join(str(d) for d in flashed_devices))
    if failed_devices:
        logging.critical('The following devices failed to flash:')
        logging.critical('  %s', ' '.join(str(d) for d in failed_devices))
        return exit_codes.INFRA
    return 0
Example #14
0
def main(raw_args):
    parser = argparse.ArgumentParser()
    parser.add_argument('--debug',
                        action='store_true',
                        help='Get additional debugging mode')
    parser.add_argument(
        '--output-directory',
        help='the path to the build output directory, such as out/Debug')
    parser.add_argument('--report-path',
                        default='report.html',
                        help='Report path')
    parser.add_argument('--adb-path',
                        help='Absolute path to the adb binary to use.')
    parser.add_argument(
        '--record-options',
        help=('Set recording options for app_profiler.py command.'
              ' Example: "-e task-clock:u -f 1000 -g --duration'
              ' 10" where -f means sampling frequency per second.'
              ' Try `app_profiler.py record -h` for more '
              ' information. Note that not setting this defaults'
              ' to the default record options.'))
    parser.add_argument('--show-file-line',
                        action='store_true',
                        help='Show file name and lines in the result.')
    parser.add_argument(
        '--system-wide',
        action='store_true',
        help=('Whether to profile system wide (without launching'
              'an app).'))

    script_common.AddDeviceArguments(parser)
    logging_common.AddLoggingArguments(parser)

    args = parser.parse_args(raw_args)
    logging_common.InitializeLogging(args)
    devil_chromium.Initialize(adb_path=args.adb_path)

    devices = script_common.GetDevices(args.devices, args.denylist_file)
    device = devices[0]

    if len(devices) > 1:
        raise device_errors.MultipleDevicesError(devices)

    with tempfile_ext.NamedTemporaryDirectory(
            prefix='tmp_simpleperf') as tmp_dir:
        runner = SimplePerfRunner(device, args, tmp_dir,
                                  StackAddressInterpreter(args, tmp_dir))
        runner.Run()
Example #15
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('build_path', help='Path to android build.')
    parser.add_argument('-w',
                        '--wipe',
                        action='store_true',
                        help='If set, wipes user data')
    logging_common.AddLoggingArguments(parser)
    script_common.AddDeviceArguments(parser)
    args = parser.parse_args()
    logging_common.InitializeLogging(args)

    if args.blacklist_file:
        blacklist = device_blacklist.Blacklist(args.blacklist_file).Read()
        if blacklist:
            logger.critical('Device(s) in blacklist, not flashing devices:')
            for key in blacklist:
                logger.critical('  %s', key)
            return exit_codes.INFRA

    flashed_devices = []
    failed_devices = []

    def flash(device):
        fastboot = fastboot_utils.FastbootUtils(device)
        try:
            fastboot.FlashDevice(args.build_path, wipe=args.wipe)
            flashed_devices.append(device)
        except Exception:  # pylint: disable=broad-except
            logger.exception('Device %s failed to flash.', str(device))
            failed_devices.append(device)

    devices = script_common.GetDevices(args.devices, args.blacklist_file)
    device_utils.DeviceUtils.parallel(devices).pMap(flash)

    if flashed_devices:
        logger.info('The following devices were flashed:')
        logger.info('  %s', ' '.join(str(d) for d in flashed_devices))
    if failed_devices:
        logger.critical('The following devices failed to flash:')
        logger.critical('  %s', ' '.join(str(d) for d in failed_devices))
        return exit_codes.INFRA
    return 0
Example #16
0
def main():
    # Parse options.
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-d',
                        '--device',
                        dest='devices',
                        action='append',
                        help='Serial number of Android device to use.')
    parser.add_argument('--blacklist-file', help='Device blacklist JSON file.')
    parser.add_argument('-f',
                        '--file',
                        metavar='FILE',
                        help='Save result to file instead of generating a '
                        'timestamped file name.')
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='Verbose logging.')
    parser.add_argument('host_file',
                        nargs='?',
                        help='File to which the screenshot will be saved.')

    args = parser.parse_args()

    host_file = args.host_file or args.file

    if args.verbose:
        logging.getLogger().setLevel(logging.DEBUG)

    devices = script_common.GetDevices(args.devices, args.blacklist_file)

    def screenshot(device):
        f = None
        if host_file:
            root, ext = os.path.splitext(host_file)
            f = '%s_%s%s' % (root, str(device), ext)
        f = device.TakeScreenshot(f)
        print 'Screenshot for device %s written to %s' % (str(device),
                                                          os.path.abspath(f))

    device_utils.DeviceUtils.parallel(devices).pMap(screenshot)
    return 0
Example #17
0
def GetDevice(args):
    try:
        emulator_instance = None
        if args.avd_config:
            avd_config = avd.AvdConfig(args.avd_config)
            avd_config.Install()
            emulator_instance = avd_config.CreateInstance()
            # Start the emulator w/ -writable-system s.t. we can remount the system
            # partition r/w and install our own webview provider.
            emulator_instance.Start(writable_system=True)

        devices = script_common.GetDevices(args.devices, args.denylist_file)
        device = devices[0]
        if len(devices) > 1:
            logging.warning(
                'Detection of arch and cts-release will use 1st of %d '
                'devices: %s', len(devices), device.serial)
        yield device
    finally:
        if emulator_instance:
            emulator_instance.Stop()
Example #18
0
def main(raw_args):
    parser = argparse.ArgumentParser()

    def add_common_arguments(p):
        script_common.AddDeviceArguments(p)
        script_common.AddEnvironmentArguments(p)
        p.add_argument('-v',
                       '--verbose',
                       action='count',
                       default=0,
                       help='Print more information.')
        p.add_argument('command', nargs='*')

    @contextlib.contextmanager
    def use_webview_provider(device, args):
        with UseWebViewProvider(device, args.apk, args.expected_package):
            yield

    parser.add_argument('--apk',
                        required=True,
                        help='The apk to use as the provider.')
    parser.add_argument(
        '--expected-package',
        default='',
        help="Verify apk's package name matches value, disabled by default.")
    add_common_arguments(parser)
    parser.set_defaults(func=use_webview_provider)

    args = parser.parse_args(raw_args)

    run_tests_helper.SetLogLevel(args.verbose)
    script_common.InitializeEnvironment(args)

    devices = script_common.GetDevices(args.devices, args.denylist_file)
    parallel_devices = parallelizer.SyncParallelizer(
        [args.func(d, args) for d in devices])
    with parallel_devices:
        if args.command:
            return cmd_helper.Call(args.command)
        return 0
  def record_video(presentation.device, stop_recording):
    recorder = VideoRecorder(
        presentation.device, megabits_per_second=args.bitrate, size=size, rotate=args.rotate)
    with recorder:
      stop_recording.wait()

    f = None
    if host_file:
      root, ext = os.path.splitext(host_file)
      f = '%s_%s%s' % (root, str(presentation.device), ext)
    f = recorder.Pull(f)
    print 'Video written to %s' % os.path.abspath(f)

  parallel_devices = device_utils.DeviceUtils.parallel(
      script_common.GetDevices(args.devices, args.blacklist_file),
      async=True)
  stop_recording = threading.Event()
  running_recording = parallel_devices.pMap(record_video, stop_recording)
  print 'Recording. Press Enter to stop.',
  sys.stdout.flush()
  raw_input()
  stop_recording.set()

  running_recording.pGet(None)
  return 0


if __name__ == '__main__':
  sys.exit(presentation.main())
Example #20
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--arch',
        choices=list(set(_SUPPORTED_ARCH_DICT.values())),
        default=None,
        type=str,
        help=('Architecture to for CTS tests. Will auto-determine based on '
              'the device ro.product.cpu.abi property.'))
    parser.add_argument(
        '--cts-release',
        # TODO(aluo): --platform is deprecated (the meaning is unclear).
        '--platform',
        choices=sorted(set(SDK_PLATFORM_DICT.values())),
        required=False,
        default=None,
        help='Which CTS release to use for the run. This should generally be <= '
        'device OS level (otherwise, the newer tests will fail). If '
        'unspecified, the script will auto-determine the release based on '
        'device OS level.')
    parser.add_argument(
        '--skip-expected-failures',
        action='store_true',
        help=
        "Option to skip all tests that are expected to fail.  Can't be used "
        "with test filters.")
    parser.add_argument('--apk-dir',
                        help='Directory to extract CTS APKs to. '
                        'Will use temp directory by default.')
    parser.add_argument(
        '--test-launcher-summary-output',
        '--json-results-file',
        '--write-full-results-to',
        '--isolated-script-test-output',
        dest='json_results_file',
        type=os.path.realpath,
        help='If set, will dump results in JSON form to the specified file. '
        'Note that this will also trigger saving per-test logcats to '
        'logdog.')
    parser.add_argument('-m',
                        '--module-apk',
                        dest='module_apk',
                        help='CTS module apk name in ' +
                        _WEBVIEW_CTS_GCS_PATH_FILE +
                        ' file, without the path prefix.')

    test_filter.AddFilterOptions(parser)
    script_common.AddDeviceArguments(parser)
    logging_common.AddLoggingArguments(parser)

    args, test_runner_args = parser.parse_known_args()
    logging_common.InitializeLogging(args)
    devil_chromium.Initialize()

    test_runner_args.extend(ForwardArgsToTestRunner(args))

    devices = script_common.GetDevices(args.devices, args.blacklist_file)
    device = devices[0]
    if len(devices) > 1:
        logging.warning(
            'Detection of arch and cts-release will use 1st of %d '
            'devices: %s', len(devices), device.serial)
    arch = args.arch or DetermineArch(device)
    cts_release = args.cts_release or DetermineCtsRelease(device)

    if (args.test_filter_file or args.test_filter
            or args.isolated_script_test_filter):
        # TODO(aluo): auto-determine the module based on the test filter and the
        # available tests in each module
        if not args.module_apk:
            args.module_apk = 'CtsWebkitTestCases.apk'

    platform_modules = GetCTSModuleNames(arch, cts_release)
    if args.module_apk and args.module_apk not in platform_modules:
        raise Exception('--module-apk for arch==' + arch +
                        'and cts_release==' + cts_release +
                        ' must be one of: ' + ', '.join(platform_modules))

    # Need to uninstall all previous cts webkit packages so that the
    # MockContentProvider names won't conflict with a previously installed
    # one under a different package name.  This is due to CtsWebkitTestCases's
    # package name change from M to N versions of the tests while keeping the
    # MockContentProvider's authority string the same.
    UninstallAnyCtsWebkitPackages(device)

    return RunAllCTSTests(args, arch, cts_release, test_runner_args)
Example #21
0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--arch',
      choices=list(set(_SUPPORTED_ARCH_DICT.values())),
      default=None,
      type=str,
      help=('Architecture to for CTS tests. Will auto-determine based on '
            'the device ro.product.cpu.abi property.'))
  parser.add_argument(
      '--platform',
      choices=['L', 'M', 'N', 'O'],
      required=False,
      default=None,
      help='Android platform version for CTS tests. '
           'Will auto-determine based on SDK level by default.')
  parser.add_argument(
      '--skip-expected-failures',
      action='store_true',
      help="Option to skip all tests that are expected to fail.  Can't be used "
           "with test filters.")
  parser.add_argument(
      '--apk-dir',
      help='Directory to extract CTS APKs to. '
           'Will use temp directory by default.')
  parser.add_argument(
      '--test-launcher-summary-output',
      '--json-results-file',
      '--write-full-results-to',
      '--isolated-script-test-output',
      dest='json_results_file', type=os.path.realpath,
      help='If set, will dump results in JSON form to the specified file. '
           'Note that this will also trigger saving per-test logcats to '
           'logdog.')
  parser.add_argument(
      '-m',
      '--module-apk',
      dest='module_apk',
      help='CTS module apk name in ' + _WEBVIEW_CTS_GCS_PATH_FILE +
      ' file, without the path prefix.')

  test_filter.AddFilterOptions(parser)
  script_common.AddDeviceArguments(parser)

  args, test_runner_args = parser.parse_known_args()
  devil_chromium.Initialize()

  devices = script_common.GetDevices(args.devices, args.blacklist_file)
  device = devices[0]
  if len(devices) > 1:
    logging.warning('Only single device supported, using 1st of %d devices: %s',
                    len(devices), device.serial)
  test_runner_args.extend(['-d', device.serial])

  if args.platform is None:
    args.platform = DeterminePlatform(device)
    if args.platform is None:
      raise Exception('Could not auto-determine device platform, '
                      'please specifiy --platform')

  arch = args.arch if args.arch else DetermineArch(device)

  if (args.test_filter_file or args.test_filter
      or args.isolated_script_test_filter):
    if args.skip_expected_failures:
      # TODO(aluo): allow both options to be used together so that expected
      # failures in the filtered test set can be skipped
      raise Exception('--skip-expected-failures and test filters are mutually'
                      ' exclusive')
    # TODO(aluo): auto-determine the module based on the test filter and the
    # available tests in each module
    if not args.module_apk:
      args.module_apk = 'CtsWebkitTestCases.apk'

  platform_modules = GetCTSModuleNames(arch, args.platform)
  if args.module_apk and args.module_apk not in platform_modules:
    raise Exception('--module-apk for arch==' + arch + 'and platform=='
                    + args.platform + ' must be one of: '
                    + ', '.join(platform_modules))

  return RunAllCTSTests(args, arch, test_runner_args)
def ProvisionDevices(devices,
                     denylist_file,
                     adb_key_files=None,
                     disable_location=False,
                     disable_mock_location=False,
                     disable_network=False,
                     disable_system_chrome=False,
                     emulators=False,
                     enable_java_debug=False,
                     max_battery_temp=None,
                     min_battery_level=None,
                     output_device_denylist=None,
                     reboot_timeout=None,
                     remove_system_webview=False,
                     system_app_remove_list=None,
                     system_package_remove_list=None,
                     wipe=True):
    denylist = (device_denylist.Denylist(denylist_file)
                if denylist_file else None)
    system_app_remove_list = system_app_remove_list or []
    system_package_remove_list = system_package_remove_list or []
    try:
        devices = script_common.GetDevices(devices, denylist)
    except device_errors.NoDevicesError:
        logging.error('No available devices to provision.')
        if denylist:
            logging.error('Local device denylist: %s', denylist.Read())
        raise
    devices = [d for d in devices if not emulators or d.adb.is_emulator]
    parallel_devices = device_utils.DeviceUtils.parallel(devices)

    steps = []
    if wipe:
        steps += [ProvisionStep(lambda d: Wipe(d, adb_key_files), reboot=True)]
    steps += [
        ProvisionStep(lambda d: SetProperties(
            d, enable_java_debug, disable_location, disable_mock_location),
                      reboot=not emulators)
    ]

    if disable_network:
        steps.append(ProvisionStep(DisableNetwork))

    if disable_system_chrome:
        steps.append(ProvisionStep(DisableSystemChrome))

    if max_battery_temp:
        steps.append(
            ProvisionStep(
                lambda d: WaitForBatteryTemperature(d, max_battery_temp)))

    if min_battery_level:
        steps.append(
            ProvisionStep(lambda d: WaitForCharge(d, min_battery_level)))

    if remove_system_webview:
        system_app_remove_list.extend(_SYSTEM_WEBVIEW_NAMES)

    if system_app_remove_list or system_package_remove_list:
        steps.append(
            ProvisionStep(lambda d: RemoveSystemApps(
                d, system_app_remove_list, system_package_remove_list)))

    steps.append(ProvisionStep(SetDate))
    steps.append(ProvisionStep(CheckExternalStorage))
    steps.append(ProvisionStep(StandaloneVrDeviceSetup))

    parallel_devices.pMap(ProvisionDevice, steps, denylist, reboot_timeout)

    denylisted_devices = denylist.Read() if denylist else []
    if output_device_denylist:
        with open(output_device_denylist, 'w') as f:
            json.dump(denylisted_devices, f)
    if all(d in denylisted_devices for d in devices):
        raise device_errors.NoDevicesError
    return 0
 def testGetDevices_missingDevice(self):
   with mock.patch('devil.android.device_utils.DeviceUtils.HealthyDevices',
                   return_value=[device_utils.DeviceUtils('123')]):
     with self.assertRaises(device_errors.DeviceUnreachableError):
       script_common.GetDevices(['456'], None)
 def testGetDevices_noDevices(self):
   with mock.patch('devil.android.device_utils.DeviceUtils.HealthyDevices',
                   return_value=[]):
     with self.assertRaises(device_errors.NoDevicesError):
       script_common.GetDevices(None, None)
class MultipleDevicesError(base_error.BaseError):
  def __init__(self, devices):
    super(MultipleDevicesError, self).__init__(
        'More than one presentation.device found: %s' % ', '.join(str(d) for d in devices))


def presentation.main(raw_args):
  parser = argparse.ArgumentParser(
      description="Use your keyboard as your phone's keyboard.")
  AddArguments(parser)
  args = parser.parse_args(raw_args)

  run_tests_helper.SetLogLevel(args.verbose)

  devices = script_common.GetDevices(args.devices, None)
  if len(devices) > 1:
    raise MultipleDevicesError(devices)

  def next_char():
    while True:
      yield sys.stdin.read(1)

  try:
    fd = sys.stdin.fileno()

    # See man 3 termios for more info on what this is doing.
    old_attrs = termios.tcgetattr(fd)
    new_attrs = copy.deepcopy(old_attrs)
    new_attrs[tty.LFLAG] = new_attrs[tty.LFLAG] & ~(termios.ICANON)
    new_attrs[tty.CC][tty.VMIN] = 1