예제 #1
0
def app_installed(device, apk):
    pkg = apk_helper.GetPackageName(apk)
    device.Install(apk)
    try:
        yield
    finally:
        device.Uninstall(pkg)
예제 #2
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
    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
예제 #3
0
    def UpdateExecutableIfNeeded(self):
        # TODO(crbug.com/815133): This logic should belong to backend_settings.
        for apk in self._support_apk_list:
            logging.warn('Installing %s on device if needed.', apk)
            self.platform.InstallApplication(apk)

        apk_name = self._backend_settings.GetApkName(
            self._platform_backend.device)
        is_webview_apk = apk_name is not None and (
            'SystemWebView' in apk_name or 'system_webview' in apk_name or
            'TrichromeWebView' in apk_name or 'trichrome_webview' in apk_name)
        # The WebView fallback logic prevents sideloaded WebView APKs from being
        # installed and set as the WebView implementation correctly. Disable the
        # fallback logic before installing the WebView APK to make sure the fallback
        # logic doesn't interfere.
        if is_webview_apk:
            self._platform_backend.device.SetWebViewFallbackLogic(False)

        if self._local_apk:
            logging.warn('Installing %s on device if needed.', self._local_apk)
            self.platform.InstallApplication(self._local_apk,
                                             modules=self._modules_to_install)

        if ((is_webview_apk or apk_name == 'Monochrome.apk')
                and self._platform_backend.device.build_version_sdk >=
                version_codes.NOUGAT):
            package_name = apk_helper.GetPackageName(self._local_apk)
            logging.warn('Setting %s as WebView implementation.', package_name)
            self._platform_backend.device.SetWebViewImplementation(
                package_name)
예제 #4
0
def run_android_webview(device, adapter):
    if adapter.options.package_name:
        logger.warn(
            '--package-name has no effect for android_webview, provider'
            'will be set to the --apk if it is provided.')

    if adapter.options.system_webview_shell:
        shell_pkg = apk_helper.GetPackageName(
            adapter.options.system_webview_shell)
        if shell_pkg != SYSTEM_WEBVIEW_SHELL_PKG:
            raise Exception(
                '{} has incorrect package name: {}, expected {}.'.format(
                    '--system-webview-shell apk', shell_pkg,
                    SYSTEM_WEBVIEW_SHELL_PKG))
        install_shell_as_needed = system_app.ReplaceSystemApp(
            device, shell_pkg, adapter.options.system_webview_shell)
        logger.info('Will install ' + shell_pkg + ' at ' +
                    adapter.options.system_webview_shell)
    else:
        install_shell_as_needed = no_op()

    if adapter.options.apk:
        install_webview_as_needed = webview_app.UseWebViewProvider(
            device, adapter.options.apk)
        logger.info('Will install WebView apk at ' + adapter.options.apk)
    else:
        install_webview_as_needed = no_op()

    with install_shell_as_needed, install_webview_as_needed:
        return adapter.run_test()
예제 #5
0
 def __init__(self, device):
   super(WPTWebviewAdapter, self).__init__(device)
   if self.options.system_webview_shell is not None:
     self.system_webview_shell_pkg = apk_helper.GetPackageName(
         self.options.system_webview_shell)
   else:
     self.system_webview_shell_pkg = 'org.chromium.webview_shell'
예제 #6
0
파일: system_app.py 프로젝트: zlrs/catapult
def _TemporarilyInstallApp(device, apk):
  """A context manager that installs an app while in scope."""
  device.Install(apk, reinstall=True)
  try:
    yield
  finally:
    device.Uninstall(apk_helper.GetPackageName(apk))
