org.robolectric.annotation.Config Java Examples

The following examples show how to use org.robolectric.annotation.Config. 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 Project: material-components-android   Author: material-components   File: CircularRevealHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Config(sdk = VERSION_CODES.JELLY_BEAN)
public void jbDrawsScrim() {
  helper = new CircularRevealHelper(delegate);
  helper.setCircularRevealScrimColor(Color.RED);

  helper.setRevealInfo(smallRevealInfo);

  helper.buildCircularRevealCache();
  helper.draw(canvas);
  helper.destroyCircularRevealCache();

  // Once for the BitmapShader, once for the scrim.
  verify(canvas, times(2))
      .drawCircle(
          eq(smallRevealInfo.centerX),
          eq(smallRevealInfo.centerY),
          eq(smallRevealInfo.radius),
          ArgumentMatchers.<Paint>any());
}
 
Example #2
Source Project: firebase-android-sdk   Author: firebase   File: CctTransportBackendTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Config(shadows = {OfflineConnectivityManagerShadow.class})
public void decorate_whenOffline_shouldProperlyPopulateNetworkInfo() {
  CctTransportBackend backend =
      new CctTransportBackend(RuntimeEnvironment.application, wallClock, uptimeClock, 300);

  EventInternal result =
      backend.decorate(
          EventInternal.builder()
              .setEventMillis(INITIAL_WALL_TIME)
              .setUptimeMillis(INITIAL_UPTIME)
              .setTransportName("3")
              .setEncodedPayload(new EncodedPayload(PROTOBUF_ENCODING, PAYLOAD.toByteArray()))
              .build());

  assertThat(result.get(CctTransportBackend.KEY_NETWORK_TYPE))
      .isEqualTo(String.valueOf(NetworkConnectionInfo.NetworkType.NONE.getValue()));
  assertThat(result.get(CctTransportBackend.KEY_MOBILE_SUBTYPE))
      .isEqualTo(
          String.valueOf(NetworkConnectionInfo.MobileSubtype.UNKNOWN_MOBILE_SUBTYPE.getValue()));
}
 
Example #3
Source Project: react-native-keychain   Author: oblador   File: CipherStorageKeystoreRsaEcbTests.java    License: MIT License 6 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testVerifySecureHardwareAvailability_api28() throws Exception {
  ReactApplicationContext context = getRNContext();

  // for api24+ system feature should be enabled
  shadowOf(context.getPackageManager()).setSystemFeature(PackageManager.FEATURE_FINGERPRINT, true);

  // set that hardware is available and fingerprints configured
  final FingerprintManager fm = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
  shadowOf(fm).setIsHardwareDetected(true);
  shadowOf(fm).setDefaultFingerprints(5); // 5 fingerprints are available

  int result = BiometricManager.from(context).canAuthenticate();
  assertThat(result, is(BiometricManager.BIOMETRIC_SUCCESS));

  final CipherStorage storage = new CipherStorageKeystoreAesCbc();;

  // expected RsaEcb with fingerprint
  assertThat(storage.supportsSecureHardware(), is(true));
}
 
Example #4
Source Project: JobSchedulerCompat   Author: Doist   File: JobSchedulerTest.java    License: MIT License 6 votes vote down vote up
@Test
@Config(sdk = {Build.VERSION_CODES.O, Build.VERSION_CODES.P}, shadows = {ShadowGoogleApiAvailability.class})
public void testSchedulerInApi26() {
    JobInfo api21Job = JobCreator.create(application).setRequiresCharging(true).build();
    JobInfo api24Job = JobCreator.create(application).setPeriodic(15 * 60 * 1000L, 5 * 60 * 1000L).build();
    JobInfo api26Job = JobCreator.create(application).setRequiresBatteryNotLow(true).build();

    ShadowGoogleApiAvailability.setIsGooglePlayServicesAvailable(ConnectionResult.SERVICE_MISSING);

    assertThat(jobScheduler.getSchedulerForJob(application, api21Job), instanceOf(JobSchedulerSchedulerV26.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api24Job), instanceOf(JobSchedulerSchedulerV26.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api26Job), instanceOf(JobSchedulerSchedulerV26.class));

    ShadowGoogleApiAvailability.setIsGooglePlayServicesAvailable(ConnectionResult.SUCCESS);

    assertThat(jobScheduler.getSchedulerForJob(application, api21Job), instanceOf(JobSchedulerSchedulerV26.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api24Job), instanceOf(JobSchedulerSchedulerV26.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api26Job), instanceOf(JobSchedulerSchedulerV26.class));
}
 
