Search in sources :

Example 81 with ArgumentMatcher

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

the class DistributeBeforeApiSuccessTest method setUrls.

@Test
public void setUrls() throws Exception {
    /* Setup mock. */
    Distribute.setInstallUrl("http://mock");
    Distribute.setApiUrl("https://mock2");
    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 = "http://mock";
    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());
    /* Store token. */
    Distribute.getInstance().storeUpdateToken("some token", requestId.toString());
    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("https://mock2");
        }
    }), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
}
Also used : ServiceCallback(com.microsoft.azure.mobile.http.ServiceCallback) HashMap(java.util.HashMap) 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 82 with ArgumentMatcher

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

the class BrowserUtilsTest method onlySystemBrowserNoDefaultAsNull.

@Test
public void onlySystemBrowserNoDefaultAsNull() 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);
    when(packageManager.resolveActivity(any(Intent.class), eq(PackageManager.MATCH_DEFAULT_ONLY))).thenReturn(null);
    {
        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 83 with ArgumentMatcher

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

the class DefaultChannelRaceConditionTest method disabledWhileHandlingIngestionSuccess.

@Test
public void disabledWhileHandlingIngestionSuccess() throws Exception {
    /* Set up mocking. */
    final Semaphore beforeCallSemaphore = new Semaphore(0);
    final Semaphore afterCallSemaphore = new Semaphore(0);
    Persistence mockPersistence = mock(Persistence.class);
    when(mockPersistence.countLogs(anyString())).thenReturn(1);
    when(mockPersistence.getLogs(anyString(), eq(1), anyListOf(Log.class))).then(getGetLogsAnswer(1));
    when(mockPersistence.getLogs(anyString(), eq(CLEAR_BATCH_SIZE), anyListOf(Log.class))).then(getGetLogsAnswer(0));
    DatabasePersistenceAsync mockPersistenceAsync = spy(new DatabasePersistenceAsync(mockPersistence));
    whenNew(DatabasePersistenceAsync.class).withArguments(mockPersistence).thenReturn(mockPersistenceAsync);
    IngestionHttp mockIngestion = mock(IngestionHttp.class);
    when(mockIngestion.sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class))).then(new Answer<Object>() {

        @Override
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            new Thread() {

                @Override
                public void run() {
                    beforeCallSemaphore.acquireUninterruptibly();
                    ((ServiceCallback) invocation.getArguments()[3]).onCallSucceeded("");
                    afterCallSemaphore.release();
                }
            }.start();
            return mock(ServiceCall.class);
        }
    });
    /* Simulate enable module then disable. */
    DefaultChannel channel = new DefaultChannel(mock(Context.class), UUIDUtils.randomUUID().toString(), mockPersistence, mockIngestion);
    Channel.GroupListener listener = mock(Channel.GroupListener.class);
    channel.addGroup(TEST_GROUP, 1, BATCH_TIME_INTERVAL, MAX_PARALLEL_BATCHES, listener);
    channel.setEnabled(false);
    channel.setEnabled(true);
    /* Release call to mock ingestion. */
    beforeCallSemaphore.release();
    /* Wait for callback ingestion. */
    afterCallSemaphore.acquireUninterruptibly();
    /* Verify handling success was ignored. */
    verify(listener, never()).onSuccess(any(Log.class));
    verify(listener).onFailure(any(Log.class), argThat(new ArgumentMatcher<Exception>() {

        @Override
        public boolean matches(Object argument) {
            return argument instanceof CancellationException;
        }
    }));
}
Also used : Context(android.content.Context) ServiceCall(com.microsoft.azure.mobile.http.ServiceCall) Log(com.microsoft.azure.mobile.ingestion.models.Log) Semaphore(java.util.concurrent.Semaphore) Persistence(com.microsoft.azure.mobile.persistence.Persistence) IngestionHttp(com.microsoft.azure.mobile.ingestion.IngestionHttp) ServiceCallback(com.microsoft.azure.mobile.http.ServiceCallback) CancellationException(com.microsoft.azure.mobile.CancellationException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ArgumentMatcher(org.mockito.ArgumentMatcher) LogContainer(com.microsoft.azure.mobile.ingestion.models.LogContainer) UUID(java.util.UUID) DatabasePersistenceAsync(com.microsoft.azure.mobile.persistence.DatabasePersistenceAsync) Test(org.junit.Test)

Example 84 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project pulsar by yahoo.

the class PulsarAdminToolTest method persistentTopics.

@Test
void persistentTopics() throws Exception {
    PulsarAdmin admin = Mockito.mock(PulsarAdmin.class);
    PersistentTopics mockTopics = mock(PersistentTopics.class);
    when(admin.persistentTopics()).thenReturn(mockTopics);
    CmdPersistentTopics topics = new CmdPersistentTopics(admin);
    topics.run(split("delete persistent://myprop/clust/ns1/ds1"));
    verify(mockTopics).delete("persistent://myprop/clust/ns1/ds1");
    topics.run(split("list myprop/clust/ns1"));
    verify(mockTopics).getList("myprop/clust/ns1");
    topics.run(split("subscriptions persistent://myprop/clust/ns1/ds1"));
    verify(mockTopics).getSubscriptions("persistent://myprop/clust/ns1/ds1");
    topics.run(split("unsubscribe persistent://myprop/clust/ns1/ds1 -s sub1"));
    verify(mockTopics).deleteSubscription("persistent://myprop/clust/ns1/ds1", "sub1");
    topics.run(split("stats persistent://myprop/clust/ns1/ds1"));
    verify(mockTopics).getStats("persistent://myprop/clust/ns1/ds1");
    topics.run(split("stats-internal persistent://myprop/clust/ns1/ds1"));
    verify(mockTopics).getInternalStats("persistent://myprop/clust/ns1/ds1");
    topics.run(split("partitioned-stats persistent://myprop/clust/ns1/ds1 --per-partition"));
    verify(mockTopics).getPartitionedStats("persistent://myprop/clust/ns1/ds1", true);
    topics.run(split("skip-all persistent://myprop/clust/ns1/ds1 -s sub1"));
    verify(mockTopics).skipAllMessages("persistent://myprop/clust/ns1/ds1", "sub1");
    topics.run(split("skip persistent://myprop/clust/ns1/ds1 -s sub1 -n 100"));
    verify(mockTopics).skipMessages("persistent://myprop/clust/ns1/ds1", "sub1", 100);
    topics.run(split("expire-messages persistent://myprop/clust/ns1/ds1 -s sub1 -t 100"));
    verify(mockTopics).expireMessages("persistent://myprop/clust/ns1/ds1", "sub1", 100);
    topics.run(split("expire-messages-all-subscriptions persistent://myprop/clust/ns1/ds1 -t 100"));
    verify(mockTopics).expireMessagesForAllSubscriptions("persistent://myprop/clust/ns1/ds1", 100);
    topics.run(split("create-partitioned-topic persistent://myprop/clust/ns1/ds1 --partitions 32"));
    verify(mockTopics).createPartitionedTopic("persistent://myprop/clust/ns1/ds1", 32);
    topics.run(split("get-partitioned-topic-metadata persistent://myprop/clust/ns1/ds1"));
    verify(mockTopics).getPartitionedTopicMetadata("persistent://myprop/clust/ns1/ds1");
    topics.run(split("delete-partitioned-topic persistent://myprop/clust/ns1/ds1"));
    verify(mockTopics).deletePartitionedTopic("persistent://myprop/clust/ns1/ds1");
    topics.run(split("peek-messages persistent://myprop/clust/ns1/ds1 -s sub1 -n 3"));
    verify(mockTopics).peekMessages("persistent://myprop/clust/ns1/ds1", "sub1", 3);
    // range of +/- 1 second of the expected timestamp
    class TimestampMatcher extends ArgumentMatcher<Long> {

        @Override
        public boolean matches(Object argument) {
            long timestamp = (Long) argument;
            long expectedTimestamp = System.currentTimeMillis() - (1 * 60 * 1000);
            if (timestamp < (expectedTimestamp + 1000) && timestamp > (expectedTimestamp - 1000)) {
                return true;
            }
            return false;
        }
    }
    topics.run(split("reset-cursor persistent://myprop/clust/ns1/ds1 -s sub1 -t 1m"));
    verify(mockTopics).resetCursor(Matchers.eq("persistent://myprop/clust/ns1/ds1"), Matchers.eq("sub1"), Matchers.longThat(new TimestampMatcher()));
}
Also used : PulsarAdmin(com.yahoo.pulsar.client.admin.PulsarAdmin) ArgumentMatcher(org.mockito.ArgumentMatcher) PersistentTopics(com.yahoo.pulsar.client.admin.PersistentTopics) Test(org.testng.annotations.Test)

Example 85 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project powermock by powermock.

the class PowerMockMatchersBinder method bindMatchers.

public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, final Invocation invocation) {
    List<LocalizedMatcher> lastMatchers = argumentMatcherStorage.pullLocalizedMatchers();
    validateMatchers(invocation, lastMatchers);
    // In Mockito 2.0 LocalizedMatcher no more extend ArgumentMatcher, so new list should be created.
    final List<ArgumentMatcher> argumentMatchers = extractArgumentMatchers(lastMatchers);
    final InvocationMatcher invocationWithMatchers = new InvocationMatcher(invocation, argumentMatchers) {

        @Override
        public String toString() {
            return invocation.toString();
        }
    };
    return invocationWithMatchers;
}
Also used : LocalizedMatcher(org.mockito.internal.matchers.LocalizedMatcher) ArgumentMatcher(org.mockito.ArgumentMatcher) InvocationMatcher(org.mockito.internal.invocation.InvocationMatcher)

Aggregations

ArgumentMatcher (org.mockito.ArgumentMatcher)104 Test (org.junit.Test)82 Appender (ch.qos.logback.core.Appender)23 Logger (org.slf4j.Logger)23 ArrayList (java.util.ArrayList)19 Context (android.content.Context)14 Channel (com.microsoft.azure.mobile.channel.Channel)13 ApplicationService (org.codice.ddf.admin.application.service.ApplicationService)13 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)12 Intent (android.content.Intent)11 HashMap (java.util.HashMap)11 HashSet (java.util.HashSet)10 FeaturesService (org.apache.karaf.features.FeaturesService)10 ResolveInfo (android.content.pm.ResolveInfo)9 File (java.io.File)9 Repository (org.apache.karaf.features.Repository)9 Matchers.anyString (org.mockito.Matchers.anyString)9 UUID (java.util.UUID)8 ApplicationServiceException (org.codice.ddf.admin.application.service.ApplicationServiceException)8 Log (com.microsoft.azure.mobile.ingestion.models.Log)7