Java Code Examples for com.facebook.react.bridge.JavaOnlyMap#putString()

The following examples show how to use com.facebook.react.bridge.JavaOnlyMap#putString() . 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: DialogModuleTest.java    From react-native-GPay with MIT License 6 votes vote down vote up
@Test
public void testAllOptions() {
  final JavaOnlyMap options = new JavaOnlyMap();
  options.putString("title", "Title");
  options.putString("message", "Message");
  options.putString("buttonPositive", "OK");
  options.putString("buttonNegative", "Cancel");
  options.putString("buttonNeutral", "Later");
  options.putBoolean("cancelable", false);

  mDialogModule.showAlert(options, null, null);

  final AlertFragment fragment = getFragment();
  assertNotNull("Fragment was not displayed", fragment);
  assertEquals(false, fragment.isCancelable());

  final AlertDialog dialog = (AlertDialog) fragment.getDialog();
  assertEquals("OK", dialog.getButton(DialogInterface.BUTTON_POSITIVE).getText().toString());
  assertEquals("Cancel", dialog.getButton(DialogInterface.BUTTON_NEGATIVE).getText().toString());
  assertEquals("Later", dialog.getButton(DialogInterface.BUTTON_NEUTRAL).getText().toString());
}
 
Example 2
Source File: KeychainModuleTests.java    From react-native-keychain with 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 3
Source File: KeychainModuleTests.java    From react-native-keychain with MIT License 6 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testGetSecurityLevel_NoBiometry_NoSecuredHardware_api28() throws Exception {
  // GIVE:
  final ReactApplicationContext context = getRNContext();
  final KeychainModule module = new KeychainModule(context);
  final Promise mockPromise = mock(Promise.class);

  // set key info - software method
  provider.configuration.put("isInsideSecureHardware", false);

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

  module.getSecurityLevel(options, mockPromise);

  // THEN:
  // expected AesCbc usage
  assertThat(provider.mocks.get("KeyGenerator"), notNullValue());
  assertThat(provider.mocks.get("KeyGenerator").get("AES"), notNullValue());
  assertThat(provider.mocks.get("KeyPairGenerator"), notNullValue());
  assertThat(provider.mocks.get("KeyPairGenerator").get("RSA"), notNullValue());
  verify(mockPromise).resolve(SecurityLevel.SECURE_SOFTWARE.name());
}
 
Example 4
Source File: DialogModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void testCallbackPositive() {
  final JavaOnlyMap options = new JavaOnlyMap();
  options.putString("buttonPositive", "OK");

  final SimpleCallback actionCallback = new SimpleCallback();
  mDialogModule.showAlert(options, null, actionCallback);

  final AlertDialog dialog = (AlertDialog) getFragment().getDialog();
  dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();

  assertEquals(1, actionCallback.getCalls());
  assertEquals(DialogModule.ACTION_BUTTON_CLICKED, actionCallback.getArgs()[0]);
  assertEquals(DialogInterface.BUTTON_POSITIVE, actionCallback.getArgs()[1]);
}
 
Example 5
Source File: DialogModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void testCallbackNegative() {
  final JavaOnlyMap options = new JavaOnlyMap();
  options.putString("buttonNegative", "Cancel");

  final SimpleCallback actionCallback = new SimpleCallback();
  mDialogModule.showAlert(options, null, actionCallback);

  final AlertDialog dialog = (AlertDialog) getFragment().getDialog();
  dialog.getButton(DialogInterface.BUTTON_NEGATIVE).performClick();

  assertEquals(1, actionCallback.getCalls());
  assertEquals(DialogModule.ACTION_BUTTON_CLICKED, actionCallback.getArgs()[0]);
  assertEquals(DialogInterface.BUTTON_NEGATIVE, actionCallback.getArgs()[1]);
}
 
Example 6
Source File: DialogModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void testCallbackNeutral() {
  final JavaOnlyMap options = new JavaOnlyMap();
  options.putString("buttonNeutral", "Later");

  final SimpleCallback actionCallback = new SimpleCallback();
  mDialogModule.showAlert(options, null, actionCallback);

  final AlertDialog dialog = (AlertDialog) getFragment().getDialog();
  dialog.getButton(DialogInterface.BUTTON_NEUTRAL).performClick();

  assertEquals(1, actionCallback.getCalls());
  assertEquals(DialogModule.ACTION_BUTTON_CLICKED, actionCallback.getArgs()[0]);
  assertEquals(DialogInterface.BUTTON_NEUTRAL, actionCallback.getArgs()[1]);
}
 