Example #5
Source Project: JobSchedulerCompat   Author: Doist   File: JobSchedulerTest.java    License: MIT License 6 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.N, shadows = {ShadowGoogleApiAvailability.class})
public void testSchedulerInApi24() {
    JobInfo api21Job = JobCreator.create(application).setRequiresCharging(true).build();
    JobInfo api24Job = JobCreator.create(application).setPeriodic(15 * 60 * 1000L, 5 * 60 * 1000L).build();
    JobInfo api26Job = JobCreator.create(application).setRequiresBatteryNotLow(true).build();

    ShadowGoogleApiAvailability.setIsGooglePlayServicesAvailable(ConnectionResult.SERVICE_MISSING);

    assertThat(jobScheduler.getSchedulerForJob(application, api21Job), instanceOf(JobSchedulerSchedulerV24.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api24Job), instanceOf(JobSchedulerSchedulerV24.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api26Job), instanceOf(AlarmScheduler.class));

    ShadowGoogleApiAvailability.setIsGooglePlayServicesAvailable(ConnectionResult.SUCCESS);

    assertThat(jobScheduler.getSchedulerForJob(application, api21Job), instanceOf(JobSchedulerSchedulerV24.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api24Job), instanceOf(JobSchedulerSchedulerV24.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api26Job), instanceOf(AlarmScheduler.class));
}
 
Example #6
Source Project: JobSchedulerCompat   Author: Doist   File: JobSchedulerTest.java    License: MIT License 6 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.LOLLIPOP, shadows = {ShadowGoogleApiAvailability.class})
public void testSchedulerInApi21() {
    JobInfo api21Job = JobCreator.create(application).setRequiresCharging(true).build();
    JobInfo api24Job = JobCreator.create(application).setPeriodic(15 * 60 * 1000L, 5 * 60 * 1000L).build();
    JobInfo api26Job = JobCreator.create(application).setRequiresBatteryNotLow(true).build();

    ShadowGoogleApiAvailability.setIsGooglePlayServicesAvailable(ConnectionResult.SERVICE_MISSING);

    assertThat(jobScheduler.getSchedulerForJob(application, api21Job), instanceOf(JobSchedulerSchedulerV21.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api24Job), instanceOf(AlarmScheduler.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api26Job), instanceOf(AlarmScheduler.class));

    ShadowGoogleApiAvailability.setIsGooglePlayServicesAvailable(ConnectionResult.SUCCESS);

    assertThat(jobScheduler.getSchedulerForJob(application, api21Job), instanceOf(JobSchedulerSchedulerV21.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api24Job), instanceOf(GcmScheduler.class));
    assertThat(jobScheduler.getSchedulerForJob(application, api26Job), instanceOf(AlarmScheduler.class));
}
 
