Java Code Examples for android.app.Instrumentation#getTargetContext()

The following examples show how to use android.app.Instrumentation#getTargetContext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileCompatTest.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Prefer internal over external storage, because external tends to be FAT filesystems,
 * which don't support symlinks (which we test using this method).
 */
public static File getWriteableDir(Instrumentation instrumentation) {
    Context context = instrumentation.getContext();
    Context targetContext = instrumentation.getTargetContext();

    File[] dirsToTry = new File[]{
            context.getCacheDir(),
            context.getFilesDir(),
            targetContext.getCacheDir(),
            targetContext.getFilesDir(),
            context.getExternalCacheDir(),
            context.getExternalFilesDir(null),
            targetContext.getExternalCacheDir(),
            targetContext.getExternalFilesDir(null),
            Environment.getExternalStorageDirectory(),
    };

    return getWriteableDir(dirsToTry);
}
 
Example 2
Source File: ScreenshotTest.java    From firefox-echo-show with Mozilla Public License 2.0 5 votes vote down vote up
@Before
public void setUpScreenshots() {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    targetContext = instrumentation.getTargetContext();
    device = UiDevice.getInstance(instrumentation);

    // Use this to switch between default strategy and HostScreencap strategy
    Screengrab.setDefaultScreenshotStrategy(new UiAutomatorScreenshotStrategy());
    //Screengrab.setDefaultScreenshotStrategy(new HostScreencapScreenshotStrategy(device));

    device.waitForIdle();
}
 
Example 3
Source File: ScreenshotTest.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
@Before
public void setUpScreenshots() {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    targetContext = instrumentation.getTargetContext();
    device = UiDevice.getInstance(instrumentation);

    // Use this to switch between default strategy and HostScreencap strategy
    Screengrab.setDefaultScreenshotStrategy(new UiAutomatorScreenshotStrategy());
    //Screengrab.setDefaultScreenshotStrategy(new HostScreencapScreenshotStrategy(device));

    device.waitForIdle();
}
 
Example 4
Source File: PreferencesTypeAndModeTestCase.java    From StoreBox with Apache License 2.0 5 votes vote down vote up
public InjectedContext(
        Instrumentation instr,
        String expectedName,
        Integer expectedMode,
        AtomicInteger count) {
    
    super(instr.getTargetContext());
    
    this.expectedName = expectedName;
    this.expectedMode = expectedMode;
    this.count = count;
}
 
Example 5
Source File: ZooniverseClientTest.java    From android-galaxyzoo with GNU General Public License v3.0 5 votes vote down vote up
private static ZooniverseClient createZooniverseClient(final MockWebServer server) {
    final HttpUrl mockUrl = server.url("/");

    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    final Context context = instrumentation.getTargetContext();

    return new ZooniverseClient(context, mockUrl.toString());
}
 
Example 6
Source File: TestUtils.java    From android-galaxyzoo with GNU General Public License v3.0 5 votes vote down vote up
static void setTheme() {
    //Avoid this exception:
    //java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    final Context context = instrumentation.getTargetContext();
    context.setTheme(R.style.AppTheme);

}
 
