Search in sources :

Example 21 with HttpResponse

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

the class DefaultChannelRaceConditionTest method disabledWhileHandlingIngestionSuccess.

@Test(timeout = 5000)
public void disabledWhileHandlingIngestionSuccess() {
    /* 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(), anyListOf(String.class), eq(1), anyListOf(Log.class))).then(getGetLogsAnswer(1));
    when(mockPersistence.getLogs(anyString(), anyListOf(String.class), eq(CLEAR_BATCH_SIZE), anyListOf(Log.class))).then(getGetLogsAnswer(0));
    AppCenterIngestion mockIngestion = mock(AppCenterIngestion.class);
    when(mockIngestion.isEnabled()).thenReturn(true);
    when(mockIngestion.sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class))).then(new Answer<Object>() {

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

                @Override
                public void run() {
                    beforeCallSemaphore.acquireUninterruptibly();
                    ((ServiceCallback) invocation.getArguments()[3]).onCallSucceeded(new HttpResponse(200, ""));
                    afterCallSemaphore.release();
                }
            }.start();
            return mock(ServiceCall.class);
        }
    });
    /* Simulate enable module then disable. */
    DefaultChannel channel = new DefaultChannel(mock(Context.class), UUID.randomUUID().toString(), mockPersistence, mockIngestion, mAppCenterHandler);
    Channel.GroupListener listener = mock(Channel.GroupListener.class);
    channel.addGroup(TEST_GROUP, 1, BATCH_TIME_INTERVAL, MAX_PARALLEL_BATCHES, null, 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;
        }
    }));
    verify(mockPersistence, never()).deleteLogs(anyString(), anyString());
}
Also used : Context(android.content.Context) ServiceCall(com.microsoft.appcenter.http.ServiceCall) Log(com.microsoft.appcenter.ingestion.models.Log) HttpResponse(com.microsoft.appcenter.http.HttpResponse) Semaphore(java.util.concurrent.Semaphore) Matchers.anyString(org.mockito.Matchers.anyString) Persistence(com.microsoft.appcenter.persistence.Persistence) AppCenterIngestion(com.microsoft.appcenter.ingestion.AppCenterIngestion) 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 22 with HttpResponse

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

the class DefaultChannelTest method checkPendingLogsSendsAllBatchesIfTimerIsOver.

@Test
public void checkPendingLogsSendsAllBatchesIfTimerIsOver() {
    /* Mock current time. */
    long now = 5000;
    when(System.currentTimeMillis()).thenReturn(now);
    /* Mock stored start time. */
    long startTimer = 1000;
    when(SharedPreferencesManager.getLong(eq(START_TIMER_PREFIX + TEST_GROUP))).thenReturn(startTimer);
    /* Mock persistence. */
    Persistence mockPersistence = mock(Persistence.class);
    when(mockPersistence.getLogs(any(String.class), anyListOf(String.class), anyInt(), anyListOf(Log.class))).then(getGetLogsAnswer()).then(getGetLogsAnswer(50)).then(getGetLogsAnswer(50)).then(getGetLogsAnswer(50)).then(getGetLogsAnswer(50)).then(getGetLogsAnswer(0));
    /* Mock sending logs. */
    final List<ServiceCallback> callbacks = new ArrayList<>();
    AppCenterIngestion mockIngestion = mock(AppCenterIngestion.class);
    when(mockIngestion.isEnabled()).thenReturn(true);
    when(mockIngestion.sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class))).then(new Answer<Object>() {

        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            if (args[3] instanceof ServiceCallback) {
                callbacks.add((ServiceCallback) invocation.getArguments()[3]);
            }
            return null;
        }
    });
    /* Create channel and group. */
    DefaultChannel channel = spy(new DefaultChannel(mock(Context.class), UUID.randomUUID().toString(), mockPersistence, mockIngestion, mAppCenterHandler));
    channel.addGroup(TEST_GROUP, 50, CUSTOM_INTERVAL, MAX_PARALLEL_BATCHES, null, mock(Channel.GroupListener.class));
    /* Prepare to mock timer. */
    long timeDelay = CUSTOM_INTERVAL - (now - startTimer);
    /* Enqueuing 200 events. */
    for (int i = 0; i < 200; i++) {
        channel.enqueue(mock(Log.class), TEST_GROUP, Flags.DEFAULTS);
    }
    /* Check invoke the timer with custom timestamp. */
    ArgumentCaptor<Runnable> delayedRunnable = ArgumentCaptor.forClass(Runnable.class);
    verify(mAppCenterHandler).postDelayed(delayedRunnable.capture(), eq(timeDelay));
    /* Wait for timer. */
    now = 12000;
    when(System.currentTimeMillis()).thenReturn(now);
    delayedRunnable.getValue().run();
    /* Check sending the logs batches. */
    verify(mockIngestion, times(3)).sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class));
    /* Successful finish one of sending the log. */
    callbacks.get(0).onCallSucceeded(new HttpResponse(200, ""));
    verify(mockPersistence).deleteLogs(any(String.class), any(String.class));
    /* Check rest logs sending. */
    verify(mockIngestion, times(4)).sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class));
}
Also used : Log(com.microsoft.appcenter.ingestion.models.Log) ArrayList(java.util.ArrayList) HttpResponse(com.microsoft.appcenter.http.HttpResponse) Matchers.anyString(org.mockito.Matchers.anyString) Persistence(com.microsoft.appcenter.persistence.Persistence) AppCenterIngestion(com.microsoft.appcenter.ingestion.AppCenterIngestion) 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 23 with HttpResponse

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

