@Override public Task<Boolean> matchesAsync(T object, ParseSQLiteDatabase db) { Object objectValue; try { objectValue = getValue(object, key); } catch (ParseException e) { return Task.forError(e); } return Task.forResult(matchesEqualConstraint(queryConstraintValue, objectValue)); } });
@Override public Task<Boolean> matchesAsync(T object, ParseSQLiteDatabase db) { try { Object value = getValue(object, key); return Task.forResult(matchesStatelessConstraint(operator, constraint, value, allKeyConstraints)); } catch (ParseException e) { return Task.forError(e); } } };
/** * Wraps the runnable operation and keeps it in sync with the given tcs, so we know how many * operations are running (currentTasks.size()) and can cancel them. */ private <TResult> Task<TResult> perform(Callable<Task<TResult>> runnable, final TaskCompletionSource<?> tcs) { currentTasks.add(tcs); Task<TResult> task; try { task = runnable.call(); } catch (Exception e) { task = Task.forError(e); } return task.continueWithTask(new Continuation<TResult, Task<TResult>>() { @Override public Task<TResult> then(Task<TResult> task) { tcs.trySetResult(null); // release currentTasks.remove(tcs); return task; } }); }
content = new String(ParseIOUtils.toByteArray(responseStream)); } catch (IOException e) { return Task.forError(e); } finally { ParseIOUtils.closeQuietly(responseStream); return Task.forError(newPermanentException(json.optInt("code"), json.optString("error"))); } else if (statusCode >= 500) { // 5XX return Task.forError(newTemporaryException(json.optInt("code"), json.optString("error"))); return Task.forError(newTemporaryException("bad json response", e)); return Task.forError(newPermanentException(ParseException.OTHER_CAUSE, content));
/** * /batch is the only endpoint that doesn't return a JSONObject... It returns a JSONArray, but * let's wrap that with a JSONObject {@code { "results": <original response%gt; }}. */ @Override protected Task<JSONObject> onResponseAsync(ParseHttpResponse response, ProgressCallback downloadProgressCallback) { InputStream responseStream = null; String content; try { responseStream = response.getContent(); content = new String(ParseIOUtils.toByteArray(responseStream)); } catch (IOException e) { return Task.forError(e); } finally { ParseIOUtils.closeQuietly(responseStream); } JSONObject json; try { JSONArray results = new JSONArray(content); json = new JSONObject(); json.put(KEY_RESULTS, results); } catch (JSONException e) { return Task.forError(newTemporaryException("bad json response", e)); } return Task.forResult(json); } }
private ParseConfigController mockParseConfigControllerWithException(Exception exception) { ParseConfigController controller = mock(ParseConfigController.class); when(controller.getAsync(anyString())) .thenReturn(Task.<ParseConfig>forError(exception)); return controller; }
private ParseCurrentConfigController mockParseCurrentConfigControllerWithException( Exception exception) { ParseCurrentConfigController controller = mock(ParseCurrentConfigController.class); when(controller.getCurrentConfigAsync()) .thenReturn(Task.<ParseConfig>forError(exception)); return controller; } }
@Test public void testGetAsyncWithCurrentUserReadFromDiskFailure() throws Exception { ParseObjectStore<ParseUser> store = (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class); when(store.getAsync()).thenReturn(Task.<ParseUser>forError(new RuntimeException("failure"))); CachedCurrentUserController controller = new CachedCurrentUserController(store); ParseUser currentUser = ParseTaskUtils.wait(controller.getAsync(false)); assertNull(currentUser); }
@Test public void testDeleteAsyncFailure() throws Exception { OfflineStore lds = mock(OfflineStore.class); when(lds.unpinAllObjectsAsync(anyString())) .thenReturn(Task.<Void>forError(new RuntimeException("failure"))); Parse.setLocalDatastore(lds); @SuppressWarnings("unchecked") ParseObjectStore<ParseUser> legacy = mock(ParseObjectStore.class); when(legacy.deleteAsync()).thenReturn(Task.<Void>forResult(null)); OfflineObjectStore<ParseUser> store = new OfflineObjectStore<>(ParseUser.class, PIN_NAME, legacy); thrown.expect(RuntimeException.class); ParseTaskUtils.wait(store.deleteAsync()); verify(legacy, times(1)).deleteAsync(); }
@Test public void testFailingFindAllPinned() throws Exception { OfflineStore offlineStore = mock(OfflineStore.class); Parse.setLocalDatastore(offlineStore); when(offlineStore.findFromPinAsync(eq(EventuallyPin.PIN_NAME), any(ParseQuery.State.class), any(ParseUser.class))) .thenReturn(Task.forError(new SQLiteException())); ParsePlugins plugins = mock(ParsePlugins.class); ParsePlugins.set(plugins); when(plugins.restClient()).thenReturn(ParseHttpClient.createClient(null)); thrown.expect(SQLiteException.class); ParseTaskUtils.wait(EventuallyPin.findAllPinned()); } }
@Test public void testLogOutAsyncWithDeleteInDiskCurrentUserFailure() throws Exception { ParseObjectStore<ParseUser> store = (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class); when(store.getAsync()).thenReturn(Task.<ParseUser>forResult(null)); when(store.deleteAsync()).thenReturn(Task.<Void>forError(new RuntimeException("failure"))); CachedCurrentUserController controller = new CachedCurrentUserController(store); ParseTaskUtils.wait(controller.logOutAsync()); // Make sure controller state is correct assertNull(controller.currentUser); assertFalse(controller.currentUserMatchesDisk); }
@Test public void testSubscribeInBackgroundFail() throws Exception { ParsePushChannelsController controller = mock(ParsePushChannelsController.class); ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error"); when(controller.subscribeInBackground(anyString())).thenReturn(Task.<Void>forError(exception)); ParseCorePlugins.getInstance().registerPushChannelsController(controller); Task<Void> pushTask = ParsePush.subscribeInBackground("test"); pushTask.waitForCompletion(); verify(controller, times(1)).subscribeInBackground("test"); assertTrue(pushTask.isFaulted()); assertSame(exception, pushTask.getError()); }
@Test public void testUnsubscribeInBackgroundFail() throws Exception { ParsePushChannelsController controller = mock(ParsePushChannelsController.class); ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error"); when(controller.unsubscribeInBackground(anyString())) .thenReturn(Task.<Void>forError(exception)); ParseCorePlugins.getInstance().registerPushChannelsController(controller); Task<Void> pushTask = ParsePush.unsubscribeInBackground("test"); pushTask.waitForCompletion(); verify(controller, times(1)).unsubscribeInBackground("test"); assertTrue(pushTask.isFaulted()); assertSame(exception, pushTask.getError()); }
@Test public void testMissingRequiredFieldWhenSaveAsync() throws Exception { String sessionToken = "sessionToken"; Task<Void> toAwait = Task.forResult(null); ParseCurrentInstallationController controller = mockCurrentInstallationController(); ParseObjectController objController = mock(ParseObjectController.class); // mock return task when Installation was deleted on the server Task<ParseObject.State> taskError = Task.forError(new ParseException(ParseException.MISSING_REQUIRED_FIELD_ERROR, "")); // mock return task when Installation was re-saved to the server Task<ParseObject.State> task = Task.forResult(null); when(objController.saveAsync( any(ParseObject.State.class), any(ParseOperationSet.class), eq(sessionToken), any(ParseDecoder.class))) .thenReturn(taskError) .thenReturn(task); ParseCorePlugins.getInstance() .registerObjectController(objController); ParseInstallation installation = ParseInstallation.getCurrentInstallation(); assertNotNull(installation); installation.put("key", "value"); ParseTaskUtils.wait(installation.saveAsync(sessionToken, toAwait)); verify(controller).getAsync(); verify(objController, times(2)).saveAsync( any(ParseObject.State.class), any(ParseOperationSet.class), eq(sessionToken), any(ParseDecoder.class)); }
@Test public void testLoginWithAsyncWithLinkedLazyUseAndResolveLazinessFailure() throws Exception { // Register a mock currentUserController to make getCurrentUser work ParseUser currentUser = new ParseUser(); Map<String, String> oldAnonymousAuthData = new HashMap<>(); oldAnonymousAuthData.put("oldKey", "oldToken"); currentUser.putAuthData(ParseAnonymousUtils.AUTH_TYPE, oldAnonymousAuthData); ParseUser partialMockCurrentUser = spy(currentUser); when(partialMockCurrentUser.getSessionToken()).thenReturn("oldSessionToken"); doReturn(Task.<ParseUser>forError(new Exception())) .when(partialMockCurrentUser) .resolveLazinessAsync(Matchers.<Task<Void>>any()); ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class); when(currentUserController.getAsync(false)).thenReturn(Task.forResult(partialMockCurrentUser)); ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController); String authType = "facebook"; Map<String, String> authData = new HashMap<>(); authData.put("token", "123"); Task<ParseUser> loginTask = ParseUser.logInWithInBackground(authType, authData); loginTask.waitForCompletion(); // Make sure we try to resolveLaziness verify(partialMockCurrentUser, times(1)).resolveLazinessAsync(Matchers.<Task<Void>>any()); // Make sure we do not save new authData assertNull(partialMockCurrentUser.getAuthData().get("facebook")); // Make sure we restore anonymity after resolve laziness failure assertEquals(oldAnonymousAuthData, partialMockCurrentUser.getAuthData() .get(ParseAnonymousUtils.AUTH_TYPE)); // Make sure task fails assertTrue(loginTask.isFaulted()); }
@Test public void testSubscribeInBackgroundWithCallbackFail() throws Exception { ParsePushChannelsController controller = mock(ParsePushChannelsController.class); final ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error"); when(controller.subscribeInBackground(anyString())).thenReturn(Task.<Void>forError(exception)); ParseCorePlugins.getInstance().registerPushChannelsController(controller); ParsePush push = new ParsePush(); final Semaphore done = new Semaphore(0); final Capture<Exception> exceptionCapture = new Capture<>(); ParsePush.subscribeInBackground("test", new SaveCallback() { @Override public void done(ParseException e) { exceptionCapture.set(e); done.release(); } }); assertSame(exception, exceptionCapture.get()); assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS)); verify(controller, times(1)).subscribeInBackground("test"); }
@Test public void testUnsubscribeInBackgroundWithCallbackFail() throws Exception { ParsePushChannelsController controller = mock(ParsePushChannelsController.class); final ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error"); when(controller.unsubscribeInBackground(anyString())) .thenReturn(Task.<Void>forError(exception)); ParseCorePlugins.getInstance().registerPushChannelsController(controller); ParsePush push = new ParsePush(); final Semaphore done = new Semaphore(0); final Capture<Exception> exceptionCapture = new Capture<>(); ParsePush.unsubscribeInBackground("test", new SaveCallback() { @Override public void done(ParseException e) { exceptionCapture.set(e); done.release(); } }); assertSame(exception, exceptionCapture.get()); assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS)); verify(controller, times(1)).unsubscribeInBackground("test"); }
@Test public void testSetAsyncWithPersistFailure() throws Exception { // Mock currentUser in memory ParseUser oldCurrentUser = mock(ParseUser.class); when(oldCurrentUser.logOutAsync(anyBoolean())).thenReturn(Task.<Void>forResult(null)); ParseUser currentUser = new ParseUser(); ParseObjectStore<ParseUser> store = (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class); when(store.setAsync(currentUser)) .thenReturn(Task.<Void>forError(new RuntimeException("failure"))); CachedCurrentUserController controller = new CachedCurrentUserController(store); controller.currentUser = oldCurrentUser; ParseTaskUtils.wait(controller.setAsync(currentUser)); // Make sure oldCurrentUser logout verify(oldCurrentUser, times(1)).logOutAsync(false); // Verify we tried to persist verify(store, times(1)).setAsync(currentUser); // TODO(mengyan): Find a way to verify user.synchronizeAllAuthData() is called // Verify newUser is currentUser assertTrue(currentUser.isCurrentUser()); // Make sure in memory currentUser is up to date assertSame(currentUser, controller.currentUser); // Make sure in currentUserMatchesDisk since we can not write to disk assertFalse(controller.currentUserMatchesDisk); }
@Test public void testGetAsyncWithCurrentUserReadFromDiskFailureAndLazyLogin() throws Exception { ParseObjectStore<ParseUser> store = (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class); when(store.getAsync()).thenReturn(Task.<ParseUser>forError(new RuntimeException("failure"))); CachedCurrentUserController controller = new CachedCurrentUserController(store); ParseUser currentUser = ParseTaskUtils.wait(controller.getAsync(true)); // We need to make sure the user is created by lazy login assertTrue(currentUser.isLazy()); assertTrue(currentUser.isCurrentUser()); assertSame(controller.currentUser, currentUser); assertFalse(controller.currentUserMatchesDisk); // We do not test the lazy login auth data here, it is covered in lazyLogin() unit test }
@Test public void testSignUpAsyncWithNoCurrentUserAndSignUpFailure() { // Register a mock currentUserController to make getCurrentUser work ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class); when(currentUserController.getAsync(anyBoolean())) .thenReturn(Task.<ParseUser>forResult(null)); ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController); // Register a mock userController to make logIn work ParseUserController userController = mock(ParseUserController.class); ParseException signUpException = new ParseException(ParseException.OTHER_CAUSE, "test"); when(userController.signUpAsync( any(ParseUser.State.class), any(ParseOperationSet.class), anyString())) .thenReturn(Task.<ParseUser.State>forError(signUpException)); ParseCorePlugins.getInstance().registerUserController(userController); ParseUser user = new ParseUser(); user.put("key", "value"); user.setUsername("userName"); user.setPassword("password"); Task<Void> signUpTask = user.signUpAsync(Task.<Void>forResult(null)); // Make sure we sign up the user verify(userController, times(1)).signUpAsync( any(ParseUser.State.class), any(ParseOperationSet.class), anyString()); // Make sure user's data is correct assertEquals("value", user.getString("key")); // Make sure we never set the current user verify(currentUserController, never()).setAsync(user); // Make sure task is failed assertTrue(signUpTask.isFaulted()); assertSame(signUpException, signUpTask.getError()); }