示例#1
0
    def Start(self, read_only=True, snapshot_save=False, window=False):
        """Starts the emulator running an instance of the given AVD."""
        with tempfile_ext.TemporaryFileName() as socket_path, (
                contextlib.closing(socket.socket(socket.AF_UNIX))) as sock:
            sock.bind(socket_path)
            emulator_cmd = [
                self._emulator_path,
                '-avd',
                self._avd_name,
                '-report-console',
                'unix:%s' % socket_path,
            ]
            if read_only:
                emulator_cmd.append('-read-only')
            if not snapshot_save:
                emulator_cmd.append('-no-snapshot-save')
            emulator_env = {}
            if self._emulator_home:
                emulator_env['ANDROID_EMULATOR_HOME'] = self._emulator_home
            if window:
                if 'DISPLAY' in os.environ:
                    emulator_env['DISPLAY'] = os.environ.get('DISPLAY')
                else:
                    raise AvdException(
                        'Emulator failed to start: DISPLAY not defined')
            else:
                emulator_cmd.append('-no-window')
            sock.listen(1)

            logging.info('Starting emulator.')

            # TODO(jbudorick): Add support for logging emulator stdout & stderr at
            # higher logging levels.
            self._sink = open('/dev/null', 'w')
            self._emulator_proc = cmd_helper.Popen(emulator_cmd,
                                                   stdout=self._sink,
                                                   stderr=self._sink,
                                                   env=emulator_env)

            # Waits for the emulator to report its serial as requested via
            # -report-console. See http://bit.ly/2lK3L18 for more.
            def listen_for_serial(s):
                logging.info('Waiting for connection from emulator.')
                with contextlib.closing(s.accept()[0]) as conn:
                    val = conn.recv(1024)
                    return 'emulator-%d' % int(val)

            try:
                self._emulator_serial = timeout_retry.Run(listen_for_serial,
                                                          timeout=30,
                                                          retries=0,
                                                          args=[sock])
                logging.info('%s started', self._emulator_serial)
            except Exception as e:
                self.Stop()
                raise AvdException('Emulator failed to start: %s' % str(e))
示例#2
0
 def Start(self):
     """Start recording video."""
     self._recorder_stdout = tempfile.mkstemp()[1]
     self._recorder = cmd_helper.Popen(self._args,
                                       stdout=open(self._recorder_stdout,
                                                   'w'))
     if not self._device.GetPids('screenrecord'):
         raise RuntimeError(
             'Recording failed. Is your device running Android '
             'KitKat or later?')
    def _StartInstance(self):
        """Starts an AVD instance.

    Returns:
      A (Popen, str) 2-tuple that includes the process and serial.
    """
        # Start up the AVD.
        with tempfile_ext.TemporaryFileName() as socket_path, (
                contextlib.closing(socket.socket(socket.AF_UNIX))) as sock:
            sock.bind(socket_path)
            emulator_cmd = [
                self._emulator_path,
                '-avd',
                self._avd_name,
                '-report-console',
                'unix:%s' % socket_path,
                '-read-only',
                '-no-window',
            ]
            emulator_env = {}
            if self._emulator_home:
                emulator_env['ANDROID_EMULATOR_HOME'] = self._emulator_home
            sock.listen(1)
            emulator_proc = cmd_helper.Popen(emulator_cmd, env=emulator_env)

            def listen_for_serial(s):
                logging.info('Waiting for connection from emulator.')
                with contextlib.closing(s.accept()[0]) as conn:
                    val = conn.recv(1024)
                    return 'emulator-%d' % int(val)

            try:
                emulator_serial = timeout_retry.Run(listen_for_serial,
                                                    timeout=30,
                                                    retries=0,
                                                    args=[sock])
            except Exception:
                emulator_proc.terminate()
                raise

            return (emulator_proc, emulator_serial)