the class MSAAuthenticationProvider method acquireToken.

@Override
public void acquireToken(String ticketKey, final AuthenticationProvider.AuthenticationCallback callback) {
    Map<String, String> headers = new HashMap<>();
    headers.put(DefaultHttpClient.CONTENT_TYPE_KEY, "application/x-www-form-urlencoded");
    mHttpClient.callAsync(TOKEN_URL, DefaultHttpClient.METHOD_POST, headers, new HttpClient.CallTemplate() {

        @Override
        public String buildRequestBody() {
            return REDIRECT_URI_PARAM + CLIENT_ID_PARAM + "&grant_type=" + REFRESH_TOKEN + "&" + REFRESH_TOKEN + "=" + mRefreshToken + "&scope=" + mRefreshTokenScope;
        }

        @Override
        public void onBeforeCalling(URL url, Map<String, String> headers) {
            AppCenterLog.verbose(AppCenter.LOG_TAG, "Calling " + url + "...");
        }
    }, new ServiceCallback() {

        @Override
        public void onCallSucceeded(HttpResponse httpResponse) {
            try {
                JSONObject response = new JSONObject(httpResponse.getPayload());
                String accessToken = response.getString("access_token");
                String userId = response.getString(USER_ID);
                long expiresIn = response.getLong(EXPIRES_IN) * 1000L;
                Date expiryDate = new Date(System.currentTimeMillis() + expiresIn);
                sSharedPreferences.edit().putString(MSA_REFRESH_TOKEN_KEY, mRefreshToken).apply();
                sSharedPreferences.edit().putString(MSA_TOKEN_KEY, userId).apply();
                callback.onAuthenticationResult(accessToken, expiryDate);
            } catch (JSONException e) {
                onCallFailed(e);
            }
        }

        @Override
        public void onCallFailed(Exception e) {
            callback.onAuthenticationResult(null, null);
            handleCallFailure(e);
        }
    });
}
Also used : HashMap(java.util.HashMap) HttpResponse(com.microsoft.appcenter.http.HttpResponse) JSONException(org.json.JSONException) URL(java.net.URL) Date(java.util.Date) HttpException(com.microsoft.appcenter.http.HttpException) JSONException(org.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) JSONObject(org.json.JSONObject) HttpUtils.createHttpClient(com.microsoft.appcenter.http.HttpUtils.createHttpClient) HttpClient(com.microsoft.appcenter.http.HttpClient) DefaultHttpClient(com.microsoft.appcenter.http.DefaultHttpClient)

Example 24 with HttpResponse

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

the class DistributeBeforeDownloadTest method postponeDialog.