Example #7
Source Project: Auth0.Android   Author: auth0   File: CryptoUtilTest.java    License: MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.P)
@Test
@Config(sdk = 28)
public void shouldUseExistingRSAKeyPairRebuildingTheEntryOnAPI28AndUp() throws Exception {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 28);
    KeyStore.PrivateKeyEntry entry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class);
    PrivateKey privateKey = PowerMockito.mock(PrivateKey.class);
    Certificate certificate = PowerMockito.mock(Certificate.class);

    ArgumentCaptor<Object> varargsCaptor = ArgumentCaptor.forClass(Object.class);
    PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(true);
    PowerMockito.when(keyStore.getKey(KEY_ALIAS, null)).thenReturn(privateKey);
    PowerMockito.when(keyStore.getCertificate(KEY_ALIAS)).thenReturn(certificate);
    PowerMockito.whenNew(KeyStore.PrivateKeyEntry.class).withAnyArguments().thenReturn(entry);

    KeyStore.PrivateKeyEntry rsaEntry = cryptoUtil.getRSAKeyEntry();
    PowerMockito.verifyNew(KeyStore.PrivateKeyEntry.class).withArguments(varargsCaptor.capture());
    assertThat(rsaEntry, is(notNullValue()));
    assertThat(rsaEntry, is(entry));
    assertThat(varargsCaptor.getAllValues(), is(notNullValue()));
    PrivateKey capturedPrivateKey = (PrivateKey) varargsCaptor.getAllValues().get(0);
    Certificate[] capturedCertificatesArray = (Certificate[]) varargsCaptor.getAllValues().get(1);
    assertThat(capturedPrivateKey, is(privateKey));
    assertThat(capturedCertificatesArray[0], is(certificate));
    assertThat(capturedCertificatesArray.length, is(1));
}
 
Example #8
Source Project: JobSchedulerCompat   Author: Doist   File: JobSchedulerSchedulerTest.java    License: MIT License 6 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testScheduleJobWithPieOption() {
    JobInfo.Builder builder = createJob(1);
    builder.setRequiredNetwork(
            new NetworkRequest.Builder()
                    .addCapability(NET_CAPABILITY_INTERNET)
                    .addCapability(NET_CAPABILITY_VALIDATED)
                    .removeCapability(NET_CAPABILITY_NOT_VPN)
                    .addCapability(NET_CAPABILITY_NOT_ROAMING)
                    .build());
    builder.setEstimatedNetworkBytes(1024, 128);
    builder.setImportantWhileForeground(true);
    builder.setPrefetch(true);
    JobInfo job = builder.build();

    scheduler.schedule(job);

    android.app.job.JobInfo nativeJob = getPendingJob(job.getId());
    assertNotNull(nativeJob);
    assertNativeJobInfoMatchesJobInfo(nativeJob, job);
}
 
Example #9
Source Project: CrossBow   Author: patrick-doyle   File: CrossbowImageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testImageFadeDrawable() {
    ColorDrawable defaultDrawable = new ColorDrawable(Color.BLUE);

    CrossbowImage.Builder builder = new CrossbowImage.Builder(RuntimeEnvironment.application, null, null);
    builder.placeholder(defaultDrawable);
    builder.scale(ImageView.ScaleType.CENTER);
    builder.fade(200);
    CrossbowImage crossbowImage = builder.into(imageView).load();

    Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ALPHA_8);
    crossbowImage.setBitmap(bitmap, false);

    TransitionDrawable drawable = (TransitionDrawable) imageView.getDrawable();
    assertTrue(drawable.getNumberOfLayers() == 2);
}
 
Example #10
Source Project: neatle   Author: inovait   File: LolipopLEScannerTest.java    License: MIT License 6 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.LOLLIPOP)
public void startScanWithUuidsOnLollipop() {
    BluetoothAdapter testAdapter = Mockito.mock(BluetoothAdapter.class);
    Mockito.when(testAdapter.startLeScan(Mockito.<UUID[]>any(),
            Mockito.<BluetoothAdapter.LeScanCallback>any())).thenReturn(true);

    LolipopLEScanner scanner = new LolipopLEScanner(TEST_CONFIGURATION);

    scanner.onStart(testAdapter, 0);

    Mockito.verify(testAdapter, Mockito.only()).startLeScan(Mockito.argThat(new ArgumentMatcher<UUID[]>() {
        @Override
        public boolean matches(UUID[] uuids) {
            return uuids.length == 1 && TEST_UUID.equals(uuids[0]);
        }
    }), Mockito.<BluetoothAdapter.LeScanCallback>any());
}
 
