def WaitForInstrumentation(self, package_name, runner_name, wait_time=120):
        """Waits for given instrumentation to be present on device

    Args:
      wait_time: time in seconds to wait

    Raises:
      WaitForResponseTimedOutError if wait_time elapses and instrumentation
      still not present.
    """
        instrumentation_path = "%s/%s" % (package_name, runner_name)
        logger.Log("Waiting for instrumentation to be present")
        # Query the package manager
        try:
            command = "pm list instrumentation | grep %s" % instrumentation_path
            self._WaitForShellCommandContents(command,
                                              "instrumentation:",
                                              wait_time,
                                              raise_abort=False)
        except errors.WaitForResponseTimedOutError:
            logger.Log(
                "Could not find instrumentation %s on device. Does the "
                "instrumentation in test's AndroidManifest.xml match definition"
                "in test_defs.xml?" % instrumentation_path)
            raise
    def Sync(self, retry_count=3, runtime_restart=False):
        """Perform a adb sync.

    Blocks until device package manager is responding.

    Args:
      retry_count: number of times to retry sync before failing
      runtime_restart: stop runtime during sync and restart afterwards, useful
        for syncing system libraries (core, framework etc)

    Raises:
      WaitForResponseTimedOutError if package manager does not respond
      AbortError if unrecoverable error occurred
    """
        output = ""
        error = None
        if runtime_restart:
            self.SendShellCommand("setprop ro.monkey 1",
                                  retry_count=retry_count)
            # manual rest bootcomplete flag
            self.SendShellCommand("setprop dev.bootcomplete 0",
                                  retry_count=retry_count)
            self.SendShellCommand("stop", retry_count=retry_count)

        try:
            output = self.SendCommand("sync", retry_count=retry_count)
        except errors.AbortError as e:
            error = e
            output = e.msg
        if "Read-only file system" in output:
            logger.SilentLog(output)
            logger.Log("Remounting read-only filesystem")
            self.SendCommand("remount")
            output = self.SendCommand("sync", retry_count=retry_count)
        elif "No space left on device" in output:
            logger.SilentLog(output)
            logger.Log("Restarting device runtime")
            self.SendShellCommand("stop", retry_count=retry_count)
            output = self.SendCommand("sync", retry_count=retry_count)
            self.SendShellCommand("start", retry_count=retry_count)
        elif error is not None:
            # exception occurred that cannot be recovered from
            raise error
        logger.SilentLog(output)
        if runtime_restart:
            # start runtime and wait till boot complete flag is set
            self.SendShellCommand("start", retry_count=retry_count)
            self.WaitForBootComplete()
            # press the MENU key, this will disable key guard if runtime is started
            # with ro.monkey set to 1
            self.SendShellCommand("input keyevent 82", retry_count=retry_count)
        else:
            self.WaitForDevicePm()
        return output
    def WaitForBootComplete(self, wait_time=120):
        """Waits for targeted device's bootcomplete flag to be set.

    Args:
      wait_time: time in seconds to wait

    Raises:
      WaitForResponseTimedOutError if wait_time elapses and pm still does not
      respond.
    """
        logger.Log("Waiting for boot complete...")
        self.SendCommand("wait-for-device")
        # Now the device is there, but may not be running.
        # Query the package manager with a basic command
        boot_complete = False
        attempts = 0
        wait_period = 5
        while not boot_complete and (attempts * wait_period) < wait_time:
            output = self.SendShellCommand("getprop dev.bootcomplete",
                                           retry_count=1)
            output = output.strip()
            if output == "1":
                boot_complete = True
            else:
                time.sleep(wait_period)
                attempts += 1
        if not boot_complete:
            raise errors.WaitForResponseTimedOutError(
                "dev.bootcomplete flag was not set after %s seconds" %
                wait_time)