@Test
public void postponeDialog() throws Exception {
    /* Mock we already have redirection parameters. */
    when(SharedPreferencesManager.getString(PREFERENCE_KEY_DISTRIBUTION_GROUP_ID)).thenReturn("some group");
    when(SharedPreferencesManager.getString(PREFERENCE_KEY_UPDATE_TOKEN)).thenReturn("some token");
    mockSessionContext();
    when(mHttpClient.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) {
            ((ServiceCallback) invocation.getArguments()[4]).onCallSucceeded(new HttpResponse(200, "mock"));
            return mock(ServiceCall.class);
        }
    });
    ReleaseDetails releaseDetails = mock(ReleaseDetails.class);
    when(releaseDetails.getId()).thenReturn(4);
    when(releaseDetails.getVersion()).thenReturn(7);
    String distributionGroupId = UUID.randomUUID().toString();
    when(releaseDetails.getDistributionGroupId()).thenReturn(distributionGroupId);
    when(ReleaseDetails.parse(anyString())).thenReturn(releaseDetails);
    /* Trigger call. */
    start();
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    /* Verify dialog. */
    ArgumentCaptor<DialogInterface.OnClickListener> clickListener = ArgumentCaptor.forClass(DialogInterface.OnClickListener.class);
    verify(mDialogBuilder).setNegativeButton(eq(R.string.appcenter_distribute_update_dialog_postpone), clickListener.capture());
    verify(mDialog).show();
    /* Postpone it. */
    long now = 20122112L;
    mockStatic(System.class);
    when(System.currentTimeMillis()).thenReturn(now);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) {
            when(SharedPreferencesManager.getLong(invocation.getArguments()[0].toString(), 0)).thenReturn((Long) invocation.getArguments()[1]);
            return null;
        }
    }).when(SharedPreferencesManager.class);
    SharedPreferencesManager.putLong(eq(PREFERENCE_KEY_POSTPONE_TIME), anyLong());
    clickListener.getValue().onClick(mDialog, DialogInterface.BUTTON_NEGATIVE);
    when(mDialog.isShowing()).thenReturn(false);
    /* Verify. */
    verifyStatic();
    SharedPreferencesManager.remove(PREFERENCE_KEY_DOWNLOAD_STATE);
    verifyStatic();
    SharedPreferencesManager.remove(PREFERENCE_KEY_RELEASE_DETAILS);
    verifyStatic();
    SharedPreferencesManager.putLong(eq(PREFERENCE_KEY_POSTPONE_TIME), eq(now));
    /* Verify we didn't track distribution group stats since we already had redirection parameters. */
    verifyStatic(never());
    SharedPreferencesManager.putString(PREFERENCE_KEY_DISTRIBUTION_GROUP_ID, distributionGroupId);
    verify(mDistributeInfoTracker, never()).updateDistributionGroupId(distributionGroupId);
    verify(mChannel, never()).enqueue(any(DistributionStartSessionLog.class), eq(Distribute.getInstance().getGroupName()), eq(DEFAULTS));
    /* Verify no more calls, e.g. happened only once. */
    Distribute.getInstance().onActivityPaused(mock(Activity.class));
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    verify(mDialog).show();
    verify(mHttpClient).callAsync(anyString(), anyString(), anyMapOf(String.class, String.class), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
    /* Restart should check release and should not show dialog again until 1 day has elapsed. */
    now += DistributeConstants.POSTPONE_TIME_THRESHOLD - 1;
    when(System.currentTimeMillis()).thenReturn(now);
    restartProcessAndSdk();
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    verify(mDialog).show();
    /* Now its time to show again. */
    now += 1;
    when(System.currentTimeMillis()).thenReturn(now);
    restartProcessAndSdk();
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    verify(mDialog, times(2)).show();
    /* Postpone again. */
    clickListener = ArgumentCaptor.forClass(DialogInterface.OnClickListener.class);
    verify(mDialogBuilder, times(2)).setNegativeButton(eq(R.string.appcenter_distribute_update_dialog_postpone), clickListener.capture());
    clickListener.getValue().onClick(mDialog, DialogInterface.BUTTON_NEGATIVE);
    /* Check postpone again. */
    restartProcessAndSdk();
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    verify(mDialog, times(2)).show();
    /* If mandatory release, we ignore postpone and still show dialog. */
    when(releaseDetails.isMandatoryUpdate()).thenReturn(true);
    restartProcessAndSdk();
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    verify(mDialog, times(3)).show();
    /* Set back in time to make SDK clean state and force update. */
    verifyStatic(never());
    SharedPreferencesManager.remove(PREFERENCE_KEY_POSTPONE_TIME);
    when(releaseDetails.isMandatoryUpdate()).thenReturn(false);
    now = 1;
    when(System.currentTimeMillis()).thenReturn(now);
    restartProcessAndSdk();
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    verify(mDialog, times(4)).show();
    verifyStatic();
    SharedPreferencesManager.remove(PREFERENCE_KEY_POSTPONE_TIME);
}
Also used : ServiceCall(com.microsoft.appcenter.http.ServiceCall) DialogInterface(android.content.DialogInterface) DistributionStartSessionLog(com.microsoft.appcenter.distribute.ingestion.models.DistributionStartSessionLog) HttpResponse(com.microsoft.appcenter.http.HttpResponse) Activity(android.app.Activity) Matchers.anyString(org.mockito.Matchers.anyString) PowerMockito.doAnswer(org.powermock.api.mockito.PowerMockito.doAnswer) Answer(org.mockito.stubbing.Answer) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 25 with HttpResponse

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