Example #11
Source Project: android-job   Author: evernote   File: JobProxyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Config(sdk = 21)
public void verifyNoRecoverWithAlarmManager() throws Exception {
    Context context = BaseJobManagerTest.createMockContext();
    Context applicationContext = context.getApplicationContext();

    AlarmManager alarmManager = getAlarmManager(applicationContext);

    when(applicationContext.getSystemService(Context.ALARM_SERVICE)).thenReturn(null);
    when(applicationContext.getSystemService(Context.JOB_SCHEDULER_SERVICE)).thenReturn(null);

    JobManager.create(context);

    new JobRequest.Builder("tag")
            .setExecutionWindow(200_000, 300_000)
            .build()
            .schedule();

    verifyAlarmCount(alarmManager, 0);
}
 
Example #12
Source Project: Freezer   Author: florent37   File: CustomRobolectricTestRunner.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected AndroidManifest getAppManifest(Config config) {
    String path = PATH_MANIFEST;

    // android studio has a different execution root for tests than pure gradle
    // so we avoid here manual effort to get them running inside android studio
    if (!new File(path).exists()) {
        path = PATH_PREFIX + path;
    }

    config = overwriteConfig(config, CONFIG_MANIFEST, path);
    config = overwriteConfig(config, CONFIG_ASSET_DIR, PATH_ASSET);
    config = overwriteConfig(config, CONFIG_RESOURCE_DIR, PATH_RESOURCE);
    config = overwriteConfig(config, CONFIG_PACKAGE_NAME, PACKAGE_NAME);

    return super.getAppManifest(config);
}
 
Example #13
@Override
 protected AndroidManifest getAppManifest(Config config) {
   //String appRoot = "D:\\TmpCodingProjects\\TripComputer\\app\\src\\main\\";
   String appRoot = "../app/src/main/";
   String manifestPath = appRoot + "AndroidManifest.xml";
   String resDir = appRoot + "res";
   String assetsDir = appRoot + "assets";
   AndroidManifest manifest = createAppManifest(Fs.fileFromPath(manifestPath),
     Fs.fileFromPath(resDir),
     Fs.fileFromPath(assetsDir));

// If you change the package - don't forget to change the build.gradle and the AndroidManifest.xml
   manifest.setPackageName("com.soagrowers.android");
   // Robolectric is already going to look in the  'app' dir ...
   // so no need to add to package name
   return manifest;
 }
 
Example #14
Source Project: react-native-keychain   Author: oblador   File: KeychainModuleTests.java    License: MIT License 6 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testGetSecurityLevel_NoBiometry_api28() throws Exception {
  // GIVE:
  final ReactApplicationContext context = getRNContext();
  final KeychainModule module = new KeychainModule(context);
  final Promise mockPromise = mock(Promise.class);

  // WHEN:
  final JavaOnlyMap options = new JavaOnlyMap();
  options.putString(Maps.ACCESS_CONTROL, AccessControl.DEVICE_PASSCODE);

  module.getSecurityLevel(options, mockPromise);

  // THEN:
  verify(mockPromise).resolve(SecurityLevel.SECURE_HARDWARE.name());
}
 
Example #15
Source Project: android-job   Author: evernote   File: JobProxyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Config(sdk = 21)
public void verifyMaxExecutionDelayIsNotSetInJobScheduler() {
    Context context = BaseJobManagerTest.createMockContext();
    Context applicationContext = context.getApplicationContext();

    JobScheduler scheduler = getJobScheduler(applicationContext);
    when(applicationContext.getSystemService(Context.JOB_SCHEDULER_SERVICE)).thenReturn(scheduler);

    JobManager.create(context);

    new JobRequest.Builder("tag")
            .setExecutionWindow(3_000L, 4_000L)
            .setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
            .setRequirementsEnforced(true)
            .build()
            .schedule();

    List<JobInfo> allPendingJobs = scheduler.getAllPendingJobs();
    assertThat(allPendingJobs).hasSize(1);

    JobInfo jobInfo = allPendingJobs.get(0);
    assertThat(jobInfo.getMinLatencyMillis()).isEqualTo(3_000L);
    assertThat(jobInfo.getMaxExecutionDelayMillis()).isGreaterThan(4_000L);
}
 
