Search in sources :

Example 16 with ServiceCallback

use of com.microsoft.appcenter.http.ServiceCallback in project mobile-center-sdk-android by Microsoft.

the class DefaultChannelTest method maxRequestsInitial.

@Test
@SuppressWarnings("unchecked")
public void maxRequestsInitial() throws Persistence.PersistenceException {
    Persistence mockPersistence = mock(Persistence.class);
    IngestionHttp mockIngestion = mock(IngestionHttp.class);
    when(mockPersistence.countLogs(any(String.class))).thenReturn(100);
    when(mockPersistence.getLogs(any(String.class), anyInt(), any(ArrayList.class))).then(getGetLogsAnswer());
    final List<ServiceCallback> callbacks = new ArrayList<>();
    when(mockIngestion.sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class))).then(new Answer<Object>() {

        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            if (args[3] instanceof ServiceCallback) {
                callbacks.add((ServiceCallback) invocation.getArguments()[3]);
            }
            return null;
        }
    });
    /* Init channel with mocks. */
    DefaultChannel channel = new DefaultChannel(mock(Context.class), UUIDUtils.randomUUID().toString(), mockPersistence, mockIngestion, mCoreHandler);
    channel.addGroup(TEST_GROUP, 50, BATCH_TIME_INTERVAL, MAX_PARALLEL_BATCHES, null);
    /* Enqueue enough logs to be split in N + 1 maximum requests. */
    for (int i = 0; i < 100; i++) {
        channel.enqueue(mock(Log.class), TEST_GROUP);
    }
    /* Verify all logs stored, N requests sent, not log deleted yet. */
    verify(mockPersistence, times(100)).putLog(eq(TEST_GROUP), any(Log.class));
    verify(mockIngestion, times(3)).sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class));
    verify(mockPersistence, never()).deleteLogs(any(String.class), any(String.class));
    /* Make 1 of the call succeed. Verify log deleted. */
    callbacks.get(0).onCallSucceeded("");
    verify(mockPersistence).deleteLogs(any(String.class), any(String.class));
    /* The request N+1 is now unlocked. */
    verify(mockIngestion, times(4)).sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class));
    /* Unlock all requests and check logs deleted. */
    for (int i = 1; i < 4; i++) callbacks.get(i).onCallSucceeded("");
    verify(mockPersistence, times(4)).deleteLogs(any(String.class), any(String.class));
    /* The counter should be 0 now as we sent data. */
    assertEquals(0, channel.getCounter(TEST_GROUP));
    /* Only 2 batches after channel start (non initial logs), verify timer interactions. */
    verify(mHandler, times(2)).postDelayed(any(Runnable.class), eq(BATCH_TIME_INTERVAL));
    verify(mHandler, times(2)).removeCallbacks(any(Runnable.class));
}
Also used : Context(android.content.Context) Log(com.microsoft.appcenter.ingestion.models.Log) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) Persistence(com.microsoft.appcenter.persistence.Persistence) IngestionHttp(com.microsoft.appcenter.ingestion.IngestionHttp) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) InvocationOnMock(org.mockito.invocation.InvocationOnMock) LogContainer(com.microsoft.appcenter.ingestion.models.LogContainer) UUID(java.util.UUID) Test(org.junit.Test)

Example 17 with ServiceCallback

use of com.microsoft.appcenter.http.ServiceCallback in project mobile-center-sdk-android by Microsoft.

the class IngestionHttpTest method sendAsync.