예제 #7
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([(os.path.abspath(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)
예제 #8
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')
    parser.add_option('--output-directory', help='The output directory.')
    options, _ = parser.parse_args()

    constants.SetBuildType(options.configuration_name)

    devil_chromium.Initialize(
        output_directory=os.path.abspath(options.output_directory))

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

    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)
예제 #9
0
def _FindAllPossibleBrowsers(finder_options, android_platform):
  """Testable version of FindAllAvailableBrowsers."""
  if not android_platform:
    return []
  possible_browsers = []

  for apk in finder_options.webview_embedder_apk:
    if not os.path.exists(apk):
      raise exceptions.PathMissingError(
          'Unable to find apk specified by --webview-embedder-apk=%s' % apk)

  # Add the exact APK if given.
  if _CanPossiblyHandlePath(finder_options.browser_executable):
    if not os.path.exists(finder_options.browser_executable):
      raise exceptions.PathMissingError(
          'Unable to find exact apk specified by --browser-executable=%s' %
          finder_options.browser_executable)

    package_name = apk_helper.GetPackageName(finder_options.browser_executable)
    try:
      backend_settings = next(
          b for b in ANDROID_BACKEND_SETTINGS if b.package == package_name)
    except StopIteration:
      raise exceptions.UnknownPackageError(
          '%s specified by --browser-executable has an unknown package: %s' %
          (finder_options.browser_executable, package_name))

    possible_browsers.append(PossibleAndroidBrowser(
        'exact',
        finder_options,
        android_platform,
        backend_settings,
        finder_options.browser_executable))

  if finder_options.IsBrowserTypeRelevant('reference'):
    reference_browser = _GetReferenceAndroidBrowser(
        android_platform, finder_options)
    if reference_browser:
      possible_browsers.append(reference_browser)

  # Add any other known available browsers.
  for settings in ANDROID_BACKEND_SETTINGS:
    if finder_options.IsBrowserTypeRelevant(settings.browser_type):
      local_apk = None
      if finder_options.IsBrowserTypeReference():
        local_apk = _FetchReferenceApk(
            android_platform, finder_options.IsBrowserTypeBundle())

      if settings.IsWebView():
        p_browser = PossibleAndroidBrowser(
            settings.browser_type, finder_options, android_platform, settings,
            local_apk=local_apk, target_os='android_webview')
      else:
        p_browser = PossibleAndroidBrowser(
            settings.browser_type, finder_options, android_platform, settings,
            local_apk=local_apk)
      if p_browser.IsAvailable():
        possible_browsers.append(p_browser)
  return possible_browsers
예제 #10
0
 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), self._chrome_root)
     return browser.Browser(mandoline_backend, self._platform_backend,
                            self._credentials_path)
예제 #11
0
def _InstallApp(device, apk):
    """ Make apk installed while in scope. """
    package_name = apk_helper.GetPackageName(apk)
    device.Install(apk, reinstall=True, timeout=_WEBVIEW_INSTALL_TIMEOUT)
    try:
        yield
    finally:
        device.Uninstall(package_name)
예제 #12
0
def _InstallApp(device, apk):
    """ Make apk installed while in scope. """
    package_name = apk_helper.GetPackageName(apk)
    device.Install(apk, reinstall=True)
    try:
        yield
    finally:
        device.Uninstall(package_name)
예제 #13
0
 def __init__(self, config, chrome_root):
   self.adb_path = adb_wrapper.AdbWrapper.GetAdbPath()
   self.config = config
   self.paths = Paths(config, chrome_root)
   self.device = None
   self.shell_args = []
   self.target_package = apk_helper.GetPackageName(self.paths.apk_path)
   self.temp_gdb_dir = None