def RunCommand(cmd, timeout_time=None, retry_count=3, return_output=True,
               stdin_input=None):
  """Spawn and retry a subprocess to run the given shell command.

  Args:
    cmd: shell command to run
    timeout_time: time in seconds to wait for command to run before aborting.
    retry_count: number of times to retry command
    return_output: if True return output of command as string. Otherwise,
      direct output of command to stdout.
    stdin_input: data to feed to stdin
  Returns:
    output of command
  """
  result = None
  while True:
    try:
      result = RunOnce(cmd, timeout_time=timeout_time,
                       return_output=return_output, stdin_input=stdin_input)
    except errors.WaitForResponseTimedOutError:
      if retry_count == 0:
        raise
      retry_count -= 1
      logger.Log("No response for %s, retrying" % cmd)
    else:
      # Success
      return result
 def EnableAdbRoot(self):
     """Enable adb root on device."""
     output = self.SendCommand("root")
     if "adbd is already running as root" in output:
         return True
     elif "restarting adbd as root" in output:
         # device will disappear from adb, wait for it to come back
         self.SendCommand("wait-for-device")
         return True
     else:
         logger.Log("Unrecognized output from adb root: %s" % output)
         return False
    def WaitForProcessEnd(self, name, wait_time=120):
        """Wait until a process is no longer running on the device.

    Args:
      name: the process name as it appears in `ps`
      wait_time: time in seconds to wait

    Raises:
      WaitForResponseTimedOutError if wait_time elapses and the process is
          still running
    """
        logger.Log("Waiting for process %s to end" % name)
        self._WaitForShellCommandContents("ps", name, wait_time, invert=True)
    def WaitForProcess(self, name, wait_time=120):
        """Wait until a process is running on the device.

    Args:
      name: the process name as it appears in `ps`
      wait_time: time in seconds to wait

    Raises:
      WaitForResponseTimedOutError if wait_time elapses and the process is
          still not running
    """
        logger.Log("Waiting for process %s" % name)
        self.SendCommand("wait-for-device")
        self._WaitForShellCommandContents("ps", name, wait_time)
    def WaitForDevicePm(self, wait_time=120):
        """Waits for targeted device's package manager to be up.

    Args:
      wait_time: time in seconds to wait

    Raises:
      WaitForResponseTimedOutError if wait_time elapses and pm still does not
      respond.
    """
        logger.Log("Waiting for device package manager...")
        self.SendCommand("wait-for-device")
        # Now the device is there, but may not be running.
        # Query the package manager with a basic command
        try:
            self._WaitForShellCommandContents("pm path android", "package:",
                                              wait_time)
        except errors.WaitForResponseTimedOutError:
            raise errors.WaitForResponseTimedOutError(
                "Package manager did not respond after %s seconds" % wait_time)
    def StartInstrumentationNoResults(self,
                                      package_name,
                                      runner_name,
                                      no_window_animation=False,
                                      raw_mode=False,
                                      instrumentation_args={}):
        """Runs instrumentation and dumps output to stdout.

    Equivalent to StartInstrumentation, but will dump instrumentation
    'normal' output to stdout, instead of parsing return results. Command will
    never timeout.
    """
        adb_command_string = self.PreviewInstrumentationCommand(
            package_name,
            runner_name,
            no_window_animation=no_window_animation,
            raw_mode=raw_mode,
            instrumentation_args=instrumentation_args)
        logger.Log(adb_command_string)
        run_command.RunCommand(adb_command_string, return_output=False)
    def Pull(self, src, dest):
        """Pulls the file src on the device onto dest on the host.

    Args:
      src: absolute file path of file on device to pull
      dest: destination file path on host

    Returns:
      True if success and False otherwise.
    """
        # Create the base dir if it doesn't exist already
        if not os.path.exists(os.path.dirname(dest)):
            os.makedirs(os.path.dirname(dest))

        if self.DoesFileExist(src):
            self.SendCommand("pull %s %s" % (src, dest), timeout_time=60)
            return True
        else:
            logger.Log("ADB Pull Failed: Source file %s does not exist." % src)
            return False
 def Run():
   global error_occurred
   try:
     pipe.communicate(input=stdin_input)
     output = None
     if return_output:
       output_dest.seek(0)
       output = output_dest.read()
       output_dest.close()
     if output is not None and len(output) > 0:
       so.append(output)
   except OSError as e:
     logger.SilentLog("failed to retrieve stdout from: %s" % cmd)
     logger.Log(e)
     so.append("ERROR")
     error_occurred = True
   if pipe.returncode:
     logger.SilentLog("Error: %s returned %d error code" %(cmd,
         pipe.returncode))
     error_occurred = True
    def StartInstrumentation(self,
                             instrumentation_path,
                             timeout_time=60 * 10,
                             no_window_animation=False,
                             profile=False,
                             instrumentation_args={},
                             silent_log=False):
        """Runs an instrumentation class on the target.

    Returns a dictionary containing the key value pairs from the
    instrumentations result bundle and a list of TestResults. Also handles the
    interpreting of error output from the device and raises the necessary
    exceptions.

    Args:
      instrumentation_path: string. It should be the fully classified package
      name, and instrumentation test runner, separated by "/"
        e.g. com.android.globaltimelaunch/.GlobalTimeLaunch
      timeout_time: Timeout value for the am command.
      no_window_animation: boolean, Whether you want window animations enabled
        or disabled
      profile: If True, profiling will be turned on for the instrumentation.
      instrumentation_args: Dictionary of key value bundle arguments to pass to
      instrumentation.
      silent_log: If True, the invocation of the instrumentation test runner
        will not be logged.

    Returns:
      (test_results, inst_finished_bundle)

      test_results: a list of TestResults
      inst_finished_bundle (dict): Key/value pairs contained in the bundle that
        is passed into ActivityManager.finishInstrumentation(). Included in this
        bundle is the return code of the Instrumentation process, any error
        codes reported by the activity manager, and any results explicitly added
        by the instrumentation code.

     Raises:
       WaitForResponseTimedOutError: if timeout occurred while waiting for
         response to adb instrument command
       DeviceUnresponsiveError: if device system process is not responding
       InstrumentationError: if instrumentation failed to run
    """

        command_string = self._BuildInstrumentationCommandPath(
            instrumentation_path,
            no_window_animation=no_window_animation,
            profile=profile,
            raw_mode=True,
            instrumentation_args=instrumentation_args)
        if silent_log:
            logger.SilentLog(command_string)
        else:
            logger.Log(command_string)
        (test_results,
         inst_finished_bundle) = (am_instrument_parser.ParseAmInstrumentOutput(
             self.SendShellCommand(command_string,
                                   timeout_time=timeout_time,
                                   retry_count=2)))
        if "code" not in inst_finished_bundle:
            logger.Log(
                'No code available. inst_finished_bundle contains: %s ' %
                inst_finished_bundle)
            raise errors.InstrumentationError(
                "no test results... device setup "
                "correctly?")

        if inst_finished_bundle["code"] == "0":
            long_msg_result = "no error message"
            if "longMsg" in inst_finished_bundle:
                long_msg_result = inst_finished_bundle["longMsg"]
                logger.Log("Error! Test run failed: %s" % long_msg_result)
            raise errors.InstrumentationError(long_msg_result)

        if "INSTRUMENTATION_ABORTED" in inst_finished_bundle:
            logger.Log("INSTRUMENTATION ABORTED!")
            raise errors.DeviceUnresponsiveError

        return (test_results, inst_finished_bundle)