Example 7
Source File: NetworkingModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void testFailPostWithoutContentType() throws Exception {
  RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class);
  ReactApplicationContext context = mock(ReactApplicationContext.class);
  when(context.getJSModule(any(Class.class))).thenReturn(emitter);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class);
  when(clientBuilder.build()).thenReturn(httpClient);
  when(httpClient.newBuilder()).thenReturn(clientBuilder);
  NetworkingModule networkingModule = new NetworkingModule(context, "", httpClient);

  JavaOnlyMap body = new JavaOnlyMap();
  body.putString("string", "This is request body");

  mockEvents();

  networkingModule.sendRequest(
    "POST",
    "http://somedomain/bar",
    0,
    JavaOnlyArray.of(),
    body,
    /* responseType */ "text",
    /* useIncrementalUpdates*/ true,
    /* timeout */ 0,
    /* withCredentials */ false);

  verifyErrorEmit(emitter, 0);
}
 
Example 8
Source File: ShareModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void testShareDialog() {
  final String title = "Title";
  final String message = "Message";
  final String dialogTitle = "Dialog Title";

  JavaOnlyMap content = new JavaOnlyMap();
  content.putString("title", title);
  content.putString("message", message);

  final SimplePromise promise = new SimplePromise();

  mShareModule.share(content, dialogTitle, promise);

  final Intent chooserIntent = 
    ((ShadowApplication)ShadowExtractor.extract(RuntimeEnvironment.application)).getNextStartedActivity();
  assertNotNull("Dialog was not displayed", chooserIntent);
  assertEquals(Intent.ACTION_CHOOSER, chooserIntent.getAction());
  assertEquals(dialogTitle, chooserIntent.getExtras().get(Intent.EXTRA_TITLE));

  final Intent contentIntent = (Intent)chooserIntent.getExtras().get(Intent.EXTRA_INTENT);
  assertNotNull("Intent was not built correctly", contentIntent);
  assertEquals(Intent.ACTION_SEND, contentIntent.getAction());
  assertEquals(title, contentIntent.getExtras().get(Intent.EXTRA_SUBJECT));
  assertEquals(message, contentIntent.getExtras().get(Intent.EXTRA_TEXT));

  assertEquals(1, promise.getResolved());
}
 
Example 9
Source File: BlobModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void testResolveMap() {
  JavaOnlyMap blob = new JavaOnlyMap();
  blob.putString("blobId", mBlobId);
  blob.putInt("offset", 0);
  blob.putInt("size", mBytes.length);

  assertArrayEquals(mBytes, mBlobModule.resolve(blob));
}
 
Example 10
Source File: BlobModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void testCreateFromParts() {
  String id = UUID.randomUUID().toString();

  JavaOnlyMap blobData = new JavaOnlyMap();
  blobData.putString("blobId", mBlobId);
  blobData.putInt("offset", 0);
  blobData.putInt("size", mBytes.length);
  JavaOnlyMap blob = new JavaOnlyMap();
  blob.putMap("data", blobData);
  blob.putString("type", "blob");

  String stringData = "i \u2665 dogs";
  byte[] stringBytes = stringData.getBytes(Charset.forName("UTF-8"));
  JavaOnlyMap string = new JavaOnlyMap();
  string.putString("data", stringData);
  string.putString("type", "string");

  JavaOnlyArray parts = new JavaOnlyArray();
  parts.pushMap(blob);
  parts.pushMap(string);

  mBlobModule.createFromParts(parts, id);

  int resultSize = mBytes.length + stringBytes.length;

  byte[] result = mBlobModule.resolve(id, 0, resultSize);

  ByteBuffer buffer = ByteBuffer.allocate(resultSize);
  buffer.put(mBytes);
  buffer.put(stringBytes);

  assertArrayEquals(result, buffer.array());
}
 
Example 11
Source File: JSONParserTest.java    From react-native-navigation with MIT License 5 votes vote down vote up
@Test
public void parsesMap() throws Exception {
    JavaOnlyMap input = new JavaOnlyMap();
    input.putString("keyString", "stringValue");
    input.putInt("keyInt", 123);
    input.putDouble("keyDouble", 123.456);
    input.putBoolean("keyBoolean", true);
    input.putArray("keyArray", new JavaOnlyArray());
    input.putMap("keyMap", new JavaOnlyMap());
    input.putNull("bla");

    JSONObject result = new JSONParser().parse(input);


    assertThat(result.keys()).containsOnly(
            "keyString",
            "keyInt",
            "keyDouble",
            "keyBoolean",
            "keyMap",
            "keyArray");

    assertThat(result.get("keyString")).isEqualTo("stringValue");
    assertThat(result.get("keyInt")).isEqualTo(123);
    assertThat(result.get("keyDouble")).isEqualTo(123.456);
    assertThat(result.get("keyBoolean")).isEqualTo(true);
    assertThat(result.getJSONObject("keyMap").keys()).isEmpty();
    assertThat(result.getJSONArray("keyArray").length()).isZero();
}
 
