Java Code Examples for androidx.test.core.app.ApplicationProvider#getApplicationContext()

The following examples show how to use androidx.test.core.app.ApplicationProvider#getApplicationContext() . 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: LocationsGPSUpdaterNoPermissionTest.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void locationsGPSUpdater_shouldEmitPermissionRequestAndonRequestResultFalse() {
    Application context = ApplicationProvider.getApplicationContext();
    ShadowApplication shadowContext = Shadows.shadowOf(context);
    shadowContext.setSystemService(Context.LOCATION_SERVICE, mockLocationManager);
    LocationsGPSUpdater locationsGPSUpdater = new LocationsGPSUpdater(context);

    doThrow(SecurityException.class)
            .when(mockLocationManager)
            .requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    1000,
                    1,
                    mockLocationListener);

    locationsGPSUpdater.requestLocationUpdates(mockLocationListener, mockRequestUpdatesListener, 1000);

    verify(mockRequestUpdatesListener, times(1)).onRequestResult(false);
    verify(mockErrorListener, times(1)).onError(any());
    verify(mockLocationListener, never()).onLocationChanged(any());
}
 
Example 2
Source File: StreamTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testWatchStreamStopBeforeHandshake() throws Exception {
  AsyncQueue testQueue = new AsyncQueue();
  GrpcMetadataProvider mockGrpcProvider = mock(GrpcMetadataProvider.class);
  Datastore datastore =
      new Datastore(
          IntegrationTestUtil.testEnvDatabaseInfo(),
          testQueue,
          new EmptyCredentialsProvider(),
          ApplicationProvider.getApplicationContext(),
          mockGrpcProvider);
  StreamStatusCallback streamCallback = new StreamStatusCallback() {};
  final WatchStream watchStream = datastore.createWatchStream(streamCallback);

  testQueue.enqueueAndForget(watchStream::start);
  waitFor(streamCallback.openSemaphore);

  // Stop should call watchStreamStreamDidClose.
  testQueue.runSync(watchStream::stop);
  assertThat(streamCallback.closeSemaphore.availablePermits()).isEqualTo(1);
  verify(mockGrpcProvider, times(1)).updateMetadata(any());
}
 
Example 3
Source File: SchemaManagerTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void upgradingV3ToV4_nonEmptyDB_isLossless() {
  int oldVersion = 3;
  int newVersion = 4;
  SchemaManager schemaManager =
      new SchemaManager(ApplicationProvider.getApplicationContext(), DB_NAME, oldVersion);
  SQLiteEventStore store = new SQLiteEventStore(clock, new UptimeClock(), CONFIG, schemaManager);
  // We simulate operations as done by an older SQLLiteEventStore at V1
  // We cannot simulate older operations with a newer client
  PersistedEvent event1 = simulatedPersistOnV1Database(schemaManager, CONTEXT1, EVENT1);

  // Upgrade to V4
  schemaManager.onUpgrade(schemaManager.getWritableDatabase(), oldVersion, newVersion);
  assertThat(store.loadBatch(CONTEXT1)).containsExactly(event1);

  long inlineRows =
      store
          .getDb()
          .compileStatement("SELECT COUNT(*) from events where inline = 1")
          .simpleQueryForLong();
  assertThat(inlineRows).isEqualTo(1);
}
 
Example 4
Source File: WayTodayStartStopTest.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void activity_shouldStartWayTodayContiniously() {
    try (ActivityScenario<MainActivity> ignored = ActivityScenario.launch(MainActivity.class)) {
        Application application = ApplicationProvider.getApplicationContext();
        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(application);

        assertThat(LocationsTracker.isUpdating, is(false));

        ViewInteraction vi = onView(withId(R.id.btn_waytoday));
        vi.perform(click());
        onView(withText(R.string.freq_continuously))
                .perform(click());
        ArgumentCaptor<LocationsTracker.TrackingState> state =
                ArgumentCaptor.forClass(LocationsTracker.TrackingState.class);

        verify(mockTrackingStateListener, timeout(5000).atLeast(1)).onStateChange(state.capture());
        List<LocationsTracker.TrackingState> states =
                state.getAllValues();
        assertThat(states.size(), greaterThan(0));
        assertThat(states.get(0).isUpdating, is(true));
        assertThat(LocationsTracker.isUpdating, is(true));
        assertThat(p.getInt("freq", -1), equalTo(1));
    }
}
 