Example 7
Source File: InstrumentationLeakDetector.java    From DoraemonKit with Apache License 2.0 4 votes vote down vote up
public @NonNull InstrumentationLeakResults detectLeaks() {
  Instrumentation instrumentation = getInstrumentation();
  Context context = instrumentation.getTargetContext();
  RefWatcher refWatcher = LeakCanary.installedRefWatcher();
  Set<String> retainedKeys = refWatcher.getRetainedKeys();

  if (refWatcher.isEmpty()) {
    return InstrumentationLeakResults.NONE;
  }

  instrumentation.waitForIdleSync();
  if (refWatcher.isEmpty()) {
    return InstrumentationLeakResults.NONE;
  }

  GcTrigger.DEFAULT.runGc();
  if (refWatcher.isEmpty()) {
    return InstrumentationLeakResults.NONE;
  }

  // Waiting for any delayed UI post (e.g. scroll) to clear. This shouldn't be needed, but
  // Android simply has way too many delayed posts that aren't canceled when views are detached.
  SystemClock.sleep(2000);

  if (refWatcher.isEmpty()) {
    return InstrumentationLeakResults.NONE;
  }

  // Aaand we wait some more.
  // 4 seconds (2+2) is greater than the 3 seconds delay for
  // FINISH_TOKEN in android.widget.Filter
  SystemClock.sleep(2000);
  GcTrigger.DEFAULT.runGc();

  if (refWatcher.isEmpty()) {
    return InstrumentationLeakResults.NONE;
  }

  // We're always reusing the same file since we only execute this once at a time.
  File heapDumpFile = new File(context.getFilesDir(), "instrumentation_tests_heapdump.hprof");
  try {
    Debug.dumpHprofData(heapDumpFile.getAbsolutePath());
  } catch (Exception e) {
    CanaryLog.d(e, "Could not dump heap");
    return InstrumentationLeakResults.NONE;
  }

  HeapDump.Builder heapDumpBuilder = refWatcher.getHeapDumpBuilder();
  HeapAnalyzer heapAnalyzer =
      new HeapAnalyzer(heapDumpBuilder.excludedRefs, AnalyzerProgressListener.NONE,
          heapDumpBuilder.reachabilityInspectorClasses);

  List<TrackedReference> trackedReferences = heapAnalyzer.findTrackedReferences(heapDumpFile);

  List<InstrumentationLeakResults.Result> detectedLeaks = new ArrayList<>();
  List<InstrumentationLeakResults.Result> excludedLeaks = new ArrayList<>();
  List<InstrumentationLeakResults.Result> failures = new ArrayList<>();

  for (TrackedReference trackedReference : trackedReferences) {
    // Ignore any Weak Reference that this test does not care about.
    if (!retainedKeys.contains(trackedReference.key)) {
      continue;
    }

    HeapDump heapDump = HeapDump.builder()
        .heapDumpFile(heapDumpFile)
        .referenceKey(trackedReference.key)
        .referenceName(trackedReference.name)
        .excludedRefs(heapDumpBuilder.excludedRefs)
        .reachabilityInspectorClasses(heapDumpBuilder.reachabilityInspectorClasses)
        .build();

    AnalysisResult analysisResult =
        heapAnalyzer.checkForLeak(heapDumpFile, trackedReference.key, false);

    InstrumentationLeakResults.Result leakResult =
        new InstrumentationLeakResults.Result(heapDump, analysisResult);

    if (analysisResult.leakFound) {
      if (!analysisResult.excludedLeak) {
        detectedLeaks.add(leakResult);
      } else {
        excludedLeaks.add(leakResult);
      }
    } else if (analysisResult.failure != null) {
      failures.add(leakResult);
    }
  }

  CanaryLog.d("Found %d proper leaks, %d excluded leaks and %d leak analysis failures",
      detectedLeaks.size(),
      excludedLeaks.size(),
      failures.size());

  return new InstrumentationLeakResults(detectedLeaks, excludedLeaks, failures);
}
 
Example 8
Source File: KeysAndDefaultValuesTestCase.java    From StoreBox with Apache License 2.0 4 votes vote down vote up
public InjectedContext(Instrumentation instr, SharedPreferences prefs) {
    super(instr.getTargetContext());
    
    this.prefs = prefs;
}
 
Example 9
Source File: ZooniverseClientWithRealServerTest.java    From android-galaxyzoo with GNU General Public License v3.0 4 votes vote down vote up
private static ZooniverseClient createZooniverseClient() {
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    final Context context = instrumentation.getTargetContext();
    return new ZooniverseClient(context, Config.SERVER);
}
 
Example 10
Source File: SaveModeTestCase.java    From StoreBox with Apache License 2.0 3 votes vote down vote up
public InjectedContext(
        Instrumentation instr, SharedPreferences prefs) {
    
    super(instr.getTargetContext());
    
    this.prefs = prefs;
}
 
Example 11
Source File: ForwardingMethodsTestCase.java    From StoreBox with Apache License 2.0 3 votes vote down vote up
public InjectedContext(
        Instrumentation instr, SharedPreferences prefs) {

    super(instr.getTargetContext());

    this.prefs = prefs;
}