@Test
public void sendAsync() throws Exception {
    /* Build some payload. */
    LogContainer container = new LogContainer();
    Log log = mock(Log.class);
    List<Log> logs = new ArrayList<>();
    logs.add(log);
    container.setLogs(logs);
    LogSerializer serializer = mock(LogSerializer.class);
    when(serializer.serializeContainer(any(LogContainer.class))).thenReturn("mockPayload");
    /* Configure mock HTTP. */
    HttpClientNetworkStateHandler httpClient = mock(HttpClientNetworkStateHandler.class);
    whenNew(HttpClientNetworkStateHandler.class).withAnyArguments().thenReturn(httpClient);
    final ServiceCall call = mock(ServiceCall.class);
    final AtomicReference<HttpClient.CallTemplate> callTemplate = new AtomicReference<>();
    when(httpClient.callAsync(anyString(), anyString(), anyMapOf(String.class, String.class), any(HttpClient.CallTemplate.class), any(ServiceCallback.class))).then(new Answer<ServiceCall>() {

        @Override
        public ServiceCall answer(InvocationOnMock invocation) throws Throwable {
            callTemplate.set((HttpClient.CallTemplate) invocation.getArguments()[3]);
            return call;
        }
    });
    /* Test calling code. */
    IngestionHttp ingestionHttp = new IngestionHttp(mock(Context.class), serializer);
    ingestionHttp.setLogUrl("http://mock");
    String appSecret = UUIDUtils.randomUUID().toString();
    UUID installId = UUIDUtils.randomUUID();
    ServiceCallback serviceCallback = mock(ServiceCallback.class);
    assertEquals(call, ingestionHttp.sendAsync(appSecret, installId, container, serviceCallback));
    /* Verify call to http client. */
    HashMap<String, String> expectedHeaders = new HashMap<>();
    expectedHeaders.put(IngestionHttp.APP_SECRET, appSecret);
    expectedHeaders.put(IngestionHttp.INSTALL_ID, installId.toString());
    verify(httpClient).callAsync(eq("http://mock" + IngestionHttp.API_PATH), eq(METHOD_POST), eq(expectedHeaders), notNull(HttpClient.CallTemplate.class), eq(serviceCallback));
    assertNotNull(callTemplate.get());
    assertEquals("mockPayload", callTemplate.get().buildRequestBody());
    /* Verify close. */
    ingestionHttp.close();
    verify(httpClient).close();
    /* Verify reopen. */
    ingestionHttp.reopen();
    verify(httpClient).reopen();
}
Also used : Context(android.content.Context) ServiceCall(com.microsoft.appcenter.http.ServiceCall) AppCenterLog(com.microsoft.appcenter.utils.AppCenterLog) Log(com.microsoft.appcenter.ingestion.models.Log) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) LogSerializer(com.microsoft.appcenter.ingestion.models.json.LogSerializer) Matchers.anyString(org.mockito.Matchers.anyString) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) InvocationOnMock(org.mockito.invocation.InvocationOnMock) LogContainer(com.microsoft.appcenter.ingestion.models.LogContainer) HttpClientNetworkStateHandler(com.microsoft.appcenter.http.HttpClientNetworkStateHandler) UUID(java.util.UUID) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 18 with ServiceCallback

use of com.microsoft.appcenter.http.ServiceCallback in project mobile-center-sdk-android by Microsoft.

the class AbstractDistributeAfterDownloadTest method setUpDownload.