Example #16
Source Project: Forage   Author: Plastix   File: ForageRoboelectricIntegrationTestRunner.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Override
public Config getConfig(@NonNull Method method) {
    final Config defaultConfig = super.getConfig(method);
    return new Config.Implementation(
            new int[]{SDK_EMULATE_LEVEL},
            defaultConfig.manifest(),
            defaultConfig.qualifiers(),
            defaultConfig.packageName(),
            defaultConfig.abiSplit(),
            defaultConfig.resourceDir(),
            defaultConfig.assetDir(),
            defaultConfig.buildDir(),
            defaultConfig.shadows(),
            defaultConfig.instrumentedPackages(),
            ForageUnitTestApplication.class,
            defaultConfig.libraries(),
            defaultConfig.constants() == Void.class ? BuildConfig.class : defaultConfig.constants()
    );
}
 
Example #17
Source Project: react-native-keychain   Author: oblador   File: KeychainModuleTests.java    License: MIT License 5 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testGetSecurityLevel_Unspecified_api28() throws Exception {
  // GIVE:
  final ReactApplicationContext context = getRNContext();
  final KeychainModule module = new KeychainModule(context);
  final Promise mockPromise = mock(Promise.class);

  // WHEN:
  module.getSecurityLevel(null, mockPromise);

  // THEN:
  verify(mockPromise).resolve(SecurityLevel.SECURE_HARDWARE.name());
}
 
Example #18
Source Project: react-native-keychain   Author: oblador   File: KeychainModuleTests.java    License: MIT License 5 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.M)
public void testGetSecurityLevel_Unspecified_api23() throws Exception {
  // GIVE:
  final ReactApplicationContext context = getRNContext();
  final KeychainModule module = new KeychainModule(context);
  final Promise mockPromise = mock(Promise.class);

  // WHEN:
  module.getSecurityLevel(null, mockPromise);

  // THEN:
  verify(mockPromise).resolve(SecurityLevel.SECURE_HARDWARE.name());
}
 
Example #19
Source Project: picasso-transformations   Author: TannerPerrien   File: BaseTransformationTest.java    License: Apache License 2.0 5 votes vote down vote up
protected Bitmap getCopyOfBitmap() {
    if (sBitmap == null) {
        try {
            URL url = new URL(TULIP_IMG_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            sBitmap = ShadowBitmapFactory.decodeStream(input);
        } catch (IOException e) {
        }
    }
    return sBitmap.copy(Bitmap.Config.ARGB_8888, false);
}
 
Example #20
Source Project: react-native-keychain   Author: oblador   File: KeychainModuleTests.java    License: MIT License 5 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.M)
public void testMigrateStorageFromOlder_api23() throws Exception {
  // GIVEN:
  final ReactApplicationContext context = getRNContext();
  final CipherStorage aes = Mockito.mock(CipherStorage.class);
  final CipherStorage rsa = Mockito.mock(CipherStorage.class);
  when(rsa.getCipherStorageName()).thenReturn("dummy");

  final CipherStorage.DecryptionResult decrypted = new CipherStorage.DecryptionResult("user", "password");
  final CipherStorage.EncryptionResult encrypted = new CipherStorage.EncryptionResult("user".getBytes(), "password".getBytes(), rsa);
  final KeychainModule module = new KeychainModule(context);
  final SharedPreferences prefs = context.getSharedPreferences(PrefsStorage.KEYCHAIN_DATA, Context.MODE_PRIVATE);

  when(
    rsa.encrypt(eq("dummy"), eq("user"), eq("password"), any())
  ).thenReturn(encrypted);

  // WHEN:
  module.migrateCipherStorage("dummy", rsa, aes, decrypted);
  final String username = prefs.getString(PrefsStorage.getKeyForUsername("dummy"), "");
  final String password = prefs.getString(PrefsStorage.getKeyForPassword("dummy"), "");
  final String cipherName = prefs.getString(PrefsStorage.getKeyForCipherStorage("dummy"), "");

  // THEN:
  //   delete of key from old storage
  //   re-store of encrypted data in shared preferences
  verify(rsa).encrypt("dummy", "user", "password", SecurityLevel.ANY);
  verify(aes).removeKey("dummy");

  // Base64.DEFAULT force '\n' char in the end of string
  assertThat(username, is("dXNlcg==\n"));
  assertThat(password, is("cGFzc3dvcmQ=\n"));
  assertThat(cipherName, is("dummy"));
}
 
