示例#1
0
    def Install(self, apk_path, reinstall=False, timeout=None, retries=None):
        """Install an APK.

    Noop if an identical APK is already installed.

    Args:
      apk_path: A string containing the path to the APK to install.
      reinstall: A boolean indicating if we should keep any existing app data.
      timeout: timeout in seconds
      retries: number of retries

    Raises:
      CommandFailedError if the installation fails.
      CommandTimeoutError if the installation times out.
      DeviceUnreachableError on missing device.
    """
        package_name = apk_helper.GetPackageName(apk_path)
        device_path = self.GetApplicationPath(package_name)
        if device_path is not None:
            should_install = bool(
                self._GetChangedFilesImpl(apk_path, device_path))
            if should_install and not reinstall:
                self.adb.Uninstall(package_name)
        else:
            should_install = True
        if should_install:
            self.adb.Install(apk_path, reinstall=reinstall)
示例#2
0
def main(argv):
  parser = optparse.OptionParser()
  AddInstallAPKOption(parser)
  options, args = parser.parse_args(argv)
  constants.SetBuildType(options.build_type)
  ValidateInstallAPKOption(parser, options)
  if len(args) > 1:
    raise Exception('Error: Unknown argument:', args[1:])

  retry_times = 5
  retry_interval = 15
  while retry_times > 0:
    devices = android_commands.GetAttachedDevices()
    if not devices:
      print 'No connected devices found, '\
            'kill adb server and retry in %d seconds...' % retry_interval
      android_commands.AndroidCommands().KillAdbServer()
      time.sleep(retry_interval)
      retry_interval *= 2
      retry_times -= 1
    else:
      break

  if not devices:
    raise Exception('Error: no connected devices')

  if not options.apk_package:
    options.apk_package = apk_helper.GetPackageName(options.apk)

  pool = multiprocessing.Pool(len(devices))
  # Send a tuple (apk_path, apk_package, device) per device.
  pool.map(_InstallApk, zip([options.apk] * len(devices),
                            [options.apk_package] * len(devices),
                            [options.keep_data] * len(devices),
                            devices))
    def __init__(self, args, error_func):
        """Constructor.

    Args:
      args: Command line arguments.
    """
        super(UirobotTestInstance, self).__init__()
        if not args.app_under_test:
            error_func('Must set --app-under-test.')
        self._app_under_test = args.app_under_test
        self._minutes = args.minutes

        if args.remote_device_file:
            with open(args.remote_device_file) as remote_device_file:
                device_json = json.load(remote_device_file)
        else:
            device_json = {}
        device_type = device_json.get('device_type', 'Android')
        if args.device_type:
            if device_type and device_type != args.device_type:
                logging.info('Overriding device_type from %s to %s',
                             device_type, args.device_type)
            device_type = args.device_type

        if device_type == 'Android':
            self._suite = 'Android Uirobot'
            self._package_name = apk_helper.GetPackageName(
                self._app_under_test)
        elif device_type == 'iOS':
            self._suite = 'iOS Uirobot'
            self._package_name = self._app_under_test
示例#4
0
def TriggerSymlinkScript(options):
    device = build_device.GetBuildDeviceFromPath(
        options.build_device_configuration)
    if not device:
        return

    apk_package = apk_helper.GetPackageName(options.apk)
    apk_libraries_dir = '/data/data/%s/lib' % apk_package

    device_dir = os.path.dirname(options.script_device_path)
    mkdir_cmd = ('if [ ! -e %(dir)s ]; then mkdir -p %(dir)s; fi ' % {
        'dir': device_dir
    })
    RunShellCommand(device, mkdir_cmd)
    device.PushChangedFiles([(options.script_host_path,
                              options.script_device_path)])

    trigger_cmd = ('APK_LIBRARIES_DIR=%(apk_libraries_dir)s; '
                   'STRIPPED_LIBRARIES_DIR=%(target_dir)s; '
                   '. %(script_device_path)s') % {
                       'apk_libraries_dir': apk_libraries_dir,
                       'target_dir': options.target_dir,
                       'script_device_path': options.script_device_path
                   }
    RunShellCommand(device, trigger_cmd)
示例#5
0
def CreateAppData(device, old_apk, app_data):
    device.Install(old_apk)
    raw_input('Set the application state. Once ready, press enter and '
              'select "Backup my data" on the device.')
    package_name = apk_helper.GetPackageName(old_apk)
    device.adb.Backup(app_data, packages=[package_name])
    logging.critical('Application data saved to %s' % app_data)
