use of com.microsoft.azure.mobile.http.HttpClientNetworkStateHandler in project mobile-center-sdk-android by Microsoft.
the class DistributeBeforeApiSuccessTest method disableWhileCheckingRelease.
@Test
public void disableWhileCheckingRelease() 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);
ServiceCall firstCall = mock(ServiceCall.class);
when(httpClient.callAsync(anyString(), anyString(), anyMapOf(String.class, String.class), any(HttpClient.CallTemplate.class), any(ServiceCallback.class))).thenReturn(firstCall).thenReturn(mock(ServiceCall.class));
HashMap<String, String> headers = new HashMap<>();
headers.put(DistributeConstants.HEADER_API_TOKEN, "some token");
/* The call is only triggered when app is resumed. */
Distribute.getInstance().onStarted(mContext, "a", mock(Channel.class));
verify(httpClient, never()).callAsync(anyString(), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
Distribute.getInstance().onActivityResumed(mock(Activity.class));
verify(httpClient).callAsync(anyString(), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
/* Verify cancel on disabling. */
verify(firstCall, never()).cancel();
Distribute.setEnabled(false);
verify(firstCall).cancel();
/* No more call on that one. */
Distribute.setEnabled(true);
Distribute.setEnabled(false);
verify(firstCall).cancel();
}
use of com.microsoft.azure.mobile.http.HttpClientNetworkStateHandler in project mobile-center-sdk-android by Microsoft.
the class DistributeBeforeDownloadTest method disableBeforeDownload.
@Test
@PrepareForTest(AsyncTaskUtils.class)
public void disableBeforeDownload() 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);
}
});
ReleaseDetails releaseDetails = mock(ReleaseDetails.class);
when(releaseDetails.getId()).thenReturn(4);
when(releaseDetails.getVersion()).thenReturn(7);
when(ReleaseDetails.parse(anyString())).thenReturn(releaseDetails);
mockStatic(AsyncTaskUtils.class);
when(InstallerUtils.isUnknownSourcesEnabled(any(Context.class))).thenReturn(true);
/* Trigger call. */
Distribute.getInstance().onStarted(mContext, "a", mock(Channel.class));
Distribute.getInstance().onActivityResumed(mock(Activity.class));
/* Verify dialog. */
ArgumentCaptor<DialogInterface.OnClickListener> clickListener = ArgumentCaptor.forClass(DialogInterface.OnClickListener.class);
verify(mDialogBuilder).setPositiveButton(eq(R.string.mobile_center_distribute_update_dialog_download), clickListener.capture());
verify(mDialog).show();
/* Disable. */
Distribute.setEnabled(false);
verifyStatic();
PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_STATE);
/* Click on download. */
clickListener.getValue().onClick(mDialog, DialogInterface.BUTTON_POSITIVE);
when(mDialog.isShowing()).thenReturn(false);
/* Since we were disabled, no action but toast to explain what happened. */
verify(mToast).show();
/* 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(httpClient).callAsync(anyString(), anyString(), anyMapOf(String.class, String.class), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
verifyStatic();
PreferencesStorage.remove(PREFERENCE_KEY_DOWNLOAD_STATE);
/* Verify no download scheduled. */
verifyStatic(never());
AsyncTaskUtils.execute(anyString(), any(DownloadTask.class), Mockito.<Void>anyVararg());
}
use of com.microsoft.azure.mobile.http.HttpClientNetworkStateHandler in project mobile-center-sdk-android by Microsoft.
the class DistributeBeforeDownloadTest method moreRecentVersionCode.
@Test
public void moreRecentVersionCode() 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");
ReleaseDetails releaseDetails = mock(ReleaseDetails.class);
when(releaseDetails.getId()).thenReturn(4);
when(releaseDetails.getVersion()).thenReturn(7);
when(releaseDetails.getShortVersion()).thenReturn("7.0");
when(ReleaseDetails.parse(anyString())).thenReturn(releaseDetails);
when(InstallerUtils.isUnknownSourcesEnabled(any(Context.class))).thenReturn(true);
/* Trigger call. */
Distribute.getInstance().onStarted(mContext, "a", mock(Channel.class));
Distribute.getInstance().onActivityResumed(mock(Activity.class));
verify(httpClient).callAsync(anyString(), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
/* Verify dialog. */
verify(mDialogBuilder).setTitle(R.string.mobile_center_distribute_update_dialog_title);
verify(mDialogBuilder).setMessage("unit-test-app7.07");
verify(mDialogBuilder).create();
verify(mDialog).show();
/* After that if we resume app we refresh dialog. */
Distribute.getInstance().onActivityPaused(mock(Activity.class));
Distribute.getInstance().onActivityResumed(mock(Activity.class));
/* No more http call. */
verify(httpClient).callAsync(anyString(), anyString(), eq(headers), any(HttpClient.CallTemplate.class), any(ServiceCallback.class));
/* But dialog refreshed. */
InOrder order = inOrder(mDialog);
order.verify(mDialog).hide();
order.verify(mDialog).show();
order.verifyNoMoreInteractions();
verify(mDialog, times(2)).show();
verify(mDialogBuilder, times(2)).create();
/* Disable does not hide the dialog. */
Distribute.setEnabled(false);
/* We already called hide once, make sure its not called a second time. */
verify(mDialog).hide();
/* Also no toast if we don't click on actionable button. */
verify(mToast, never()).show();
}
use of com.microsoft.azure.mobile.http.HttpClientNetworkStateHandler 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_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);
Distribute.getInstance().onStarted(mContext, "a", mock(Channel.class));
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.mobile_center_distribute_update_dialog_download), clickListener.capture());
clickListener.getValue().onClick(mDialog, DialogInterface.BUTTON_POSITIVE);
}
use of com.microsoft.azure.mobile.http.HttpClientNetworkStateHandler in project mobile-center-sdk-android by Microsoft.
the class Distribute method getLatestReleaseDetails.
/**
* Get latest release details from server.
*
* @param updateToken token to secure API call.
*/
@VisibleForTesting
synchronized void getLatestReleaseDetails(@NonNull String updateToken) {
MobileCenterLog.debug(LOG_TAG, "Get latest release details...");
HttpClientRetryer retryer = new HttpClientRetryer(new DefaultHttpClient());
NetworkStateHelper networkStateHelper = NetworkStateHelper.getSharedInstance(mContext);
HttpClient httpClient = new HttpClientNetworkStateHandler(retryer, networkStateHelper);
String url = mApiUrl + String.format(GET_LATEST_RELEASE_PATH_FORMAT, mAppSecret, computeReleaseHash(mPackageInfo));
Map<String, String> headers = new HashMap<>();
headers.put(HEADER_API_TOKEN, updateToken);
final Object releaseCallId = mCheckReleaseCallId = new Object();
mCheckReleaseApiCall = httpClient.callAsync(url, METHOD_GET, headers, new HttpClient.CallTemplate() {
@Override
public String buildRequestBody() throws JSONException {
/* Only GET is used by Distribute service. This method is never getting called. */
return null;
}
@Override
public void onBeforeCalling(URL url, Map<String, String> headers) {
if (MobileCenterLog.getLogLevel() <= VERBOSE) {
/* Log url. */
String urlString = url.toString().replaceAll(mAppSecret, HttpUtils.hideSecret(mAppSecret));
MobileCenterLog.verbose(LOG_TAG, "Calling " + urlString + "...");
/* Log headers. */
Map<String, String> logHeaders = new HashMap<>(headers);
String apiToken = logHeaders.get(HEADER_API_TOKEN);
if (apiToken != null) {
logHeaders.put(HEADER_API_TOKEN, HttpUtils.hideSecret(apiToken));
}
MobileCenterLog.verbose(LOG_TAG, "Headers: " + logHeaders);
}
}
}, new ServiceCallback() {
@Override
public void onCallSucceeded(final String payload) {
/* onPostExecute is not always called on UI thread due to an old Android bug. */
HandlerUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
handleApiCallSuccess(releaseCallId, payload, ReleaseDetails.parse(payload));
} catch (JSONException e) {
onCallFailed(e);
}
}
});
}
@Override
public void onCallFailed(Exception e) {
handleApiCallFailure(releaseCallId, e);
}
});
}
Aggregations