Example 5
Source File: FragmentsSelectTest.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void setupActivity() {
    Application application = ApplicationProvider.getApplicationContext();
    ShadowApplication shadowApplication = shadowOf(application);
    shadowApplication.grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION);
    Intent intent = new Intent(application, ITagsService.class);
    ITagsService iTagsService = new ITagsService();
    shadowApplication.setComponentNameAndServiceForBindServiceForIntent(
            intent,
            new ComponentName(ITagApplication.class.getPackage().getName(),ITagsService.class.getName()),
            iTagsService.onBind(null)
    );
    mockBluetoothManager = Mockito.mock(BluetoothManager.class);
    ShadowContextImpl shadowContext = Shadow.extract(application.getBaseContext());
    shadowContext.setSystemService(Context.BLUETOOTH_SERVICE, mockBluetoothManager);
}
 
Example 6
Source File: SpecTestCase.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Sets up a new client. Is used to initially setup the client initially and after every restart.
 */
private void initClient() {
  queue = new AsyncQueue();
  datastore = new MockDatastore(databaseInfo, queue, ApplicationProvider.getApplicationContext());

  ComponentProvider.Configuration configuration =
      new ComponentProvider.Configuration(
          ApplicationProvider.getApplicationContext(),
          queue,
          databaseInfo,
          datastore,
          currentUser,
          maxConcurrentLimboResolutions,
          new FirebaseFirestoreSettings.Builder().build());

  ComponentProvider provider =
      initializeComponentProvider(configuration, garbageCollectionEnabled);
  localPersistence = provider.getPersistence();
  remoteStore = provider.getRemoteStore();
  syncEngine = provider.getSyncEngine();
  eventManager = provider.getEventManager();
}
 
Example 7
Source File: DatabaseTest.java    From call_manage with MIT License 5 votes vote down vote up
@Before
public void createDb() {
    Context context = ApplicationProvider.getApplicationContext();
    mDb = AppDatabase.getDatabase(context);
    mContactDao = mDb.getContactDao();
    mCGroupDao = mDb.getCGroupDao();
}
 
Example 8
Source File: IntegrationTestUtil.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public static FirebaseFirestore testFirestore(
    String projectId,
    Logger.Level logLevel,
    FirebaseFirestoreSettings settings,
    String persistenceKey) {
  // This unfortunately is a global setting that affects existing Firestore clients.
  Logger.setLogLevel(logLevel);

  // TODO: Remove this once this is ready to ship.
  Persistence.INDEXING_SUPPORT_ENABLED = true;

  Context context = ApplicationProvider.getApplicationContext();
  DatabaseId databaseId = DatabaseId.forDatabase(projectId, DatabaseId.DEFAULT_DATABASE_ID);

  ensureStrictMode();

  AsyncQueue asyncQueue = new AsyncQueue();

  FirebaseFirestore firestore =
      AccessHelper.newFirebaseFirestore(
          context,
          databaseId,
          persistenceKey,
          MockCredentialsProvider.instance(),
          asyncQueue,
          /*firebaseApp=*/ null,
          /*instanceRegistry=*/ (dbId) -> {});
  waitFor(AccessHelper.clearPersistence(firestore));
  firestore.setFirestoreSettings(settings);
  firestoreStatus.put(firestore, true);

  return firestore;
}
 
Example 9
Source File: SchemaManagerTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void upgradingV1ToLatest_emptyDatabase_allowsPersistsAfterUpgrade() {
  int oldVersion = 1;
  int newVersion = SCHEMA_VERSION;
  SchemaManager schemaManager =
      new SchemaManager(ApplicationProvider.getApplicationContext(), DB_NAME, oldVersion);

  SQLiteEventStore store = new SQLiteEventStore(clock, new UptimeClock(), CONFIG, schemaManager);

  schemaManager.onUpgrade(schemaManager.getWritableDatabase(), oldVersion, newVersion);
  PersistedEvent newEvent1 = store.persist(CONTEXT1, EVENT1);

  assertThat(store.loadBatch(CONTEXT1)).containsExactly(newEvent1);
}
 
Example 10
Source File: SchemaManagerMigrationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void upgrade_downgrade_upgrade_migratesSuccessfully() {
  SchemaManager schemaManager =
      new SchemaManager(ApplicationProvider.getApplicationContext(), DB_NAME, lowVersion);

  schemaManager.onUpgrade(schemaManager.getWritableDatabase(), lowVersion, highVersion);
  simulatorMap.get(highVersion).simulate(schemaManager);

  schemaManager.onDowngrade(schemaManager.getWritableDatabase(), highVersion, lowVersion);
  simulatorMap.get(lowVersion).simulate(schemaManager);

  schemaManager.onUpgrade(schemaManager.getWritableDatabase(), lowVersion, highVersion);
  simulatorMap.get(highVersion).simulate(schemaManager);
}
 
Example 11
Source File: SchemaManagerMigrationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void upgrade_migratesSuccessfully() {
  SchemaManager schemaManager =
      new SchemaManager(ApplicationProvider.getApplicationContext(), DB_NAME, lowVersion);
  schemaManager.onUpgrade(schemaManager.getWritableDatabase(), lowVersion, highVersion);
  simulatorMap.get(highVersion).simulate(schemaManager);
}
 