示例#6
0
  def __init__(self, apk_path, jar_path):
    test_jar.TestJar.__init__(self, jar_path)

    if not os.path.exists(apk_path):
      raise Exception('%s not found, please build it' % apk_path)
    self._apk_path = apk_path
    self._apk_name = os.path.splitext(os.path.basename(apk_path))[0]
    self._package_name = apk_helper.GetPackageName(self._apk_path)
 def Create(self, finder_options):
   self._InitPlatformIfNeeded()
   mandoline_backend = android_mandoline_backend.AndroidMandolineBackend(
       self._platform_backend, finder_options.browser_options,
       finder_options.target_arch, self.browser_type, self._build_path,
       apk_helper.GetPackageName(self._local_apk))
   return browser.Browser(
       mandoline_backend, self._platform_backend, self._credentials_path)
示例#8
0
 def __init__(self, config):
     self.adb_path = constants.GetAdbPath()
     self.paths = Paths(config)
     self.device = None
     self.shell_args = []
     self.target_package = apk_helper.GetPackageName(self.paths.apk_path)
     self.temp_gdb_dir = None
     # This is used by decive_utils.Install to check if the apk needs updating.
     constants.SetOutputDirectory(self.paths.build_dir)
  def InstallTestPackage(self):
    apk_path = os.path.join(
        constants.GetOutDirectory(), 'apks', '%s.apk' % _PACKAGE_NAME)

    if not os.path.exists(apk_path):
      raise Exception('%s not found, please build it' % apk_path)

    package_name = apk_helper.GetPackageName(apk_path)
    self.adb.ManagedInstall(apk_path, package_name)
示例#10
0
def main():
    parser = optparse.OptionParser()
    parser.add_option('--apk-path', help='Path to .apk to install.')
    parser.add_option(
        '--split-apk-path',
        help='Path to .apk splits (can specify multiple times, causes '
        '--install-multiple to be used.',
        action='append')
    parser.add_option('--android-sdk-tools',
                      help='Path to the Android SDK build tools folder. ' +
                      'Required when using --split-apk-path.')
    parser.add_option(
        '--install-record',
        help='Path to install record (touched only when APK is installed).')
    parser.add_option('--build-device-configuration',
                      help='Path to build device configuration.')
    parser.add_option('--stamp', help='Path to touch on success.')
    parser.add_option('--configuration-name',
                      help='The build CONFIGURATION_NAME')
    options, _ = parser.parse_args()

    device = build_device.GetBuildDeviceFromPath(
        options.build_device_configuration)
    if not device:
        return

    constants.SetBuildType(options.configuration_name)

    serial_number = device.GetSerialNumber()
    apk_package = apk_helper.GetPackageName(options.apk_path)

    metadata_path = '%s.%s.device.time.stamp' % (options.apk_path,
                                                 serial_number)

    # If the APK on the device does not match the one that was last installed by
    # the build, then the APK has to be installed (regardless of the md5 record).
    force_install = HasInstallMetadataChanged(device, apk_package,
                                              metadata_path)

    def Install():
        if options.split_apk_path:
            device.InstallSplitApk(options.apk_path, options.split_apk_path)
        else:
            device.Install(options.apk_path, reinstall=True)

        RecordInstallMetadata(device, apk_package, metadata_path)
        build_utils.Touch(options.install_record)

    record_path = '%s.%s.md5.stamp' % (options.apk_path, serial_number)
    md5_check.CallAndRecordIfStale(Install,
                                   record_path=record_path,
                                   input_paths=[options.apk_path],
                                   force=force_install)

    if options.stamp:
        build_utils.Touch(options.stamp)
示例#11
0
 def _initializeDriverAttributes(self):
     self._driver_apk = os.path.join(constants.GetOutDirectory(),
                                     constants.SDK_BUILD_APKS_DIR,
                                     'OnDeviceInstrumentationDriver.apk')
     if os.path.exists(self._driver_apk):
         self._driver_package = apk_helper.GetPackageName(self._driver_apk)
         self._driver_name = apk_helper.GetInstrumentationName(
             self._driver_apk)
     else:
         self._driver_apk = None
示例#12
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)
示例#13
0
  def Install(self, apk_path):
    """Installs specified package if necessary.

    Args:
      apk_path: Path to .apk file to install.
    """

    if (os.path.exists(os.path.join(
        constants.GetOutDirectory('Release'), 'md5sum_bin_host'))):
      constants.SetBuildType('Release')
    elif (os.path.exists(os.path.join(
        constants.GetOutDirectory('Debug'), 'md5sum_bin_host'))):
      constants.SetBuildType('Debug')

    apk_package_name = apk_helper.GetPackageName(apk_path)
    return self._adb.ManagedInstall(apk_path, package_name=apk_package_name)