void setUpDownload(boolean mandatoryUpdate) throws Exception {
    /* Allow unknown sources. */
    when(InstallerUtils.isUnknownSourcesEnabled(any(Context.class))).thenReturn(true);
    /* Mock download manager. */
    when(mContext.getSystemService(Context.DOWNLOAD_SERVICE)).thenReturn(mDownloadManager);
    whenNew(DownloadManager.Request.class).withAnyArguments().thenReturn(mDownloadRequest);
    when(mDownloadManager.enqueue(mDownloadRequest)).thenReturn(DOWNLOAD_ID);
    /* Mock notification manager. */
    when(mContext.getSystemService(NOTIFICATION_SERVICE)).thenReturn(mNotificationManager);
    /* Mock updates to storage. */
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            when(PreferencesStorage.getLong(invocation.getArguments()[0].toString(), INVALID_DOWNLOAD_IDENTIFIER)).thenReturn((Long) invocation.getArguments()[1]);
            return null;
        }
    }).when(PreferencesStorage.class);
    PreferencesStorage.putLong(eq(PREFERENCE_KEY_DOWNLOAD_ID), anyLong());
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            when(PreferencesStorage.getLong(invocation.getArguments()[0].toString(), INVALID_DOWNLOAD_IDENTIFIER)).thenReturn(INVALID_DOWNLOAD_IDENTIFIER);
            return null;
        }
    }).when(PreferencesStorage.class);
    PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_ID);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            when(PreferencesStorage.getInt(invocation.getArguments()[0].toString(), DOWNLOAD_STATE_COMPLETED)).thenReturn((Integer) invocation.getArguments()[1]);
            return null;
        }
    }).when(PreferencesStorage.class);
    PreferencesStorage.putInt(eq(PREFERENCE_KEY_DOWNLOAD_STATE), anyInt());
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            when(PreferencesStorage.getInt(invocation.getArguments()[0].toString(), DOWNLOAD_STATE_COMPLETED)).thenReturn(DOWNLOAD_STATE_COMPLETED);
            return null;
        }
    }).when(PreferencesStorage.class);
    PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_STATE);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            when(PreferencesStorage.getString(invocation.getArguments()[0].toString())).thenReturn(invocation.getArguments()[1].toString());
            return null;
        }
    }).when(PreferencesStorage.class);
    PreferencesStorage.putString(eq(PREFERENCE_KEY_RELEASE_DETAILS), anyString());
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            when(PreferencesStorage.getString(invocation.getArguments()[0].toString())).thenReturn(null);
            return null;
        }
    }).when(PreferencesStorage.class);
    PreferencesStorage.remove(PREFERENCE_KEY_RELEASE_DETAILS);
    /* Mock everything that triggers a download. */
    when(PreferencesStorage.getString(PREFERENCE_KEY_DISTRIBUTION_GROUP_ID)).thenReturn("some group");
    when(PreferencesStorage.getString(PREFERENCE_KEY_UPDATE_TOKEN)).thenReturn("some token");
    HttpClientNetworkStateHandler httpClient = mock(HttpClientNetworkStateHandler.class);
    whenNew(HttpClientNetworkStateHandler.class).withAnyArguments().thenReturn(httpClient);
    when(httpClient.callAsync(anyString(), anyString(), anyMapOf(String.class, String.class), any(HttpClient.CallTemplate.class), any(ServiceCallback.class))).thenAnswer(new Answer<ServiceCall>() {

        @Override
        public ServiceCall answer(InvocationOnMock invocation) throws Throwable {
            ((ServiceCallback) invocation.getArguments()[4]).onCallSucceeded("mock");
            return mock(ServiceCall.class);
        }
    });
    ReleaseDetails releaseDetails = mock(ReleaseDetails.class);
    when(releaseDetails.getId()).thenReturn(4);
    when(releaseDetails.getVersion()).thenReturn(7);
    when(releaseDetails.getDownloadUrl()).thenReturn(mDownloadUrl);
    when(releaseDetails.isMandatoryUpdate()).thenReturn(mandatoryUpdate);
    when(ReleaseDetails.parse(anyString())).thenReturn(releaseDetails);
    mockStatic(AsyncTaskUtils.class);
    start();
    Distribute.getInstance().onActivityResumed(mActivity);
    /* Mock download asyncTask. */
    mDownloadBeforeSemaphore = new Semaphore(0);
    mDownloadAfterSemaphore = new Semaphore(0);
    mDownloadTask = new AtomicReference<>();
    when(AsyncTaskUtils.execute(anyString(), argThat(new ArgumentMatcher<DownloadTask>() {

        @Override
        public boolean matches(Object argument) {
            return argument instanceof DownloadTask;
        }
    }), Mockito.<Void>anyVararg())).then(new Answer<DownloadTask>() {

        @Override
        public DownloadTask answer(InvocationOnMock invocation) throws Throwable {
            final DownloadTask task = spy((DownloadTask) invocation.getArguments()[1]);
            mDownloadTask.set(task);
            new Thread() {

                @Override
                public void run() {
                    mDownloadBeforeSemaphore.acquireUninterruptibly();
                    task.doInBackground(null);
                    mDownloadAfterSemaphore.release();
                }
            }.start();
            return task;
        }
    });
    /* Mock remove download async task. */
    when(AsyncTaskUtils.execute(anyString(), argThat(new ArgumentMatcher<RemoveDownloadTask>() {

        @Override
        public boolean matches(Object argument) {
            return argument instanceof RemoveDownloadTask;
        }
    }), Mockito.<Void>anyVararg())).then(new Answer<RemoveDownloadTask>() {

        @Override
        public RemoveDownloadTask answer(InvocationOnMock invocation) throws Throwable {
            final RemoveDownloadTask task = (RemoveDownloadTask) invocation.getArguments()[1];
            task.doInBackground();
            return task;
        }
    });
    /* Mock download completion async task. */
    mCheckDownloadBeforeSemaphore = new Semaphore(0);
    mCheckDownloadAfterSemaphore = new Semaphore(0);
    mCompletionTask = new AtomicReference<>();
    when(AsyncTaskUtils.execute(anyString(), argThat(sCheckCompleteTask), Mockito.<Void>anyVararg())).then(new Answer<CheckDownloadTask>() {

        @Override
        public CheckDownloadTask answer(InvocationOnMock invocation) throws Throwable {
            final CheckDownloadTask task = spy((CheckDownloadTask) invocation.getArguments()[1]);
            mCompletionTask.set(task);
            new Thread() {

                @Override
                public void run() {
                    mCheckDownloadBeforeSemaphore.acquireUninterruptibly();
                    task.onPostExecute(task.doInBackground());
                    mCheckDownloadAfterSemaphore.release();
                }
            }.start();
            return task;
        }
    });
    /* Click on dialog. */
    ArgumentCaptor<DialogInterface.OnClickListener> clickListener = ArgumentCaptor.forClass(DialogInterface.OnClickListener.class);
    verify(mDialogBuilder).setPositiveButton(eq(R.string.appcenter_distribute_update_dialog_download), clickListener.capture());
    clickListener.getValue().onClick(mDialog, DialogInterface.BUTTON_POSITIVE);
}
Also used : DialogInterface(android.content.DialogInterface) Matchers.anyString(org.mockito.Matchers.anyString) Semaphore(java.util.concurrent.Semaphore) DownloadManager(android.app.DownloadManager) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) ArgumentMatcher(org.mockito.ArgumentMatcher) Context(android.content.Context) ServiceCall(com.microsoft.appcenter.http.ServiceCall) PowerMockito.doAnswer(org.powermock.api.mockito.PowerMockito.doAnswer) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpClientNetworkStateHandler(com.microsoft.appcenter.http.HttpClientNetworkStateHandler)

