Search in sources :

Example 31 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project mobile-center-sdk-android by Microsoft.

the class BrowserUtilsTest method onlySystemBrowserNoDefaultAsPicker.

@Test
public void onlySystemBrowserNoDefaultAsPicker() throws Exception {
    /* Mock no browser. */
    Activity activity = mock(Activity.class);
    doThrow(new ActivityNotFoundException()).when(activity).startActivity(argThat(CHROME_MATCHER));
    PackageManager packageManager = mock(PackageManager.class);
    when(activity.getPackageManager()).thenReturn(packageManager);
    {
        ActivityInfo activityInfo = new ActivityInfo();
        activityInfo.packageName = "system";
        activityInfo.name = "picker";
        ResolveInfo resolveInfo = new ResolveInfo();
        resolveInfo.activityInfo = activityInfo;
        when(packageManager.resolveActivity(any(Intent.class), eq(PackageManager.MATCH_DEFAULT_ONLY))).thenReturn(resolveInfo);
    }
    {
        ActivityInfo activityInfo = new ActivityInfo();
        activityInfo.packageName = "system";
        activityInfo.name = "browser";
        ResolveInfo resolveInfo = new ResolveInfo();
        resolveInfo.activityInfo = activityInfo;
        when(packageManager.queryIntentActivities(any(Intent.class), anyInt())).thenReturn(Collections.singletonList(resolveInfo));
    }
    /* Open Chrome then abort. */
    BrowserUtils.openBrowser(TEST_URL, activity);
    InOrder order = inOrder(activity);
    order.verify(activity).startActivity(argThat(CHROME_MATCHER));
    order.verify(activity).startActivity(argThat(new ArgumentMatcher<Intent>() {

        @Override
        public boolean matches(Object o) {
            Intent intent = (Intent) o;
            return Intent.ACTION_VIEW.equals(intent.getAction()) && Uri.parse(TEST_URL).equals(intent.getData()) && intent.getComponent().getClassName().equals("browser");
        }
    }));
    order.verifyNoMoreInteractions();
}
Also used : ResolveInfo(android.content.pm.ResolveInfo) ActivityInfo(android.content.pm.ActivityInfo) InOrder(org.mockito.InOrder) PackageManager(android.content.pm.PackageManager) ActivityNotFoundException(android.content.ActivityNotFoundException) ArgumentMatcher(org.mockito.ArgumentMatcher) Activity(android.app.Activity) Intent(android.content.Intent) Test(org.junit.Test)

Example 32 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project mobile-center-sdk-android by Microsoft.

the class BrowserUtilsTest method onlySystemBrowserAndIsDefault.

@Test
public void onlySystemBrowserAndIsDefault() throws Exception {
    /* Mock no browser. */
    Activity activity = mock(Activity.class);
    doThrow(new ActivityNotFoundException()).when(activity).startActivity(argThat(BrowserUtilsTest.CHROME_MATCHER));
    PackageManager packageManager = mock(PackageManager.class);
    when(activity.getPackageManager()).thenReturn(packageManager);
    {
        ActivityInfo activityInfo = new ActivityInfo();
        activityInfo.packageName = "system";
        activityInfo.name = "browser";
        ResolveInfo resolveInfo = new ResolveInfo();
        resolveInfo.activityInfo = activityInfo;
        when(packageManager.resolveActivity(any(Intent.class), eq(PackageManager.MATCH_DEFAULT_ONLY))).thenReturn(resolveInfo);
    }
    {
        ActivityInfo activityInfo = new ActivityInfo();
        activityInfo.packageName = "system";
        activityInfo.name = "browser";
        ResolveInfo resolveInfo = new ResolveInfo();
        resolveInfo.activityInfo = activityInfo;
        when(packageManager.queryIntentActivities(any(Intent.class), anyInt())).thenReturn(Collections.singletonList(resolveInfo));
    }
    /* Open Chrome then abort. */
    BrowserUtils.openBrowser(TEST_URL, activity);
    InOrder order = inOrder(activity);
    order.verify(activity).startActivity(argThat(CHROME_MATCHER));
    order.verify(activity).startActivity(argThat(new ArgumentMatcher<Intent>() {

        @Override
        public boolean matches(Object o) {
            Intent intent = (Intent) o;
            return Intent.ACTION_VIEW.equals(intent.getAction()) && Uri.parse(TEST_URL).equals(intent.getData()) && intent.getComponent().getClassName().equals("browser");
        }
    }));
    order.verifyNoMoreInteractions();
}
Also used : ResolveInfo(android.content.pm.ResolveInfo) ActivityInfo(android.content.pm.ActivityInfo) InOrder(org.mockito.InOrder) PackageManager(android.content.pm.PackageManager) ActivityNotFoundException(android.content.ActivityNotFoundException) ArgumentMatcher(org.mockito.ArgumentMatcher) Activity(android.app.Activity) Intent(android.content.Intent) Test(org.junit.Test)