Example 12
Source File: KeychainModuleTests.java    From react-native-keychain with MIT License 5 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testDowngradeBiometricToAes_api28() throws Exception {
  // GIVEN:
  final ReactApplicationContext context = getRNContext();
  final KeychainModule module = new KeychainModule(context);
  final PrefsStorage prefs = new PrefsStorage(context);
  final Cipher mockCipher = Mockito.mock(Cipher.class);
  final KeyStore mockKeyStore = Mockito.mock(KeyStore.class);
  final CipherStorage storage = module.getCipherStorageByName(KnownCiphers.RSA);
  final CipherStorage.EncryptionResult result = new CipherStorage.EncryptionResult(BYTES_USERNAME, BYTES_PASSWORD, storage);
  final Promise mockPromise = mock(Promise.class);
  final JavaOnlyMap options = new JavaOnlyMap();
  options.putString(Maps.SERVICE, "dummy");

  // store record done with RSA/Biometric cipher
  prefs.storeEncryptedEntry("dummy", result);

  assertThat(storage, instanceOf(CipherStorage.class));
  ((CipherStorageBase)storage).setCipher(mockCipher).setKeyStore(mockKeyStore);
  when(mockKeyStore.getKey(eq("dummy"), isNull())).thenReturn(null); // return empty Key!

  // WHEN:
  module.getGenericPasswordForOptions(options, mockPromise);

  // THEN:
  ArgumentCaptor<Exception> exception = ArgumentCaptor.forClass(Exception.class);
  verify(mockPromise).reject(eq(Errors.E_CRYPTO_FAILED), exception.capture());
  assertThat(exception.getValue(), instanceOf(CryptoFailedException.class));
  assertThat(exception.getValue().getCause(), instanceOf(KeyStoreAccessException.class));
  assertThat(exception.getValue().getMessage(), is("Wrapped error: Empty key extracted!"));
}
 
Example 13
Source File: NetworkingModuleTest.java    From react-native-GPay with MIT License 4 votes vote down vote up
@Test
public void testSuccessfulPostRequest() throws Exception {
  RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class);
  ReactApplicationContext context = mock(ReactApplicationContext.class);
  when(context.getJSModule(any(Class.class))).thenReturn(emitter);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          Call callMock = mock(Call.class);
          return callMock;
        }
      });
  OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class);
  when(clientBuilder.build()).thenReturn(httpClient);
  when(httpClient.newBuilder()).thenReturn(clientBuilder);
  NetworkingModule networkingModule = new NetworkingModule(context, "", httpClient);

  JavaOnlyMap body = new JavaOnlyMap();
  body.putString("string", "This is request body");

  mockEvents();
  
  networkingModule.sendRequest(
    "POST",
    "http://somedomain/bar",
    0,
    JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "text/plain")),
    body,
    /* responseType */ "text",
    /* useIncrementalUpdates*/ true,
    /* timeout */ 0,
    /* withCredentials */ false);

  ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
  verify(httpClient).newCall(argumentCaptor.capture());
  assertThat(argumentCaptor.getValue().url().toString()).isEqualTo("http://somedomain/bar");
  assertThat(argumentCaptor.getValue().headers().size()).isEqualTo(2);
  assertThat(argumentCaptor.getValue().method()).isEqualTo("POST");
  assertThat(argumentCaptor.getValue().body().contentType().type()).isEqualTo("text");
  assertThat(argumentCaptor.getValue().body().contentType().subtype()).isEqualTo("plain");
  Buffer contentBuffer = new Buffer();
  argumentCaptor.getValue().body().writeTo(contentBuffer);
  assertThat(contentBuffer.readUtf8()).isEqualTo("This is request body");
}
 
