use of com.microsoft.appcenter.http.ServiceCall in project AppCenter-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);
}
use of com.microsoft.appcenter.http.ServiceCall in project AppCenter-SDK-Android by Microsoft.
the class IngestionHttpTest method failedSerialization.
@Test
public void failedSerialization() 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);
JSONException exception = new JSONException("mock");
when(serializer.serializeContainer(any(LogContainer.class))).thenThrow(exception);
/* 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/logs?api-version=1.0.0"), eq(METHOD_POST), eq(expectedHeaders), notNull(HttpClient.CallTemplate.class), eq(serviceCallback));
assertNotNull(callTemplate.get());
try {
callTemplate.get().buildRequestBody();
Assert.fail("Expected json exception");
} catch (JSONException ignored) {
}
/* Verify close. */
ingestionHttp.close();
verify(httpClient).close();
}
use of com.microsoft.appcenter.http.ServiceCall in project AppCenter-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();
}
use of com.microsoft.appcenter.http.ServiceCall 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);
}
use of com.microsoft.appcenter.http.ServiceCall 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();
}
Aggregations