Example 12
Source File: WayTodayChangeTrackIDTest.java    From itag with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void before() {
    Application application = ApplicationProvider.getApplicationContext();
    SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(application);
    p.edit().remove("freq").apply();
    p.edit().remove("tid").apply();
    p.edit().remove("wt").apply();
    reset(mockIDListener);
    reset(mockUploadListener);
    reset(mockTrackingStateListener);
    reset(mockLocationListener);
}
 
Example 13
Source File: ExampleInstrumentedTest.java    From magellan with Apache License 2.0 5 votes vote down vote up
@Test
public void useAppContext() {
  // Context of the app under test.
  Context appContext = ApplicationProvider.getApplicationContext();

  assertEquals("com.wealthfront.magellan.sample", appContext.getPackageName());
}
 
Example 14
Source File: AlarmSchedulerTest.java    From JobSchedulerCompat with MIT License 5 votes vote down vote up
@Before
public void setup() {
    application = ApplicationProvider.getApplicationContext();
    job = JobCreator.create(application, 2000)
                    .addTriggerContentUri(new JobInfo.TriggerContentUri(Uri.parse("doist.com"), 0))
                    .setMinimumLatency(TimeUnit.HOURS.toMillis(1) /* Random constraint. */)
                    .build();
    jobStore = JobStore.get(application);
    scheduler = new AlarmScheduler(application);
}
 
Example 15
Source File: StreamTest.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void testWriteStreamStopAfterHandshake() throws Exception {
  AsyncQueue testQueue = new AsyncQueue();
  Datastore datastore =
      new Datastore(
          IntegrationTestUtil.testEnvDatabaseInfo(),
          testQueue,
          new EmptyCredentialsProvider(),
          ApplicationProvider.getApplicationContext(),
          null);
  final WriteStream[] writeStreamWrapper = new WriteStream[1];
  StreamStatusCallback streamCallback =
      new StreamStatusCallback() {
        @Override
        public void onHandshakeComplete() {
          assertThat(writeStreamWrapper[0].getLastStreamToken()).isNotEmpty();
          super.onHandshakeComplete();
        }

        @Override
        public void onWriteResponse(
            SnapshotVersion commitVersion, List<MutationResult> mutationResults) {
          assertThat(mutationResults).hasSize(1);
          assertThat(writeStreamWrapper[0].getLastStreamToken()).isNotEmpty();
          super.onWriteResponse(commitVersion, mutationResults);
        }
      };
  WriteStream writeStream = writeStreamWrapper[0] = datastore.createWriteStream(streamCallback);
  testQueue.enqueueAndForget(writeStream::start);
  waitFor(streamCallback.openSemaphore);

  // Writing before the handshake should throw
  testQueue.enqueueAndForget(
      () -> assertThrows(Throwable.class, () -> writeStream.writeMutations(mutations)));

  // Handshake should always be called
  testQueue.enqueueAndForget(writeStream::writeHandshake);
  waitFor(streamCallback.handshakeSemaphore);

  // Now writes should succeed
  testQueue.enqueueAndForget(() -> writeStream.writeMutations(mutations));
  waitFor(streamCallback.responseReceivedSemaphore);

  testQueue.runSync(writeStream::stop);
}
 
Example 16
Source File: TestApplicationModule.java    From ground-android with Apache License 2.0 4 votes vote down vote up
@Provides
static Context contextProvider() {
  return ApplicationProvider.getApplicationContext();
}
 
Example 17
Source File: BinaryImagesConverterTest.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
private static Context getContext() {
  return ApplicationProvider.getApplicationContext();
}
 
Example 18
Source File: AlarmContentObserverServiceTest.java    From JobSchedulerCompat with MIT License 4 votes vote down vote up
@Before
public void setup() {
    application = ApplicationProvider.getApplicationContext();
    jobStore = JobStore.get(application);
    service = Robolectric.buildService(ContentObserverService.class).create();
}
 
Example 19
Source File: AlarmJobServiceTest.java    From JobSchedulerCompat with MIT License 4 votes vote down vote up
@Before
public void setup() {
    application = ApplicationProvider.getApplicationContext();
    jobStore = JobStore.get(application);
    service = Robolectric.buildService(AlarmJobService.class).create();
}
 
Example 20
Source File: RobolectricTest.java    From msdkui-android with Apache License 2.0 4 votes vote down vote up
/**
 * Gets context and attach material theme.
 */
public Context getContextWithTheme() {
    final Context context = ApplicationProvider.getApplicationContext();
    context.setTheme(R.style.MSDKUIDarkTheme);
    return context;
}