示例#4
0
文件: avd.py 项目: wzis/chromium
  def Create(self, avd_name, system_image, force=False):
    """Call `avdmanager create`.

    Args:
      avd_name: name of the AVD to create.
      system_image: system image to use for the AVD.
      force: whether to force creation, overwriting any existing
        AVD with the same name.
    """
    create_cmd = [
        _DEFAULT_AVDMANAGER_PATH,
        '-v',
        'create',
        'avd',
        '-n',
        avd_name,
        '-k',
        system_image,
    ]
    if force:
      create_cmd += ['--force']

    create_proc = cmd_helper.Popen(
        create_cmd,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        env=self._env)
    output, error = create_proc.communicate(input='\n')
    if create_proc.returncode != 0:
      raise AvdException(
          'AVD creation failed',
          command=create_cmd,
          stdout=output,
          stderr=error)

    for line in output.splitlines():
      logging.info('  %s', line)
示例#5
0
    def Start(self,
              ensure_system_settings=True,
              read_only=True,
              window=False,
              writable_system=False,
              gpu_mode=_DEFAULT_GPU_MODE,
              wipe_data=False,
              debug_tags=None):
        """Starts the emulator running an instance of the given AVD.

    Note when ensure_system_settings is True, the program will wait until the
    emulator is fully booted, and then update system settings.
    """
        is_slow_start = False
        # Force to load system snapshot if detected.
        if self.HasSystemSnapshot():
            if not writable_system:
                logging.info(
                    'System snapshot found. Set "writable_system=True" '
                    'to load it properly.')
                writable_system = True
            if read_only:
                logging.info('System snapshot found. Set "read_only=False" '
                             'to load it properly.')
                read_only = False
        elif writable_system:
            is_slow_start = True
            logging.warning(
                'Emulator will be slow to start, as '
                '"writable_system=True" but system snapshot not found.')

        self._writable_system = writable_system

        with tempfile_ext.TemporaryFileName() as socket_path, (
                contextlib.closing(socket.socket(socket.AF_UNIX))) as sock:
            sock.bind(socket_path)
            emulator_cmd = [
                self._emulator_path,
                '-avd',
                self._avd_name,
                '-report-console',
                'unix:%s' % socket_path,
                '-no-boot-anim',
                # Explicitly prevent emulator from auto-saving to snapshot on exit.
                '-no-snapshot-save',
                # Explicitly set the snapshot name for auto-load
                '-snapshot',
                self.GetSnapshotName(),
            ]

            if wipe_data:
                emulator_cmd.append('-wipe-data')
            if read_only:
                emulator_cmd.append('-read-only')
            if writable_system:
                emulator_cmd.append('-writable-system')
            # Note when "--gpu-mode" is set to "host":
            #  * It needs a valid DISPLAY env, even if "--emulator-window" is false.
            #    Otherwise it may throw errors like "Failed to initialize backend
            #    EGL display". See the code in https://bit.ly/3ruiMlB as an example
            #    to setup the DISPLAY env with xvfb.
            #  * It will not work under remote sessions like chrome remote desktop.
            if gpu_mode:
                emulator_cmd.extend(['-gpu', gpu_mode])
            if debug_tags:
                emulator_cmd.extend(['-debug', debug_tags])

            emulator_env = {}
            if self._emulator_home:
                emulator_env['ANDROID_EMULATOR_HOME'] = self._emulator_home
            if 'DISPLAY' in os.environ:
                emulator_env['DISPLAY'] = os.environ.get('DISPLAY')
            if window:
                if 'DISPLAY' not in emulator_env:
                    raise AvdException(
                        'Emulator failed to start: DISPLAY not defined')
            else:
                emulator_cmd.append('-no-window')

            sock.listen(1)

            logging.info('Starting emulator...')
            logging.info(
                '  With environments: %s',
                ' '.join(['%s=%s' % (k, v) for k, v in emulator_env.items()]))
            logging.info('  With commands: %s', ' '.join(emulator_cmd))

            # TODO(jbudorick): Add support for logging emulator stdout & stderr at
            # higher logging levels.
            # Enable the emulator log when debug_tags is set.
            if not debug_tags:
                self._sink = open('/dev/null', 'w')
            self._emulator_proc = cmd_helper.Popen(emulator_cmd,
                                                   stdout=self._sink,
                                                   stderr=self._sink,
                                                   env=emulator_env)

            # Waits for the emulator to report its serial as requested via
            # -report-console. See http://bit.ly/2lK3L18 for more.
            def listen_for_serial(s):
                logging.info('Waiting for connection from emulator.')
                with contextlib.closing(s.accept()[0]) as conn:
                    val = conn.recv(1024)
                    return 'emulator-%d' % int(val)

            try:
                self._emulator_serial = timeout_retry.Run(listen_for_serial,
                                                          timeout=30,
                                                          retries=0,
                                                          args=[sock])
                logging.info('%s started', self._emulator_serial)
            except Exception as e:
                self.Stop()
                # avd.py is executed with python2.
                # pylint: disable=W0707
                raise AvdException('Emulator failed to start: %s' % str(e))

        # Set the system settings in "Start" here instead of setting in "Create"
        # because "Create" is used during AVD creation, and we want to avoid extra
        # turn-around on rolling AVD.
        if ensure_system_settings:
            assert self.device is not None, '`instance.device` not initialized.'
            self.device.WaitUntilFullyBooted(
                timeout=120 if is_slow_start else 30)
            _EnsureSystemSettings(self.device)