Example 19 with ServiceCallback

use of com.microsoft.appcenter.http.ServiceCallback in project mobile-center-sdk-android by Microsoft.

the class DistributeBeforeApiSuccessTest method disableBeforeCheckReleaseSucceed.

@Test
public void disableBeforeCheckReleaseSucceed() throws Exception {
    /* Mock we already have token. */
    when(PreferencesStorage.getString(PREFERENCE_KEY_UPDATE_TOKEN)).thenReturn("some token");
    HttpClientNetworkStateHandler httpClient = mock(HttpClientNetworkStateHandler.class);
    whenNew(HttpClientNetworkStateHandler.class).withAnyArguments().thenReturn(httpClient);
    final Semaphore beforeSemaphore = new Semaphore(0);
    final Semaphore afterSemaphore = new Semaphore(0);
    when(httpClient.callAsync(anyString(), anyString(), anyMapOf(String.class, String.class), any(HttpClient.CallTemplate.class), any(ServiceCallback.class))).thenAnswer(new Answer<ServiceCall>() {

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

                @Override
                public void run() {
                    beforeSemaphore.acquireUninterruptibly();
                    ((ServiceCallback) invocation.getArguments()[4]).onCallSucceeded("mock");
                    afterSemaphore.release();
                }
            }.start();
            return mock(ServiceCall.class);
        }
    });
    HashMap<String, String> headers = new HashMap<>();
    headers.put(DistributeConstants.HEADER_API_TOKEN, "some token");
    /* Trigger call. */
    start();
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    verify(httpClient).callAsync(anyString(), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
    /* Disable before it succeeds. */
    Distribute.setEnabled(false);
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_STATE);
    verifyStatic(never());
    PreferencesStorage.remove(PREFERENCE_KEY_UPDATE_TOKEN);
    beforeSemaphore.release();
    afterSemaphore.acquireUninterruptibly();
    /* Verify complete workflow call skipped. i.e. no more call to delete the state. */
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_STATE);
    /* After that if we resume app nothing happens. */
    Distribute.getInstance().onActivityPaused(mock(Activity.class));
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    verify(httpClient).callAsync(anyString(), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
    verify(mDialog, never()).show();
}
Also used : ServiceCall(com.microsoft.appcenter.http.ServiceCall) HashMap(java.util.HashMap) Activity(android.app.Activity) Semaphore(java.util.concurrent.Semaphore) Matchers.anyString(org.mockito.Matchers.anyString) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpClientNetworkStateHandler(com.microsoft.appcenter.http.HttpClientNetworkStateHandler) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 20 with ServiceCallback