Example 14
Source File: NetworkingModuleTest.java    From react-native-GPay with MIT License 4 votes vote down vote up
@Test
public void testMultipartPostRequestSimple() throws Exception {
  PowerMockito.mockStatic(RequestBodyUtil.class);
  when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class)))
      .thenReturn(mock(InputStream.class));
  when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class)))
      .thenReturn(mock(RequestBody.class));
  when(RequestBodyUtil.createProgressRequest(any(RequestBody.class), any(ProgressListener.class)))
      .thenCallRealMethod();

  JavaOnlyMap body = new JavaOnlyMap();
  JavaOnlyArray formData = new JavaOnlyArray();
  JavaOnlyMap bodyPart = new JavaOnlyMap();
  bodyPart.putString("string", "value");
  bodyPart.putArray(
      "headers",
      JavaOnlyArray.from(
          Arrays.asList(
              JavaOnlyArray.of("content-disposition", "name"))));
  formData.pushMap(bodyPart);
  body.putArray("formData", formData);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  when(httpClient.newCall(any(Request.class))).thenAnswer(
      new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          Call callMock = mock(Call.class);
          return callMock;
        }
      });
  OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class);
  when(clientBuilder.build()).thenReturn(httpClient);
  when(httpClient.newBuilder()).thenReturn(clientBuilder);
  NetworkingModule networkingModule =
    new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient);
  networkingModule.sendRequest(
    "POST",
    "http://someurl/uploadFoo",
    0,
    new JavaOnlyArray(),
    body,
    /* responseType */ "text",
    /* useIncrementalUpdates*/ true,
    /* timeout */ 0,
    /* withCredentials */ false);

  // verify url, method, headers
  ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
  verify(httpClient).newCall(argumentCaptor.capture());
  assertThat(argumentCaptor.getValue().url().toString()).isEqualTo("http://someurl/uploadFoo");
  assertThat(argumentCaptor.getValue().method()).isEqualTo("POST");
  assertThat(argumentCaptor.getValue().body().contentType().type()).
      isEqualTo(MultipartBody.FORM.type());
  assertThat(argumentCaptor.getValue().body().contentType().subtype()).
      isEqualTo(MultipartBody.FORM.subtype());
  Headers requestHeaders = argumentCaptor.getValue().headers();
  assertThat(requestHeaders.size()).isEqualTo(1);
}
 
Example 15
Source File: NetworkingModuleTest.java    From react-native-GPay with MIT License 4 votes vote down vote up
@Test
public void testMultipartPostRequestHeaders() throws Exception {
  PowerMockito.mockStatic(RequestBodyUtil.class);
  when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class)))
      .thenReturn(mock(InputStream.class));
  when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class)))
      .thenReturn(mock(RequestBody.class));
  when(RequestBodyUtil.createProgressRequest(any(RequestBody.class), any(ProgressListener.class)))
      .thenCallRealMethod();

  List<JavaOnlyArray> headers = Arrays.asList(
          JavaOnlyArray.of("Accept", "text/plain"),
          JavaOnlyArray.of("User-Agent", "React test agent/1.0"),
          JavaOnlyArray.of("content-type", "multipart/form-data"));

  JavaOnlyMap body = new JavaOnlyMap();
  JavaOnlyArray formData = new JavaOnlyArray();
  JavaOnlyMap bodyPart = new JavaOnlyMap();
  bodyPart.putString("string", "value");
  bodyPart.putArray(
      "headers",
      JavaOnlyArray.from(
          Arrays.asList(
              JavaOnlyArray.of("content-disposition", "name"))));
  formData.pushMap(bodyPart);
  body.putArray("formData", formData);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  when(httpClient.newCall(any(Request.class))).thenAnswer(
      new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          Call callMock = mock(Call.class);
          return callMock;
        }
      });
  OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class);
  when(clientBuilder.build()).thenReturn(httpClient);
  when(httpClient.newBuilder()).thenReturn(clientBuilder);
  NetworkingModule networkingModule =
    new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient);
  networkingModule.sendRequest(
    "POST",
    "http://someurl/uploadFoo",
    0,
    JavaOnlyArray.from(headers),
    body,
    /* responseType */ "text",
    /* useIncrementalUpdates*/ true,
    /* timeout */ 0,
    /* withCredentials */ false);

  // verify url, method, headers
  ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
  verify(httpClient).newCall(argumentCaptor.capture());
  assertThat(argumentCaptor.getValue().url().toString()).isEqualTo("http://someurl/uploadFoo");
  assertThat(argumentCaptor.getValue().method()).isEqualTo("POST");
  assertThat(argumentCaptor.getValue().body().contentType().type()).
      isEqualTo(MultipartBody.FORM.type());
  assertThat(argumentCaptor.getValue().body().contentType().subtype()).
      isEqualTo(MultipartBody.FORM.subtype());
  Headers requestHeaders = argumentCaptor.getValue().headers();
  assertThat(requestHeaders.size()).isEqualTo(3);
  assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain");
  assertThat(requestHeaders.get("User-Agent")).isEqualTo("React test agent/1.0");
  assertThat(requestHeaders.get("content-type")).isEqualTo("multipart/form-data");
}