示例#6
0
  def Start(self,
            read_only=True,
            snapshot_save=False,
            window=False,
            writable_system=False):
    """Starts the emulator running an instance of the given AVD."""

    with tempfile_ext.TemporaryFileName() as socket_path, (contextlib.closing(
        socket.socket(socket.AF_UNIX))) as sock:
      sock.bind(socket_path)
      emulator_cmd = [
          self._emulator_path,
          '-avd',
          self._avd_name,
          '-report-console',
          'unix:%s' % socket_path,
          '-no-boot-anim',
      ]

      android_avd_home = os.path.join(self._emulator_home, 'avd')
      avd_dir = os.path.join(android_avd_home, '%s.avd' % self._avd_name)

      hardware_qemu_path = os.path.join(avd_dir, 'hardware-qemu.ini')
      if os.path.exists(hardware_qemu_path):
        with open(hardware_qemu_path) as hardware_qemu_file:
          hardware_qemu_contents = ini.load(hardware_qemu_file)
      else:
        hardware_qemu_contents = {}

      if read_only:
        emulator_cmd.append('-read-only')
      if not snapshot_save:
        emulator_cmd.append('-no-snapshot-save')
      if writable_system:
        emulator_cmd.append('-writable-system')

      emulator_env = {}
      if self._emulator_home:
        emulator_env['ANDROID_EMULATOR_HOME'] = self._emulator_home
      if window:
        if 'DISPLAY' in os.environ:
          emulator_env['DISPLAY'] = os.environ.get('DISPLAY')
        else:
          raise AvdException('Emulator failed to start: DISPLAY not defined')
      else:
        emulator_cmd.append('-no-window')

      hardware_qemu_contents['hw.sdCard'] = 'true'
      if self._avd_config.avd_settings.sdcard.size:
        sdcard_path = os.path.join(self._emulator_home, 'avd',
                                   '%s.avd' % self._avd_name, 'cr-sdcard.img')
        if not os.path.exists(sdcard_path):
          mksdcard_path = os.path.join(
              os.path.dirname(self._emulator_path), 'mksdcard')
          mksdcard_cmd = [
              mksdcard_path,
              self._avd_config.avd_settings.sdcard.size,
              sdcard_path,
          ]
          cmd_helper.RunCmd(mksdcard_cmd)

        emulator_cmd.extend(['-sdcard', sdcard_path])
        hardware_qemu_contents['hw.sdCard.path'] = sdcard_path

      with open(hardware_qemu_path, 'w') as hardware_qemu_file:
        ini.dump(hardware_qemu_contents, hardware_qemu_file)

      sock.listen(1)

      logging.info('Starting emulator.')

      # TODO(jbudorick): Add support for logging emulator stdout & stderr at
      # higher logging levels.
      self._sink = open('/dev/null', 'w')
      self._emulator_proc = cmd_helper.Popen(
          emulator_cmd, stdout=self._sink, stderr=self._sink, env=emulator_env)

      # Waits for the emulator to report its serial as requested via
      # -report-console. See http://bit.ly/2lK3L18 for more.
      def listen_for_serial(s):
        logging.info('Waiting for connection from emulator.')
        with contextlib.closing(s.accept()[0]) as conn:
          val = conn.recv(1024)
          return 'emulator-%d' % int(val)

      try:
        self._emulator_serial = timeout_retry.Run(
            listen_for_serial, timeout=30, retries=0, args=[sock])
        logging.info('%s started', self._emulator_serial)
      except Exception as e:
        self.Stop()
        raise AvdException('Emulator failed to start: %s' % str(e))