예제 #14
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 _CanPossiblyHandlePath(finder_options.browser_executable):
        if not os.path.exists(finder_options.browser_executable):
            raise exceptions.PathMissingError(
                'Unable to find exact apk specified by --browser-executable=%s'
                % finder_options.browser_executable)

        package_name = apk_helper.GetPackageName(
            finder_options.browser_executable)
        try:
            backend_settings = next(backend_settings
                                    for target_package, backend_settings in
                                    CHROME_PACKAGE_NAMES.itervalues()
                                    if package_name == target_package)
        except StopIteration:
            raise exceptions.UnknownPackageError(
                '%s specified by --browser-executable has an unknown package: %s'
                % (finder_options.browser_executable, package_name))

        possible_browsers.append(
            PossibleAndroidBrowser('exact', finder_options, android_platform,
                                   backend_settings(package_name),
                                   finder_options.browser_executable))

    # Add the reference build if found.
    os_version = dependency_util.GetChromeApkOsVersion(
        android_platform.GetOSVersionName())
    arch = android_platform.GetArchName()
    try:
        reference_build = binary_manager.FetchPath('chrome_stable', arch,
                                                   'android', os_version)
    except (binary_manager.NoPathFoundError, binary_manager.CloudStorageError):
        reference_build = None

    if reference_build and os.path.exists(reference_build):
        # TODO(aiolos): how do we stably map the android chrome_stable apk to the
        # correct package name?
        package, backend_settings = CHROME_PACKAGE_NAMES['android-chrome']
        possible_browsers.append(
            PossibleAndroidBrowser('reference',
                                   finder_options, android_platform,
                                   backend_settings(package), reference_build))

    # Add any known local versions.
    for name, package_info in CHROME_PACKAGE_NAMES.iteritems():
        package, backend_settings = package_info
        p_browser = PossibleAndroidBrowser(name, finder_options,
                                           android_platform,
                                           backend_settings(package))
        if p_browser.IsAvailable():
            possible_browsers.append(p_browser)
    return possible_browsers
예제 #15
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',
                        dest='denylist_file',
                        help=argparse.SUPPRESS)
    parser.add_argument('--denylist-file', help='Device denylist 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)

    devil_chromium.Initialize()

    denylist = (device_denylist.Denylist(args.denylist_file)
                if args.denylist_file else None)

    devices = device_utils.DeviceUtils.HealthyDevices(denylist)
    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)
예제 #16
0
    def rest_args(self):
        rest_args = super(WPTAndroidAdapter, self).rest_args

        # Here we add all of the arguments required to run WPT tests on Android.
        rest_args.extend([self.options.wpt_path])

        # vpython has packages needed by wpt, so force it to skip the setup
        rest_args.extend(["--venv=../../", "--skip-venv-setup"])

        rest_args.extend([
            "run",
            "--test-type=" + self.options.test_type,
            self.options.product,
            "--webdriver-binary",
            self.options.webdriver_binary,
            "--headless",
            "--no-pause-after-test",
            "--no-capture-stdio",
            "--no-manifest-download",
            "--no-fail-on-unexpected",
            #TODO(aluo): Tune this as tests are stabilized
            "--timeout-multiplier",
            "0.25",
        ])

        # Lets weblayer know it's running in test mode.
        if self.options.product == 'android_weblayer':
            rest_args.extend(["--binary-arg=--run-web-tests"])

        # Default to the apk's package name for chrome_android
        if not self.options.package_name:
            if self.options.product == 'chrome_android':
                if self.options.apk:
                    pkg = apk_helper.GetPackageName(self.options.apk)
                    logger.info(
                        "Defaulting --package-name to that of the apk: %s",
                        pkg)
                    rest_args.extend(['--package-name', pkg])
                else:
                    raise Exception(
                        'chrome_android requires --package-name or --apk.')
        else:
            rest_args.extend(['--package-name', self.options.package_name])

        if self.options.verbose >= 3:
            rest_args.extend([
                "--log-mach=-", "--log-mach-level=debug", "--log-mach-verbose"
            ])

        if self.options.verbose >= 4:
            rest_args.extend([
                '--webdriver-arg=--verbose', '--webdriver-arg="--log-path=-"'
            ])

        rest_args.extend(self.pass_through_wpt_args)

        return rest_args
예제 #17
0
    def __init__(self, apk_path, jar_path, test_support_apk_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)
        self._test_support_apk_path = test_support_apk_path