示例#14
0
def CreateLinks(options):
    libraries = build_utils.ReadJson(options.libraries_json)
    apk_package = apk_helper.GetPackageName(options.apk)

    adb = android_commands.AndroidCommands()
    serial_number = adb.Adb().GetSerialNumber()
    for lib in libraries:
        host_path = os.path.join(options.libraries_dir, lib)

        md5_stamp = '%s.%s.link.md5' % (host_path, serial_number)
        md5_checker = md5_check.Md5Checker(stamp=md5_stamp, inputs=[host_path])
        if md5_checker.IsStale():
            link = '/data/data/' + apk_package + '/lib/' + lib
            target = options.target_dir + '/' + lib
            RunLinkCommand(adb, target, link)
            md5_checker.Write()
示例#15
0
def TestUpdate(device, old_apk, new_apk, app_data):
    device.Install(old_apk)
    device.adb.Restore(app_data)
    # Restore command is not synchronous
    raw_input('Select "Restore my data" on the device. Then press enter to '
              'continue.')

    package_name = apk_helper.GetPackageName(new_apk)
    device_path = device.GetApplicationPath(package_name)
    if not device_path:
        raise Exception('Expected package %s to already be installed. '
                        'Package name might have changed!' % package_name)

    logging.info('Verifying that %s can be overinstalled.', new_apk)
    device.adb.Install(new_apk, reinstall=True)
    logging.critical('Successfully updated to the new apk. Please verify that '
                     'the application data is preserved.')
示例#16
0
def main(argv):
    if not build_utils.IsDeviceReady():
        build_utils.PrintBigWarning(
            'Zero (or multiple) devices attached. Skipping APK install.')
        return

    parser = optparse.OptionParser()
    parser.add_option('--android-sdk-tools', help='Path to Android SDK tools.')
    parser.add_option('--apk-path', help='Path to .apk to install.')
    parser.add_option(
        '--install-record',
        help='Path to install record (touched only when APK is installed).')
    parser.add_option('--stamp', help='Path to touch on success.')
    options, _ = parser.parse_args()

    # TODO(cjhopman): Should this install to all devices/be configurable?
    install_cmd = [
        os.path.join(options.android_sdk_tools, 'adb'), 'install', '-r',
        options.apk_path
    ]

    serial_number = android_commands.AndroidCommands().Adb().GetSerialNumber()
    apk_package = apk_helper.GetPackageName(options.apk_path)

    metadata_path = '%s.%s.device.time.stamp' % (options.apk_path,
                                                 serial_number)

    # If the APK on the device does not match the one that was last installed by
    # the build, then the APK has to be installed (regardless of the md5 record).
    force_install = HasInstallMetadataChanged(apk_package, metadata_path)

    def Install():
        build_utils.CheckCallDie(install_cmd)
        RecordInstallMetadata(apk_package, metadata_path)
        build_utils.Touch(options.install_record)

    record_path = '%s.%s.md5.stamp' % (options.apk_path, serial_number)
    md5_check.CallAndRecordIfStale(Install,
                                   record_path=record_path,
                                   input_paths=[options.apk_path],
                                   input_strings=install_cmd,
                                   force=force_install)

    if options.stamp:
        build_utils.Touch(options.stamp)