Example #21
Source Project: android-job   Author: evernote   File: JobConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.LOLLIPOP)
public void verifyMinIntervalChanged() {
    assertThat(JobRequest.getMinInterval()).isEqualTo(JobRequest.MIN_INTERVAL);
    assertThat(JobRequest.getMinFlex()).isEqualTo(JobRequest.MIN_FLEX);

    JobConfig.setAllowSmallerIntervalsForMarshmallow(true);

    assertThat(JobRequest.getMinInterval()).isLessThan(JobRequest.MIN_INTERVAL);
    assertThat(JobRequest.getMinFlex()).isLessThan(JobRequest.MIN_FLEX);
}
 
Example #22
Source Project: Auth0.Android   Author: auth0   File: TelemetryTest.java    License: MIT License 5 votes vote down vote up
@Test
@Config(sdk = 23)
public void shouldAlwaysIncludeAndroidVersionAPI23() {
    Telemetry telemetry = new Telemetry("auth0-java", null);
    assertThat(telemetry.getEnvironment(), is(notNullValue()));
    assertThat(telemetry.getEnvironment().get("android"), is("23"));
}
 
Example #23
Source Project: fresco   Author: facebook   File: IterativeBoxBlurFilterTest.java    License: MIT License 5 votes vote down vote up
@Test
public void maxRadiusBitmapBlurInPlace() {
  IterativeBoxBlurFilter.boxBlurBitmapInPlace(mBitmap, 1, RenderScriptBlurFilter.BLUR_MAX_RADIUS);
  assertNotNull(mBitmap);
  assertEquals(mBitmap.getWidth(), BITMAP_SIZE);
  assertEquals(mBitmap.getHeight(), BITMAP_SIZE);
  assertEquals(mBitmap.getConfig(), Bitmap.Config.ARGB_8888);
}
 
Example #24
Source Project: Auth0.Android   Author: auth0   File: CryptoUtilTest.java    License: MIT License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.O_MR1)
@Test
@Config(sdk = 27)
public void shouldUseExistingRSAKeyPairOnAPI27AndDown() throws Exception {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 27);
    KeyStore.PrivateKeyEntry entry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class);
    PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(true);
    PowerMockito.when(keyStore.getEntry(KEY_ALIAS, null)).thenReturn(entry);

    KeyStore.PrivateKeyEntry rsaEntry = cryptoUtil.getRSAKeyEntry();
    assertThat(rsaEntry, is(notNullValue()));
    assertThat(rsaEntry, is(entry));
}
 
Example #25
Source Project: scene   Author: bytedance   File: GroupSceneUtilityTests.java    License: Apache License 2.0 5 votes vote down vote up
@Config(minSdk = Build.VERSION_CODES.JELLY_BEAN_MR1, maxSdk = Build.VERSION_CODES.P)
@LooperMode(PAUSED)
@Test
public void testNotImmediateSetupInActivityOnDestroy() {
    ActivityController<TestActivity> controller = Robolectric.buildActivity(TestActivity.class).create().start().resume().pause().stop().destroy();
    TestActivity activity = controller.get();
    GroupSceneDelegate sceneDelegate = GroupSceneUtility.setupWithActivity(activity, TestScene.class).immediate(false).build();
    GroupScene groupScene = sceneDelegate.getGroupScene();
    assertNotNull(groupScene);

    assertEquals(State.NONE, groupScene.getState());
    shadowOf(getMainLooper()).idle();//execute Handler posted task
    assertEquals(State.NONE, groupScene.getState());
}
 