예제 #18
0
  def SetUpProcess(cls):
    """Prepares the test device"""
    super(WebViewCrxSmokeTests, cls).SetUpProcess()
    assert cls._finder_options.crx_file, '--crx-file is required'
    assert cls._finder_options.component_name, '--component-name is required'

    cls.SetBrowserOptions(cls._finder_options)
    webview_package_name = cls._finder_options.webview_package_name

    if not webview_package_name:
      webview_provider_apk = (cls._browser_to_create
                              .settings.GetApkName(cls._device))
      webview_apk_path = util.FindLatestApkOnHost(
          cls._finder_options.chrome_root, webview_provider_apk)
      webview_package_name = apk_helper.GetPackageName(webview_apk_path)

    cls._device_components_dir = ('/data/data/%s/app_webview/components' %
                                  webview_package_name)
    logcat_output_dir = (
        os.path.dirname(cls._typ_runner.args.write_full_results_to or '') or
        os.getcwd())

    # Set up a logcat monitor
    cls._logcat_monitor = logcat_monitor.LogcatMonitor(
        cls._device.adb,
        output_file=os.path.join(logcat_output_dir,
                                 '%s_logcat.txt' % cls.Name()),
        filter_specs=_LOGCAT_FILTERS)
    cls._logcat_monitor.Start()

    cls._MaybeClearOutComponentsDir()
    component_id = _COMPONENT_NAME_TO_DATA.get(
        cls._finder_options.component_name).component_id
    with zipfile.ZipFile(cls._finder_options.crx_file) as crx_archive, \
        NamedTemporaryDirectory() as tmp_dir,                          \
        crx_archive.open('manifest.json') as manifest:
      crx_device_dir = posixpath.join(
          cls._device_components_dir, 'cps',
          component_id, '1_%s' % json.loads(manifest.read())['version'])

      try:
        # Create directory on the test device for the CRX files
        logger.info('Creating directory %r on device' % crx_device_dir)
        output = cls._device.RunShellCommand(
            ['mkdir', '-p', crx_device_dir])
        logger.debug('Recieved the following output from adb: %s' % output)
      except Exception as e:
        logger.exception('Exception %r was raised' % str(e))
        raise

      # Move CRX files to the device directory
      crx_archive.extractall(tmp_dir)
      cls._MoveNewCrxToDevice(tmp_dir, crx_device_dir)

    # Start the browser after the device is in a clean state and the CRX
    # files are loaded onto the device
    cls.StartBrowser()
    def UpdateExecutableIfNeeded(self):
        # TODO(crbug.com/815133): This logic should belong to backend_settings.
        for apk in self._support_apk_list:
            logging.warn('Installing %s on device if needed.', apk)
            self.platform.InstallApplication(apk)

        apk_name = self._backend_settings.GetApkName(
            self._platform_backend.device)
        is_webview_apk = apk_name is not None and (
            'SystemWebView' in apk_name or 'system_webview' in apk_name or
            'TrichromeWebView' in apk_name or 'trichrome_webview' in apk_name)
        # The WebView fallback logic prevents sideloaded WebView APKs from being
        # installed and set as the WebView implementation correctly. Disable the
        # fallback logic before installing the WebView APK to make sure the fallback
        # logic doesn't interfere.
        if is_webview_apk:
            self._platform_backend.device.SetWebViewFallbackLogic(False)

        if self._local_apk:
            logging.warn('Installing %s on device if needed.', self._local_apk)
            self.platform.InstallApplication(self._local_apk,
                                             modules=self._modules_to_install)
            if self._compile_apk:
                package_name = apk_helper.GetPackageName(self._local_apk)
                logging.warn('Compiling %s.', package_name)
                self._platform_backend.device.RunShellCommand(
                    [
                        'cmd', 'package', 'compile', '-m', self._compile_apk,
                        '-f', package_name
                    ],
                    check_return=True)

        sdk_version = self._platform_backend.device.build_version_sdk
        # Bundles are in the ../bin directory, so it's safer to just check the
        # correct name is part of the path.
        is_monochrome = apk_name is not None and (
            apk_name == 'Monochrome.apk' or 'monochrome_bundle' in apk_name)
        if ((is_webview_apk or
             (is_monochrome and sdk_version < version_codes.Q))
                and sdk_version >= version_codes.NOUGAT):
            package_name = apk_helper.GetPackageName(self._local_apk)
            logging.warn('Setting %s as WebView implementation.', package_name)
            self._platform_backend.device.SetWebViewImplementation(
                package_name)