示例#17
0
def main(argv):
  parser = optparse.OptionParser()
  parser.add_option('--apk-path',
      help='Path to .apk to install.')
  parser.add_option('--install-record',
      help='Path to install record (touched only when APK is installed).')
  parser.add_option('--build-device-configuration',
      help='Path to build device configuration.')
  parser.add_option('--stamp',
      help='Path to touch on success.')
  parser.add_option('--configuration-name',
      help='The build CONFIGURATION_NAME')
  options, _ = parser.parse_args()

  device = build_device.GetBuildDeviceFromPath(
      options.build_device_configuration)
  if not device:
    return

  constants.SetBuildType(options.configuration_name)

  serial_number = device.GetSerialNumber()
  apk_package = apk_helper.GetPackageName(options.apk_path)

  metadata_path = '%s.%s.device.time.stamp' % (options.apk_path, serial_number)

  # If the APK on the device does not match the one that was last installed by
  # the build, then the APK has to be installed (regardless of the md5 record).
  force_install = HasInstallMetadataChanged(device, apk_package, metadata_path)

  def Install():
    device.Install(options.apk_path, reinstall=True)
    RecordInstallMetadata(device, apk_package, metadata_path)
    build_utils.Touch(options.install_record)


  record_path = '%s.%s.md5.stamp' % (options.apk_path, serial_number)
  md5_check.CallAndRecordIfStale(
      Install,
      record_path=record_path,
      input_paths=[options.apk_path],
      force=force_install)

  if options.stamp:
    build_utils.Touch(options.stamp)
    def __initializeApkAttributes(self, args, error_func):
        if args.apk_under_test.endswith('.apk'):
            self._apk_under_test = args.apk_under_test
        else:
            self._apk_under_test = os.path.join(constants.GetOutDirectory(),
                                                constants.SDK_BUILD_APKS_DIR,
                                                '%s.apk' % args.apk_under_test)

        if not os.path.exists(self._apk_under_test):
            error_func('Unable to find APK under test: %s' %
                       self._apk_under_test)

        if args.test_apk.endswith('.apk'):
            test_apk_root = os.path.splitext(os.path.basename(
                args.test_apk))[0]
            self._test_apk = args.test_apk
        else:
            test_apk_root = args.test_apk
            self._test_apk = os.path.join(constants.GetOutDirectory(),
                                          constants.SDK_BUILD_APKS_DIR,
                                          '%s.apk' % args.test_apk)

        self._test_jar = os.path.join(constants.GetOutDirectory(),
                                      constants.SDK_BUILD_TEST_JAVALIB_DIR,
                                      '%s.jar' % test_apk_root)
        self._test_support_apk = os.path.join(
            constants.GetOutDirectory(), constants.SDK_BUILD_TEST_JAVALIB_DIR,
            '%sSupport.apk' % test_apk_root)

        if not os.path.exists(self._test_apk):
            error_func('Unable to find test APK: %s' % self._test_apk)
        if not os.path.exists(self._test_jar):
            error_func('Unable to find test JAR: %s' % self._test_jar)

        self._test_package = apk_helper.GetPackageName(self.test_apk)
        self._test_runner = apk_helper.GetInstrumentationName(self.test_apk)

        self._package_info = None
        for package_info in constants.PACKAGE_INFO.itervalues():
            if self._test_package == package_info.test_package:
                self._package_info = package_info
        if not self._package_info:
            error_func('Unable to find package info for %s' %
                       self._test_package)
示例#19
0
    def Install(self, apk_path, reinstall=False, timeout=None, retries=None):
        """Install an APK.

    Noop if an identical APK is already installed.

    Args:
      apk_path: A string containing the path to the APK to install.
      reinstall: A boolean indicating if we should keep any existing app data.
      timeout: timeout in seconds
      retries: number of retries

    Raises:
      CommandFailedError if the installation fails.
      CommandTimeoutError if the installation times out.
      DeviceUnreachableError on missing device.
    """
        package_name = apk_helper.GetPackageName(apk_path)
        device_path = self.old_interface.GetApplicationPath(package_name)
        if device_path is not None:
            files_changed = self.old_interface.GetFilesChanged(
                apk_path, device_path, ignore_filenames=True)
            if len(files_changed) > 0:
                should_install = True
                if not reinstall:
                    out = self.old_interface.Uninstall(package_name)
                    for line in out.splitlines():
                        if 'Failure' in line:
                            raise device_errors.CommandFailedError(
                                line.strip(), device=str(self))
            else:
                should_install = False
        else:
            should_install = True
        if should_install:
            try:
                out = self.old_interface.Install(apk_path, reinstall=reinstall)
                for line in out.splitlines():
                    if 'Failure' in line:
                        raise device_errors.CommandFailedError(
                            line.strip(), device=str(self))
            except AssertionError as e:
                raise device_errors.CommandFailedError(
                    str(e), device=str(self)), None, sys.exc_info()[2]