Example 33 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project mobile-center-sdk-android by Microsoft.

the class DistributeBeforeApiSuccessTest method happyPathUntilHangingCall.

@Test
public void happyPathUntilHangingCall() throws Exception {
    /* Setup mock. */
    HttpClientNetworkStateHandler httpClient = mock(HttpClientNetworkStateHandler.class);
    whenNew(HttpClientNetworkStateHandler.class).withAnyArguments().thenReturn(httpClient);
    UUID requestId = UUID.randomUUID();
    when(UUIDUtils.randomUUID()).thenReturn(requestId);
    when(PreferencesStorage.getString(PREFERENCE_KEY_REQUEST_ID)).thenReturn(requestId.toString());
    /* Start and resume: open browser. */
    Distribute.getInstance().onStarted(mContext, "a", mock(Channel.class));
    Distribute.getInstance().onActivityResumed(mActivity);
    verifyStatic();
    String url = DistributeConstants.DEFAULT_INSTALL_URL;
    url += String.format(UPDATE_SETUP_PATH_FORMAT, "a");
    url += "?" + PARAMETER_RELEASE_HASH + "=" + TEST_HASH;
    url += "&" + PARAMETER_REDIRECT_ID + "=" + mContext.getPackageName();
    url += "&" + PARAMETER_REQUEST_ID + "=" + requestId.toString();
    url += "&" + PARAMETER_PLATFORM + "=" + PARAMETER_PLATFORM_VALUE;
    BrowserUtils.openBrowser(url, mActivity);
    verifyStatic();
    PreferencesStorage.putString(PREFERENCE_KEY_REQUEST_ID, requestId.toString());
    /* If browser already opened, activity changed must not recall it. */
    Distribute.getInstance().onActivityPaused(mActivity);
    Distribute.getInstance().onActivityResumed(mActivity);
    verifyStatic();
    BrowserUtils.openBrowser(url, mActivity);
    verifyStatic();
    PreferencesStorage.putString(PREFERENCE_KEY_REQUEST_ID, requestId.toString());
    /* Store token. */
    Distribute.getInstance().storeUpdateToken("some token", requestId.toString());
    /* Verify behavior. */
    verifyStatic();
    PreferencesStorage.putString(PREFERENCE_KEY_UPDATE_TOKEN, "some token");
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_REQUEST_ID);
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_ID);
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_STATE);
    HashMap<String, String> headers = new HashMap<>();
    headers.put(DistributeConstants.HEADER_API_TOKEN, "some token");
    verify(httpClient).callAsync(argThat(new ArgumentMatcher<String>() {

        @Override
        public boolean matches(Object argument) {
            return argument.toString().startsWith(DistributeConstants.DEFAULT_API_URL);
        }
    }), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
    /* If call already made, activity changed must not recall it. */
    Distribute.getInstance().onActivityPaused(mActivity);
    Distribute.getInstance().onActivityResumed(mActivity);
    /* Verify behavior. */
    verifyStatic();
    PreferencesStorage.putString(PREFERENCE_KEY_UPDATE_TOKEN, "some token");
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_REQUEST_ID);
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_ID);
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_STATE);
    verify(httpClient).callAsync(argThat(new ArgumentMatcher<String>() {

        @Override
        public boolean matches(Object argument) {
            return argument.toString().startsWith(DistributeConstants.DEFAULT_API_URL);
        }
    }), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
    /* Call is still in progress. If we restart app, nothing happens we still wait. */
    restartResumeLauncher(mActivity);
    Distribute.getInstance().onActivityPaused(mActivity);
    Distribute.getInstance().onActivityStopped(mActivity);
    Distribute.getInstance().onActivityDestroyed(mActivity);
    Distribute.getInstance().onActivityCreated(mActivity, mock(Bundle.class));
    Distribute.getInstance().onActivityResumed(mActivity);
    /* Verify behavior not changed. */
    verifyStatic();
    BrowserUtils.openBrowser(url, mActivity);
    verifyStatic();
    PreferencesStorage.putString(PREFERENCE_KEY_UPDATE_TOKEN, "some token");
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_REQUEST_ID);
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_ID);
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_STATE);
    verify(httpClient).callAsync(argThat(new ArgumentMatcher<String>() {

        @Override
        public boolean matches(Object argument) {
            return argument.toString().startsWith(DistributeConstants.DEFAULT_API_URL);
        }
    }), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
}
Also used : ServiceCallback(com.microsoft.azure.mobile.http.ServiceCallback) HashMap(java.util.HashMap) Bundle(android.os.Bundle) Channel(com.microsoft.azure.mobile.channel.Channel) ArgumentMatcher(org.mockito.ArgumentMatcher) Matchers.anyString(org.mockito.Matchers.anyString) HttpClientNetworkStateHandler(com.microsoft.azure.mobile.http.HttpClientNetworkStateHandler) UUID(java.util.UUID) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 34 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project mobile-center-sdk-android by Microsoft.