def get_package_name(apk_path):
    """Get package name from apk

  Args:
    apk_path: Path to apk

  Returns:
    Package name of apk
  """
    return apk_helper.GetPackageName(apk_path)
예제 #21
0
 def __init__(self, config, chrome_root):
     self.adb_path = constants.GetAdbPath()
     self.config = config
     self.paths = Paths(config, chrome_root)
     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)
예제 #22
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 _CanPossiblyHandlePath(finder_options.browser_executable):
        if not os.path.exists(finder_options.browser_executable):
            raise exceptions.PathMissingError(
                'Unable to find exact apk specified by --browser-executable=%s'
                % finder_options.browser_executable)

        package_name = apk_helper.GetPackageName(
            finder_options.browser_executable)
        try:
            backend_settings = next(b for b in ANDROID_BACKEND_SETTINGS
                                    if b.package == package_name)
        except StopIteration:
            raise exceptions.UnknownPackageError(
                '%s specified by --browser-executable has an unknown package: %s'
                % (finder_options.browser_executable, package_name))

        possible_browsers.append(
            PossibleAndroidBrowser('exact', finder_options, android_platform,
                                   backend_settings,
                                   finder_options.browser_executable))

    # Add the reference build if found.
    os_version = dependency_util.GetChromeApkOsVersion(
        android_platform.GetOSVersionName())
    arch = android_platform.GetArchName()
    try:
        reference_build = binary_manager.FetchPath('chrome_stable', arch,
                                                   'android', os_version)
    except (binary_manager.NoPathFoundError, binary_manager.CloudStorageError):
        reference_build = None

    if reference_build and os.path.exists(reference_build):
        # TODO(aiolos): how do we stably map the android chrome_stable apk to the
        # correct backend settings?
        possible_browsers.append(
            PossibleAndroidBrowser(
                'reference', finder_options, android_platform,
                android_browser_backend_settings.ANDROID_CHROME,
                reference_build))

    # Add any other known available browsers.
    for settings in ANDROID_BACKEND_SETTINGS:
        p_browser = PossibleAndroidBrowser(settings.browser_type,
                                           finder_options, android_platform,
                                           settings)
        if p_browser.IsAvailable():
            possible_browsers.append(p_browser)
    return possible_browsers
예제 #23
0
def _TemporarilyInstallApp(device, apk, install_timeout=None):
    """A context manager that installs an app while in scope."""
    if install_timeout is None:
        device.Install(apk, reinstall=True)
    else:
        device.Install(apk, reinstall=True, timeout=install_timeout)

    try:
        yield
    finally:
        device.Uninstall(apk_helper.GetPackageName(apk))
예제 #24
0
    def rest_args(self):
        rest_args = super(WPTAndroidAdapter, self).rest_args

        # Here we add all of the arguments required to run WPT tests on Android.
        rest_args.extend([self.options.wpt_path])

        # vpython has packages needed by wpt, so force it to skip the setup
        rest_args.extend(["--venv=../../", "--skip-venv-setup"])

        rest_args.extend([
            "run",
            "--test-type=" + self.options.test_type,
            self.options.product,
            "--webdriver-binary",
            self.options.webdriver_binary,
            "--headless",
            "--no-pause-after-test",
            "--no-capture-stdio",
            "--no-manifest-download",
        ])
        # if metadata was created then add the metadata directory
        # to the list of wpt arguments
        if self._metadata_dir:
            rest_args.extend(['--metadata', self._metadata_dir])

        # Default to the apk's package name for chrome_android
        if not self.options.package_name:
            if self.options.product == 'chrome_android':
                if self.options.apk:
                    pkg = apk_helper.GetPackageName(self.options.apk)
                    logger.info(
                        "Defaulting --package-name to that of the apk: %s",
                        pkg)
                    rest_args.extend(['--package-name', pkg])
                else:
                    raise Exception(
                        'chrome_android requires --package-name or --apk.')
        else:
            rest_args.extend(['--package-name', self.options.package_name])

        if self.options.verbose >= 3:
            rest_args.extend([
                "--log-mach=-", "--log-mach-level=debug", "--log-mach-verbose"
            ])

        if self.options.verbose >= 4:
            rest_args.extend([
                '--webdriver-arg=--verbose', '--webdriver-arg="--log-path=-"'
            ])

        rest_args.extend(self.pass_through_wpt_args)

        return rest_args