Example #26
Source Project: firebase-android-sdk   Author: firebase   File: ConfigFetchHttpClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.KITKAT /* 19 */)
public void fetch_localeUsesToStringBelowLollipop() throws Exception {
  String languageTag = "zh-Hant-TW"; // Taiwan Chinese in traditional script
  String languageString = "zh_TW_#Hant";
  context.getResources().getConfiguration().setLocale(Locale.forLanguageTag(languageTag));

  setServerResponseTo(noChangeResponseBody, SECOND_ETAG);

  Map<String, String> userProperties = ImmutableMap.of("up1", "hello", "up2", "world");
  fetch(FIRST_ETAG, userProperties);

  JSONObject requestBody = new JSONObject(fakeHttpURLConnection.getOutputStream().toString());
  assertThat(requestBody.get(LANGUAGE_CODE)).isEqualTo(languageString);
}
 
Example #27
Source Project: graphhopper-navigation-android   Author: graphhopper   File: ReplayJsonRouteLocationMapperTest.java    License: MIT License 5 votes vote down vote up
@Test
@Config(sdk = 26)
public void checksVerticalAccuracyMapping() {
  List<ReplayLocationDto> anyReplayLocations = new ArrayList<>(1);
  ReplayLocationDto aReplayLocation = new ReplayLocationDto();
  aReplayLocation.setVerticalAccuracyMeters(8.0f);
  anyReplayLocations.add(aReplayLocation);
  ReplayJsonRouteLocationMapper theReplayJsonRouteLocationMapper = new ReplayJsonRouteLocationMapper(anyReplayLocations);

  List<Location> locations = theReplayJsonRouteLocationMapper.toLocations();

  Location theLocation = locations.get(0);
  assertEquals(8.0, theLocation.getVerticalAccuracyMeters(), DELTA);
}
 
Example #28
Source Project: material-components-android   Author: material-components   File: StaticLayoutBuilderCompatTest.java    License: Apache License 2.0 5 votes vote down vote up
@Config(minSdk = LOLLIPOP, maxSdk = VERSION_CODES.P)
@Test
public void createStaticLayout_withMaxLines_LongString() throws Exception {
  int maxLines = 3;

  StaticLayout staticLayout =
      StaticLayoutBuilderCompat.obtain(LONG_STRING, new TextPaint(), 100)
          .setAlignment(Alignment.ALIGN_NORMAL)
          .setIncludePad(true)
          .setEllipsize(TruncateAt.END)
          .setMaxLines(maxLines)
          .build();

  assertThat(staticLayout).isNotNull();
}
 
Example #29
Source Project: auth   Author: bleeding182   File: OAuthAccountManagerTest.java    License: MIT License 5 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.LOLLIPOP)
public void logout_preLollipop() {
    accountManager.login(account.name, tokens, AccountData.EMPTY);

    accountManager.logout();

    assertFalse(accountManager.isLoggedIn());
}
 
Example #30
Source Project: material-components-android   Author: material-components   File: RippleUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Config(sdk = VERSION_CODES.O_MR1)
public void testValidateColor_transparentDefaultColor_returnsSelf_oreoMr1_logsWarning() {
  ColorStateList rippleColor = createTransparentDefaultColor();
  assertThat(RippleUtils.sanitizeRippleDrawableColor(rippleColor)).isEqualTo(rippleColor);
  logged.expectLogMessage(
      Log.WARN, RippleUtils.LOG_TAG, RippleUtils.TRANSPARENT_DEFAULT_COLOR_WARNING);
}