the class DistributeWarnUnknownSourcesTest method clickSettingsThenEnableThenBack.

@Test
@PrepareForTest(AsyncTaskUtils.class)
public void clickSettingsThenEnableThenBack() throws Exception {
    /* Click settings. */
    Intent intent = mock(Intent.class);
    whenNew(Intent.class).withArguments(Settings.ACTION_SECURITY_SETTINGS).thenReturn(intent);
    ArgumentCaptor<DialogInterface.OnClickListener> clickListener = ArgumentCaptor.forClass(DialogInterface.OnClickListener.class);
    verify(mDialogBuilder).setPositiveButton(eq(R.string.mobile_center_distribute_unknown_sources_dialog_settings), clickListener.capture());
    clickListener.getValue().onClick(mUnknownSourcesDialog, DialogInterface.BUTTON_POSITIVE);
    when(mUnknownSourcesDialog.isShowing()).thenReturn(false);
    /* Verify navigation. */
    verify(mFirstActivity).startActivity(intent);
    /* Simulate we go to settings, change value then go back. */
    mockStatic(AsyncTaskUtils.class);
    Distribute.getInstance().onActivityPaused(mFirstActivity);
    when(InstallerUtils.isUnknownSourcesEnabled(mContext)).thenReturn(true);
    Distribute.getInstance().onActivityResumed(mFirstActivity);
    /* No more dialog, start download. */
    verify(mDialog).show();
    verify(mDialog, never()).hide();
    verify(mUnknownSourcesDialog).show();
    verify(mUnknownSourcesDialog, never()).hide();
    verifyStatic();
    AsyncTaskUtils.execute(anyString(), argThat(new ArgumentMatcher<AsyncTask<Object, ?, ?>>() {

        @Override
        public boolean matches(Object argument) {
            return argument instanceof DownloadTask;
        }
    }), anyVararg());
}
Also used : DialogInterface(android.content.DialogInterface) ArgumentMatcher(org.mockito.ArgumentMatcher) Intent(android.content.Intent) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 35 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project mobile-center-sdk-android by Microsoft.

the class CryptoTest method setUp.