示例#7
0
    def RunTests(self, results):
        wrapper_path = os.path.join(constants.GetOutDirectory(), 'bin',
                                    'helper', self._test_instance.suite)

        # This avoids searching through the classparth jars for tests classes,
        # which takes about 1-2 seconds.
        # Do not shard when a test filter is present since we do not know at this
        # point which tests will be filtered out.
        if (self._test_instance.shards == 1 or self._test_instance.test_filter
                or self._test_instance.suite in _EXCLUDED_SUITES):
            test_classes = []
            shards = 1
        else:
            test_classes = _GetTestClasses(wrapper_path)
            shards = ChooseNumOfShards(test_classes,
                                       self._test_instance.shards)

        logging.info('Running tests on %d shard(s).', shards)
        group_test_list = GroupTestsForShard(shards, test_classes)

        with tempfile_ext.NamedTemporaryDirectory() as temp_dir:
            cmd_list = [[wrapper_path] for _ in range(shards)]
            json_result_file_paths = [
                os.path.join(temp_dir, 'results%d.json' % i)
                for i in range(shards)
            ]
            jar_args_list = self._CreateJarArgsList(json_result_file_paths,
                                                    group_test_list, shards)
            for i in range(shards):
                cmd_list[i].extend(
                    ['--jar-args',
                     '"%s"' % ' '.join(jar_args_list[i])])

            jvm_args = self._CreateJvmArgsList()
            if jvm_args:
                for cmd in cmd_list:
                    cmd.extend(['--jvm-args', '"%s"' % ' '.join(jvm_args)])

            AddPropertiesJar(cmd_list, temp_dir,
                             self._test_instance.resource_apk)

            procs = []
            temp_files = []
            for index, cmd in enumerate(cmd_list):
                # First process prints to stdout, the rest write to files.
                if index == 0:
                    sys.stdout.write('\nShard 0 output:\n')
                    procs.append(
                        cmd_helper.Popen(
                            cmd,
                            stdout=sys.stdout,
                            stderr=subprocess.STDOUT,
                        ))
                else:
                    temp_file = tempfile.TemporaryFile()
                    temp_files.append(temp_file)
                    procs.append(
                        cmd_helper.Popen(
                            cmd,
                            stdout=temp_file,
                            stderr=temp_file,
                        ))

            PrintProcessesStdout(procs, temp_files)

            results_list = []
            try:
                for json_file_path in json_result_file_paths:
                    with open(json_file_path, 'r') as f:
                        results_list += json_results.ParseResultsFromJson(
                            json.loads(f.read()))
            except IOError:
                # In the case of a failure in the JUnit or Robolectric test runner
                # the output json file may never be written.
                results_list = [
                    base_test_result.BaseTestResult(
                        'Test Runner Failure',
                        base_test_result.ResultType.UNKNOWN)
                ]

            test_run_results = base_test_result.TestRunResults()
            test_run_results.AddResults(results_list)
            results.append(test_run_results)