def TriggerSymlinkScript(options):
    apk_package = apk_helper.GetPackageName(options.apk)
    apk_libraries_dir = '/data/data/%s/lib' % apk_package

    adb = android_commands.AndroidCommands()
    device_dir = os.path.dirname(options.script_device_path)
    mkdir_cmd = ('if [ ! -e %(dir)s ]; then mkdir -p %(dir)s; fi ' % {
        'dir': device_dir
    })
    RunShellCommand(adb, mkdir_cmd)
    adb.PushIfNeeded(options.script_host_path, options.script_device_path)

    trigger_cmd = ('APK_LIBRARIES_DIR=%(apk_libraries_dir)s; '
                   'STRIPPED_LIBRARIES_DIR=%(target_dir)s; '
                   '. %(script_device_path)s') % {
                       'apk_libraries_dir': apk_libraries_dir,
                       'target_dir': options.target_dir,
                       'script_device_path': options.script_device_path
                   }
    RunShellCommand(adb, trigger_cmd)
示例#21
0
  def Install(self, apk_path, reinstall=False, timeout=None, retries=None):
    """Install an APK.

    Noop if an identical APK is already installed.

    Args:
      apk_path: A string containing the path to the APK to install.
      reinstall: A boolean indicating if we should keep any existing app data.
      timeout: Same as for |IsOnline|.
      retries: Same as for |IsOnline|.
    Raises:
      CommandFailedError if the installation fails.
      CommandTimeoutError if the installation times out.
    """
    package_name = apk_helper.GetPackageName(apk_path)
    device_path = self.old_interface.GetApplicationPath(package_name)
    if device_path is not None:
      files_changed = self.old_interface.GetFilesChanged(
          apk_path, device_path, ignore_filenames=True)
      if len(files_changed) > 0:
        should_install = True
        if not reinstall:
          out = self.old_interface.Uninstall(package_name)
          for line in out.splitlines():
            if 'Failure' in line:
              raise device_errors.CommandFailedError(
                  ['adb', 'uninstall', package_name], line.strip())
      else:
        should_install = False
    else:
      should_install = True
    if should_install:
      try:
        out = self.old_interface.Install(apk_path, reinstall=reinstall)
        for line in out.splitlines():
          if 'Failure' in line:
            raise device_errors.CommandFailedError(
                ['adb', 'install', apk_path], line.strip())
      except AssertionError as e:
        raise device_errors.CommandFailedError(
            ['adb', 'install', apk_path], str(e))
示例#22
0
    def __init__(self, args, error_func):
        """Constructor.

    Args:
      args: Command line arguments.
    """
        super(UirobotTestInstance, self).__init__()
        if not args.app_under_test:
            error_func('Must set --app-under-test.')
        self._app_under_test = args.app_under_test

        if args.device_type == 'Android':
            self._suite = 'Android Uirobot'
            self._package_name = apk_helper.GetPackageName(
                self._app_under_test)

        elif args.device_type == 'iOS':
            self._suite = 'iOS Uirobot'
            self._package_name = self._app_under_test

        self._minutes = args.minutes
示例#23
0
def main(argv):
    parser = optparse.OptionParser()
    AddInstallAPKOption(parser)
    options, args = parser.parse_args(argv)
    ValidateInstallAPKOption(parser, options)
    if len(args) > 1:
        raise Exception('Error: Unknown argument:', args[1:])

    devices = android_commands.GetAttachedDevices()
    if not devices:
        raise Exception('Error: no connected devices')

    if not options.apk_package:
        options.apk_package = apk_helper.GetPackageName(options.apk)

    pool = multiprocessing.Pool(len(devices))
    # Send a tuple (apk_path, apk_package, device) per device.
    pool.map(
        _InstallApk,
        zip([options.apk] * len(devices), [options.apk_package] * len(devices),
            [options.keep_data] * len(devices), devices))
示例#24
0
def _FindAllPossibleBrowsers(finder_options, android_platform):
    """Testable version of FindAllAvailableBrowsers."""
    if not android_platform:
        return []
    possible_browsers = []

    # Add the exact APK if given.
    if (finder_options.browser_executable
            and CanPossiblyHandlePath(finder_options.browser_executable)):
        normalized_path = os.path.expanduser(finder_options.browser_executable)

        exact_package = apk_helper.GetPackageName(normalized_path)
        if not exact_package:
            raise exceptions.PackageDetectionError(
                'Unable to find package for %s specified by --browser-executable'
                % normalized_path)

        package_info = next((info
                             for info in CHROME_PACKAGE_NAMES.itervalues()
                             if info[0] == exact_package), None)
        if package_info:
            [package, backend_settings, _] = package_info
            possible_browsers.append(
                PossibleAndroidBrowser('exact', finder_options,
                                       android_platform,
                                       backend_settings(package),
                                       normalized_path))
        else:
            raise exceptions.UnknownPackageError(
                '%s specified by --browser-executable has an unknown package: %s'
                % (normalized_path, exact_package))

    for name, package_info in CHROME_PACKAGE_NAMES.iteritems():
        package, backend_settings, local_apk = package_info
        b = PossibleAndroidBrowser(name, finder_options, android_platform,
                                   backend_settings(package), local_apk)
        if b.platform.CanLaunchApplication(package) or b.HaveLocalAPK():
            possible_browsers.append(b)
    return possible_browsers