@Before
@SuppressWarnings("WrongConstant")
public void setUp() throws Exception {
    when(mContext.getApplicationContext()).thenReturn(mContext);
    mockStatic(KeyStore.class);
    mockStatic(KeyPairGenerator.class);
    mockStatic(Base64.class);
    when(Base64.encodeToString(any(byte[].class), anyInt())).thenAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            return new String((byte[]) invocation.getArguments()[0]);
        }
    });
    when(Base64.decode(anyString(), anyInt())).thenAnswer(new Answer<byte[]>() {

        @Override
        public byte[] answer(InvocationOnMock invocation) throws Throwable {
            return invocation.getArguments()[0].toString().getBytes();
        }
    });
    when(KeyStore.getInstance(ANDROID_KEY_STORE)).thenReturn(mKeyStore);
    /* Mock some RSA specifics. */
    whenNew(KeyPairGeneratorSpec.Builder.class).withAnyArguments().thenReturn(mRsaBuilder);
    when(mRsaBuilder.setAlias(anyString())).thenReturn(mRsaBuilder);
    when(mRsaBuilder.setSubject(any(X500Principal.class))).thenReturn(mRsaBuilder);
    when(mRsaBuilder.setStartDate(any(Date.class))).thenReturn(mRsaBuilder);
    when(mRsaBuilder.setEndDate(any(Date.class))).thenReturn(mRsaBuilder);
    when(mRsaBuilder.setSerialNumber(any(BigInteger.class))).thenReturn(mRsaBuilder);
    when(mRsaBuilder.setKeySize(anyInt())).thenReturn(mRsaBuilder);
    when(KeyPairGenerator.getInstance(anyString(), anyString())).thenReturn(mock(KeyPairGenerator.class));
    KeyStore.PrivateKeyEntry rsaKey = mock(KeyStore.PrivateKeyEntry.class);
    when(mKeyStore.getEntry(argThat(new ArgumentMatcher<String>() {

        @Override
        public boolean matches(Object argument) {
            return String.valueOf(argument).contains(CIPHER_RSA);
        }
    }), any(KeyStore.ProtectionParameter.class))).thenReturn(rsaKey);
    when(rsaKey.getCertificate()).thenReturn(mRsaCert);
    when(mCipher.doFinal(any(byte[].class))).thenAnswer(new Answer<byte[]>() {

        @Override
        public byte[] answer(InvocationOnMock invocation) throws Throwable {
            return (byte[]) invocation.getArguments()[0];
        }
    });
    /* Mock some AES specifics. */
    KeyStore.SecretKeyEntry aesKey = mock(KeyStore.SecretKeyEntry.class);
    whenNew(KeyGenParameterSpec.Builder.class).withAnyArguments().thenReturn(mAesBuilder);
    when(mAesBuilder.setBlockModes(anyString())).thenReturn(mAesBuilder);
    when(mAesBuilder.setEncryptionPaddings(anyString())).thenReturn(mAesBuilder);
    when(mAesBuilder.setKeySize(anyInt())).thenReturn(mAesBuilder);
    when(mAesBuilder.setKeyValidityForOriginationEnd(any(Date.class))).thenReturn(mAesBuilder);
    when(mAesBuilder.build()).thenReturn(mock(KeyGenParameterSpec.class));
    when(mKeyStore.getEntry(argThat(new ArgumentMatcher<String>() {

        @Override
        public boolean matches(Object argument) {
            return String.valueOf(argument).contains(CIPHER_AES);
        }
    }), any(KeyStore.ProtectionParameter.class))).thenReturn(aesKey);
    when(mCryptoFactory.getKeyGenerator(anyString(), anyString())).thenReturn(mock(CryptoUtils.IKeyGenerator.class));
    final byte[] mockInitVector = "IV".getBytes();
    when(mCipher.getBlockSize()).thenReturn(mockInitVector.length);
    when(mCipher.getIV()).thenReturn(mockInitVector);
    when(mCipher.doFinal(any(byte[].class), anyInt(), anyInt())).thenAnswer(new Answer<byte[]>() {

        @Override
        public byte[] answer(InvocationOnMock invocation) throws Throwable {
            byte[] input = (byte[]) invocation.getArguments()[0];
            int offset = (int) invocation.getArguments()[1];
            int length = (int) invocation.getArguments()[2];
            byte[] data = new byte[length];
            System.arraycopy(input, offset, data, 0, length);
            return data;
        }
    });
    /* Mock ciphers. */
    when(mCryptoFactory.getCipher(anyString(), anyString())).thenReturn(mCipher);
}
Also used : KeyPairGeneratorSpec(android.security.KeyPairGeneratorSpec) KeyGenParameterSpec(android.security.keystore.KeyGenParameterSpec) Matchers.anyString(org.mockito.Matchers.anyString) KeyPairGenerator(java.security.KeyPairGenerator) KeyStore(java.security.KeyStore) Date(java.util.Date) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ArgumentMatcher(org.mockito.ArgumentMatcher) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) Before(org.junit.Before)

Aggregations

ArgumentMatcher (org.mockito.ArgumentMatcher)142 Test (org.junit.Test)116 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)36 Context (android.content.Context)26 Matchers.anyString (org.mockito.Matchers.anyString)26 HashMap (java.util.HashMap)25 Appender (ch.qos.logback.core.Appender)23 Logger (org.slf4j.Logger)23 ArrayList (java.util.ArrayList)19 UUID (java.util.UUID)19 Intent (android.content.Intent)18 File (java.io.File)15 ResolveInfo (android.content.pm.ResolveInfo)14 PackageManager (android.content.pm.PackageManager)13 Channel (com.microsoft.azure.mobile.channel.Channel)13 ApplicationService (org.codice.ddf.admin.application.service.ApplicationService)13 InvocationOnMock (org.mockito.invocation.InvocationOnMock)13 IOException (java.io.IOException)12 ServiceCallback (com.microsoft.appcenter.http.ServiceCallback)11 Activity (android.app.Activity)10