the class DistributeBeforeDownloadTest method updateASecondTimeClearsPreviousReleaseCache.

@Test
public void updateASecondTimeClearsPreviousReleaseCache() throws Exception {
    /* Mock first update completed. */
    mockStatic(DistributeUtils.class);
    when(DistributeUtils.getStoredDownloadState()).thenReturn(DOWNLOAD_STATE_COMPLETED);
    when(mReleaseDetails.getVersion()).thenReturn(6);
    when(mReleaseDetails.getId()).thenReturn(1);
    when(DistributeUtils.loadCachedReleaseDetails()).thenReturn(mReleaseDetails);
    ReleaseDownloader cachedReleaseDownloader = mock(ReleaseDownloader.class);
    when(ReleaseDownloaderFactory.create(any(Context.class), same(mReleaseDetails), any(ReleaseDownloadListener.class))).thenReturn(cachedReleaseDownloader);
    when(cachedReleaseDownloader.getReleaseDetails()).thenReturn(mReleaseDetails);
    /* Mock next release. */
    final ReleaseDetails nextReleaseDetails = mock(ReleaseDetails.class);
    when(nextReleaseDetails.getId()).thenReturn(2);
    when(nextReleaseDetails.getVersion()).thenReturn(7);
    when(ReleaseDetails.parse(anyString())).thenReturn(nextReleaseDetails);
    ReleaseDownloader nextReleaseDownloader = mock(ReleaseDownloader.class);
    when(ReleaseDownloaderFactory.create(any(Context.class), same(nextReleaseDetails), any(ReleaseDownloadListener.class))).thenReturn(nextReleaseDownloader);
    when(nextReleaseDownloader.getReleaseDetails()).thenReturn(nextReleaseDetails);
    /* Simulate cache update. */
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) {
            when(DistributeUtils.loadCachedReleaseDetails()).thenReturn(nextReleaseDetails);
            return null;
        }
    }).when(SharedPreferencesManager.class);
    SharedPreferencesManager.putString(eq(PREFERENCE_KEY_RELEASE_DETAILS), anyString());
    /* Mock we receive a second update. */
    when(mHttpClient.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) {
            ((ServiceCallback) invocation.getArguments()[4]).onCallSucceeded(new HttpResponse(200, "mock"));
            return mock(ServiceCall.class);
        }
    });
    /* Trigger call. */
    start();
    Distribute.getInstance().onActivityResumed(mock(Activity.class));
    verify(mHttpClient).callAsync(anyString(), anyString(), anyMapOf(String.class, String.class), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
    /* Verify prompt is shown. */
    verify(mDialog).show();
    /* Verify previous download canceled. */
    verify(cachedReleaseDownloader).cancel();
}
Also used : SessionContext(com.microsoft.appcenter.utils.context.SessionContext) Context(android.content.Context) ServiceCall(com.microsoft.appcenter.http.ServiceCall) HttpResponse(com.microsoft.appcenter.http.HttpResponse) Activity(android.app.Activity) Matchers.anyString(org.mockito.Matchers.anyString) ReleaseDownloader(com.microsoft.appcenter.distribute.download.ReleaseDownloader) PowerMockito.doAnswer(org.powermock.api.mockito.PowerMockito.doAnswer) Answer(org.mockito.stubbing.Answer) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

HttpResponse (com.microsoft.appcenter.http.HttpResponse)36 ServiceCallback (com.microsoft.appcenter.http.ServiceCallback)33 Matchers.anyString (org.mockito.Matchers.anyString)31 Test (org.junit.Test)30 InvocationOnMock (org.mockito.invocation.InvocationOnMock)25 ServiceCall (com.microsoft.appcenter.http.ServiceCall)22 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)20 Activity (android.app.Activity)18 Context (android.content.Context)12 HttpException (com.microsoft.appcenter.http.HttpException)12 AppCenterIngestion (com.microsoft.appcenter.ingestion.AppCenterIngestion)10 Log (com.microsoft.appcenter.ingestion.models.Log)10 LogContainer (com.microsoft.appcenter.ingestion.models.LogContainer)10 Persistence (com.microsoft.appcenter.persistence.Persistence)10 HashMap (java.util.HashMap)9 UUID (java.util.UUID)9 DistributionStartSessionLog (com.microsoft.appcenter.distribute.ingestion.models.DistributionStartSessionLog)7 Answer (org.mockito.stubbing.Answer)7 PowerMockito.doAnswer (org.powermock.api.mockito.PowerMockito.doAnswer)6 DialogInterface (android.content.DialogInterface)5