Search in sources :

Example 66 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.appcenter_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 67 with ArgumentMatcher

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

the class AppCenterTest method uncaughtExceptionHandlerInterrupted.

@Test
public void uncaughtExceptionHandlerInterrupted() throws Exception {
    /* Mock semaphore to be interrupted while waiting. */
    Semaphore semaphore = mock(Semaphore.class);
    whenNew(Semaphore.class).withAnyArguments().thenReturn(semaphore);
    when(semaphore.tryAcquire(anyLong(), any(TimeUnit.class))).thenThrow(new InterruptedException());
    /* Setup mock App Center. */
    Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = mock(Thread.UncaughtExceptionHandler.class);
    when(Thread.getDefaultUncaughtExceptionHandler()).thenReturn(defaultUncaughtExceptionHandler);
    AppCenter.configure(mApplication, DUMMY_APP_SECRET);
    AppCenter.UncaughtExceptionHandler handler = AppCenter.getInstance().getUncaughtExceptionHandler();
    assertNotNull(handler);
    assertEquals(defaultUncaughtExceptionHandler, handler.getDefaultUncaughtExceptionHandler());
    verifyStatic();
    Thread.setDefaultUncaughtExceptionHandler(eq(handler));
    /* Simulate crash to shutdown channel. */
    Thread thread = mock(Thread.class);
    Throwable exception = mock(Throwable.class);
    handler.uncaughtException(thread, exception);
    /* Channel still shut down in the thread, the interruption is in the waiting one. */
    verify(mChannel).shutdown();
    /* Verify we still chain exception handlers correctly. */
    verify(defaultUncaughtExceptionHandler).uncaughtException(eq(thread), eq(exception));
    /* Verify we log a warning on interruption. */
    verifyStatic();
    AppCenterLog.warn(eq(LOG_TAG), anyString(), argThat(new ArgumentMatcher<Throwable>() {

        @Override
        public boolean matches(Object argument) {
            return argument instanceof InterruptedException;
        }
    }));
}
Also used : ArgumentMatcher(org.mockito.ArgumentMatcher) TimeUnit(java.util.concurrent.TimeUnit) Matchers.anyObject(org.mockito.Matchers.anyObject) Semaphore(java.util.concurrent.Semaphore) HandlerThread(android.os.HandlerThread) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 68 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));
    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, mCoreHandler);
    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.appcenter.http.ServiceCall) Log(com.microsoft.appcenter.ingestion.models.Log) Semaphore(java.util.concurrent.Semaphore) Persistence(com.microsoft.appcenter.persistence.Persistence) IngestionHttp(com.microsoft.appcenter.ingestion.IngestionHttp) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) CancellationException(com.microsoft.appcenter.CancellationException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ArgumentMatcher(org.mockito.ArgumentMatcher) LogContainer(com.microsoft.appcenter.ingestion.models.LogContainer) UUID(java.util.UUID) Test(org.junit.Test)

Example 69 with ArgumentMatcher

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

the class DefaultHttpClientTest method get200image.

@Test
public void get200image() throws Exception {
    /* Set log level to verbose to test shorter app secret as well. */
    AppCenter.setLogLevel(VERBOSE);
    /* Configure mock HTTP. */
    String urlString = "http://mock/get";
    URL url = mock(URL.class);
    whenNew(URL.class).withArguments(urlString).thenReturn(url);
    HttpURLConnection urlConnection = mock(HttpURLConnection.class);
    when(url.openConnection()).thenReturn(urlConnection);
    when(urlConnection.getResponseCode()).thenReturn(200);
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    when(urlConnection.getOutputStream()).thenReturn(buffer);
    ByteArrayInputStream inputStream = spy(new ByteArrayInputStream("fake binary".getBytes()));
    when(urlConnection.getInputStream()).thenReturn(inputStream);
    when(urlConnection.getHeaderField("Content-Type")).thenReturn("image/png");
    /* Configure API client. */
    HttpClient.CallTemplate callTemplate = mock(HttpClient.CallTemplate.class);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    /* Test calling code. */
    Map<String, String> headers = new HashMap<>();
    ServiceCallback serviceCallback = mock(ServiceCallback.class);
    mockCall();
    httpClient.callAsync(urlString, METHOD_GET, headers, callTemplate, serviceCallback);
    verify(serviceCallback).onCallSucceeded("fake binary");
    verifyNoMoreInteractions(serviceCallback);
    verify(urlConnection).setRequestMethod("GET");
    verify(urlConnection, never()).setDoOutput(true);
    verify(urlConnection).disconnect();
    verify(inputStream).close();
    verify(callTemplate).onBeforeCalling(eq(url), anyMapOf(String.class, String.class));
    verify(callTemplate, never()).buildRequestBody();
    httpClient.close();
    /* Test binary placeholder used in logging code instead of real payload. */
    verifyStatic();
    AppCenterLog.info(anyString(), argThat(new ArgumentMatcher<String>() {

        @Override
        public boolean matches(Object argument) {
            String logMessage = argument.toString();
            return logMessage.contains("<binary>") && !logMessage.contains("fake binary");
        }
    }));
}
Also used : HashMap(java.util.HashMap) Matchers.anyString(org.mockito.Matchers.anyString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) ByteArrayInputStream(java.io.ByteArrayInputStream) ArgumentMatcher(org.mockito.ArgumentMatcher) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 70 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project core-java by SpineEventEngine.

the class StandShould method entityFilterMatcher.

@SuppressWarnings("OverlyComplexAnonymousInnerClass")
private static ArgumentMatcher<EntityFilters> entityFilterMatcher(final Collection<ProjectId> projectIds) {
    // ALL the expected IDs.
    return new ArgumentMatcher<EntityFilters>() {

        @Override
        public boolean matches(EntityFilters argument) {
            boolean everyElementPresent = true;
            for (EntityId entityId : argument.getIdFilter().getIdsList()) {
                final Any idAsAny = entityId.getId();
                final Message rawId = unpack(idAsAny);
                if (rawId instanceof ProjectId) {
                    final ProjectId convertedProjectId = (ProjectId) rawId;
                    everyElementPresent = everyElementPresent && projectIds.contains(convertedProjectId);
                } else {
                    everyElementPresent = false;
                }
            }
            return everyElementPresent;
        }
    };
}
Also used : EntityId(io.spine.client.EntityId) Message(com.google.protobuf.Message) ArgumentMatcher(org.mockito.ArgumentMatcher) EntityFilters(io.spine.client.EntityFilters) ProjectId(io.spine.test.projection.ProjectId) Any(com.google.protobuf.Any)

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