use of com.amplifyframework.datastore.appsync.ModelWithMetadata in project amplify-android by aws-amplify.
the class AWSDataStorePluginTest method clearStopsSyncAndDeletesDatabase.
/**
* Verify that when the clear method is called, the following happens
* - All remote synchronization processes are stopped
* - The database is deleted.
* - On the next interaction with the DataStore, the synchronization processes are restarted.
* @throws JSONException on failure to arrange plugin config
* @throws AmplifyException on failure to arrange API plugin via Amplify facade
*/
@Test
public void clearStopsSyncAndDeletesDatabase() throws AmplifyException, JSONException {
ApiCategory mockApiCategory = mockApiCategoryWithGraphQlApi();
ApiPlugin<?> mockApiPlugin = mockApiCategory.getPlugin(MOCK_API_PLUGIN_NAME);
JSONObject dataStorePluginJson = new JSONObject().put("syncIntervalInMinutes", 60);
AWSDataStorePlugin awsDataStorePlugin = AWSDataStorePlugin.builder().modelProvider(modelProvider).apiCategory(mockApiCategory).build();
SynchronousDataStore synchronousDataStore = SynchronousDataStore.delegatingTo(awsDataStorePlugin);
awsDataStorePlugin.configure(dataStorePluginJson, context);
awsDataStorePlugin.initialize(context);
// Trick the DataStore since it's not getting initialized as part of the Amplify.initialize call chain
Amplify.Hub.publish(HubChannel.DATASTORE, HubEvent.create(InitializationStatus.SUCCEEDED));
// Setup objects
Person person1 = createPerson("Test", "Dummy I");
Person person2 = createPerson("Test", "Dummy II");
// Mock responses for person 1
doAnswer(invocation -> {
int indexOfResponseConsumer = 1;
Consumer<GraphQLResponse<ModelWithMetadata<Person>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
ModelMetadata modelMetadata = new ModelMetadata(person1.getId(), false, 1, Temporal.Timestamp.now());
ModelWithMetadata<Person> modelWithMetadata = new ModelWithMetadata<>(person1, modelMetadata);
onResponse.accept(new GraphQLResponse<>(modelWithMetadata, Collections.emptyList()));
return mock(GraphQLOperation.class);
}).when(mockApiPlugin).mutate(any(), any(), any());
HubAccumulator apiInteractionObserver = HubAccumulator.create(HubChannel.DATASTORE, DataStoreChannelEventName.OUTBOX_MUTATION_PROCESSED, 1).start();
// Save person 1
synchronousDataStore.save(person1);
Person result1 = synchronousDataStore.get(Person.class, person1.getId());
assertEquals(person1, result1);
apiInteractionObserver.await();
verify(mockApiCategory).mutate(argThat(getMatcherFor(person1)), any(), any());
// Mock responses for person 2
doAnswer(invocation -> {
int indexOfResponseConsumer = 1;
Consumer<GraphQLResponse<ModelWithMetadata<Person>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
ModelMetadata modelMetadata = new ModelMetadata(person2.getId(), false, 1, Temporal.Timestamp.now());
ModelWithMetadata<Person> modelWithMetadata = new ModelWithMetadata<>(person2, modelMetadata);
onResponse.accept(new GraphQLResponse<>(modelWithMetadata, Collections.emptyList()));
return mock(GraphQLOperation.class);
}).when(mockApiPlugin).mutate(any(), any(), any());
// Do the thing!
synchronousDataStore.clear();
assertRemoteSubscriptionsCancelled();
apiInteractionObserver = HubAccumulator.create(HubChannel.DATASTORE, DataStoreChannelEventName.OUTBOX_MUTATION_PROCESSED, 1).start();
HubAccumulator orchestratorInitObserver = HubAccumulator.create(HubChannel.DATASTORE, DataStoreChannelEventName.READY, 1).start();
// Interact with the DataStore after the clear
synchronousDataStore.save(person2);
// Verify person 2 was published to the cloud
apiInteractionObserver.await();
// Verify the orchestrator started back up and subscriptions are active.
orchestratorInitObserver.await();
assertRemoteSubscriptionsStarted();
Person result2 = synchronousDataStore.get(Person.class, person2.getId());
assertEquals(person2, result2);
verify(mockApiCategory, atLeastOnce()).mutate(argThat(getMatcherFor(person2)), any(), any());
}
use of com.amplifyframework.datastore.appsync.ModelWithMetadata in project amplify-android by aws-amplify.
the class AWSDataStorePluginTest method stopStopsSyncUntilNextInteraction.
/**
* Verify that when the stop method is called, the following happens
* - All remote synchronization processes are stopped
* - On the next interaction with the DataStore, the synchronization processes are restarted.
* @throws JSONException on failure to arrange plugin config
* @throws AmplifyException on failure to arrange API plugin via Amplify facade
*/
@Test
public void stopStopsSyncUntilNextInteraction() throws AmplifyException, JSONException {
ApiCategory mockApiCategory = mockApiCategoryWithGraphQlApi();
ApiPlugin<?> mockApiPlugin = mockApiCategory.getPlugin(MOCK_API_PLUGIN_NAME);
JSONObject dataStorePluginJson = new JSONObject().put("syncIntervalInMinutes", 60);
AWSDataStorePlugin awsDataStorePlugin = AWSDataStorePlugin.builder().modelProvider(modelProvider).apiCategory(mockApiCategory).build();
SynchronousDataStore synchronousDataStore = SynchronousDataStore.delegatingTo(awsDataStorePlugin);
awsDataStorePlugin.configure(dataStorePluginJson, context);
awsDataStorePlugin.initialize(context);
// Trick the DataStore since it's not getting initialized as part of the Amplify.initialize call chain
Amplify.Hub.publish(HubChannel.DATASTORE, HubEvent.create(InitializationStatus.SUCCEEDED));
// Setup objects
Person person1 = createPerson("Test", "Dummy I");
Person person2 = createPerson("Test", "Dummy II");
// Mock responses for person 1
doAnswer(invocation -> {
int indexOfResponseConsumer = 1;
Consumer<GraphQLResponse<ModelWithMetadata<Person>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
ModelMetadata modelMetadata = new ModelMetadata(person1.getId(), false, 1, Temporal.Timestamp.now());
ModelWithMetadata<Person> modelWithMetadata = new ModelWithMetadata<>(person1, modelMetadata);
onResponse.accept(new GraphQLResponse<>(modelWithMetadata, Collections.emptyList()));
return mock(GraphQLOperation.class);
}).when(mockApiPlugin).mutate(any(), any(), any());
HubAccumulator apiInteractionObserver = HubAccumulator.create(HubChannel.DATASTORE, DataStoreChannelEventName.OUTBOX_MUTATION_PROCESSED, 1).start();
// Save person 1
synchronousDataStore.save(person1);
Person result1 = synchronousDataStore.get(Person.class, person1.getId());
assertEquals(person1, result1);
apiInteractionObserver.await();
verify(mockApiCategory).mutate(argThat(getMatcherFor(person1)), any(), any());
// Mock responses for person 2
doAnswer(invocation -> {
int indexOfResponseConsumer = 1;
Consumer<GraphQLResponse<ModelWithMetadata<Person>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
ModelMetadata modelMetadata = new ModelMetadata(person2.getId(), false, 1, Temporal.Timestamp.now());
ModelWithMetadata<Person> modelWithMetadata = new ModelWithMetadata<>(person2, modelMetadata);
onResponse.accept(new GraphQLResponse<>(modelWithMetadata, Collections.emptyList()));
return mock(GraphQLOperation.class);
}).when(mockApiPlugin).mutate(any(), any(), any());
// Do the thing!
synchronousDataStore.stop();
assertRemoteSubscriptionsCancelled();
apiInteractionObserver = HubAccumulator.create(HubChannel.DATASTORE, DataStoreChannelEventName.OUTBOX_MUTATION_PROCESSED, 1).start();
HubAccumulator orchestratorInitObserver = HubAccumulator.create(HubChannel.DATASTORE, DataStoreChannelEventName.READY, 1).start();
// Interact with the DataStore after the stop
synchronousDataStore.save(person2);
// Verify person 2 was published to the cloud
apiInteractionObserver.await();
// Verify the orchestrator started back up and subscriptions are active.
orchestratorInitObserver.await();
assertRemoteSubscriptionsStarted();
// Verify person 1 and 2 are in the DataStore
List<Person> results = synchronousDataStore.list(Person.class);
assertEquals(Arrays.asList(person1, person2), results);
verify(mockApiCategory, atLeastOnce()).mutate(argThat(getMatcherFor(person2)), any(), any());
}
use of com.amplifyframework.datastore.appsync.ModelWithMetadata in project amplify-android by aws-amplify.
the class AWSDataStorePluginTest method mockApiCategoryWithGraphQlApi.
@SuppressWarnings("unchecked")
private ApiCategory mockApiCategoryWithGraphQlApi() throws AmplifyException {
ApiCategory mockApiCategory = spy(ApiCategory.class);
ApiPlugin<?> mockApiPlugin = mock(ApiPlugin.class);
when(mockApiPlugin.getPluginKey()).thenReturn(MOCK_API_PLUGIN_NAME);
when(mockApiPlugin.getCategoryType()).thenReturn(CategoryType.API);
ApiEndpointStatusChangeEvent eventData = new ApiEndpointStatusChangeEvent(ApiEndpointStatusChangeEvent.ApiEndpointStatus.REACHABLE, ApiEndpointStatusChangeEvent.ApiEndpointStatus.UNKOWN);
HubEvent<ApiEndpointStatusChangeEvent> hubEvent = HubEvent.create(ApiChannelEventName.API_ENDPOINT_STATUS_CHANGED, eventData);
// Make believe that queries return response immediately
doAnswer(invocation -> {
// Mock the API emitting an ApiEndpointStatusChangeEvent event.
Amplify.Hub.publish(HubChannel.API, hubEvent);
int indexOfResponseConsumer = 1;
Consumer<GraphQLResponse<PaginatedResult<ModelWithMetadata<Person>>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
PaginatedResult<ModelWithMetadata<Person>> data = new PaginatedResult<>(Collections.emptyList(), null);
onResponse.accept(new GraphQLResponse<>(data, Collections.emptyList()));
return null;
}).when(mockApiPlugin).query(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class));
// Make believe that subscriptions return response immediately
doAnswer(invocation -> {
int indexOfStartConsumer = 1;
Consumer<String> onStart = invocation.getArgument(indexOfStartConsumer);
GraphQLOperation<?> mockOperation = mock(GraphQLOperation.class);
doAnswer(opAnswer -> {
this.subscriptionCancelledCounter.incrementAndGet();
return null;
}).when(mockOperation).cancel();
this.subscriptionStartedCounter.incrementAndGet();
// Trigger the subscription start event.
onStart.accept(RandomString.string());
return mockOperation;
}).when(mockApiPlugin).subscribe(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class), any(Consumer.class), any(Action.class));
mockApiCategory.addPlugin(mockApiPlugin);
mockApiCategory.configure(new ApiCategoryConfiguration(), getApplicationContext());
mockApiCategory.initialize(getApplicationContext());
return mockApiCategory;
}
use of com.amplifyframework.datastore.appsync.ModelWithMetadata in project amplify-android by aws-amplify.
the class ConflictResolverIntegrationTest method mockApiCategoryWithGraphQlApi.
@SuppressWarnings("unchecked")
private ApiCategory mockApiCategoryWithGraphQlApi() throws AmplifyException {
ApiCategory mockApiCategory = spy(ApiCategory.class);
ApiPlugin<?> mockApiPlugin = mock(ApiPlugin.class);
when(mockApiPlugin.getPluginKey()).thenReturn(MOCK_API_PLUGIN_NAME);
when(mockApiPlugin.getCategoryType()).thenReturn(CategoryType.API);
ApiEndpointStatusChangeEvent eventData = new ApiEndpointStatusChangeEvent(ApiEndpointStatusChangeEvent.ApiEndpointStatus.REACHABLE, ApiEndpointStatusChangeEvent.ApiEndpointStatus.UNKOWN);
HubEvent<ApiEndpointStatusChangeEvent> hubEvent = HubEvent.create(ApiChannelEventName.API_ENDPOINT_STATUS_CHANGED, eventData);
// Make believe that queries return response immediately
doAnswer(invocation -> {
// Mock the API emitting an ApiEndpointStatusChangeEvent event.
Amplify.Hub.publish(HubChannel.API, hubEvent);
int indexOfResponseConsumer = 1;
Consumer<GraphQLResponse<PaginatedResult<ModelWithMetadata<Person>>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
PaginatedResult<ModelWithMetadata<Person>> data = new PaginatedResult<>(Collections.emptyList(), null);
onResponse.accept(new GraphQLResponse<>(data, Collections.emptyList()));
return null;
}).when(mockApiPlugin).query(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class));
mockApiCategory.addPlugin(mockApiPlugin);
mockApiCategory.configure(new ApiCategoryConfiguration(), getApplicationContext());
mockApiCategory.initialize(getApplicationContext());
return mockApiCategory;
}
use of com.amplifyframework.datastore.appsync.ModelWithMetadata in project amplify-android by aws-amplify.
the class AppSyncClientInstrumentationTest method testAllOperations.
/**
* Tests the operations in AppSyncClient.
* @throws DataStoreException If any call to AppSync endpoint fails to return a response
* @throws AmplifyException On failure to obtain ModelSchema
*/
@Test
@SuppressWarnings("MethodLength")
public void testAllOperations() throws AmplifyException {
ModelSchema blogOwnerSchema = ModelSchema.fromModelClass(BlogOwner.class);
ModelSchema postSchema = ModelSchema.fromModelClass(Post.class);
ModelSchema blogSchema = ModelSchema.fromModelClass(Blog.class);
long startTimeSeconds = TimeUnit.MILLISECONDS.toSeconds(new Date().getTime());
// Create simple model with no relationship
BlogOwner owner = BlogOwner.builder().name("David").build();
ModelWithMetadata<BlogOwner> blogOwnerCreateResult = create(owner, blogOwnerSchema);
BlogOwner actual = blogOwnerCreateResult.getModel();
ModelAssert.assertEqualsIgnoringTimestamps(owner, actual);
assertEquals(new Integer(1), blogOwnerCreateResult.getSyncMetadata().getVersion());
// TODO: BE AWARE THAT THE DELETED PROPERTY RETURNS NULL INSTEAD OF FALSE
assertNull(blogOwnerCreateResult.getSyncMetadata().isDeleted());
assertTrue(blogOwnerCreateResult.getSyncMetadata().getId().endsWith(owner.getId()));
// Subscribe to Blog creations
Observable<GraphQLResponse<ModelWithMetadata<Blog>>> blogCreations = onCreate(blogSchema);
// Now, actually create a Blog
Blog blog = Blog.builder().name("Create test").owner(owner).build();
ModelWithMetadata<Blog> blogCreateResult = create(blog, blogSchema);
// Currently cannot do BlogOwner.justId because it will assign the id to the name field.
// This is being fixed
assertEquals(blog.getId(), blogCreateResult.getModel().getId());
assertEquals(blog.getName(), blogCreateResult.getModel().getName());
assertEquals(blog.getOwner().getId(), blogCreateResult.getModel().getOwner().getId());
assertEquals(new Integer(1), blogCreateResult.getSyncMetadata().getVersion());
assertNull(blogCreateResult.getSyncMetadata().isDeleted());
Temporal.Timestamp createdBlogLastChangedAt = blogCreateResult.getSyncMetadata().getLastChangedAt();
assertNotNull(createdBlogLastChangedAt);
assertTrue(createdBlogLastChangedAt.getSecondsSinceEpoch() > startTimeSeconds);
assertTrue(blogCreateResult.getSyncMetadata().getId().endsWith(blog.getId()));
// TODO: Subscriptions are currently failing. More investigation required to fix this part of the test.
// Validate that subscription picked up the mutation and end the subscription since we're done with.
// TestObserver<ModelWithMetadata<Blog>> blogCreationSubscriber = TestObserver.create();
// blogCreations
// .map(GraphQLResponse::getData)
// .subscribe(blogCreationSubscriber);
// blogCreationSubscriber.assertValue(blogCreateResult);
// Create Posts which Blog hasMany of
Post post1 = Post.builder().title("Post 1").status(PostStatus.ACTIVE).rating(4).blog(blog).build();
Post post2 = Post.builder().title("Post 2").status(PostStatus.INACTIVE).rating(-1).blog(blog).build();
Post post1ModelResult = create(post1, postSchema).getModel();
Post post2ModelResult = create(post2, postSchema).getModel();
// Results only have blog ID so strip out other information from the original post blog
ModelAssert.assertEqualsIgnoringTimestamps(post1.copyOfBuilder().blog(Blog.justId(blog.getId())).build(), post1ModelResult);
ModelAssert.assertEqualsIgnoringTimestamps(post2.copyOfBuilder().blog(Blog.justId(blog.getId())).build(), post2ModelResult);
// Update model
Blog updatedBlog = blog.copyOfBuilder().name("Updated blog").build();
long updateBlogStartTimeSeconds = TimeUnit.MILLISECONDS.toSeconds(new Date().getTime());
ModelWithMetadata<Blog> blogUpdateResult = update(updatedBlog, blogSchema, 1);
assertEquals(updatedBlog.getName(), blogUpdateResult.getModel().getName());
assertEquals(updatedBlog.getOwner().getId(), blogUpdateResult.getModel().getOwner().getId());
assertEquals(updatedBlog.getId(), blogUpdateResult.getModel().getId());
assertEquals(2, blogUpdateResult.getModel().getPosts().size());
assertEquals(new Integer(2), blogUpdateResult.getSyncMetadata().getVersion());
assertNull(blogUpdateResult.getSyncMetadata().isDeleted());
Temporal.Timestamp updatedBlogLastChangedAt = blogUpdateResult.getSyncMetadata().getLastChangedAt();
assertNotNull(updatedBlogLastChangedAt);
assertTrue(updatedBlogLastChangedAt.getSecondsSinceEpoch() > updateBlogStartTimeSeconds);
// Delete one of the posts
ModelWithMetadata<Post> post1DeleteResult = delete(post1, postSchema, 1);
ModelAssert.assertEqualsIgnoringTimestamps(post1.copyOfBuilder().blog(Blog.justId(blog.getId())).build(), post1DeleteResult.getModel());
Boolean isDeleted = post1DeleteResult.getSyncMetadata().isDeleted();
assertEquals(Boolean.TRUE, isDeleted);
// Try to delete a post with a bad version number
List<GraphQLResponse.Error> post2DeleteErrors = deleteExpectingResponseErrors(post2, postSchema, 0);
assertEquals("Conflict resolver rejects mutation.", post2DeleteErrors.get(0).getMessage());
// Run sync on Blogs
// TODO: This is currently a pretty worthless test - mainly for setting a debug point and manually inspecting
// When you call sync with a null lastSync it gives only one entry per object (the latest state)
Iterable<ModelWithMetadata<Blog>> blogSyncResult = sync(api.buildSyncRequest(blogSchema, null, 1000, QueryPredicates.all()));
assertTrue(blogSyncResult.iterator().hasNext());
// Run sync on Posts
// TODO: This is currently a pretty worthless test - mainly for setting a debug point and manually inspecting
// When you call sync with a lastSyncTime it gives you one entry per version of that object which was created
// since that time.
Iterable<ModelWithMetadata<Post>> postSyncResult = sync(api.buildSyncRequest(postSchema, startTimeSeconds, 1000, QueryPredicates.all()));
assertTrue(postSyncResult.iterator().hasNext());
}
Aggregations