use of com.amplifyframework.testmodels.commentsblog.Post in project amplify-android by aws-amplify.
the class SyncProcessorTest method dataStoreHubEventsTriggered.
/**
* During a base sync, there are a series of events that should be emitted.
* This test verifies that these events are published via Amplify Hub depending
* on actions takes for each available model.
* @throws DataStoreException Not expected.
* @throws InterruptedException Not expected.
*/
@Test
public void dataStoreHubEventsTriggered() throws DataStoreException, InterruptedException {
// Arrange - BEGIN
int expectedModelCount = Arrays.asList(Post.class, BlogOwner.class).size();
// Collects one syncQueriesStarted event.
HubAccumulator syncStartAccumulator = createAccumulator(syncQueryStartedForModels(modelCount), 1);
// Collects one syncQueriesReady event.
HubAccumulator syncQueryReadyAccumulator = createAccumulator(forEvent(DataStoreChannelEventName.SYNC_QUERIES_READY), 1);
// Collects one modelSynced event for each model.
HubAccumulator modelSyncedAccumulator = createAccumulator(forEvent(DataStoreChannelEventName.MODEL_SYNCED), expectedModelCount);
// Add a couple of seed records so they can be deleted/updated.
storageAdapter.save(DRUM_POST.getModel());
storageAdapter.save(BLOGGER_ISLA.getModel());
// Mock sync query results for a couple of models.
AppSyncMocking.sync(appSync).mockSuccessResponse(Post.class, DELETED_DRUM_POST).mockSuccessResponse(BlogOwner.class, BLOGGER_ISLA, BLOGGER_JAMESON);
// Start the accumulators.
syncQueryReadyAccumulator.start();
syncStartAccumulator.start();
modelSyncedAccumulator.start();
TestObserver<ModelWithMetadata<? extends Model>> hydrationObserver = TestObserver.create();
// Arrange - END
// Act: kickoff sync.
syncProcessor.hydrate().subscribe(hydrationObserver);
// Check - BEGIN
// Verify that sync completes.
assertTrue(hydrationObserver.await(OP_TIMEOUT_MS, TimeUnit.MILLISECONDS));
hydrationObserver.assertNoErrors();
hydrationObserver.assertComplete();
// Verify that syncQueriesStarted was emitted once.
assertEquals(1, syncStartAccumulator.await((int) OP_TIMEOUT_MS, TimeUnit.MILLISECONDS).size());
// Verify that syncQueriesReady was emitted once.
assertEquals(1, syncQueryReadyAccumulator.await((int) OP_TIMEOUT_MS, TimeUnit.MILLISECONDS).size());
// Get the list of modelSynced events captured.
List<HubEvent<?>> hubEvents = modelSyncedAccumulator.await((int) OP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
// Verify that [number of events] = [number of models]
assertEquals(expectedModelCount, hubEvents.size());
ModelSyncedEvent expectedBlogOwnerCounts = new ModelSyncedEvent("BlogOwner", true, 1, 1, 0);
ModelSyncedEvent expectedPostCounts = new ModelSyncedEvent("Post", true, 0, 0, 1);
// For each event (excluding system models), verify the desired count.
for (HubEvent<?> event : hubEvents) {
ModelSyncedEvent eventData = (ModelSyncedEvent) event.getData();
assertTrue(eventData.isFullSync());
assertFalse(eventData.isDeltaSync());
String eventModel = eventData.getModel();
switch(eventModel) {
case "BlogOwner":
// One BlogOwner added and one updated.
assertEquals(expectedBlogOwnerCounts, eventData);
break;
case "Post":
// One post deleted.
assertEquals(expectedPostCounts, eventData);
break;
default:
// Exclude system models
if (!SYSTEM_MODEL_NAMES.contains(eventModel)) {
ModelSyncedEvent otherCounts = new ModelSyncedEvent(eventModel, true, 0, 0, 0);
assertEquals(otherCounts, eventData);
}
}
}
// Check - END
}
use of com.amplifyframework.testmodels.commentsblog.Post in project amplify-android by aws-amplify.
the class PendingMutationTest method pendingMutationsAreComparable.
/**
* It is possible to sort pending mutations according to their TimeBasedUUID field.
* @throws AmplifyException On failure to arrange model schema
*/
@Test
public void pendingMutationsAreComparable() throws AmplifyException {
// First, create a bunch of pending mutations.
final List<PendingMutation<? extends Model>> expectedOrder = new ArrayList<>();
final int desiredQuantity = 10;
for (int index = 0; index < desiredQuantity; index++) {
// to make sure the comparator can work across model types
if (new SecureRandom().nextBoolean()) {
BlogOwner blogger = BlogOwner.builder().name(String.format(Locale.US, "Blogger #%d", index)).build();
ModelSchema schema = ModelSchema.fromModelClass(BlogOwner.class);
expectedOrder.add(PendingMutation.creation(blogger, schema));
} else {
Post post = Post.builder().title(String.format(Locale.US, "Title #%d", index)).status(PostStatus.ACTIVE).rating(5).build();
ModelSchema schema = ModelSchema.fromModelClass(Post.class);
expectedOrder.add(PendingMutation.creation(post, schema));
}
}
// Okay! Now, shuffle them.
List<PendingMutation<? extends Model>> shuffled = new ArrayList<>(expectedOrder);
Collections.shuffle(shuffled, new SecureRandom());
// Now sort them according to the item comparator, {@link PendingMutation#compareTo(Object)}.
List<PendingMutation<? extends Model>> actualOrder = new ArrayList<>(shuffled);
Collections.sort(actualOrder);
assertEquals(expectedOrder, actualOrder);
}
use of com.amplifyframework.testmodels.commentsblog.Post in project amplify-android by aws-amplify.
the class AppSyncRequestFactoryTest method validateMutationGenerationOnCreateComment.
/**
* Validates creation of a "create a model" request.
* @throws DataStoreException On failure to interrogate the model fields.
* @throws AmplifyException On failure to parse ModelSchema from model class
* @throws JSONException from JSONAssert.assertEquals.
*/
@Test
public void validateMutationGenerationOnCreateComment() throws AmplifyException, JSONException {
Post post = Post.justId("9a4295d6-8225-495a-a531-beffc8b7ae7d");
Comment comment = Comment.builder().id("426f8e8d-ea0f-4839-a73f-6a2a38565ba1").content("toast").post(post).build();
ModelSchema schema = ModelSchema.fromModelClass(Comment.class);
JSONAssert.assertEquals(Resources.readAsString("create-comment-request.txt"), AppSyncRequestFactory.buildCreationRequest(schema, comment, DEFAULT_STRATEGY).getContent(), true);
}
use of com.amplifyframework.testmodels.commentsblog.Post in project amplify-android by aws-amplify.
the class SQLiteStorageAdapterDeleteTest method deleteModelCascades.
/**
* Assert that delete deletes item in the SQLite database without
* violating foreign key constraints.
* @throws DataStoreException On unexpected failure manipulating items in/out of DataStore
*/
@Test
public void deleteModelCascades() throws DataStoreException {
// Create 1 blog owner, which has 3 blogs each, which has 3 posts each.
// Insert 1 blog owner, 3 blogs, 9 posts
Set<String> expected = new HashSet<>();
BlogOwner ownerModel = BlogOwner.builder().name("Blog Owner 1").build();
adapter.save(ownerModel);
expected.add(ownerModel.getId());
for (int blog = 1; blog <= 3; blog++) {
Blog blogModel = Blog.builder().name("Blog " + blog).owner(ownerModel).build();
adapter.save(blogModel);
expected.add(blogModel.getId());
for (int post = 1; post <= 3; post++) {
Post postModel = Post.builder().title("Post " + post).status(PostStatus.INACTIVE).rating(5).blog(blogModel).build();
adapter.save(postModel);
expected.add(postModel.getId());
}
}
// Observe deletions
TestObserver<String> deleteObserver = adapter.observe().filter(change -> StorageItemChange.Type.DELETE.equals(change.type())).map(StorageItemChange::item).map(Model::getId).test();
// Triggers a delete.
// Deletes every saved model to prevent foreign key constraint violation
adapter.delete(ownerModel);
// Assert that cascaded deletions are observed.
deleteObserver.assertValueCount(13);
assertEquals(expected, new HashSet<>(deleteObserver.values()));
// Get data from the database and assert that everything is deleted.
assertTrue(adapter.query(BlogOwner.class).isEmpty());
assertTrue(adapter.query(Blog.class).isEmpty());
assertTrue(adapter.query(Post.class).isEmpty());
}
use of com.amplifyframework.testmodels.commentsblog.Post in project amplify-android by aws-amplify.
the class SQLiteStorageAdapterObserveQueryTest method querySavedDataWithNumericalPredicates.
/**
* Test querying the saved item in the SQLite database with
* predicate conditions.
*
* @throws DataStoreException On unexpected failure manipulating items in/out of DataStore
* @throws InterruptedException On unexpected failure manipulating items in/out of DataStore
*/
@Test
public void querySavedDataWithNumericalPredicates() throws DataStoreException, InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
CountDownLatch changeLatch = new CountDownLatch(1);
final List<Post> savedModels = new ArrayList<>();
final int numModels = 10;
BlogOwner blogOwner = BlogOwner.builder().name("Test Dummy").build();
adapter.save(blogOwner);
Blog blog = Blog.builder().name("Blogging for Dummies").owner(blogOwner).build();
adapter.save(blog);
for (int counter = 0; counter < numModels; counter++) {
final Post post = Post.builder().title("titlePrefix:" + counter).status(PostStatus.INACTIVE).rating(counter).blog(blog).build();
adapter.save(post);
savedModels.add(post);
}
// 1, 4, 5, 6
QueryPredicate predicate = Post.RATING.ge(4).and(Post.RATING.lt(7)).or(Post.RATING.eq(1).and(Post.RATING.ne(7)));
Consumer<Cancelable> observationStarted = NoOpConsumer.create();
AtomicInteger count = new AtomicInteger(0);
Consumer<DataStoreQuerySnapshot<Post>> onQuerySnapshot = value -> {
if (count.get() == 0) {
List<Post> expected = Arrays.asList(savedModels.get(1), savedModels.get(4), savedModels.get(5), savedModels.get(6));
assertEquals(new HashSet<>(expected), new HashSet<>(value.getItems()));
latch.countDown();
} else if (count.get() == 2) {
assertEquals(5, value.getItems().size());
assertTrue(value.getItems().contains(savedModels.get(1)));
assertTrue(value.getItems().contains(savedModels.get(4)));
assertTrue(value.getItems().contains(savedModels.get(5)));
assertTrue(value.getItems().contains(savedModels.get(6)));
assertTrue(value.getItems().contains(savedModels.get(11)));
changeLatch.countDown();
}
count.incrementAndGet();
};
Consumer<DataStoreException> onObservationError = NoOpConsumer.create();
Action onObservationComplete = NoOpAction.create();
adapter.observeQuery(Post.class, new ObserveQueryOptions(predicate, null), observationStarted, onQuerySnapshot, onObservationError, onObservationComplete);
assertTrue(latch.await(15, TimeUnit.SECONDS));
for (int counter = 3; counter < 5; counter++) {
final Post post = Post.builder().title("titlePrefix:" + counter + "change").status(PostStatus.INACTIVE).rating(counter).blog(blog).build();
adapter.save(post);
savedModels.add(post);
}
assertTrue(changeLatch.await(30, TimeUnit.SECONDS));
}
Aggregations