method2testcases stringlengths 118 3.08k |
|---|
### Question:
ParseRole extends ParseObject { public static ParseQuery<ParseRole> getQuery() { return ParseQuery.getQuery(ParseRole.class); } ParseRole(); ParseRole(String name); ParseRole(String name, ParseACL acl); void setName(String name); String getName(); ParseRelation<ParseUser> getUsers(); ParseRelation<ParseRole> getRoles(); @Override void put(String key, Object value); static ParseQuery<ParseRole> getQuery(); }### Answer:
@Test public void testGetQuery() { ParseQuery<?> query = ParseRole.getQuery(); assertEquals(ParseCorePlugins.getInstance().getSubclassingController().getClassName(ParseRole.class), query.getBuilder().getClassName()); } |
### Question:
ParseCorePlugins { public void registerQueryController(ParseQueryController controller) { if (!queryController.compareAndSet(null, controller)) { throw new IllegalStateException( "Another query controller was already registered: " + queryController.get()); } } private ParseCorePlugins(); static ParseCorePlugins getInstance(); ParseObjectController getObjectController(); void registerObjectController(ParseObjectController controller); ParseUserController getUserController(); void registerUserController(ParseUserController controller); ParseSessionController getSessionController(); void registerSessionController(ParseSessionController controller); ParseCurrentUserController getCurrentUserController(); void registerCurrentUserController(ParseCurrentUserController controller); ParseQueryController getQueryController(); void registerQueryController(ParseQueryController controller); ParseFileController getFileController(); void registerFileController(ParseFileController controller); ParseAnalyticsController getAnalyticsController(); void registerAnalyticsController(ParseAnalyticsController controller); ParseCloudCodeController getCloudCodeController(); void registerCloudCodeController(ParseCloudCodeController controller); ParseConfigController getConfigController(); void registerConfigController(ParseConfigController controller); ParsePushController getPushController(); void registerPushController(ParsePushController controller); ParsePushChannelsController getPushChannelsController(); void registerPushChannelsController(ParsePushChannelsController controller); ParseCurrentInstallationController getCurrentInstallationController(); void registerCurrentInstallationController(ParseCurrentInstallationController controller); ParseAuthenticationManager getAuthenticationManager(); void registerAuthenticationManager(ParseAuthenticationManager manager); ParseDefaultACLController getDefaultACLController(); void registerDefaultACLController(ParseDefaultACLController controller); ParseSchemaController getSchemaController(); LocalIdManager getLocalIdManager(); void registerLocalIdManager(LocalIdManager manager); ParseObjectSubclassingController getSubclassingController(); void registerSubclassingController(ParseObjectSubclassingController controller); }### Answer:
@Test public void testRegisterQueryController() { ParseQueryController controller = new TestQueryController(); ParseCorePlugins.getInstance().registerQueryController(controller); assertSame(controller, ParseCorePlugins.getInstance().getQueryController()); } |
### Question:
ParseCorePlugins { public void registerFileController(ParseFileController controller) { if (!fileController.compareAndSet(null, controller)) { throw new IllegalStateException( "Another file controller was already registered: " + fileController.get()); } } private ParseCorePlugins(); static ParseCorePlugins getInstance(); ParseObjectController getObjectController(); void registerObjectController(ParseObjectController controller); ParseUserController getUserController(); void registerUserController(ParseUserController controller); ParseSessionController getSessionController(); void registerSessionController(ParseSessionController controller); ParseCurrentUserController getCurrentUserController(); void registerCurrentUserController(ParseCurrentUserController controller); ParseQueryController getQueryController(); void registerQueryController(ParseQueryController controller); ParseFileController getFileController(); void registerFileController(ParseFileController controller); ParseAnalyticsController getAnalyticsController(); void registerAnalyticsController(ParseAnalyticsController controller); ParseCloudCodeController getCloudCodeController(); void registerCloudCodeController(ParseCloudCodeController controller); ParseConfigController getConfigController(); void registerConfigController(ParseConfigController controller); ParsePushController getPushController(); void registerPushController(ParsePushController controller); ParsePushChannelsController getPushChannelsController(); void registerPushChannelsController(ParsePushChannelsController controller); ParseCurrentInstallationController getCurrentInstallationController(); void registerCurrentInstallationController(ParseCurrentInstallationController controller); ParseAuthenticationManager getAuthenticationManager(); void registerAuthenticationManager(ParseAuthenticationManager manager); ParseDefaultACLController getDefaultACLController(); void registerDefaultACLController(ParseDefaultACLController controller); ParseSchemaController getSchemaController(); LocalIdManager getLocalIdManager(); void registerLocalIdManager(LocalIdManager manager); ParseObjectSubclassingController getSubclassingController(); void registerSubclassingController(ParseObjectSubclassingController controller); }### Answer:
@Test public void testRegisterFileController() { ParseFileController controller = new TestFileController(); ParseCorePlugins.getInstance().registerFileController(controller); assertSame(controller, ParseCorePlugins.getInstance().getFileController()); } |
### Question:
ParseCorePlugins { public void registerAnalyticsController(ParseAnalyticsController controller) { if (!analyticsController.compareAndSet(null, controller)) { throw new IllegalStateException( "Another analytics controller was already registered: " + analyticsController.get()); } } private ParseCorePlugins(); static ParseCorePlugins getInstance(); ParseObjectController getObjectController(); void registerObjectController(ParseObjectController controller); ParseUserController getUserController(); void registerUserController(ParseUserController controller); ParseSessionController getSessionController(); void registerSessionController(ParseSessionController controller); ParseCurrentUserController getCurrentUserController(); void registerCurrentUserController(ParseCurrentUserController controller); ParseQueryController getQueryController(); void registerQueryController(ParseQueryController controller); ParseFileController getFileController(); void registerFileController(ParseFileController controller); ParseAnalyticsController getAnalyticsController(); void registerAnalyticsController(ParseAnalyticsController controller); ParseCloudCodeController getCloudCodeController(); void registerCloudCodeController(ParseCloudCodeController controller); ParseConfigController getConfigController(); void registerConfigController(ParseConfigController controller); ParsePushController getPushController(); void registerPushController(ParsePushController controller); ParsePushChannelsController getPushChannelsController(); void registerPushChannelsController(ParsePushChannelsController controller); ParseCurrentInstallationController getCurrentInstallationController(); void registerCurrentInstallationController(ParseCurrentInstallationController controller); ParseAuthenticationManager getAuthenticationManager(); void registerAuthenticationManager(ParseAuthenticationManager manager); ParseDefaultACLController getDefaultACLController(); void registerDefaultACLController(ParseDefaultACLController controller); ParseSchemaController getSchemaController(); LocalIdManager getLocalIdManager(); void registerLocalIdManager(LocalIdManager manager); ParseObjectSubclassingController getSubclassingController(); void registerSubclassingController(ParseObjectSubclassingController controller); }### Answer:
@Test public void testRegisterAnalyticsController() { ParseAnalyticsController controller = new TestAnalyticsController(); ParseCorePlugins.getInstance().registerAnalyticsController(controller); assertSame(controller, ParseCorePlugins.getInstance().getAnalyticsController()); } |
### Question:
ParseAnalyticsController { public Task<Void> trackAppOpenedInBackground(String pushHash, String sessionToken) { ParseRESTCommand command = ParseRESTAnalyticsCommand.trackAppOpenedCommand(pushHash, sessionToken); Task<JSONObject> eventuallyTask = eventuallyQueue.enqueueEventuallyAsync(command, null); return eventuallyTask.makeVoid(); } ParseAnalyticsController(ParseEventuallyQueue eventuallyQueue); Task<Void> trackEventInBackground(final String name,
Map<String, String> dimensions, String sessionToken); Task<Void> trackAppOpenedInBackground(String pushHash, String sessionToken); }### Answer:
@Test public void testTrackAppOpened() throws Exception { ParseEventuallyQueue queue = mock(ParseEventuallyQueue.class); when(queue.enqueueEventuallyAsync(any(ParseRESTCommand.class), any(ParseObject.class))) .thenReturn(Task.forResult(new JSONObject())); ParseAnalyticsController controller = new ParseAnalyticsController(queue); ParseTaskUtils.wait(controller.trackAppOpenedInBackground("pushHash", "sessionToken")); ArgumentCaptor<ParseRESTCommand> command = ArgumentCaptor.forClass(ParseRESTCommand.class); ArgumentCaptor<ParseObject> object = ArgumentCaptor.forClass(ParseObject.class); verify(queue, times(1)).enqueueEventuallyAsync(command.capture(), object.capture()); assertNull(object.getValue()); assertTrue(command.getValue() instanceof ParseRESTAnalyticsCommand); assertTrue(command.getValue().httpPath.contains(ParseRESTAnalyticsCommand.EVENT_APP_OPENED)); assertEquals("sessionToken", command.getValue().getSessionToken()); assertEquals("pushHash", command.getValue().jsonParameters.get("push_hash")); } |
### Question:
ParseCorePlugins { public void registerCloudCodeController(ParseCloudCodeController controller) { if (!cloudCodeController.compareAndSet(null, controller)) { throw new IllegalStateException( "Another cloud code controller was already registered: " + cloudCodeController.get()); } } private ParseCorePlugins(); static ParseCorePlugins getInstance(); ParseObjectController getObjectController(); void registerObjectController(ParseObjectController controller); ParseUserController getUserController(); void registerUserController(ParseUserController controller); ParseSessionController getSessionController(); void registerSessionController(ParseSessionController controller); ParseCurrentUserController getCurrentUserController(); void registerCurrentUserController(ParseCurrentUserController controller); ParseQueryController getQueryController(); void registerQueryController(ParseQueryController controller); ParseFileController getFileController(); void registerFileController(ParseFileController controller); ParseAnalyticsController getAnalyticsController(); void registerAnalyticsController(ParseAnalyticsController controller); ParseCloudCodeController getCloudCodeController(); void registerCloudCodeController(ParseCloudCodeController controller); ParseConfigController getConfigController(); void registerConfigController(ParseConfigController controller); ParsePushController getPushController(); void registerPushController(ParsePushController controller); ParsePushChannelsController getPushChannelsController(); void registerPushChannelsController(ParsePushChannelsController controller); ParseCurrentInstallationController getCurrentInstallationController(); void registerCurrentInstallationController(ParseCurrentInstallationController controller); ParseAuthenticationManager getAuthenticationManager(); void registerAuthenticationManager(ParseAuthenticationManager manager); ParseDefaultACLController getDefaultACLController(); void registerDefaultACLController(ParseDefaultACLController controller); ParseSchemaController getSchemaController(); LocalIdManager getLocalIdManager(); void registerLocalIdManager(LocalIdManager manager); ParseObjectSubclassingController getSubclassingController(); void registerSubclassingController(ParseObjectSubclassingController controller); }### Answer:
@Test public void testRegisterCloudCodeController() { ParseCloudCodeController controller = new TestCloudCodeController(); ParseCorePlugins.getInstance().registerCloudCodeController(controller); assertSame(controller, ParseCorePlugins.getInstance().getCloudCodeController()); } |
### Question:
ParseCorePlugins { public void registerConfigController(ParseConfigController controller) { if (!configController.compareAndSet(null, controller)) { throw new IllegalStateException( "Another config controller was already registered: " + configController.get()); } } private ParseCorePlugins(); static ParseCorePlugins getInstance(); ParseObjectController getObjectController(); void registerObjectController(ParseObjectController controller); ParseUserController getUserController(); void registerUserController(ParseUserController controller); ParseSessionController getSessionController(); void registerSessionController(ParseSessionController controller); ParseCurrentUserController getCurrentUserController(); void registerCurrentUserController(ParseCurrentUserController controller); ParseQueryController getQueryController(); void registerQueryController(ParseQueryController controller); ParseFileController getFileController(); void registerFileController(ParseFileController controller); ParseAnalyticsController getAnalyticsController(); void registerAnalyticsController(ParseAnalyticsController controller); ParseCloudCodeController getCloudCodeController(); void registerCloudCodeController(ParseCloudCodeController controller); ParseConfigController getConfigController(); void registerConfigController(ParseConfigController controller); ParsePushController getPushController(); void registerPushController(ParsePushController controller); ParsePushChannelsController getPushChannelsController(); void registerPushChannelsController(ParsePushChannelsController controller); ParseCurrentInstallationController getCurrentInstallationController(); void registerCurrentInstallationController(ParseCurrentInstallationController controller); ParseAuthenticationManager getAuthenticationManager(); void registerAuthenticationManager(ParseAuthenticationManager manager); ParseDefaultACLController getDefaultACLController(); void registerDefaultACLController(ParseDefaultACLController controller); ParseSchemaController getSchemaController(); LocalIdManager getLocalIdManager(); void registerLocalIdManager(LocalIdManager manager); ParseObjectSubclassingController getSubclassingController(); void registerSubclassingController(ParseObjectSubclassingController controller); }### Answer:
@Test public void testRegisterConfigController() { ParseConfigController controller = new TestConfigController(); ParseCorePlugins.getInstance().registerConfigController(controller); assertSame(controller, ParseCorePlugins.getInstance().getConfigController()); } |
### Question:
ParseCorePlugins { public void registerPushController(ParsePushController controller) { if (!pushController.compareAndSet(null, controller)) { throw new IllegalStateException( "Another push controller was already registered: " + pushController.get()); } } private ParseCorePlugins(); static ParseCorePlugins getInstance(); ParseObjectController getObjectController(); void registerObjectController(ParseObjectController controller); ParseUserController getUserController(); void registerUserController(ParseUserController controller); ParseSessionController getSessionController(); void registerSessionController(ParseSessionController controller); ParseCurrentUserController getCurrentUserController(); void registerCurrentUserController(ParseCurrentUserController controller); ParseQueryController getQueryController(); void registerQueryController(ParseQueryController controller); ParseFileController getFileController(); void registerFileController(ParseFileController controller); ParseAnalyticsController getAnalyticsController(); void registerAnalyticsController(ParseAnalyticsController controller); ParseCloudCodeController getCloudCodeController(); void registerCloudCodeController(ParseCloudCodeController controller); ParseConfigController getConfigController(); void registerConfigController(ParseConfigController controller); ParsePushController getPushController(); void registerPushController(ParsePushController controller); ParsePushChannelsController getPushChannelsController(); void registerPushChannelsController(ParsePushChannelsController controller); ParseCurrentInstallationController getCurrentInstallationController(); void registerCurrentInstallationController(ParseCurrentInstallationController controller); ParseAuthenticationManager getAuthenticationManager(); void registerAuthenticationManager(ParseAuthenticationManager manager); ParseDefaultACLController getDefaultACLController(); void registerDefaultACLController(ParseDefaultACLController controller); ParseSchemaController getSchemaController(); LocalIdManager getLocalIdManager(); void registerLocalIdManager(LocalIdManager manager); ParseObjectSubclassingController getSubclassingController(); void registerSubclassingController(ParseObjectSubclassingController controller); }### Answer:
@Test public void testRegisterPushController() { ParsePushController controller = new TestPushController(); ParseCorePlugins.getInstance().registerPushController(controller); assertSame(controller, ParseCorePlugins.getInstance().getPushController()); } |
### Question:
ParseCorePlugins { public void registerPushChannelsController(ParsePushChannelsController controller) { if (!pushChannelsController.compareAndSet(null, controller)) { throw new IllegalStateException( "Another pushChannels controller was already registered: " + pushChannelsController.get()); } } private ParseCorePlugins(); static ParseCorePlugins getInstance(); ParseObjectController getObjectController(); void registerObjectController(ParseObjectController controller); ParseUserController getUserController(); void registerUserController(ParseUserController controller); ParseSessionController getSessionController(); void registerSessionController(ParseSessionController controller); ParseCurrentUserController getCurrentUserController(); void registerCurrentUserController(ParseCurrentUserController controller); ParseQueryController getQueryController(); void registerQueryController(ParseQueryController controller); ParseFileController getFileController(); void registerFileController(ParseFileController controller); ParseAnalyticsController getAnalyticsController(); void registerAnalyticsController(ParseAnalyticsController controller); ParseCloudCodeController getCloudCodeController(); void registerCloudCodeController(ParseCloudCodeController controller); ParseConfigController getConfigController(); void registerConfigController(ParseConfigController controller); ParsePushController getPushController(); void registerPushController(ParsePushController controller); ParsePushChannelsController getPushChannelsController(); void registerPushChannelsController(ParsePushChannelsController controller); ParseCurrentInstallationController getCurrentInstallationController(); void registerCurrentInstallationController(ParseCurrentInstallationController controller); ParseAuthenticationManager getAuthenticationManager(); void registerAuthenticationManager(ParseAuthenticationManager manager); ParseDefaultACLController getDefaultACLController(); void registerDefaultACLController(ParseDefaultACLController controller); ParseSchemaController getSchemaController(); LocalIdManager getLocalIdManager(); void registerLocalIdManager(LocalIdManager manager); ParseObjectSubclassingController getSubclassingController(); void registerSubclassingController(ParseObjectSubclassingController controller); }### Answer:
@Test public void testRegisterPushChannelsController() { ParsePushChannelsController controller = new ParsePushChannelsController(); ParseCorePlugins.getInstance().registerPushChannelsController(controller); assertSame(controller, ParseCorePlugins.getInstance().getPushChannelsController()); } |
### Question:
CachedCurrentInstallationController implements ParseCurrentInstallationController { @Override public Task<Boolean> existsAsync() { synchronized (mutex) { if (currentInstallation != null) { return Task.forResult(true); } } return taskQueue.enqueue(new Continuation<Void, Task<Boolean>>() { @Override public Task<Boolean> then(Task<Void> toAwait) throws Exception { return toAwait.continueWithTask(new Continuation<Void, Task<Boolean>>() { @Override public Task<Boolean> then(Task<Void> task) throws Exception { return store.existsAsync(); } }); } }); } CachedCurrentInstallationController(
ParseObjectStore<ParseInstallation> store, InstallationId installationId); @Override Task<Void> setAsync(final ParseInstallation installation); @Override Task<ParseInstallation> getAsync(); @Override Task<Boolean> existsAsync(); @Override void clearFromMemory(); @Override void clearFromDisk(); @Override boolean isCurrent(ParseInstallation installation); }### Answer:
@Test public void testExistAsyncFromMemory() throws Exception { CachedCurrentInstallationController controller = new CachedCurrentInstallationController(null, null); controller.currentInstallation = mock(ParseInstallation.class); assertTrue(ParseTaskUtils.wait(controller.existsAsync())); }
@Test public void testExistAsyncFromStore() throws Exception { ParseObjectStore<ParseInstallation> store = mock(ParseObjectStore.class); when(store.existsAsync()).thenReturn(Task.forResult(true)); CachedCurrentInstallationController controller = new CachedCurrentInstallationController(store, null); assertTrue(ParseTaskUtils.wait(controller.existsAsync())); verify(store, times(1)).existsAsync(); } |
### Question:
CachedCurrentInstallationController implements ParseCurrentInstallationController { @Override public void clearFromMemory() { synchronized (mutex) { currentInstallation = null; } } CachedCurrentInstallationController(
ParseObjectStore<ParseInstallation> store, InstallationId installationId); @Override Task<Void> setAsync(final ParseInstallation installation); @Override Task<ParseInstallation> getAsync(); @Override Task<Boolean> existsAsync(); @Override void clearFromMemory(); @Override void clearFromDisk(); @Override boolean isCurrent(ParseInstallation installation); }### Answer:
@Test public void testClearFromMemory() throws Exception { CachedCurrentInstallationController controller = new CachedCurrentInstallationController(null, null); controller.currentInstallation = mock(ParseInstallation.class); controller.clearFromMemory(); assertNull(controller.currentInstallation); } |
### Question:
CachedCurrentInstallationController implements ParseCurrentInstallationController { @Override public void clearFromDisk() { synchronized (mutex) { currentInstallation = null; } try { installationId.clear(); ParseTaskUtils.wait(store.deleteAsync()); } catch (ParseException e) { } } CachedCurrentInstallationController(
ParseObjectStore<ParseInstallation> store, InstallationId installationId); @Override Task<Void> setAsync(final ParseInstallation installation); @Override Task<ParseInstallation> getAsync(); @Override Task<Boolean> existsAsync(); @Override void clearFromMemory(); @Override void clearFromDisk(); @Override boolean isCurrent(ParseInstallation installation); }### Answer:
@Test public void testClearFromDisk() throws Exception { InstallationId installationId = mock(InstallationId.class); ParseObjectStore<ParseInstallation> store = mock(ParseObjectStore.class); when(store.deleteAsync()).thenReturn(Task.<Void>forResult(null)); CachedCurrentInstallationController controller = new CachedCurrentInstallationController(store, installationId); controller.currentInstallation = mock(ParseInstallation.class); controller.clearFromDisk(); assertNull(controller.currentInstallation); verify(store, times(1)).deleteAsync(); verify(installationId, times(1)).clear(); } |
### Question:
ParseRESTUserCommand extends ParseRESTCommand { public static ParseRESTUserCommand getCurrentUserCommand(String sessionToken) { return new ParseRESTUserCommand("users/me", ParseHttpRequest.Method.GET, null, sessionToken); } private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken, boolean isRevocableSessionEnabled); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
JSONObject parameters,
String sessionToken, boolean isRevocableSessionEnabled); static ParseRESTUserCommand getCurrentUserCommand(String sessionToken); static ParseRESTUserCommand signUpUserCommand(JSONObject parameters, String sessionToken,
boolean revocableSession); static ParseRESTUserCommand logInUserCommand(String username, String password,
boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(
String authType, Map<String, String> authData, boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(JSONObject parameters,
String sessionToken, boolean revocableSession); static ParseRESTUserCommand resetPasswordResetCommand(String email); int getStatusCode(); }### Answer:
@Test public void testGetCurrentUserCommand() throws Exception { ParseRESTUserCommand command = ParseRESTUserCommand.getCurrentUserCommand("sessionToken"); assertEquals("users/me", command.httpPath); assertEquals(ParseHttpRequest.Method.GET, command.method); assertNull(command.jsonParameters); assertEquals("sessionToken", command.getSessionToken()); } |
### Question:
ParseRESTUserCommand extends ParseRESTCommand { public static ParseRESTUserCommand logInUserCommand(String username, String password, boolean revocableSession) { Map<String, String> parameters = new HashMap<>(); parameters.put("username", username); parameters.put("password", password); return new ParseRESTUserCommand( "login", ParseHttpRequest.Method.GET, parameters, null, revocableSession); } private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken, boolean isRevocableSessionEnabled); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
JSONObject parameters,
String sessionToken, boolean isRevocableSessionEnabled); static ParseRESTUserCommand getCurrentUserCommand(String sessionToken); static ParseRESTUserCommand signUpUserCommand(JSONObject parameters, String sessionToken,
boolean revocableSession); static ParseRESTUserCommand logInUserCommand(String username, String password,
boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(
String authType, Map<String, String> authData, boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(JSONObject parameters,
String sessionToken, boolean revocableSession); static ParseRESTUserCommand resetPasswordResetCommand(String email); int getStatusCode(); }### Answer:
@Test public void testLogInUserCommand() throws Exception { ParseRESTUserCommand command = ParseRESTUserCommand.logInUserCommand( "userName", "password", true); assertEquals("login", command.httpPath); assertEquals(ParseHttpRequest.Method.GET, command.method); assertEquals("userName", command.jsonParameters.getString("username")); assertEquals("password", command.jsonParameters.getString("password")); assertNull(command.getSessionToken()); } |
### Question:
ParseRESTUserCommand extends ParseRESTCommand { public static ParseRESTUserCommand resetPasswordResetCommand(String email) { Map<String, String> parameters = new HashMap<>(); parameters.put("email", email); return new ParseRESTUserCommand( "requestPasswordReset", ParseHttpRequest.Method.POST, parameters, null); } private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken, boolean isRevocableSessionEnabled); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
JSONObject parameters,
String sessionToken, boolean isRevocableSessionEnabled); static ParseRESTUserCommand getCurrentUserCommand(String sessionToken); static ParseRESTUserCommand signUpUserCommand(JSONObject parameters, String sessionToken,
boolean revocableSession); static ParseRESTUserCommand logInUserCommand(String username, String password,
boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(
String authType, Map<String, String> authData, boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(JSONObject parameters,
String sessionToken, boolean revocableSession); static ParseRESTUserCommand resetPasswordResetCommand(String email); int getStatusCode(); }### Answer:
@Test public void testResetPasswordResetCommand() throws Exception { ParseRESTUserCommand command = ParseRESTUserCommand.resetPasswordResetCommand("test@parse.com"); assertEquals("requestPasswordReset", command.httpPath); assertEquals(ParseHttpRequest.Method.POST, command.method); assertEquals("test@parse.com", command.jsonParameters.getString("email")); assertNull(command.getSessionToken()); } |
### Question:
ParseRESTUserCommand extends ParseRESTCommand { public static ParseRESTUserCommand signUpUserCommand(JSONObject parameters, String sessionToken, boolean revocableSession) { return new ParseRESTUserCommand( "users", ParseHttpRequest.Method.POST, parameters, sessionToken, revocableSession); } private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken, boolean isRevocableSessionEnabled); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
JSONObject parameters,
String sessionToken, boolean isRevocableSessionEnabled); static ParseRESTUserCommand getCurrentUserCommand(String sessionToken); static ParseRESTUserCommand signUpUserCommand(JSONObject parameters, String sessionToken,
boolean revocableSession); static ParseRESTUserCommand logInUserCommand(String username, String password,
boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(
String authType, Map<String, String> authData, boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(JSONObject parameters,
String sessionToken, boolean revocableSession); static ParseRESTUserCommand resetPasswordResetCommand(String email); int getStatusCode(); }### Answer:
@Test public void testSignUpUserCommand() throws Exception { JSONObject parameters = new JSONObject(); parameters.put("key", "value"); ParseRESTUserCommand command = ParseRESTUserCommand.signUpUserCommand(parameters, "sessionToken", true); assertEquals("users", command.httpPath); assertEquals(ParseHttpRequest.Method.POST, command.method); assertEquals("value", command.jsonParameters.getString("key")); assertEquals("sessionToken", command.getSessionToken()); } |
### Question:
ParseRESTUserCommand extends ParseRESTCommand { @Override protected void addAdditionalHeaders(ParseHttpRequest.Builder requestBuilder) { super.addAdditionalHeaders(requestBuilder); if (isRevocableSessionEnabled) { requestBuilder.addHeader(HEADER_REVOCABLE_SESSION, HEADER_TRUE); } } private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken, boolean isRevocableSessionEnabled); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
JSONObject parameters,
String sessionToken, boolean isRevocableSessionEnabled); static ParseRESTUserCommand getCurrentUserCommand(String sessionToken); static ParseRESTUserCommand signUpUserCommand(JSONObject parameters, String sessionToken,
boolean revocableSession); static ParseRESTUserCommand logInUserCommand(String username, String password,
boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(
String authType, Map<String, String> authData, boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(JSONObject parameters,
String sessionToken, boolean revocableSession); static ParseRESTUserCommand resetPasswordResetCommand(String email); int getStatusCode(); }### Answer:
@Test public void testAddAdditionalHeaders() throws Exception { JSONObject parameters = new JSONObject(); parameters.put("key", "value"); ParseRESTUserCommand command = ParseRESTUserCommand.signUpUserCommand(parameters, "sessionToken", true); ParseHttpRequest.Builder requestBuilder = new ParseHttpRequest.Builder(); command.addAdditionalHeaders(requestBuilder); assertEquals("1", requestBuilder.build().getHeader("X-Parse-Revocable-Session")); } |
### Question:
ParseRESTUserCommand extends ParseRESTCommand { @Override protected Task<JSONObject> onResponseAsync(ParseHttpResponse response, ProgressCallback progressCallback) { statusCode = response.getStatusCode(); return super.onResponseAsync(response, progressCallback); } private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken, boolean isRevocableSessionEnabled); private ParseRESTUserCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
JSONObject parameters,
String sessionToken, boolean isRevocableSessionEnabled); static ParseRESTUserCommand getCurrentUserCommand(String sessionToken); static ParseRESTUserCommand signUpUserCommand(JSONObject parameters, String sessionToken,
boolean revocableSession); static ParseRESTUserCommand logInUserCommand(String username, String password,
boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(
String authType, Map<String, String> authData, boolean revocableSession); static ParseRESTUserCommand serviceLogInUserCommand(JSONObject parameters,
String sessionToken, boolean revocableSession); static ParseRESTUserCommand resetPasswordResetCommand(String email); int getStatusCode(); }### Answer:
@Test public void testOnResponseAsync() throws Exception { ParseRESTUserCommand command = ParseRESTUserCommand.getCurrentUserCommand("sessionToken"); String content = "content"; String contentType = "application/json"; int statusCode = 200; ParseHttpResponse response = new ParseHttpResponse.Builder() .setContent(new ByteArrayInputStream(content.getBytes())) .setContentType(contentType) .setStatusCode(statusCode) .build(); command.onResponseAsync(response, null); assertEquals(200, command.getStatusCode()); } |
### Question:
CachedCurrentInstallationController implements ParseCurrentInstallationController { @Override public boolean isCurrent(ParseInstallation installation) { synchronized (mutex) { return currentInstallation == installation; } } CachedCurrentInstallationController(
ParseObjectStore<ParseInstallation> store, InstallationId installationId); @Override Task<Void> setAsync(final ParseInstallation installation); @Override Task<ParseInstallation> getAsync(); @Override Task<Boolean> existsAsync(); @Override void clearFromMemory(); @Override void clearFromDisk(); @Override boolean isCurrent(ParseInstallation installation); }### Answer:
@Test public void testIsCurrent() throws Exception { CachedCurrentInstallationController controller = new CachedCurrentInstallationController(null, null); ParseInstallation installation = mock(ParseInstallation.class); controller.currentInstallation = installation; assertTrue(controller.isCurrent(installation)); assertFalse(controller.isCurrent(new ParseInstallation())); } |
### Question:
ParseCloudCodeController { Object convertCloudResponse(Object result) { if (result instanceof JSONObject) { JSONObject jsonResult = (JSONObject)result; result = jsonResult.opt("result"); } ParseDecoder decoder = ParseDecoder.get(); Object finalResult = decoder.decode(result); if (finalResult != null) { return finalResult; } return result; } ParseCloudCodeController(ParseHttpClient restClient); Task<T> callFunctionInBackground(final String name,
final Map<String, ?> params, String sessionToken); }### Answer:
@Test public void testConvertCloudResponseNullResponse() throws Exception { ParseHttpClient restClient = mock(ParseHttpClient.class); ParseCloudCodeController controller = new ParseCloudCodeController(restClient); Object result = controller.convertCloudResponse(null); assertNull(result); }
@Test public void testConvertCloudResponseJsonResponseWithResultField() throws Exception { ParseHttpClient restClient = mock(ParseHttpClient.class); ParseCloudCodeController controller = new ParseCloudCodeController(restClient); JSONObject response = new JSONObject(); response.put("result", "test"); Object result = controller.convertCloudResponse(response); assertThat(result, instanceOf(String.class)); assertEquals("test", result); }
@Test public void testConvertCloudResponseJsonArrayResponse() throws Exception { ParseHttpClient restClient = mock(ParseHttpClient.class); ParseCloudCodeController controller = new ParseCloudCodeController(restClient); JSONArray response = new JSONArray(); response.put(0, "test"); response.put(1, true); response.put(2, 2); Object result = controller.convertCloudResponse(response); assertThat(result, instanceOf(List.class)); List listResult = (List)result; assertEquals(3, listResult.size()); assertEquals("test", listResult.get(0)); assertEquals(true, listResult.get(1)); assertEquals(2, listResult.get(2)); } |
### Question:
ParseAuthenticationManager { public void register(final String authType, AuthenticationCallback callback) { if (authType == null) { throw new IllegalArgumentException("Invalid authType: " + null); } synchronized (lock) { if (this.callbacks.containsKey(authType)) { throw new IllegalStateException("Callback already registered for <" + authType + ">: " + this.callbacks.get(authType)); } this.callbacks.put(authType, callback); } if (ParseAnonymousUtils.AUTH_TYPE.equals(authType)) { return; } controller.getAsync(false).onSuccessTask(new Continuation<ParseUser, Task<Void>>() { @Override public Task<Void> then(Task<ParseUser> task) throws Exception { ParseUser user = task.getResult(); if (user != null) { return user.synchronizeAuthDataAsync(authType); } return null; } }); } ParseAuthenticationManager(ParseCurrentUserController controller); void register(final String authType, AuthenticationCallback callback); Task<Boolean> restoreAuthenticationAsync(String authType, final Map<String, String> authData); Task<Void> deauthenticateAsync(String authType); }### Answer:
@Test public void testRegisterMultipleShouldThrow() { when(controller.getAsync(false)).thenReturn(Task.<ParseUser>forResult(null)); AuthenticationCallback provider2 = mock(AuthenticationCallback.class); manager.register("test_provider", provider); thrown.expect(IllegalStateException.class); manager.register("test_provider", provider2); }
@Test public void testRegisterAnonymous() { manager.register("anonymous", mock(AuthenticationCallback.class)); verifyNoMoreInteractions(controller); }
@Test public void testRegister() { ParseUser user = mock(ParseUser.class); when(controller.getAsync(false)).thenReturn(Task.forResult(user)); manager.register("test_provider", provider); verify(controller).getAsync(false); verify(user).synchronizeAuthDataAsync("test_provider"); } |
### Question:
ParseGeoPoint implements Parcelable { @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof ParseGeoPoint)) { return false; } if (obj == this) { return true; } return ((ParseGeoPoint) obj).getLatitude() == latitude && ((ParseGeoPoint) obj).getLongitude() == longitude; } ParseGeoPoint(); ParseGeoPoint(double latitude, double longitude); ParseGeoPoint(ParseGeoPoint point); protected ParseGeoPoint(Parcel source); ParseGeoPoint(Parcel source, ParseParcelDecoder decoder); void setLatitude(double latitude); double getLatitude(); void setLongitude(double longitude); double getLongitude(); double distanceInRadiansTo(ParseGeoPoint point); double distanceInKilometersTo(ParseGeoPoint point); double distanceInMilesTo(ParseGeoPoint point); static Task<ParseGeoPoint> getCurrentLocationInBackground(long timeout); static void getCurrentLocationInBackground(long timeout, LocationCallback callback); static Task<ParseGeoPoint> getCurrentLocationInBackground(long timeout, Criteria criteria); static void getCurrentLocationInBackground(long timeout, Criteria criteria,
LocationCallback callback); @Override boolean equals(Object obj); @Override String toString(); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseGeoPoint> CREATOR; }### Answer:
@Test public void testEquals() { ParseGeoPoint pointA = new ParseGeoPoint(30d, 50d); ParseGeoPoint pointB = new ParseGeoPoint(30d, 50d); ParseGeoPoint pointC = new ParseGeoPoint(45d, 45d); assertTrue(pointA.equals(pointB)); assertTrue(pointA.equals(pointA)); assertTrue(pointB.equals(pointA)); assertFalse(pointA.equals(null)); assertFalse(pointA.equals(true)); assertFalse(pointA.equals(pointC)); } |
### Question:
ParsePush { public void setChannel(String channel) { builder.channelSet(Collections.singletonList(channel)); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testSetChannel() { ParsePush push = new ParsePush(); push.setChannel("test"); push.setMessage("message"); ParsePush.State state = push.builder.build(); assertEquals(1, state.channelSet().size()); assertTrue(state.channelSet().contains("test")); } |
### Question:
ParsePush { public void setChannels(Collection<String> channels) { builder.channelSet(channels); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testSetChannels() { ParsePush push = new ParsePush(); List<String> channels = new ArrayList<>(); channels.add("test"); channels.add("testAgain"); push.setChannels(channels); push.setMessage("message"); ParsePush.State state = push.builder.build(); assertEquals(2, state.channelSet().size()); assertTrue(state.channelSet().contains("test")); assertTrue(state.channelSet().contains("testAgain")); } |
### Question:
ParsePush { public void setData(JSONObject data) { builder.data(data); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testSetData() throws Exception { ParsePush push = new ParsePush(); JSONObject data = new JSONObject(); data.put("key", "value"); data.put("keyAgain", "valueAgain"); push.setData(data); ParsePush.State state = push.builder.build(); assertEquals(data, state.data(), JSONCompareMode.NON_EXTENSIBLE); } |
### Question:
ParsePush { public void setMessage(String message) { JSONObject data = new JSONObject(); try { data.put(KEY_DATA_MESSAGE, message); } catch (JSONException e) { PLog.e(TAG, "JSONException in setMessage", e); } setData(data); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testSetMessage() throws Exception { ParsePush push = new ParsePush(); push.setMessage("test"); ParsePush.State state = push.builder.build(); JSONObject data = state.data(); assertEquals("test", data.getString(ParsePush.KEY_DATA_MESSAGE)); } |
### Question:
ParsePush { public void setExpirationTime(long time) { builder.expirationTime(time); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testSetExpirationTime() throws Exception { ParsePush push = new ParsePush(); push.setExpirationTime(10000); push.setMessage("message"); ParsePush.State state = push.builder.build(); assertEquals(10000, state.expirationTime().longValue()); } |
### Question:
ParsePush { public void setExpirationTimeInterval(long timeInterval) { builder.expirationTimeInterval(timeInterval); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testSetExpirationTimeInterval() throws Exception { ParsePush push = new ParsePush(); push.setExpirationTimeInterval(10000); push.setMessage("message"); ParsePush.State state = push.builder.build(); assertEquals(10000, state.expirationTimeInterval().longValue()); } |
### Question:
ParsePush { public void clearExpiration() { builder.expirationTime(null); builder.expirationTimeInterval(null); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testClearExpiration() { ParsePush push = new ParsePush(); push.setExpirationTimeInterval(10000); push.setMessage("message"); ParsePush.State state = push.builder.build(); assertEquals(10000, state.expirationTimeInterval().longValue()); push.clearExpiration(); state = push.builder.build(); assertNull(state.expirationTimeInterval()); push.setExpirationTime(200); state = push.builder.build(); assertEquals(200, state.expirationTime().longValue()); push.clearExpiration(); state = push.builder.build(); assertNull(state.expirationTime()); } |
### Question:
ParsePush { public void setPushTime(long time) { builder.pushTime(time); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testSetPushTime() throws Exception { ParsePush push = new ParsePush(); long time = System.currentTimeMillis() / 1000 + 1000; push.setPushTime(time); push.setMessage("message"); ParsePush.State state = push.builder.build(); assertEquals(time, state.pushTime().longValue()); } |
### Question:
ParsePush { @Deprecated public void setPushToIOS(boolean pushToIOS) { builder.pushToIOS(pushToIOS); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testSetPushToIOS() throws Exception { ParsePush push = new ParsePush(); push.setPushToIOS(true); push.setMessage("message"); ParsePush.State state = push.builder.build(); assertTrue(state.pushToIOS()); } |
### Question:
ParsePush { @Deprecated public void setPushToAndroid(boolean pushToAndroid) { builder.pushToAndroid(pushToAndroid); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testSetPushToAndroid() throws Exception { ParsePush push = new ParsePush(); push.setPushToAndroid(true); push.setMessage("message"); ParsePush.State state = push.builder.build(); assertTrue(state.pushToAndroid()); } |
### Question:
ParsePush { public void setQuery(ParseQuery<ParseInstallation> query) { builder.query(query); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testSetQuery() throws Exception { ParsePush push = new ParsePush(); ParseQuery<ParseInstallation> query = ParseInstallation.getQuery(); query.getBuilder() .whereEqualTo("foo", "bar"); push.setQuery(query); push.setMessage("message"); ParsePush.State state = push.builder.build(); ParseQuery.State<ParseInstallation> queryState = state.queryState(); JSONObject queryStateJson = queryState.toJSON(PointerEncoder.get()); assertEquals("bar", queryStateJson.getJSONObject("where").getString("foo")); } |
### Question:
ParsePush { static ParsePushChannelsController getPushChannelsController() { return ParseCorePlugins.getInstance().getPushChannelsController(); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testGetPushChannelsController() { ParsePushChannelsController controller = mock(ParsePushChannelsController.class); ParseCorePlugins.getInstance().registerPushChannelsController(controller); assertSame(controller, ParsePush.getPushChannelsController()); } |
### Question:
ParsePush { static ParsePushController getPushController() { return ParseCorePlugins.getInstance().getPushController(); } ParsePush(); ParsePush(ParsePush push); private ParsePush(State.Builder builder); static Task<Void> subscribeInBackground(String channel); static void subscribeInBackground(String channel, SaveCallback callback); static Task<Void> unsubscribeInBackground(String channel); static void unsubscribeInBackground(String channel, SaveCallback callback); static Task<Void> sendMessageInBackground(String message,
ParseQuery<ParseInstallation> query); static void sendMessageInBackground(String message, ParseQuery<ParseInstallation> query,
SendCallback callback); static Task<Void> sendDataInBackground(JSONObject data,
ParseQuery<ParseInstallation> query); static void sendDataInBackground(JSONObject data, ParseQuery<ParseInstallation> query,
SendCallback callback); void setChannel(String channel); void setChannels(Collection<String> channels); void setQuery(ParseQuery<ParseInstallation> query); void setExpirationTime(long time); void setExpirationTimeInterval(long timeInterval); void clearExpiration(); void setPushTime(long time); @Deprecated void setPushToIOS(boolean pushToIOS); @Deprecated void setPushToAndroid(boolean pushToAndroid); void setData(JSONObject data); void setMessage(String message); Task<Void> sendInBackground(); void send(); void sendInBackground(SendCallback callback); }### Answer:
@Test public void testGetPushController() { ParsePushController controller = mock(ParsePushController.class); ParseCorePlugins.getInstance().registerPushController(controller); assertSame(controller, ParsePush.getPushController()); } |
### Question:
ParseAnalytics { static ParseAnalyticsController getAnalyticsController() { return ParseCorePlugins.getInstance().getAnalyticsController(); } static Task<Void> trackAppOpenedInBackground(Intent intent); @Deprecated static void trackAppOpened(Intent intent); static void trackAppOpenedInBackground(Intent intent, SaveCallback callback); @Deprecated static void trackEvent(String name); static void trackEventInBackground(String name, SaveCallback callback); @Deprecated static void trackEvent(String name, Map<String, String> dimensions); static void trackEventInBackground(String name, Map<String, String> dimensions, SaveCallback callback); static Task<Void> trackEventInBackground(String name); static Task<Void> trackEventInBackground(final String name,
Map<String, String> dimensions); }### Answer:
@Test public void testGetAnalyticsController() throws Exception{ assertSame(controller, ParseAnalytics.getAnalyticsController()); } |
### Question:
FileObjectStore implements ParseObjectStore<T> { @Override public Task<Void> setAsync(final T object) { return Task.call(new Callable<Void>() { @Override public Void call() throws Exception { saveToDisk(coder, object, file); return null; } }, ParseExecutors.io()); } FileObjectStore(Class<T> clazz, File file, ParseObjectCurrentCoder coder); FileObjectStore(String className, File file, ParseObjectCurrentCoder coder); @Override Task<Void> setAsync(final T object); @Override Task<T> getAsync(); @Override Task<Boolean> existsAsync(); @Override Task<Void> deleteAsync(); }### Answer:
@Test public void testSetAsync() throws Exception { File file = new File(temporaryFolder.getRoot(), "test"); ParseUser.State state = mock(ParseUser.State.class); JSONObject json = new JSONObject(); json.put("foo", "bar"); ParseUserCurrentCoder coder = mock(ParseUserCurrentCoder.class); when(coder.encode(eq(state), (ParseOperationSet) isNull(), any(PointerEncoder.class))) .thenReturn(json); FileObjectStore<ParseUser> store = new FileObjectStore<>(ParseUser.class, file, coder); ParseUser user = mock(ParseUser.class); when(user.getState()).thenReturn(state); ParseTaskUtils.wait(store.setAsync(user)); JSONObject jsonAgain = ParseFileUtils.readFileToJSONObject(file); assertEquals(json, jsonAgain, JSONCompareMode.STRICT); } |
### Question:
FileObjectStore implements ParseObjectStore<T> { @Override public Task<T> getAsync() { return Task.call(new Callable<T>() { @Override public T call() throws Exception { if (!file.exists()) { return null; } return getFromDisk(coder, file, ParseObject.State.newBuilder(className)); } }, ParseExecutors.io()); } FileObjectStore(Class<T> clazz, File file, ParseObjectCurrentCoder coder); FileObjectStore(String className, File file, ParseObjectCurrentCoder coder); @Override Task<Void> setAsync(final T object); @Override Task<T> getAsync(); @Override Task<Boolean> existsAsync(); @Override Task<Void> deleteAsync(); }### Answer:
@Test public void testGetAsync() throws Exception { File file = new File(temporaryFolder.getRoot(), "test"); JSONObject json = new JSONObject(); ParseFileUtils.writeJSONObjectToFile(file, json); ParseUser.State.Builder builder = new ParseUser.State.Builder(); builder.put("foo", "bar"); ParseUserCurrentCoder coder = mock(ParseUserCurrentCoder.class); when(coder.decode(any(ParseUser.State.Builder.class), any(JSONObject.class), any(ParseDecoder.class))) .thenReturn(builder); FileObjectStore<ParseUser> store = new FileObjectStore<>(ParseUser.class, file, coder); ParseUser user = ParseTaskUtils.wait(store.getAsync()); assertEquals("bar", user.getState().get("foo")); } |
### Question:
PushServiceUtils { static PushHandler createPushHandler() { return PushHandler.Factory.create(ManifestInfo.getPushType()); } static boolean runService(Context context, @NonNull Intent intent); }### Answer:
@Test public void testDefaultHandler() { ManifestInfo.setPushType(PushType.NONE); PushHandler handler = PushServiceUtils.createPushHandler(); assertTrue(handler instanceof PushHandler.FallbackHandler); ManifestInfo.setPushType(PushType.GCM); handler = PushServiceUtils.createPushHandler(); assertTrue(handler instanceof GcmPushHandler); } |
### Question:
ParseTextUtils { static String join(CharSequence delimiter, Iterable tokens) { StringBuilder sb = new StringBuilder(); boolean firstTime = true; for (Object item: tokens) { if (firstTime) { firstTime = false; } else { sb.append(delimiter); } sb.append(item); } return sb.toString(); } private ParseTextUtils(); static boolean isEmpty(CharSequence text); static boolean equals(CharSequence a, CharSequence b); }### Answer:
@Test public void testJoinMultipleItems() { String joined = ParseTextUtils.join(",", Arrays.asList("one", "two", "three")); assertEquals("one,two,three", joined); }
@Test public void testJoinSingleItem() { String joined = ParseTextUtils.join(",", Collections.singletonList("one")); assertEquals("one", joined); } |
### Question:
FileObjectStore implements ParseObjectStore<T> { @Override public Task<Boolean> existsAsync() { return Task.call(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return file.exists(); } }, ParseExecutors.io()); } FileObjectStore(Class<T> clazz, File file, ParseObjectCurrentCoder coder); FileObjectStore(String className, File file, ParseObjectCurrentCoder coder); @Override Task<Void> setAsync(final T object); @Override Task<T> getAsync(); @Override Task<Boolean> existsAsync(); @Override Task<Void> deleteAsync(); }### Answer:
@Test public void testExistsAsync() throws Exception { File file = temporaryFolder.newFile("test"); FileObjectStore<ParseUser> store = new FileObjectStore<>(ParseUser.class, file, null); assertTrue(ParseTaskUtils.wait(store.existsAsync())); temporaryFolder.delete(); assertFalse(ParseTaskUtils.wait(store.existsAsync())); } |
### Question:
FileObjectStore implements ParseObjectStore<T> { @Override public Task<Void> deleteAsync() { return Task.call(new Callable<Void>() { @Override public Void call() throws Exception { if (file.exists() && !ParseFileUtils.deleteQuietly(file)) { throw new RuntimeException("Unable to delete"); } return null; } }, ParseExecutors.io()); } FileObjectStore(Class<T> clazz, File file, ParseObjectCurrentCoder coder); FileObjectStore(String className, File file, ParseObjectCurrentCoder coder); @Override Task<Void> setAsync(final T object); @Override Task<T> getAsync(); @Override Task<Boolean> existsAsync(); @Override Task<Void> deleteAsync(); }### Answer:
@Test public void testDeleteAsync() throws Exception { File file = temporaryFolder.newFile("test"); FileObjectStore<ParseUser> store = new FileObjectStore<>(ParseUser.class, file, null); assertTrue(file.exists()); ParseTaskUtils.wait(store.deleteAsync()); assertFalse(file.exists()); } |
### Question:
ParseACL implements Parcelable { Map<String, Permissions> getPermissionsById() { return permissionsById; } ParseACL(); ParseACL(ParseACL acl); ParseACL(ParseUser owner); ParseACL(Parcel source, ParseParcelDecoder decoder); static void setDefaultACL(ParseACL acl, boolean withAccessForCurrentUser); void setPublicReadAccess(boolean allowed); boolean getPublicReadAccess(); void setPublicWriteAccess(boolean allowed); boolean getPublicWriteAccess(); void setReadAccess(String userId, boolean allowed); boolean getReadAccess(String userId); void setWriteAccess(String userId, boolean allowed); boolean getWriteAccess(String userId); void setReadAccess(ParseUser user, boolean allowed); boolean getReadAccess(ParseUser user); void setWriteAccess(ParseUser user, boolean allowed); boolean getWriteAccess(ParseUser user); boolean getRoleReadAccess(String roleName); void setRoleReadAccess(String roleName, boolean allowed); boolean getRoleWriteAccess(String roleName); void setRoleWriteAccess(String roleName, boolean allowed); boolean getRoleReadAccess(ParseRole role); void setRoleReadAccess(ParseRole role, boolean allowed); boolean getRoleWriteAccess(ParseRole role); void setRoleWriteAccess(ParseRole role, boolean allowed); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseACL> CREATOR; }### Answer:
@Test public void testConstructor() throws Exception { ParseACL acl = new ParseACL(); assertEquals(0, acl.getPermissionsById().size()); } |
### Question:
ParseConfigController { ParseCurrentConfigController getCurrentConfigController() { return currentConfigController; } ParseConfigController(ParseHttpClient restClient,
ParseCurrentConfigController currentConfigController); Task<ParseConfig> getAsync(String sessionToken); }### Answer:
@Test public void testConstructor() throws Exception { ParseHttpClient restClient = mock(ParseHttpClient.class); ParseCurrentConfigController currentConfigController = mock(ParseCurrentConfigController.class); ParseConfigController controller = new ParseConfigController(restClient, currentConfigController); assertSame(currentConfigController, controller.getCurrentConfigController()); } |
### Question:
ParseACL implements Parcelable { public void setReadAccess(String userId, boolean allowed) { if (userId == null) { throw new IllegalArgumentException("cannot setReadAccess for null userId"); } boolean writePermission = getWriteAccess(userId); setPermissionsIfNonEmpty(userId, allowed, writePermission); } ParseACL(); ParseACL(ParseACL acl); ParseACL(ParseUser owner); ParseACL(Parcel source, ParseParcelDecoder decoder); static void setDefaultACL(ParseACL acl, boolean withAccessForCurrentUser); void setPublicReadAccess(boolean allowed); boolean getPublicReadAccess(); void setPublicWriteAccess(boolean allowed); boolean getPublicWriteAccess(); void setReadAccess(String userId, boolean allowed); boolean getReadAccess(String userId); void setWriteAccess(String userId, boolean allowed); boolean getWriteAccess(String userId); void setReadAccess(ParseUser user, boolean allowed); boolean getReadAccess(ParseUser user); void setWriteAccess(ParseUser user, boolean allowed); boolean getWriteAccess(ParseUser user); boolean getRoleReadAccess(String roleName); void setRoleReadAccess(String roleName, boolean allowed); boolean getRoleWriteAccess(String roleName); void setRoleWriteAccess(String roleName, boolean allowed); boolean getRoleReadAccess(ParseRole role); void setRoleReadAccess(ParseRole role, boolean allowed); boolean getRoleWriteAccess(ParseRole role); void setRoleWriteAccess(ParseRole role, boolean allowed); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseACL> CREATOR; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testSetReadAccessWithNullUserId() throws Exception { ParseACL acl = new ParseACL(); String userId = null; acl.setReadAccess(userId, true); }
@Test(expected = IllegalArgumentException.class) public void testSetUserReadAccessWithNotSavedNotLazyUser() throws Exception { ParseUser user = new ParseUser(); ParseACL acl = new ParseACL(); acl.setReadAccess(user, true); } |
### Question:
ParseACL implements Parcelable { public void setWriteAccess(String userId, boolean allowed) { if (userId == null) { throw new IllegalArgumentException("cannot setWriteAccess for null userId"); } boolean readPermission = getReadAccess(userId); setPermissionsIfNonEmpty(userId, readPermission, allowed); } ParseACL(); ParseACL(ParseACL acl); ParseACL(ParseUser owner); ParseACL(Parcel source, ParseParcelDecoder decoder); static void setDefaultACL(ParseACL acl, boolean withAccessForCurrentUser); void setPublicReadAccess(boolean allowed); boolean getPublicReadAccess(); void setPublicWriteAccess(boolean allowed); boolean getPublicWriteAccess(); void setReadAccess(String userId, boolean allowed); boolean getReadAccess(String userId); void setWriteAccess(String userId, boolean allowed); boolean getWriteAccess(String userId); void setReadAccess(ParseUser user, boolean allowed); boolean getReadAccess(ParseUser user); void setWriteAccess(ParseUser user, boolean allowed); boolean getWriteAccess(ParseUser user); boolean getRoleReadAccess(String roleName); void setRoleReadAccess(String roleName, boolean allowed); boolean getRoleWriteAccess(String roleName); void setRoleWriteAccess(String roleName, boolean allowed); boolean getRoleReadAccess(ParseRole role); void setRoleReadAccess(ParseRole role, boolean allowed); boolean getRoleWriteAccess(ParseRole role); void setRoleWriteAccess(ParseRole role, boolean allowed); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseACL> CREATOR; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testSetWriteAccessWithNullUserId() throws Exception { ParseACL acl = new ParseACL(); String userId = null; acl.setWriteAccess(userId, true); }
@Test(expected = IllegalArgumentException.class) public void testSetUserWriteAccessWithNotSavedNotLazyUser() throws Exception { ParseUser user = new ParseUser(); ParseACL acl = new ParseACL(); acl.setWriteAccess(user, true); } |
### Question:
ParseACL implements Parcelable { public void setRoleReadAccess(String roleName, boolean allowed) { setReadAccess(KEY_ROLE_PREFIX + roleName, allowed); } ParseACL(); ParseACL(ParseACL acl); ParseACL(ParseUser owner); ParseACL(Parcel source, ParseParcelDecoder decoder); static void setDefaultACL(ParseACL acl, boolean withAccessForCurrentUser); void setPublicReadAccess(boolean allowed); boolean getPublicReadAccess(); void setPublicWriteAccess(boolean allowed); boolean getPublicWriteAccess(); void setReadAccess(String userId, boolean allowed); boolean getReadAccess(String userId); void setWriteAccess(String userId, boolean allowed); boolean getWriteAccess(String userId); void setReadAccess(ParseUser user, boolean allowed); boolean getReadAccess(ParseUser user); void setWriteAccess(ParseUser user, boolean allowed); boolean getWriteAccess(ParseUser user); boolean getRoleReadAccess(String roleName); void setRoleReadAccess(String roleName, boolean allowed); boolean getRoleWriteAccess(String roleName); void setRoleWriteAccess(String roleName, boolean allowed); boolean getRoleReadAccess(ParseRole role); void setRoleReadAccess(ParseRole role, boolean allowed); boolean getRoleWriteAccess(ParseRole role); void setRoleWriteAccess(ParseRole role, boolean allowed); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseACL> CREATOR; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testSetRoleReadAccessWithInvalidRole() throws Exception { ParseRole role = new ParseRole(); role.setName("Player"); ParseACL acl = new ParseACL(); acl.setRoleReadAccess(role, true); }
@Test public void testSetRoleReadAccess() throws Exception { ParseRole role = new ParseRole(); role.setName("Player"); role.setObjectId("test"); ParseACL acl = new ParseACL(); acl.setRoleReadAccess(role, true); assertTrue(acl.getRoleReadAccess(role)); assertEquals(1, acl.getPermissionsById().size()); } |
### Question:
ParseACL implements Parcelable { public void setRoleWriteAccess(String roleName, boolean allowed) { setWriteAccess(KEY_ROLE_PREFIX + roleName, allowed); } ParseACL(); ParseACL(ParseACL acl); ParseACL(ParseUser owner); ParseACL(Parcel source, ParseParcelDecoder decoder); static void setDefaultACL(ParseACL acl, boolean withAccessForCurrentUser); void setPublicReadAccess(boolean allowed); boolean getPublicReadAccess(); void setPublicWriteAccess(boolean allowed); boolean getPublicWriteAccess(); void setReadAccess(String userId, boolean allowed); boolean getReadAccess(String userId); void setWriteAccess(String userId, boolean allowed); boolean getWriteAccess(String userId); void setReadAccess(ParseUser user, boolean allowed); boolean getReadAccess(ParseUser user); void setWriteAccess(ParseUser user, boolean allowed); boolean getWriteAccess(ParseUser user); boolean getRoleReadAccess(String roleName); void setRoleReadAccess(String roleName, boolean allowed); boolean getRoleWriteAccess(String roleName); void setRoleWriteAccess(String roleName, boolean allowed); boolean getRoleReadAccess(ParseRole role); void setRoleReadAccess(ParseRole role, boolean allowed); boolean getRoleWriteAccess(ParseRole role); void setRoleWriteAccess(ParseRole role, boolean allowed); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseACL> CREATOR; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testSetRoleWriteAccessWithInvalidRole() throws Exception { ParseRole role = new ParseRole(); role.setName("Player"); ParseACL acl = new ParseACL(); acl.setRoleWriteAccess(role, true); }
@Test public void testSetRoleWriteAccess() throws Exception { ParseRole role = new ParseRole(); role.setName("Player"); role.setObjectId("test"); ParseACL acl = new ParseACL(); acl.setRoleWriteAccess(role, true); assertTrue(acl.getRoleWriteAccess(role)); assertEquals(1, acl.getPermissionsById().size()); } |
### Question:
ParseACL implements Parcelable { public boolean getPublicReadAccess() { return getReadAccess(PUBLIC_KEY); } ParseACL(); ParseACL(ParseACL acl); ParseACL(ParseUser owner); ParseACL(Parcel source, ParseParcelDecoder decoder); static void setDefaultACL(ParseACL acl, boolean withAccessForCurrentUser); void setPublicReadAccess(boolean allowed); boolean getPublicReadAccess(); void setPublicWriteAccess(boolean allowed); boolean getPublicWriteAccess(); void setReadAccess(String userId, boolean allowed); boolean getReadAccess(String userId); void setWriteAccess(String userId, boolean allowed); boolean getWriteAccess(String userId); void setReadAccess(ParseUser user, boolean allowed); boolean getReadAccess(ParseUser user); void setWriteAccess(ParseUser user, boolean allowed); boolean getWriteAccess(ParseUser user); boolean getRoleReadAccess(String roleName); void setRoleReadAccess(String roleName, boolean allowed); boolean getRoleWriteAccess(String roleName); void setRoleWriteAccess(String roleName, boolean allowed); boolean getRoleReadAccess(ParseRole role); void setRoleReadAccess(ParseRole role, boolean allowed); boolean getRoleWriteAccess(ParseRole role); void setRoleWriteAccess(ParseRole role, boolean allowed); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseACL> CREATOR; }### Answer:
@Test public void testGetPublicReadAccess() throws Exception { ParseACL acl = new ParseACL(); acl.setPublicWriteAccess(true); assertTrue(acl.getPublicWriteAccess()); } |
### Question:
ParseACL implements Parcelable { public boolean getPublicWriteAccess() { return getWriteAccess(PUBLIC_KEY); } ParseACL(); ParseACL(ParseACL acl); ParseACL(ParseUser owner); ParseACL(Parcel source, ParseParcelDecoder decoder); static void setDefaultACL(ParseACL acl, boolean withAccessForCurrentUser); void setPublicReadAccess(boolean allowed); boolean getPublicReadAccess(); void setPublicWriteAccess(boolean allowed); boolean getPublicWriteAccess(); void setReadAccess(String userId, boolean allowed); boolean getReadAccess(String userId); void setWriteAccess(String userId, boolean allowed); boolean getWriteAccess(String userId); void setReadAccess(ParseUser user, boolean allowed); boolean getReadAccess(ParseUser user); void setWriteAccess(ParseUser user, boolean allowed); boolean getWriteAccess(ParseUser user); boolean getRoleReadAccess(String roleName); void setRoleReadAccess(String roleName, boolean allowed); boolean getRoleWriteAccess(String roleName); void setRoleWriteAccess(String roleName, boolean allowed); boolean getRoleReadAccess(ParseRole role); void setRoleReadAccess(ParseRole role, boolean allowed); boolean getRoleWriteAccess(ParseRole role); void setRoleWriteAccess(ParseRole role, boolean allowed); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseACL> CREATOR; }### Answer:
@Test public void testGetPublicWriteAccess() throws Exception { ParseACL acl = new ParseACL(); acl.setPublicWriteAccess(true); assertTrue(acl.getPublicWriteAccess()); } |
### Question:
ParseACL implements Parcelable { public boolean getRoleReadAccess(String roleName) { return getReadAccess(KEY_ROLE_PREFIX + roleName); } ParseACL(); ParseACL(ParseACL acl); ParseACL(ParseUser owner); ParseACL(Parcel source, ParseParcelDecoder decoder); static void setDefaultACL(ParseACL acl, boolean withAccessForCurrentUser); void setPublicReadAccess(boolean allowed); boolean getPublicReadAccess(); void setPublicWriteAccess(boolean allowed); boolean getPublicWriteAccess(); void setReadAccess(String userId, boolean allowed); boolean getReadAccess(String userId); void setWriteAccess(String userId, boolean allowed); boolean getWriteAccess(String userId); void setReadAccess(ParseUser user, boolean allowed); boolean getReadAccess(ParseUser user); void setWriteAccess(ParseUser user, boolean allowed); boolean getWriteAccess(ParseUser user); boolean getRoleReadAccess(String roleName); void setRoleReadAccess(String roleName, boolean allowed); boolean getRoleWriteAccess(String roleName); void setRoleWriteAccess(String roleName, boolean allowed); boolean getRoleReadAccess(ParseRole role); void setRoleReadAccess(ParseRole role, boolean allowed); boolean getRoleWriteAccess(ParseRole role); void setRoleWriteAccess(ParseRole role, boolean allowed); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseACL> CREATOR; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetRoleReadAccessWithInvalidRole() throws Exception { ParseACL acl = new ParseACL(); ParseRole role = new ParseRole(); role.setName("Player"); acl.getRoleReadAccess(role); }
@Test public void testGetRoleReadAccess() throws Exception { ParseACL acl = new ParseACL(); ParseRole role = new ParseRole(); role.setName("Player"); role.setObjectId("test"); acl.setRoleReadAccess(role, true); assertTrue(acl.getRoleReadAccess(role)); } |
### Question:
ParseACL implements Parcelable { public boolean getRoleWriteAccess(String roleName) { return getWriteAccess(KEY_ROLE_PREFIX + roleName); } ParseACL(); ParseACL(ParseACL acl); ParseACL(ParseUser owner); ParseACL(Parcel source, ParseParcelDecoder decoder); static void setDefaultACL(ParseACL acl, boolean withAccessForCurrentUser); void setPublicReadAccess(boolean allowed); boolean getPublicReadAccess(); void setPublicWriteAccess(boolean allowed); boolean getPublicWriteAccess(); void setReadAccess(String userId, boolean allowed); boolean getReadAccess(String userId); void setWriteAccess(String userId, boolean allowed); boolean getWriteAccess(String userId); void setReadAccess(ParseUser user, boolean allowed); boolean getReadAccess(ParseUser user); void setWriteAccess(ParseUser user, boolean allowed); boolean getWriteAccess(ParseUser user); boolean getRoleReadAccess(String roleName); void setRoleReadAccess(String roleName, boolean allowed); boolean getRoleWriteAccess(String roleName); void setRoleWriteAccess(String roleName, boolean allowed); boolean getRoleReadAccess(ParseRole role); void setRoleReadAccess(ParseRole role, boolean allowed); boolean getRoleWriteAccess(ParseRole role); void setRoleWriteAccess(ParseRole role, boolean allowed); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseACL> CREATOR; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetRoleWriteAccessWithInvalidRole() throws Exception { ParseACL acl = new ParseACL(); ParseRole role = new ParseRole(); role.setName("Player"); acl.getRoleWriteAccess(role); }
@Test public void testGetRoleWriteAccess() throws Exception { ParseACL acl = new ParseACL(); ParseRole role = new ParseRole(); role.setName("Player"); role.setObjectId("test"); acl.setRoleWriteAccess(role, true); assertTrue(acl.getRoleWriteAccess(role)); } |
### Question:
ParseACL implements Parcelable { boolean isShared() { return shared; } ParseACL(); ParseACL(ParseACL acl); ParseACL(ParseUser owner); ParseACL(Parcel source, ParseParcelDecoder decoder); static void setDefaultACL(ParseACL acl, boolean withAccessForCurrentUser); void setPublicReadAccess(boolean allowed); boolean getPublicReadAccess(); void setPublicWriteAccess(boolean allowed); boolean getPublicWriteAccess(); void setReadAccess(String userId, boolean allowed); boolean getReadAccess(String userId); void setWriteAccess(String userId, boolean allowed); boolean getWriteAccess(String userId); void setReadAccess(ParseUser user, boolean allowed); boolean getReadAccess(ParseUser user); void setWriteAccess(ParseUser user, boolean allowed); boolean getWriteAccess(ParseUser user); boolean getRoleReadAccess(String roleName); void setRoleReadAccess(String roleName, boolean allowed); boolean getRoleWriteAccess(String roleName); void setRoleWriteAccess(String roleName, boolean allowed); boolean getRoleReadAccess(ParseRole role); void setRoleReadAccess(ParseRole role, boolean allowed); boolean getRoleWriteAccess(ParseRole role); void setRoleWriteAccess(ParseRole role, boolean allowed); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseACL> CREATOR; }### Answer:
@Test public void testIsShared() throws Exception { ParseACL acl = new ParseACL(); acl.setShared(true); assertTrue(acl.isShared()); } |
### Question:
OfflineObjectStore implements ParseObjectStore<T> { @Override public Task<Void> setAsync(final T object) { return ParseObject.unpinAllInBackground(pinName).continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(Task<Void> task) throws Exception { return object.pinInBackground(pinName, false); } }); } OfflineObjectStore(Class<T> clazz, String pinName, ParseObjectStore<T> legacy); OfflineObjectStore(String className, String pinName, ParseObjectStore<T> legacy); @Override Task<Void> setAsync(final T object); @Override Task<T> getAsync(); @Override Task<Boolean> existsAsync(); @Override Task<Void> deleteAsync(); }### Answer:
@Test public void testSetAsync() throws Exception { OfflineStore lds = mock(OfflineStore.class); when(lds.unpinAllObjectsAsync(anyString())).thenReturn(Task.<Void>forResult(null)); when(lds.pinAllObjectsAsync(anyString(), anyList(), anyBoolean())) .thenReturn(Task.forResult(null)); Parse.setLocalDatastore(lds); OfflineObjectStore<ParseUser> store = new OfflineObjectStore<>(ParseUser.class, PIN_NAME, null); ParseUser user = mock(ParseUser.class); ParseTaskUtils.wait(store.setAsync(user)); verify(lds, times(1)).unpinAllObjectsAsync(PIN_NAME); verify(user, times(1)).pinInBackground(PIN_NAME, false); } |
### Question:
PushService extends Service { @Override public void onCreate() { super.onCreate(); if (ParsePlugins.get() == null) { PLog.e(TAG, "The Parse push service cannot start because Parse.initialize " + "has not yet been called. If you call Parse.initialize from " + "an Activity's onCreate, that call should instead be in the " + "Application.onCreate. Be sure your Application class is registered " + "in your AndroidManifest.xml with the android:name property of your " + "<application> tag."); stopSelf(); return; } executor = Executors.newSingleThreadExecutor(); handler = PushServiceUtils.createPushHandler(); dispatchOnServiceCreated(this); } PushService(); @Override void onCreate(); @Override int onStartCommand(final Intent intent, int flags, final int startId); @Override IBinder onBind(Intent intent); @Override void onDestroy(); }### Answer:
@Test public void testOnCreate() { controller.create(); verify(callbacks, times(1)).onServiceCreated(service); } |
### Question:
ParseRESTQueryCommand extends ParseRESTCommand { public static <T extends ParseObject> ParseRESTQueryCommand findCommand( ParseQuery.State<T> state, String sessionToken) { String httpPath = String.format("classes/%s", state.className()); Map <String, String> parameters = encode(state, false); return new ParseRESTQueryCommand( httpPath, ParseHttpRequest.Method.GET, parameters, sessionToken); } private ParseRESTQueryCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken); static ParseRESTQueryCommand findCommand(
ParseQuery.State<T> state, String sessionToken); static ParseRESTQueryCommand countCommand(
ParseQuery.State<T> state, String sessionToken); }### Answer:
@Test public void testFindCommand() throws Exception { ParseQuery.State<ParseObject> state = new ParseQuery.State.Builder<>("TestObject") .selectKeys(Arrays.asList("key", "kayAgain")) .build(); ParseRESTQueryCommand command = ParseRESTQueryCommand.findCommand(state, "sessionToken"); assertEquals("classes/TestObject", command.httpPath); assertEquals(ParseHttpRequest.Method.GET, command.method); assertEquals("sessionToken", command.getSessionToken()); Map<String, String> parameters = ParseRESTQueryCommand.encode(state, false); JSONObject jsonParameters = (JSONObject) NoObjectsEncoder.get().encode(parameters); assertEquals(jsonParameters, command.jsonParameters, JSONCompareMode.NON_EXTENSIBLE); } |
### Question:
ParseRESTQueryCommand extends ParseRESTCommand { public static <T extends ParseObject> ParseRESTQueryCommand countCommand( ParseQuery.State<T> state, String sessionToken) { String httpPath = String.format("classes/%s", state.className()); Map <String, String> parameters = encode(state, true); return new ParseRESTQueryCommand( httpPath, ParseHttpRequest.Method.GET, parameters, sessionToken); } private ParseRESTQueryCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken); static ParseRESTQueryCommand findCommand(
ParseQuery.State<T> state, String sessionToken); static ParseRESTQueryCommand countCommand(
ParseQuery.State<T> state, String sessionToken); }### Answer:
@Test public void testCountCommand() throws Exception { ParseQuery.State<ParseObject> state = new ParseQuery.State.Builder<>("TestObject") .selectKeys(Arrays.asList("key", "kayAgain")) .build(); ParseRESTQueryCommand command = ParseRESTQueryCommand.countCommand(state, "sessionToken"); assertEquals("classes/TestObject", command.httpPath); assertEquals(ParseHttpRequest.Method.GET, command.method); assertEquals("sessionToken", command.getSessionToken()); Map<String, String> parameters = ParseRESTQueryCommand.encode(state, true); JSONObject jsonParameters = (JSONObject) NoObjectsEncoder.get().encode(parameters); assertEquals(jsonParameters, command.jsonParameters, JSONCompareMode.NON_EXTENSIBLE); } |
### Question:
ParseRESTCommand extends ParseRequest<JSONObject> { static String toDeterministicString(Object o) throws JSONException { JSONStringer stringer = new JSONStringer(); addToStringer(stringer, o); return stringer.toString(); } ParseRESTCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
Map<String, ?> parameters,
String sessionToken); ParseRESTCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
JSONObject jsonParameters,
String sessionToken); private ParseRESTCommand(
String httpPath,
ParseHttpRequest.Method httpMethod,
JSONObject jsonParameters,
String localId, String sessionToken); ParseRESTCommand(Init<?> builder); static ParseRESTCommand fromJSONObject(JSONObject jsonObject); @Override Task<JSONObject> executeAsync(
final ParseHttpClient client,
final ProgressCallback uploadProgressCallback,
final ProgressCallback downloadProgressCallback,
final Task<Void> cancellationToken); String getCacheKey(); JSONObject toJSONObject(); String getSessionToken(); String getOperationSetUUID(); void setLocalId(String localId); String getLocalId(); void resolveLocalIds(); void retainLocalIds(); void releaseLocalIds(); public String masterKey; }### Answer:
@Test public void testToDeterministicString() throws Exception { JSONArray nestedJSONArray = new JSONArray() .put(true) .put(1) .put("test"); JSONObject nestedJSON = new JSONObject() .put("bool", false) .put("int", 2) .put("string", "test"); JSONObject json = new JSONObject() .put("json", nestedJSON) .put("jsonArray", nestedJSONArray) .put("bool", true) .put("int", 3) .put("string", "test"); String jsonString = ParseRESTCommand.toDeterministicString(json); JSONObject jsonAgain = new JSONObject(jsonString); assertEquals(json, jsonAgain, JSONCompareMode.NON_EXTENSIBLE); } |
### Question:
PushService extends Service { void setPushHandler(PushHandler handler) { this.handler = handler; } PushService(); @Override void onCreate(); @Override int onStartCommand(final Intent intent, int flags, final int startId); @Override IBinder onBind(Intent intent); @Override void onDestroy(); }### Answer:
@Test public void testStartCommand() throws Exception { controller.create(); service.setPushHandler(handler); final TaskCompletionSource<Void> tcs = new TaskCompletionSource<>(); final Task<Void> handleTask = tcs.getTask(); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { tcs.setResult(null); return null; } }).when(handler).handlePush(any(Intent.class)); controller.startCommand(0, 0); handleTask.waitForCompletion(); verify(callbacks, times(1)).onServiceCreated(service); verify(handler, times(1)).handlePush(any(Intent.class)); } |
### Question:
NetworkQueryController extends AbstractQueryController { <T extends ParseObject> List<T> convertFindResponse(ParseQuery.State<T> state, JSONObject response) throws JSONException { ArrayList<T> answer = new ArrayList<>(); JSONArray results = response.getJSONArray("results"); if (results == null) { PLog.d(TAG, "null results in find response"); } else { String resultClassName = response.optString("className", null); if (resultClassName == null) { resultClassName = state.className(); } for (int i = 0; i < results.length(); ++i) { JSONObject data = results.getJSONObject(i); T object = ParseObject.fromJSON(data, resultClassName, ParseDecoder.get(), state.selectedKeys()); answer.add(object); ParseQuery.RelationConstraint relation = (ParseQuery.RelationConstraint) state.constraints().get("$relatedTo"); if (relation != null) { relation.getRelation().addKnownObject(object); } } } return answer; } NetworkQueryController(ParseHttpClient restClient); @Override Task<List<T>> findAsync(
ParseQuery.State<T> state, ParseUser user, Task<Void> cancellationToken); @Override Task<Integer> countAsync(
ParseQuery.State<T> state, ParseUser user, Task<Void> cancellationToken); }### Answer:
@Test public void testConvertFindResponse() throws Exception { JSONObject mockResponse = generateBasicMockResponse(); ParseQuery.State mockState = mock(ParseQuery.State.class); when(mockState.className()).thenReturn("Test"); when(mockState.selectedKeys()).thenReturn(null); when(mockState.constraints()).thenReturn(new ParseQuery.QueryConstraints()); NetworkQueryController controller = new NetworkQueryController(mock(ParseHttpClient.class)); List<ParseObject> objects = controller.convertFindResponse(mockState, mockResponse); verifyBasicParseObjects(mockResponse, objects, "Test"); } |
### Question:
OfflineQueryController extends AbstractQueryController { @Override public <T extends ParseObject> Task<List<T>> findAsync( ParseQuery.State<T> state, ParseUser user, Task<Void> cancellationToken) { if (state.isFromLocalDatastore()) { return offlineStore.findFromPinAsync(state.pinName(), state, user); } else { return networkController.findAsync(state, user, cancellationToken); } } OfflineQueryController(OfflineStore store, ParseQueryController network); @Override Task<List<T>> findAsync(
ParseQuery.State<T> state,
ParseUser user,
Task<Void> cancellationToken); @Override Task<Integer> countAsync(
ParseQuery.State<T> state,
ParseUser user,
Task<Void> cancellationToken); }### Answer:
@Test public void testFindFromNetwork() { TestNetworkQueryController networkController = new TestNetworkQueryController(); OfflineQueryController controller = new OfflineQueryController(null, networkController); ParseQuery.State<ParseObject> state = new ParseQuery.State.Builder<>("TestObject") .build(); controller.findAsync(state, null, null); networkController.verifyFind(); }
@Test public void testFindFromLDS() { Parse.enableLocalDatastore(null); TestOfflineStore offlineStore = new TestOfflineStore(); OfflineQueryController controller = new OfflineQueryController(offlineStore, null); ParseQuery.State<ParseObject> state = new ParseQuery.State.Builder<>("TestObject") .fromLocalDatastore() .build(); controller.findAsync(state, null, null); offlineStore.verifyFind(); } |
### Question:
OfflineQueryController extends AbstractQueryController { @Override public <T extends ParseObject> Task<Integer> countAsync( ParseQuery.State<T> state, ParseUser user, Task<Void> cancellationToken) { if (state.isFromLocalDatastore()) { return offlineStore.countFromPinAsync(state.pinName(), state, user); } else { return networkController.countAsync(state, user, cancellationToken); } } OfflineQueryController(OfflineStore store, ParseQueryController network); @Override Task<List<T>> findAsync(
ParseQuery.State<T> state,
ParseUser user,
Task<Void> cancellationToken); @Override Task<Integer> countAsync(
ParseQuery.State<T> state,
ParseUser user,
Task<Void> cancellationToken); }### Answer:
@Test public void testCountFromNetwork() { TestNetworkQueryController networkController = new TestNetworkQueryController(); OfflineQueryController controller = new OfflineQueryController(null, networkController); ParseQuery.State<ParseObject> state = new ParseQuery.State.Builder<>("TestObject") .build(); controller.countAsync(state, null, null); networkController.verifyCount(); }
@Test public void testCountFromLDS() { Parse.enableLocalDatastore(null); TestOfflineStore offlineStore = new TestOfflineStore(); OfflineQueryController controller = new OfflineQueryController(offlineStore, null); ParseQuery.State<ParseObject> state = new ParseQuery.State.Builder<>("TestObject") .fromLocalDatastore() .build(); controller.countAsync(state, null, null); offlineStore.verifyCount(); } |
### Question:
Lists { static <T> List<List<T>> partition(List<T> list, int size) { return new Partition<>(list, size); } }### Answer:
@Test public void testPartition() throws Exception { List<Integer> list = new ArrayList<>(); for (int i = 0; i < 99; i++) { list.add(i); } List<List<Integer>> partitions = Lists.partition(list, 5); assertEquals(20, partitions.size()); int count = 0; for (int i = 0; i < 19; i++) { List<Integer> partition = partitions.get(i); assertEquals(5, partition.size()); for (int j : partition) { assertEquals(count, j); count += 1; } } assertEquals(4, partitions.get(19).size()); for (int i = 0; i < 4; i++) { assertEquals(95 + i, partitions.get(19).get(i).intValue()); } }
@Test public void testPartition() { List<Integer> list = new ArrayList<>(); for (int i = 0; i < 99; i++) { list.add(i); } List<List<Integer>> partitions = Lists.partition(list, 5); assertEquals(20, partitions.size()); int count = 0; for (int i = 0; i < 19; i++) { List<Integer> partition = partitions.get(i); assertEquals(5, partition.size()); for (int j : partition) { assertEquals(count, j); count += 1; } } assertEquals(4, partitions.get(19).size()); for (int i = 0; i < 4; i++) { assertEquals(95 + i, partitions.get(19).get(i).intValue()); } } |
### Question:
ParseKeyValueCache { static int size() { File[] files = getKeyValueCacheDir().listFiles(); if (files == null) { return 0; } return files.length; } }### Answer:
@Test public void testGetSizeWithoutCacheDir() throws Exception { assertTrue(keyValueCacheDir.exists()); keyValueCacheDir.delete(); assertFalse(keyValueCacheDir.exists()); assertEquals(0, ParseKeyValueCache.size()); }
@Test public void testGetSizeWithoutCacheDir() { assertTrue(keyValueCacheDir.exists()); keyValueCacheDir.delete(); assertFalse(keyValueCacheDir.exists()); assertEquals(0, ParseKeyValueCache.size()); } |
### Question:
NetworkQueryController extends AbstractQueryController { @Override public <T extends ParseObject> Task<List<T>> findAsync( ParseQuery.State<T> state, ParseUser user, Task<Void> cancellationToken) { String sessionToken = user != null ? user.getSessionToken() : null; return findAsync(state, sessionToken, cancellationToken); } NetworkQueryController(ParseHttpClient restClient); @Override Task<List<T>> findAsync(
ParseQuery.State<T> state, ParseUser user, Task<Void> cancellationToken); @Override Task<Integer> countAsync(
ParseQuery.State<T> state, ParseUser user, Task<Void> cancellationToken); }### Answer:
@Test public void testFindAsyncWithSessionToken() throws Exception { JSONObject mockResponse = generateBasicMockResponse(); mockResponse.put("trace", "serverTrace"); ParseHttpClient restClient = ParseTestUtils.mockParseHttpClientWithResponse(mockResponse, 200, "OK"); ParseQuery.State mockState = mock(ParseQuery.State.class); when(mockState.className()).thenReturn("Test"); when(mockState.selectedKeys()).thenReturn(null); when(mockState.constraints()).thenReturn(new ParseQuery.QueryConstraints()); NetworkQueryController controller = new NetworkQueryController(restClient); Task<List<ParseObject>> findTask = controller.findAsync(mockState, "sessionToken", null); ParseTaskUtils.wait(findTask); List<ParseObject> objects = findTask.getResult(); verifyBasicParseObjects(mockResponse, objects, "Test"); } |
### Question:
ParseInstallation extends ParseObject { @Override public void setObjectId(String newObjectId) { throw new RuntimeException("Installation's objectId cannot be changed"); } ParseInstallation(); static ParseInstallation getCurrentInstallation(); static ParseQuery<ParseInstallation> getQuery(); String getInstallationId(); @Override void setObjectId(String newObjectId); }### Answer:
@Test (expected = RuntimeException.class) public void testInstallationObjectIdCannotBeChanged() throws Exception { boolean hasException = false; ParseInstallation installation = new ParseInstallation(); try { installation.put("objectId", "abc"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("Cannot modify")); hasException = true; } assertTrue(hasException); installation.setObjectId("abc"); } |
### Question:
ParseInstallation extends ParseObject { @Override Task<Void> handleSaveResultAsync(ParseObject.State result, ParseOperationSet operationsBeforeSave) { Task<Void> task = super.handleSaveResultAsync(result, operationsBeforeSave); if (result == null) { return task; } return task.onSuccessTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(Task<Void> task) throws Exception { return getCurrentInstallationController().setAsync(ParseInstallation.this); } }); } ParseInstallation(); static ParseInstallation getCurrentInstallation(); static ParseQuery<ParseInstallation> getQuery(); String getInstallationId(); @Override void setObjectId(String newObjectId); }### Answer:
@Test public void testHandleSaveResultAsync() throws Exception { ParseCurrentInstallationController controller = mock(ParseCurrentInstallationController.class); when(controller.setAsync(any(ParseInstallation.class))).thenReturn(Task.<Void>forResult(null)); ParseCorePlugins.getInstance().registerCurrentInstallationController(controller); ParseInstallation.State state = new ParseInstallation.State.Builder("_Installation") .put("key", "value") .build(); ParseInstallation installation = new ParseInstallation(); installation.put("keyAgain", "valueAgain"); ParseOperationSet operationSet = installation.startSave(); ParseTaskUtils.wait(installation.handleSaveResultAsync(state, operationSet)); assertEquals("value", installation.get("key")); assertEquals("valueAgain", installation.get("keyAgain")); verify(controller, times(1)).setAsync(installation); } |
### Question:
ParseInstallation extends ParseObject { @Override Task<Void> handleFetchResultAsync(final ParseObject.State newState) { return super.handleFetchResultAsync(newState).onSuccessTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(Task<Void> task) throws Exception { return getCurrentInstallationController().setAsync(ParseInstallation.this); } }); } ParseInstallation(); static ParseInstallation getCurrentInstallation(); static ParseQuery<ParseInstallation> getQuery(); String getInstallationId(); @Override void setObjectId(String newObjectId); }### Answer:
@Test public void testHandleFetchResultAsync() throws Exception { ParseCurrentInstallationController controller = mock(ParseCurrentInstallationController.class); when(controller.setAsync(any(ParseInstallation.class))).thenReturn(Task.<Void>forResult(null)); ParseCorePlugins.getInstance().registerCurrentInstallationController(controller); ParseInstallation.State state = new ParseInstallation.State.Builder("_Installation") .put("key", "value") .isComplete(true) .build(); ParseInstallation installation = new ParseInstallation(); ParseTaskUtils.wait(installation.handleFetchResultAsync(state)); assertEquals("value", installation.get("key")); verify(controller, times(1)).setAsync(installation); } |
### Question:
ParseInstallation extends ParseObject { public static ParseInstallation getCurrentInstallation() { try { return ParseTaskUtils.wait( getCurrentInstallationController().getAsync()); } catch (ParseException e) { return null; } } ParseInstallation(); static ParseInstallation getCurrentInstallation(); static ParseQuery<ParseInstallation> getQuery(); String getInstallationId(); @Override void setObjectId(String newObjectId); }### Answer:
@Test public void testGetCurrentInstallation() throws Exception { ParseCurrentInstallationController controller = mock(ParseCurrentInstallationController.class); ParseInstallation currentInstallation = new ParseInstallation(); when(controller.getAsync()).thenReturn(Task.forResult(currentInstallation)); ParseCorePlugins.getInstance().registerCurrentInstallationController(controller); ParseInstallation installation = ParseInstallation.getCurrentInstallation(); assertEquals(currentInstallation, installation); verify(controller, times(1)).getAsync(); } |
### Question:
NetworkQueryController extends AbstractQueryController { @Override public <T extends ParseObject> Task<Integer> countAsync( ParseQuery.State<T> state, ParseUser user, Task<Void> cancellationToken) { String sessionToken = user != null ? user.getSessionToken() : null; return countAsync(state, sessionToken, cancellationToken); } NetworkQueryController(ParseHttpClient restClient); @Override Task<List<T>> findAsync(
ParseQuery.State<T> state, ParseUser user, Task<Void> cancellationToken); @Override Task<Integer> countAsync(
ParseQuery.State<T> state, ParseUser user, Task<Void> cancellationToken); }### Answer:
@Test public void testCountAsyncWithSessionToken() throws Exception { JSONObject mockResponse = new JSONObject(); mockResponse.put("count", 2); ParseHttpClient restClient = ParseTestUtils.mockParseHttpClientWithResponse(mockResponse, 200, "OK"); ParseQuery.State mockState = mock(ParseQuery.State.class); when(mockState.className()).thenReturn("Test"); when(mockState.selectedKeys()).thenReturn(null); when(mockState.constraints()).thenReturn(new ParseQuery.QueryConstraints()); NetworkQueryController controller = new NetworkQueryController(restClient); Task<Integer> countTask = controller.countAsync(mockState, "sessionToken", null); ParseTaskUtils.wait(countTask); int count = countTask.getResult(); assertEquals(2, count); } |
### Question:
ParseFileUtils { public static String readFileToString(File file, Charset encoding) throws IOException { return new String(readFileToByteArray(file), encoding); } static byte[] readFileToByteArray(File file); static FileInputStream openInputStream(File file); static void writeByteArrayToFile(File file, byte[] data); static FileOutputStream openOutputStream(File file); static void moveFile(final File srcFile, final File destFile); static void copyFile(final File srcFile, final File destFile); static void copyFile(final File srcFile, final File destFile,
final boolean preserveFileDate); static void deleteDirectory(final File directory); static boolean deleteQuietly(final File file); static void cleanDirectory(final File directory); static void forceDelete(final File file); static boolean isSymlink(final File file); static String readFileToString(File file, Charset encoding); static String readFileToString(File file, String encoding); static void writeStringToFile(File file, String string, Charset encoding); static void writeStringToFile(File file, String string, String encoding); static JSONObject readFileToJSONObject(File file); static void writeJSONObjectToFile(File file, JSONObject json); static final long ONE_KB; static final long ONE_MB; }### Answer:
@Test public void testReadFileToString() throws Exception { File file = temporaryFolder.newFile("file.txt"); BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); out.write(TEST_STRING.getBytes("UTF-8")); } finally { ParseIOUtils.closeQuietly(out); } assertEquals(TEST_STRING, ParseFileUtils.readFileToString(file, "UTF-8")); } |
### Question:
ParseFileUtils { public static void writeStringToFile(File file, String string, Charset encoding) throws IOException { writeByteArrayToFile(file, string.getBytes(encoding)); } static byte[] readFileToByteArray(File file); static FileInputStream openInputStream(File file); static void writeByteArrayToFile(File file, byte[] data); static FileOutputStream openOutputStream(File file); static void moveFile(final File srcFile, final File destFile); static void copyFile(final File srcFile, final File destFile); static void copyFile(final File srcFile, final File destFile,
final boolean preserveFileDate); static void deleteDirectory(final File directory); static boolean deleteQuietly(final File file); static void cleanDirectory(final File directory); static void forceDelete(final File file); static boolean isSymlink(final File file); static String readFileToString(File file, Charset encoding); static String readFileToString(File file, String encoding); static void writeStringToFile(File file, String string, Charset encoding); static void writeStringToFile(File file, String string, String encoding); static JSONObject readFileToJSONObject(File file); static void writeJSONObjectToFile(File file, JSONObject json); static final long ONE_KB; static final long ONE_MB; }### Answer:
@Test public void testWriteStringToFile() throws Exception { File file = temporaryFolder.newFile("file.txt"); ParseFileUtils.writeStringToFile(file, TEST_STRING, "UTF-8"); InputStream in = null; String content = null; try { in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(); ParseIOUtils.copy(in, out); content = new String(out.toByteArray(), "UTF-8"); } finally { ParseIOUtils.closeQuietly(in); } assertEquals(TEST_STRING, content); } |
### Question:
ParseFileUtils { public static JSONObject readFileToJSONObject(File file) throws IOException, JSONException { String content = readFileToString(file, "UTF-8"); return new JSONObject(content); } static byte[] readFileToByteArray(File file); static FileInputStream openInputStream(File file); static void writeByteArrayToFile(File file, byte[] data); static FileOutputStream openOutputStream(File file); static void moveFile(final File srcFile, final File destFile); static void copyFile(final File srcFile, final File destFile); static void copyFile(final File srcFile, final File destFile,
final boolean preserveFileDate); static void deleteDirectory(final File directory); static boolean deleteQuietly(final File file); static void cleanDirectory(final File directory); static void forceDelete(final File file); static boolean isSymlink(final File file); static String readFileToString(File file, Charset encoding); static String readFileToString(File file, String encoding); static void writeStringToFile(File file, String string, Charset encoding); static void writeStringToFile(File file, String string, String encoding); static JSONObject readFileToJSONObject(File file); static void writeJSONObjectToFile(File file, JSONObject json); static final long ONE_KB; static final long ONE_MB; }### Answer:
@Test public void testReadFileToJSONObject() throws Exception { File file = temporaryFolder.newFile("file.txt"); BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); out.write(TEST_JSON.getBytes("UTF-8")); } finally { ParseIOUtils.closeQuietly(out); } JSONObject json = ParseFileUtils.readFileToJSONObject(file); assertNotNull(json); assertEquals("bar", json.getString("foo")); } |
### Question:
ParseFileUtils { public static void writeJSONObjectToFile(File file, JSONObject json) throws IOException { ParseFileUtils.writeByteArrayToFile(file, json.toString().getBytes(Charset.forName("UTF-8"))); } static byte[] readFileToByteArray(File file); static FileInputStream openInputStream(File file); static void writeByteArrayToFile(File file, byte[] data); static FileOutputStream openOutputStream(File file); static void moveFile(final File srcFile, final File destFile); static void copyFile(final File srcFile, final File destFile); static void copyFile(final File srcFile, final File destFile,
final boolean preserveFileDate); static void deleteDirectory(final File directory); static boolean deleteQuietly(final File file); static void cleanDirectory(final File directory); static void forceDelete(final File file); static boolean isSymlink(final File file); static String readFileToString(File file, Charset encoding); static String readFileToString(File file, String encoding); static void writeStringToFile(File file, String string, Charset encoding); static void writeStringToFile(File file, String string, String encoding); static JSONObject readFileToJSONObject(File file); static void writeJSONObjectToFile(File file, JSONObject json); static final long ONE_KB; static final long ONE_MB; }### Answer:
@Test public void testWriteJSONObjectToFile() throws Exception { File file = temporaryFolder.newFile("file.txt"); ParseFileUtils.writeJSONObjectToFile(file, new JSONObject(TEST_JSON)); InputStream in = null; String content = null; try { in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(); ParseIOUtils.copy(in, out); content = new String(out.toByteArray()); } finally { ParseIOUtils.closeQuietly(in); } JSONObject json = new JSONObject(content); assertNotNull(json); assertEquals("bar", json.getString("foo")); } |
### Question:
ParseCurrentConfigController { public Task<Void> setCurrentConfigAsync(final ParseConfig config) { return Task.call(new Callable<Void>() { @Override public Void call() throws Exception { synchronized (currentConfigMutex) { currentConfig = config; saveToDisk(config); } return null; } }, ParseExecutors.io()); } ParseCurrentConfigController(File currentConfigFile); Task<Void> setCurrentConfigAsync(final ParseConfig config); Task<ParseConfig> getCurrentConfigAsync(); }### Answer:
@Test public void testSetCurrentConfigAsyncSuccess() throws Exception { File configFile = new File(temporaryFolder.getRoot(), "config"); ParseCurrentConfigController currentConfigController = new ParseCurrentConfigController(configFile); assertFalse(configFile.exists()); assertNull(currentConfigController.currentConfig); ParseConfig config = new ParseConfig(); ParseTaskUtils.wait(currentConfigController.setCurrentConfigAsync(config)); assertTrue(configFile.exists()); assertSame(config, currentConfigController.currentConfig); } |
### Question:
ParseCurrentConfigController { public Task<ParseConfig> getCurrentConfigAsync() { return Task.call(new Callable<ParseConfig>() { @Override public ParseConfig call() throws Exception { synchronized (currentConfigMutex) { if (currentConfig == null) { ParseConfig config = getFromDisk(); currentConfig = (config != null) ? config : new ParseConfig(); } } return currentConfig; } }, ParseExecutors.io()); } ParseCurrentConfigController(File currentConfigFile); Task<Void> setCurrentConfigAsync(final ParseConfig config); Task<ParseConfig> getCurrentConfigAsync(); }### Answer:
@Test public void testGetCurrentConfigAsyncSuccessCurrentConfigAlreadySet() throws Exception { File configFile = new File(temporaryFolder.getRoot(), "config"); ParseCurrentConfigController currentConfigController = new ParseCurrentConfigController(configFile); ParseConfig config = new ParseConfig(); currentConfigController.currentConfig = config; Task<ParseConfig> getTask = currentConfigController.getCurrentConfigAsync(); ParseTaskUtils.wait(getTask); ParseConfig configAgain = getTask.getResult(); assertSame(config, configAgain); }
@Test public void testGetCurrentConfigAsyncSuccessCurrentConfigNotSetDiskConfigNotExist() throws Exception { File configFile = new File(temporaryFolder.getRoot(), "config"); ParseCurrentConfigController currentConfigController = new ParseCurrentConfigController(configFile); assertFalse(configFile.exists()); assertNull(currentConfigController.currentConfig); Task<ParseConfig> getTask = currentConfigController.getCurrentConfigAsync(); ParseTaskUtils.wait(getTask); ParseConfig config = getTask.getResult(); assertSame(config, currentConfigController.currentConfig); assertEquals(0, config.getParams().size()); } |
### Question:
ParseCurrentConfigController { void clearCurrentConfigForTesting() { synchronized (currentConfigMutex) { currentConfig = null; } } ParseCurrentConfigController(File currentConfigFile); Task<Void> setCurrentConfigAsync(final ParseConfig config); Task<ParseConfig> getCurrentConfigAsync(); }### Answer:
@Test public void testClearCurrentConfigForTestingSuccess() throws Exception { File configFile = new File(temporaryFolder.getRoot(), "config"); ParseCurrentConfigController currentConfigController = new ParseCurrentConfigController(configFile); currentConfigController.currentConfig = new ParseConfig(); assertNotNull(currentConfigController.currentConfig); currentConfigController.clearCurrentConfigForTesting(); assertNull(currentConfigController.currentConfig); }
@Test public void testClearCurrentConfigForTestingSuccess() { File configFile = new File(temporaryFolder.getRoot(), "config"); ParseCurrentConfigController currentConfigController = new ParseCurrentConfigController(configFile); currentConfigController.currentConfig = new ParseConfig(); assertNotNull(currentConfigController.currentConfig); currentConfigController.clearCurrentConfigForTesting(); assertNull(currentConfigController.currentConfig); } |
### Question:
ParseCountingByteArrayHttpBody extends ParseByteArrayHttpBody { @Override public void writeTo(OutputStream out) throws IOException { if (out == null) { throw new IllegalArgumentException("Output stream may not be null"); } int position = 0; int totalLength = content.length; while (position < totalLength) { int length = min(totalLength - position, DEFAULT_CHUNK_SIZE); out.write(content, position, length); out.flush(); if (progressCallback != null) { position += length; int progress = 100 * position / totalLength; progressCallback.done(progress); } } } ParseCountingByteArrayHttpBody(byte[] content, String contentType,
final ProgressCallback progressCallback); @Override void writeTo(OutputStream out); }### Answer:
@Test public void testWriteTo() throws IOException, InterruptedException { byte[] content = getData(); String contentType = "application/json"; final Semaphore didReportIntermediateProgress = new Semaphore(0); final Semaphore finish = new Semaphore(0); ParseCountingByteArrayHttpBody body = new ParseCountingByteArrayHttpBody( content, contentType, new ProgressCallback() { Integer maxProgressSoFar = 0; @Override public void done(Integer percentDone) { if (percentDone > maxProgressSoFar) { maxProgressSoFar = percentDone; assertTrue(percentDone >= 0 && percentDone <= 100); if (percentDone < 100 && percentDone > 0) { didReportIntermediateProgress.release(); } else if (percentDone == 100) { finish.release(); } else if (percentDone == 0) { } else { fail("percentDone should be within 0 - 100"); } } } }); ByteArrayOutputStream output = new ByteArrayOutputStream(); body.writeTo(output); assertTrue(Arrays.equals(content, output.toByteArray())); assertTrue(didReportIntermediateProgress.tryAcquire(5, TimeUnit.SECONDS)); assertTrue(finish.tryAcquire(5, TimeUnit.SECONDS)); } |
### Question:
ParseAuthenticationManager { public Task<Void> deauthenticateAsync(String authType) { final AuthenticationCallback callback; synchronized (lock) { callback = this.callbacks.get(authType); } if (callback != null) { return Task.call(new Callable<Void>() { @Override public Void call() throws Exception { callback.onRestore(null); return null; } }, ParseExecutors.io()); } return Task.forResult(null); } ParseAuthenticationManager(ParseCurrentUserController controller); void register(final String authType, AuthenticationCallback callback); Task<Boolean> restoreAuthenticationAsync(String authType, final Map<String, String> authData); Task<Void> deauthenticateAsync(String authType); }### Answer:
@Test public void testDeauthenticateAsync() throws ParseException { when(controller.getAsync(false)).thenReturn(Task.<ParseUser>forResult(null)); manager.register("test_provider", provider); ParseTaskUtils.wait(manager.deauthenticateAsync("test_provider")); verify(provider).onRestore(null); } |
### Question:
NetworkUserController implements ParseUserController { @Override public Task<ParseUser.State> getUserAsync(String sessionToken) { ParseRESTCommand command = ParseRESTUserCommand.getCurrentUserCommand(sessionToken); return command.executeAsync(client).onSuccess(new Continuation<JSONObject, ParseUser.State>() { @Override public ParseUser.State then(Task<JSONObject> task) throws Exception { JSONObject result = task.getResult(); return coder.decode(new ParseUser.State.Builder(), result, ParseDecoder.get()) .isComplete(true) .build(); } }); } NetworkUserController(ParseHttpClient client); NetworkUserController(ParseHttpClient client, boolean revocableSession); @Override Task<ParseUser.State> signUpAsync(
final ParseObject.State state,
ParseOperationSet operations,
String sessionToken); @Override Task<ParseUser.State> logInAsync(
String username, String password); @Override Task<ParseUser.State> logInAsync(
ParseUser.State state, ParseOperationSet operations); @Override Task<ParseUser.State> logInAsync(
final String authType, final Map<String, String> authData); @Override Task<ParseUser.State> getUserAsync(String sessionToken); @Override Task<Void> requestPasswordResetAsync(String email); }### Answer:
@Test public void testGetUserAsync() throws Exception { JSONObject mockResponse = generateBasicMockResponse(); ParseHttpClient restClient = ParseTestUtils.mockParseHttpClientWithResponse(mockResponse, 201, "OK"); NetworkUserController controller = new NetworkUserController(restClient, true); ParseUser.State newState = ParseTaskUtils.wait(controller.getUserAsync("sessionToken")); verifyBasicUserState(mockResponse, newState); assertTrue(newState.isComplete()); assertFalse(newState.isNew()); } |
### Question:
NetworkUserController implements ParseUserController { @Override public Task<Void> requestPasswordResetAsync(String email) { ParseRESTCommand command = ParseRESTUserCommand.resetPasswordResetCommand(email); return command.executeAsync(client).makeVoid(); } NetworkUserController(ParseHttpClient client); NetworkUserController(ParseHttpClient client, boolean revocableSession); @Override Task<ParseUser.State> signUpAsync(
final ParseObject.State state,
ParseOperationSet operations,
String sessionToken); @Override Task<ParseUser.State> logInAsync(
String username, String password); @Override Task<ParseUser.State> logInAsync(
ParseUser.State state, ParseOperationSet operations); @Override Task<ParseUser.State> logInAsync(
final String authType, final Map<String, String> authData); @Override Task<ParseUser.State> getUserAsync(String sessionToken); @Override Task<Void> requestPasswordResetAsync(String email); }### Answer:
@Test public void testRequestPasswordResetAsync() throws Exception { ParseHttpClient restClient = ParseTestUtils.mockParseHttpClientWithResponse(new JSONObject(), 200, "OK"); NetworkUserController controller = new NetworkUserController(restClient, true); ParseTaskUtils.wait(controller.requestPasswordResetAsync("sessionToken")); } |
### Question:
ParseFileController { public File getCacheFile(ParseFile.State state) { return new File(cachePath, state.name()); } ParseFileController(ParseHttpClient restClient, File cachePath); File getCacheFile(ParseFile.State state); boolean isDataAvailable(ParseFile.State state); void clearCache(); Task<ParseFile.State> saveAsync(
final ParseFile.State state,
final byte[] data,
String sessionToken,
ProgressCallback uploadProgressCallback,
Task<Void> cancellationToken); Task<ParseFile.State> saveAsync(
final ParseFile.State state,
final File file,
String sessionToken,
ProgressCallback uploadProgressCallback,
Task<Void> cancellationToken); Task<File> fetchAsync(
final ParseFile.State state,
@SuppressWarnings("UnusedParameters") String sessionToken,
final ProgressCallback downloadProgressCallback,
final Task<Void> cancellationToken); }### Answer:
@Test public void testGetCacheFile() throws Exception { File root = temporaryFolder.getRoot(); ParseFileController controller = new ParseFileController(null, root); ParseFile.State state = new ParseFile.State.Builder().name("test_file").build(); File cacheFile = controller.getCacheFile(state); assertEquals(new File(root, "test_file"), cacheFile); } |
### Question:
CachedCurrentUserController implements ParseCurrentUserController { @Override public Task<String> getCurrentSessionTokenAsync() { return getAsync(false).onSuccess(new Continuation<ParseUser, String>() { @Override public String then(Task<ParseUser> task) throws Exception { ParseUser user = task.getResult(); return user != null ? user.getSessionToken() : null; } }); } CachedCurrentUserController(ParseObjectStore<ParseUser> store); @Override Task<Void> setAsync(final ParseUser user); @Override Task<Void> setIfNeededAsync(ParseUser user); @Override Task<ParseUser> getAsync(); @Override Task<Boolean> existsAsync(); @Override boolean isCurrent(ParseUser user); @Override void clearFromMemory(); @Override void clearFromDisk(); @Override Task<String> getCurrentSessionTokenAsync(); @Override Task<Void> logOutAsync(); @Override Task<ParseUser> getAsync(final boolean shouldAutoCreateUser); }### Answer:
@Test public void testGetCurrentSessionTokenAsyncWithCurrentUserSet() throws Exception { CachedCurrentUserController controller = new CachedCurrentUserController(null); ParseUser currentUser = mock(ParseUser.class); when(currentUser.getSessionToken()).thenReturn("sessionToken"); controller.currentUser = currentUser; String sessionToken = ParseTaskUtils.wait(controller.getCurrentSessionTokenAsync()); assertEquals("sessionToken", sessionToken); } |
### Question:
CachedCurrentUserController implements ParseCurrentUserController { @Override public void clearFromMemory() { synchronized (mutex) { currentUser = null; currentUserMatchesDisk = false; } } CachedCurrentUserController(ParseObjectStore<ParseUser> store); @Override Task<Void> setAsync(final ParseUser user); @Override Task<Void> setIfNeededAsync(ParseUser user); @Override Task<ParseUser> getAsync(); @Override Task<Boolean> existsAsync(); @Override boolean isCurrent(ParseUser user); @Override void clearFromMemory(); @Override void clearFromDisk(); @Override Task<String> getCurrentSessionTokenAsync(); @Override Task<Void> logOutAsync(); @Override Task<ParseUser> getAsync(final boolean shouldAutoCreateUser); }### Answer:
@Test public void testClearFromMemory() throws Exception { CachedCurrentUserController controller = new CachedCurrentUserController(null); controller.currentUser = mock(ParseUser.class); controller.clearFromMemory(); assertNull(controller.currentUser); assertFalse(controller.currentUserMatchesDisk); }
@Test public void testClearFromMemory() { CachedCurrentUserController controller = new CachedCurrentUserController(null); controller.currentUser = mock(ParseUser.class); controller.clearFromMemory(); assertNull(controller.currentUser); assertFalse(controller.currentUserMatchesDisk); } |
### Question:
CachedCurrentUserController implements ParseCurrentUserController { @Override public void clearFromDisk() { synchronized (mutex) { currentUser = null; currentUserMatchesDisk = false; } try { ParseTaskUtils.wait(store.deleteAsync()); } catch (ParseException e) { } } CachedCurrentUserController(ParseObjectStore<ParseUser> store); @Override Task<Void> setAsync(final ParseUser user); @Override Task<Void> setIfNeededAsync(ParseUser user); @Override Task<ParseUser> getAsync(); @Override Task<Boolean> existsAsync(); @Override boolean isCurrent(ParseUser user); @Override void clearFromMemory(); @Override void clearFromDisk(); @Override Task<String> getCurrentSessionTokenAsync(); @Override Task<Void> logOutAsync(); @Override Task<ParseUser> getAsync(final boolean shouldAutoCreateUser); }### Answer:
@Test public void testClearFromDisk() throws Exception { ParseObjectStore<ParseUser> store = (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class); when(store.deleteAsync()).thenReturn(Task.<Void>forResult(null)); CachedCurrentUserController controller = new CachedCurrentUserController(store); controller.currentUser = new ParseUser(); controller.clearFromDisk(); assertNull(controller.currentUser); assertFalse(controller.currentUserMatchesDisk); verify(store, times(1)).deleteAsync(); }
@Test public void testClearFromDisk() { ParseObjectStore<ParseUser> store = (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class); when(store.deleteAsync()).thenReturn(Task.<Void>forResult(null)); CachedCurrentUserController controller = new CachedCurrentUserController(store); controller.currentUser = new ParseUser(); controller.clearFromDisk(); assertNull(controller.currentUser); assertFalse(controller.currentUserMatchesDisk); verify(store, times(1)).deleteAsync(); } |
### Question:
CachedCurrentUserController implements ParseCurrentUserController { @Override public Task<Boolean> existsAsync() { synchronized (mutex) { if (currentUser != null) { return Task.forResult(true); } } return taskQueue.enqueue(new Continuation<Void, Task<Boolean>>() { @Override public Task<Boolean> then(Task<Void> toAwait) throws Exception { return toAwait.continueWithTask(new Continuation<Void, Task<Boolean>>() { @Override public Task<Boolean> then(Task<Void> task) throws Exception { return store.existsAsync(); } }); } }); } CachedCurrentUserController(ParseObjectStore<ParseUser> store); @Override Task<Void> setAsync(final ParseUser user); @Override Task<Void> setIfNeededAsync(ParseUser user); @Override Task<ParseUser> getAsync(); @Override Task<Boolean> existsAsync(); @Override boolean isCurrent(ParseUser user); @Override void clearFromMemory(); @Override void clearFromDisk(); @Override Task<String> getCurrentSessionTokenAsync(); @Override Task<Void> logOutAsync(); @Override Task<ParseUser> getAsync(final boolean shouldAutoCreateUser); }### Answer:
@Test public void testExistsAsyncWithInMemoryCurrentUserSet() throws Exception { CachedCurrentUserController controller = new CachedCurrentUserController(null); controller.currentUser = new ParseUser(); assertTrue(ParseTaskUtils.wait(controller.existsAsync())); }
@Test public void testExistsAsyncWithInDiskCurrentUserSet() throws Exception { ParseObjectStore<ParseUser> store = (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class); when(store.existsAsync()).thenReturn(Task.forResult(true)); CachedCurrentUserController controller = new CachedCurrentUserController(store); assertTrue(ParseTaskUtils.wait(controller.existsAsync())); }
@Test public void testExistsAsyncWithNoInMemoryAndInDiskCurrentUserSet() throws Exception { ParseObjectStore<ParseUser> store = (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class); when(store.existsAsync()).thenReturn(Task.forResult(false)); CachedCurrentUserController controller = new CachedCurrentUserController(store); assertFalse(ParseTaskUtils.wait(controller.existsAsync())); } |
### Question:
ParseFileController { public boolean isDataAvailable(ParseFile.State state) { return getCacheFile(state).exists(); } ParseFileController(ParseHttpClient restClient, File cachePath); File getCacheFile(ParseFile.State state); boolean isDataAvailable(ParseFile.State state); void clearCache(); Task<ParseFile.State> saveAsync(
final ParseFile.State state,
final byte[] data,
String sessionToken,
ProgressCallback uploadProgressCallback,
Task<Void> cancellationToken); Task<ParseFile.State> saveAsync(
final ParseFile.State state,
final File file,
String sessionToken,
ProgressCallback uploadProgressCallback,
Task<Void> cancellationToken); Task<File> fetchAsync(
final ParseFile.State state,
@SuppressWarnings("UnusedParameters") String sessionToken,
final ProgressCallback downloadProgressCallback,
final Task<Void> cancellationToken); }### Answer:
@Test public void testIsDataAvailable() throws IOException { File root = temporaryFolder.getRoot(); ParseFileController controller = new ParseFileController(null, root); temporaryFolder.newFile("test_file"); ParseFile.State state = new ParseFile.State.Builder().name("test_file").build(); assertTrue(controller.isDataAvailable(state)); } |
### Question:
CachedCurrentUserController implements ParseCurrentUserController { @Override public boolean isCurrent(ParseUser user) { synchronized (mutex) { return currentUser == user; } } CachedCurrentUserController(ParseObjectStore<ParseUser> store); @Override Task<Void> setAsync(final ParseUser user); @Override Task<Void> setIfNeededAsync(ParseUser user); @Override Task<ParseUser> getAsync(); @Override Task<Boolean> existsAsync(); @Override boolean isCurrent(ParseUser user); @Override void clearFromMemory(); @Override void clearFromDisk(); @Override Task<String> getCurrentSessionTokenAsync(); @Override Task<Void> logOutAsync(); @Override Task<ParseUser> getAsync(final boolean shouldAutoCreateUser); }### Answer:
@Test public void testIsCurrent() throws Exception { CachedCurrentUserController controller = new CachedCurrentUserController(null); ParseUser currentUser = new ParseUser(); controller.currentUser = currentUser; assertTrue(controller.isCurrent(currentUser)); assertFalse(controller.isCurrent(new ParseUser())); }
@Test public void testIsCurrent() { CachedCurrentUserController controller = new CachedCurrentUserController(null); ParseUser currentUser = new ParseUser(); controller.currentUser = currentUser; assertTrue(controller.isCurrent(currentUser)); assertFalse(controller.isCurrent(new ParseUser())); } |
### Question:
NetworkObjectController implements ParseObjectController { @Override public Task<Void> deleteAsync(ParseObject.State state, String sessionToken) { ParseRESTObjectCommand command = ParseRESTObjectCommand.deleteObjectCommand( state, sessionToken); return command.executeAsync(client).makeVoid(); } NetworkObjectController(ParseHttpClient client); @Override Task<ParseObject.State> fetchAsync(
final ParseObject.State state, String sessionToken, final ParseDecoder decoder); @Override Task<ParseObject.State> saveAsync(
final ParseObject.State state,
final ParseOperationSet operations,
String sessionToken,
final ParseDecoder decoder); @Override List<Task<ParseObject.State>> saveAllAsync(
List<ParseObject.State> states,
List<ParseOperationSet> operationsList,
String sessionToken,
List<ParseDecoder> decoders); @Override Task<Void> deleteAsync(ParseObject.State state, String sessionToken); @Override List<Task<Void>> deleteAllAsync(
List<ParseObject.State> states, String sessionToken); }### Answer:
@Test public void testDeleteAsync() throws Exception { JSONObject mockResponse = new JSONObject(); ParseHttpClient restClient = ParseTestUtils.mockParseHttpClientWithResponse(mockResponse, 200, "OK"); ParseObject.State state = new ParseObject.State.Builder("Test") .objectId("testObjectId") .build(); NetworkObjectController controller = new NetworkObjectController(restClient); ParseTaskUtils.wait(controller.deleteAsync(state, "sessionToken")); } |
### Question:
ParseRelation implements Parcelable { public void add(T object) { synchronized (mutex) { ParseRelationOperation<T> operation = new ParseRelationOperation<>(Collections.singleton(object), null); targetClass = operation.getTargetClass(); getParent().performOperation(key, operation); knownObjects.add(object); } } ParseRelation(ParseObject parent, String key); ParseRelation(String targetClass); ParseRelation(JSONObject jsonObject, ParseDecoder decoder); ParseRelation(Parcel source, ParseParcelDecoder decoder); void add(T object); void remove(T object); ParseQuery<T> getQuery(); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseRelation> CREATOR; }### Answer:
@Test public void testAdd() throws Exception { ParseObject parent = new ParseObject("Parent"); ParseRelation relation = new ParseRelation(parent, "key"); ParseObject object = new ParseObject("Test"); relation.add(object); assertEquals("Test", relation.getTargetClass()); assertTrue(relation.hasKnownObject(object)); ParseRelation relationInParent = parent.getRelation("key"); assertEquals("Test", relationInParent.getTargetClass()); assertTrue(relationInParent.hasKnownObject(object)); }
@Test public void testAdd() { ParseObject parent = new ParseObject("Parent"); ParseRelation relation = new ParseRelation(parent, "key"); ParseObject object = new ParseObject("Test"); relation.add(object); assertEquals("Test", relation.getTargetClass()); assertTrue(relation.hasKnownObject(object)); ParseRelation relationInParent = parent.getRelation("key"); assertEquals("Test", relationInParent.getTargetClass()); assertTrue(relationInParent.hasKnownObject(object)); } |
### Question:
ParseFileController { public void clearCache() { File[] files = cachePath.listFiles(); if (files == null) { return; } for (File file : files) { ParseFileUtils.deleteQuietly(file); } } ParseFileController(ParseHttpClient restClient, File cachePath); File getCacheFile(ParseFile.State state); boolean isDataAvailable(ParseFile.State state); void clearCache(); Task<ParseFile.State> saveAsync(
final ParseFile.State state,
final byte[] data,
String sessionToken,
ProgressCallback uploadProgressCallback,
Task<Void> cancellationToken); Task<ParseFile.State> saveAsync(
final ParseFile.State state,
final File file,
String sessionToken,
ProgressCallback uploadProgressCallback,
Task<Void> cancellationToken); Task<File> fetchAsync(
final ParseFile.State state,
@SuppressWarnings("UnusedParameters") String sessionToken,
final ProgressCallback downloadProgressCallback,
final Task<Void> cancellationToken); }### Answer:
@Test public void testClearCache() throws IOException { File root = temporaryFolder.getRoot(); ParseFileController controller = new ParseFileController(null, root); File file1 = temporaryFolder.newFile("test_file_1"); File file2 = temporaryFolder.newFile("test_file_2"); controller.clearCache(); assertFalse(file1.exists()); assertFalse(file2.exists()); } |
### Question:
ParseRelation implements Parcelable { public void remove(T object) { synchronized (mutex) { ParseRelationOperation<T> operation = new ParseRelationOperation<>(null, Collections.singleton(object)); targetClass = operation.getTargetClass(); getParent().performOperation(key, operation); knownObjects.remove(object); } } ParseRelation(ParseObject parent, String key); ParseRelation(String targetClass); ParseRelation(JSONObject jsonObject, ParseDecoder decoder); ParseRelation(Parcel source, ParseParcelDecoder decoder); void add(T object); void remove(T object); ParseQuery<T> getQuery(); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParseRelation> CREATOR; }### Answer:
@Test public void testRemove() throws Exception { ParseObject parent = new ParseObject("Parent"); ParseRelation relation = new ParseRelation(parent, "key"); ParseObject object = new ParseObject("Test"); relation.add(object); relation.remove(object); assertEquals("Test", relation.getTargetClass()); assertFalse(relation.hasKnownObject(object)); ParseRelation relationInParent = parent.getRelation("key"); assertEquals("Test", relationInParent.getTargetClass()); assertFalse(relation.hasKnownObject(object)); }
@Test public void testRemove() { ParseObject parent = new ParseObject("Parent"); ParseRelation relation = new ParseRelation(parent, "key"); ParseObject object = new ParseObject("Test"); relation.add(object); relation.remove(object); assertEquals("Test", relation.getTargetClass()); assertFalse(relation.hasKnownObject(object)); ParseRelation relationInParent = parent.getRelation("key"); assertEquals("Test", relationInParent.getTargetClass()); assertFalse(relation.hasKnownObject(object)); } |
### Question:
HelloWorldView extends Composite { @UiHandler("showButton") void handleShowButtonClick(ClickEvent e) { if (bananaCount != 0) { foodMultipleSelect.getSelectedItems() .forEach(item -> Notify.notify(item.toString())); } else { notify("No banana, no food."); } eventBus.fireEvent(new ChangeViewEvent("showButton")); } @Inject HelloWorldView(Banana banana, EventBus eventBus,
HelloWorldViewEventHandler helloWorldViewEventHandler); void setBananaCount(int bananaCount); }### Answer:
@Test public void handleShowButtonClickWithBananaCountGreaterThanZero() throws Exception { view.handleShowButtonClick(null); verify(foodMultipleSelect, times(1)).getSelectedItems(); } |
### Question:
HelloWorldComposite { void handleAddButtonClick() { if (!titleTextBox.isEmpty() && !descriptionTextArea.isEmpty()) { TodoItem todoItem = new TodoItem(titleTextBox.getValue(), descriptionTextArea.getValue()); todoItemsListGroup.addItem(todoItem); titleTextBox.setValue(""); descriptionTextArea.setValue(""); } } @Inject HelloWorldComposite(TextBox titleTextBox, TextArea descriptionTextArea,
@Named("todoItemsListGroup") ListGroup<TodoItem> todoItemsListGroup,
@Named("doneItemsListGroup") ListGroup<TodoItem> doneItemsListGroup,
TodoItemRenderer toDoItemRenderer,
Button addButton, Layout layout); }### Answer:
@Test public void testHandleAddButtonClickTitleAndDescriptionNotEmpty() throws Exception { doReturn("Title").when(titleTextBox).getValue(); doReturn("Description").when(descriptionTextArea).getValue(); helloWorldComposite.handleAddButtonClick(); verify(todoItemsListGroup, times(1)).addItem(Matchers.<TodoItem>any()); verify(titleTextBox, times(1)).setValue(""); verify(descriptionTextArea, times(1)).setValue(""); } |
### Question:
BeetlUtil { public static boolean checkNameing(String str) { char[] commonArray = new char[str.length()]; int len = 0; if (str == null || (len = str.length()) == 0) { return false; } str.getChars(0, len, commonArray, 0); int index = 0; char word = commonArray[index++]; if (word >= 46 && word <= 57) setLog(1, word); else if (commonArray[len - 1] == 46) setLog(len, 46); else while (true) { if (word < 36 || word > 122 || chars[word - 36] == 0) { setLog(index + 1, word); return false; } if (index == len) return true; word = commonArray[index++]; } return false; } static boolean isOutsideOfRoot(String child); static String getRelPath(String siblings, String resourceId); static Writer getWriterByByteWriter(ByteWriter byteWriter); static void setWebroot(String webroot); static String getWebRoot(); static boolean checkNameing(String str); static int[] getLog(); static String reportChineseTokenError(String msg); static RuntimeException throwCastException(ClassCastException ex,GroupTemplate gt); static void autoFileFunctionRegister(GroupTemplate gt,File funtionRoot, String ns, String path,String functionSuffix); static String getParameterDescription(Class[] types); }### Answer:
@Test public void checkNameing(){ } |
### Question:
ParseHelper { static boolean isJavaLangType(String type){ return JAVA_LANG_TYPE.contains(type); } static String findGenericType(String val); }### Answer:
@Test public void isJavaLangType() { } |
### Question:
StudentRepository { public Optional<Student> findByName(String name) { for (Student student : this.studentSet) { if (student.name.equals(name)) return Optional.of(student); } return Optional.empty(); } StudentRepository(Collection<Student> students); Optional<Student> findByName(String name); }### Answer:
@Test public void whenStudentIsNotFoundThenReturnEmpty() { assertThat(studentRepository.findByName("Samantha")) .isNotPresent(); }
@Test public void whenStudentIsFoundThenReturnStudent() { assertThat(studentRepository.findByName("John")) .isPresent() .hasValueSatisfying(s -> { assertThat(s.name).isEqualTo("John"); assertThat(s.age).isEqualTo(21); }); } |
### Question:
BooksEndpoint { @POST @Path("{id}/censor") public Response censorBook(@PathParam("id") String id) { final Books matchingBooks = books.list().filterById(id); if (null == id || matchingBooks.isEmpty() || matchingBooks.first().getStatus() == States.CENSORED) { return Response.status(Response.Status.BAD_REQUEST).entity("Could not process this request").build(); } matchingBooks.first().censor(); return Response.accepted(matchingBooks.first()).build(); } BooksEndpoint(BooksRepository books); @GET @Path("") Response getAllBooks(@QueryParam("title") String title, @QueryParam("author") String author, @QueryParam("id") String id, @QueryParam("state") String state); @POST @Path("{id}/rent/{user}") Response rentBook(@PathParam("id") String id, @PathParam("user") String userId); @POST @Path("{id}/return") Response returnBook(@PathParam("id") String id); @POST @Path("{id}/censor") Response censorBook(@PathParam("id") String id); @POST @Path("{id}/uncensor") Response uncensorBook(@PathParam("id") String id); @POST @Path("{id}/prepare") Response initialPreparation(@PathParam("id") String id); @POST @Produces(MediaType.TEXT_PLAIN) @Path("") Response addNewBook(
@FormParam("title") String title,
@FormParam("author") String author
); }### Answer:
@Test public void censor_a_book() throws IOException { addBook(TDD_IN_JAVA); final Response response = censorBook(withId(0)); checkBookDetails(response, 0, hasStatus(4)); }
@Test public void cannot_retrieve_a_censored_book() throws IOException { addBook(TDD_IN_JAVA); censorBook(withId(0)); final Response book = getBook(withId(0)); book.prettyPrint(); book.then().body("empty", is(true)); } |
### Question:
Friendships { public List<String> getFriendsList(String person) { if (!friendships.containsKey(person)) { return Collections.emptyList(); } return friendships.get(person); } void makeFriends(String person1, String person2); List<String> getFriendsList(String person); boolean areFriends(String person1, String person2); }### Answer:
@Test public void alexDoesNotHaveFriends() { Assert.assertTrue("Alex does not have friends", friendships.getFriendsList("Alex").isEmpty()); }
@Test public void joeHas5Friends() { Assert.assertEquals("Joe has 5 friends", 5, friendships.getFriendsList("Joe").size()); }
@Test public void joeIsFriendWithEveryone() { List<String> friendsOfJoe = Arrays.asList("Audrey", "Peter", "Michael", "Britney", "Paul"); Assert.assertTrue( friendships.getFriendsList("Joe").containsAll(friendsOfJoe) ); } |
### Question:
Person { public List<String> getFriends() { return friends; } Person(); Person(String name); List<String> getFriends(); void addFriend(String friend); @Override String toString(); }### Answer:
@Test public void testGetFriends() throws Exception { Person p = new Person("Joe"); assertThat(p.getFriends()).isEmpty(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.