예제 #25
0
 def rest_args(self):
   args = super(WPTClankAdapter, self).rest_args
   if not self.options.chrome_package_name and not self.options.chrome_apk:
     raise Exception('Either the --chrome-package-name or --chrome-apk '
                     'command line arguments must be used.')
   if not self.options.chrome_package_name:
     self.options.chrome_package_name = apk_helper.GetPackageName(
         self.options.chrome_apk)
     logger.info("Using Chrome apk's default package %s." %
                 self.options.chrome_package_name)
   args.extend(['--package-name', self.options.chrome_package_name])
   # add the product postional argument
   args.append(CHROME_ANDROID)
   return args
예제 #26
0
    def rest_args(self):
        rest_args = super(WPTAndroidAdapter, self).rest_args

        # Here we add all of the arguments required to run WPT tests on Android.
        rest_args.extend([self.options.wpt_path])

        # vpython has packages needed by wpt, so force it to skip the setup
        rest_args.extend(["--venv=../../", "--skip-venv-setup"])

        rest_args.extend([
            "run",
            "--test-type=" + self.options.test_type,
            self.options.product,
            "--webdriver-binary",
            self.options.webdriver_binary,
            "--headless",
            "--no-pause-after-test",
            "--no-capture-stdio",
            "--no-manifest-download",
            "--no-fail-on-unexpected",
            #TODO(aluo): Tune this as tests are stabilized
            "--timeout-multiplier",
            "0.25",
        ])

        # Default to the apk's package name for chrome_android
        if not self.options.package_name:
            if self.options.product == 'chrome_android':
                if self.options.apk:
                    pkg = apk_helper.GetPackageName(self.options.apk)
                    print("Defaulting --package-name to that of the apk: {}.".
                          format(pkg))
                    rest_args.extend(['--package-name', pkg])
                else:
                    raise Exception(
                        'chrome_android requires --package-name or --apk.')
        else:
            rest_args.extend(['--package-name', self.options.package_name])

        if self.options.include:
            for i in self.options.include:
                rest_args.extend(['--include', i])

        if self.options.list_tests:
            rest_args.extend(['--list-tests'])

        return rest_args
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)):
        apk_name = os.path.basename(finder_options.browser_executable)
        package_info = next((info
                             for info in CHROME_PACKAGE_NAMES.itervalues()
                             if info[2] == apk_name), None)

        # It is okay if the APK name doesn't match any of known chrome browser APKs,
        # since it may be of a different browser (say, mandoline).
        if package_info:
            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, backend_settings, _] = package_info
            if package == exact_package:
                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