use of com.microsoft.appcenter.http.ServiceCallback in project mobile-center-sdk-android by Microsoft.

the class DistributeBeforeApiSuccessTest method checkReleaseFailsParsing.

@Test
public void checkReleaseFailsParsing() throws Exception {
    /* Mock we already have token. */
    when(PreferencesStorage.getString(PREFERENCE_KEY_UPDATE_TOKEN)).thenReturn("some token");
    HttpClientNetworkStateHandler httpClient = mock(HttpClientNetworkStateHandler.class);
    whenNew(HttpClientNetworkStateHandler.class).withAnyArguments().thenReturn(httpClient);
    when(httpClient.callAsync(anyString(), anyString(), anyMapOf(String.class, String.class), any(HttpClient.CallTemplate.class), any(ServiceCallback.class))).thenAnswer(new Answer<ServiceCall>() {

        @Override
        public ServiceCall answer(InvocationOnMock invocation) throws Throwable {
            ((ServiceCallback) invocation.getArguments()[4]).onCallSucceeded("mock");
            return mock(ServiceCall.class);
        }
    });
    HashMap<String, String> headers = new HashMap<>();
    headers.put(DistributeConstants.HEADER_API_TOKEN, "some token");
    when(ReleaseDetails.parse(anyString())).thenThrow(new JSONException("mock"));
    /* Trigger call. */
    start();
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    verify(httpClient).callAsync(anyString(), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
    /* Verify on failure we complete workflow. */
    verifyStatic();
    PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_STATE);
    /* After that if we resume app nothing happens. */
    Distribute.getInstance().onActivityPaused(mock(Activity.class));
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    verify(httpClient).callAsync(anyString(), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
}
Also used : ServiceCall(com.microsoft.appcenter.http.ServiceCall) HashMap(java.util.HashMap) JSONException(org.json.JSONException) Activity(android.app.Activity) Matchers.anyString(org.mockito.Matchers.anyString) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpClientNetworkStateHandler(com.microsoft.appcenter.http.HttpClientNetworkStateHandler) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

ServiceCallback (com.microsoft.appcenter.http.ServiceCallback)33 InvocationOnMock (org.mockito.invocation.InvocationOnMock)28 ServiceCall (com.microsoft.appcenter.http.ServiceCall)25 Matchers.anyString (org.mockito.Matchers.anyString)25 HttpClientNetworkStateHandler (com.microsoft.appcenter.http.HttpClientNetworkStateHandler)24 Test (org.junit.Test)24 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)19 Activity (android.app.Activity)18 HashMap (java.util.HashMap)13 Context (android.content.Context)10 UUID (java.util.UUID)9 DialogInterface (android.content.DialogInterface)8 LogContainer (com.microsoft.appcenter.ingestion.models.LogContainer)8 Log (com.microsoft.appcenter.ingestion.models.Log)7 Semaphore (java.util.concurrent.Semaphore)6 JSONException (org.json.JSONException)6 Persistence (com.microsoft.appcenter.persistence.Persistence)5 IOException (java.io.IOException)5 IngestionHttp (com.microsoft.appcenter.ingestion.IngestionHttp)4 ArrayList (java.util.ArrayList)4