示例#25
0
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 = android_commands.GetAttachedDevices()
    if not devices:
        raise Exception('Error: no connected devices')

    if not options.apk_package:
        options.apk_package = apk_helper.GetPackageName(options.apk)

    device_utils.DeviceUtils.parallel(devices).old_interface.ManagedInstall(
        options.apk, options.keep_data, options.apk_package).pFinish(None)
示例#26
0
def main():
    parser = optparse.OptionParser()
    parser.add_option('--apk-path', help='Path to .apk to install.')
    parser.add_option(
        '--split-apk-path',
        help='Path to .apk splits (can specify multiple times, causes '
        '--install-multiple to be used.',
        action='append')
    parser.add_option('--android-sdk-tools',
                      help='Path to the Android SDK build tools folder. ' +
                      'Required when using --split-apk-path.')
    parser.add_option(
        '--install-record',
        help='Path to install record (touched only when APK is installed).')
    parser.add_option('--build-device-configuration',
                      help='Path to build device configuration.')
    parser.add_option('--stamp', help='Path to touch on success.')
    parser.add_option('--configuration-name',
                      help='The build CONFIGURATION_NAME')
    options, _ = parser.parse_args()

    device = build_device.GetBuildDeviceFromPath(
        options.build_device_configuration)
    if not device:
        return

    constants.SetBuildType(options.configuration_name)

    serial_number = device.GetSerialNumber()
    apk_package = apk_helper.GetPackageName(options.apk_path)

    metadata_path = '%s.%s.device.time.stamp' % (options.apk_path,
                                                 serial_number)

    # If the APK on the device does not match the one that was last installed by
    # the build, then the APK has to be installed (regardless of the md5 record).
    force_install = HasInstallMetadataChanged(device, apk_package,
                                              metadata_path)

    def SelectSplits(target_config, base_apk, split_apks, android_sdk_tools):
        cmd = [
            os.path.join(android_sdk_tools, 'split-select'),
            '--target',
            target_config,
            '--base',
            base_apk,
        ]
        for split in split_apks:
            cmd.extend(('--split', split))

        # split-select outputs one path per line and a blank line at the end.
        output = build_utils.CheckOutput(cmd)
        return [x for x in output.split('\n') if x]

    def Install():
        if options.split_apk_path:
            requiredSdkVersion = constants.ANDROID_SDK_VERSION_CODES.LOLLIPOP
            actualSdkVersion = device.device.build_version_sdk
            if actualSdkVersion < requiredSdkVersion:
                raise Exception(
                    ('--split-apk-path requires sdk version %s. Device has '
                     'version %s') % (requiredSdkVersion, actualSdkVersion))
            device_config = RetrieveDeviceConfig(device.device)
            active_splits = SelectSplits(device_config, options.apk_path,
                                         options.split_apk_path,
                                         options.android_sdk_tools)

            all_apks = [options.apk_path] + active_splits
            device.device.adb.InstallMultiple(all_apks, reinstall=True)
        else:
            device.Install(options.apk_path, reinstall=True)

        RecordInstallMetadata(device, apk_package, metadata_path)
        build_utils.Touch(options.install_record)

    record_path = '%s.%s.md5.stamp' % (options.apk_path, serial_number)
    md5_check.CallAndRecordIfStale(Install,
                                   record_path=record_path,
                                   input_paths=[options.apk_path],
                                   force=force_install)

    if options.stamp:
        build_utils.Touch(options.stamp)
示例#27
0
def GetPackageName(apk_path):
    return apk_helper.GetPackageName(apk_path)
示例#28
0
 def __init__(self, apk):
     self._apk = apk
     self._package = apk_helper.GetPackageName(self._apk)
     self._runner = apk_helper.GetInstrumentationName(self._apk)
     self._component = '%s/%s' % (self._package, self._runner)
     self._enable_test_server_spawner = False
示例#29
0
 def __init__(self, apk):
   self._apk = apk
   self._package = apk_helper.GetPackageName(self._apk)
   self._runner = apk_helper.GetInstrumentationName(self._apk)
   self._component = '%s/%s' % (self._package, self._runner)