예제 #28
0
    def install(device):
        print 'Installing %s...' % args.shell_apk_path
        device.Install(args.shell_apk_path,
                       reinstall=True,
                       allow_downgrade=True)
        print 'Success'
        for path in args.support_apk_path:
            print 'Installing %s...' % path
            device.Install(path, reinstall=True, allow_downgrade=True)
            print 'Success'
        if args.switch_webview_to:
            print 'Installing %s...' % args.switch_webview_to
            device.Install(args.switch_webview_to,
                           reinstall=True,
                           allow_downgrade=True)
            package = apk_helper.GetPackageName(args.switch_webview_to)
            print 'Setting WebView implementation to %s' % package
            device.SetWebViewImplementation(package)
            print 'Done'

        if os.path.basename(args.shell_apk_path) == 'WebLayerShell.apk':
            # When launching weblayer shell use 'weblayer_shell_apk', which supports
            # more options.
            launch_cmd = [
                os.path.join(os.path.dirname(args.shell_apk_path), os.pardir,
                             'bin', 'weblayer_shell_apk'), 'launch'
            ]
            launch_cmd.extend(args.remaining_args)
            subprocess.call(launch_cmd)
        elif (os.path.basename(
                args.shell_apk_path) == 'WebLayerShellSystemWebView.apk'):
            # When launching weblayer shell use 'weblayer_shell_apk', which supports
            # more options.
            launch_cmd = [
                os.path.join(os.path.dirname(args.shell_apk_path), os.pardir,
                             'bin', 'weblayer_shell_system_webview_apk'),
                'launch'
            ]
            launch_cmd.extend(args.remaining_args)
            subprocess.call(launch_cmd)
        else:
            device.adb.Shell('monkey -p org.chromium.weblayer.shell 1')
예제 #29
0
def maybe_install_user_apk(device, apk, expected_pkg=None):
  """contextmanager to install apk on device.

  Args:
    device: DeviceUtils instance on which to install the apk.
    apk: Apk file path on host.
    expected_pkg:  Optional, check that apk's package name matches.
  Returns:
    If apk evaluates to false, returns a do-nothing contextmanager.
    Otherwise, returns a contextmanager to install apk on device.
  """
  if apk:
    pkg = apk_helper.GetPackageName(apk)
    if expected_pkg and pkg != expected_pkg:
      raise ValueError('{} has incorrect package name: {}, expected {}.'.format(
          apk, pkg, expected_pkg))
    install_as_needed = app_installed(device, apk, pkg)
    logger.info('Will install ' + pkg + ' at ' + apk)
  else:
    install_as_needed = no_op()
  return install_as_needed
예제 #30
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)):
        apk_name = os.path.basename(finder_options.browser_executable)
        normalized_path = os.path.expanduser(finder_options.browser_executable)
        exact_package = apk_helper.GetPackageName(normalized_path)
        package_info = next(
            (info for info in CHROME_PACKAGE_NAMES.itervalues()
             if info[0] == exact_package or info[2] == apk_name), None)

        # It is okay if the APK name or package doesn't match any of known chrome
        # browser APKs, since it may be of a different browser.
        if package_info:
            if not exact_package:
                raise exceptions.PackageDetectionError(
                    'Unable to find package for %s specified by --browser-executable'
                    % normalized_path)

            [package, backend_settings, _] = package_info
            if package == exact_package:
                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))

    # Add the reference build if found.
    os_version = dependency_util.GetChromeApkOsVersion(
        android_platform.GetOSVersionName())
    arch = android_platform.GetArchName()
    try:
        reference_build = binary_manager.FetchPath('chrome_stable', arch,
                                                   'android', os_version)
    except (binary_manager.NoPathFoundError, binary_manager.CloudStorageError):
        reference_build = None

    if reference_build and os.path.exists(reference_build):
        # TODO(aiolos): how do we stably map the android chrome_stable apk to the
        # correct package name?
        package, backend_settings, _ = CHROME_PACKAGE_NAMES['android-chrome']
        possible_browsers.append(
            PossibleAndroidBrowser('reference',
                                   finder_options, android_platform,
                                   backend_settings(package), reference_build))

    # Add any known local versions.
    for name, package_info in CHROME_PACKAGE_NAMES.iteritems():
        package, backend_settings, apk_name = package_info
        if apk_name and not finder_options.chrome_root:
            continue
        b = PossibleAndroidBrowser(name, finder_options, android_platform,
                                   backend_settings(package), apk_name)
        if b.platform.CanLaunchApplication(package) or b.HaveLocalAPK():
            possible_browsers.append(b)
    return possible_browsers