/**
   * Pull the output file from the device, add it to the logs, and also parse out the relevant test
   * metrics and report them.
   */
  private void logOutputFile(TestInfo testInfo, ITestInvocationListener listener)
      throws DeviceNotAvailableException {
    File outputFile = null;
    InputStreamSource outputSource = null;
    try {
      outputFile = mTestDevice.pullFileFromExternal(OUTPUT_PATH);

      if (outputFile != null) {
        CLog.d("Sending %d byte file %s into the logosphere!", outputFile.length(), outputFile);
        outputSource = new SnapshotInputStreamSource(new FileInputStream(outputFile));
        listener.testLog(
            String.format("%s_output", testInfo.mTestName), LogDataType.TEXT, outputSource);
        parseOutputFile(testInfo, new FileInputStream(outputFile), listener);
      }
    } catch (IOException e) {
      CLog.e("Got an IO Exception: %s", e);
    } finally {
      if (outputFile != null) {
        outputFile.delete();
      }
      if (outputSource != null) {
        outputSource.cancel();
      }
    }
  }
  @Override
  public void run(ITestInvocationListener listener) throws DeviceNotAvailableException {
    Assert.assertNotNull(mTestDevice);
    setupTests();

    if (mLogBtsnoop) {
      if (!enableBtsnoopLogging()) {
        CLog.e("Unable to enable btsnoop trace logging");
        throw new DeviceNotAvailableException();
      }
    }

    IRemoteAndroidTestRunner runner =
        new RemoteAndroidTestRunner(mTestPackageName, TEST_RUNNER_NAME, mTestDevice.getIDevice());
    runner.setClassName(mTestClassName);
    runner.setMaxTimeToOutputResponse(mTestTimeout, TimeUnit.MILLISECONDS);
    BugreportCollector bugListener = new BugreportCollector(listener, mTestDevice);
    bugListener.addPredicate(BugreportCollector.AFTER_FAILED_TESTCASES);

    for (TestInfo test : mTestCases) {
      String testName = test.mTestName;
      TestInfo t = test;

      if (t.mIterCount != null && t.mIterCount <= 0) {
        CLog.i("Cancelled '%s' test case with iter count %s", testName, t.mIterCount);
        continue;
      }

      // For semi-manual tests, print instructions and wait for user to continue.
      if (t.mInstructions != null) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("========================================");
        System.out.println(t.mInstructions);
        System.out.println("========================================");
        try {
          br.readLine();
        } catch (IOException e) {
          CLog.e("Continuing after IOException while waiting for confirmation: %s", e.getMessage());
        }
      }

      // Run the test
      cleanOutputFile();
      if (mLogHcidump) {
        mHcidumpCommand = new HcidumpCommand();
        mHcidumpCommand.startHcidump();
      }

      if (t.mIterKey != null && t.mIterCount != null) {
        runner.addInstrumentationArg(t.mIterKey, t.mIterCount.toString());
      }
      if (t.mRemoteAddress != null) {
        runner.addInstrumentationArg("device_address", t.mRemoteAddress);
        if (t.mPairPasskey != null) {
          runner.addInstrumentationArg("device_pair_passkey", t.mPairPasskey);
        }
        if (t.mPairPin != null) {
          runner.addInstrumentationArg("device_pair_pin", t.mPairPin);
        }
      }
      runner.setMethodName(mTestClassName, t.mTestMethod);
      bugListener.setDescriptiveName(testName);
      mTestDevice.runInstrumentationTests(runner, bugListener);
      if (t.mIterKey != null && t.mIterCount != null) {
        runner.removeInstrumentationArg(t.mIterKey);
      }
      if (t.mRemoteAddress != null) {
        runner.removeInstrumentationArg("device_address");
        if (t.mPairPasskey != null) {
          runner.removeInstrumentationArg("device_pair_passkey");
        }
        if (t.mPairPin != null) {
          runner.removeInstrumentationArg("device_pair_pin");
        }
      }

      // Log the output file
      logOutputFile(t, listener);
      if (mLogBtsnoop) {
        File logFile = null;
        InputStreamSource logSource = null;
        try {
          logFile = mTestDevice.pullFileFromExternal(BTSNOOP_LOG_FILE);
          if (logFile != null) {
            CLog.d("Sending %d byte file %s into the logosphere!", logFile.length(), logFile);
            logSource = new SnapshotInputStreamSource(new FileInputStream(logFile));
            listener.testLog(
                String.format("%s_btsnoop", t.mTestName), LogDataType.UNKNOWN, logSource);
          }
        } catch (IOException e) {
          CLog.e("Got an IO Exception: %s", e);
        } finally {
          if (logFile != null) {
            logFile.delete();
          }
          if (logSource != null) {
            logSource.cancel();
          }
        }
      }
      if (mLogHcidump) {
        listener.testLog(
            String.format("%s_hcidump", t.mTestName),
            LogDataType.TEXT,
            mHcidumpCommand.getHcidump());
        mHcidumpCommand.stopHcidump();
        mHcidumpCommand = null;
      }
      cleanOutputFile();
    }
  }