Search in sources :

Example 1 with Post

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
}
Also used : ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) Post(com.amplifyframework.testmodels.commentsblog.Post) Model(com.amplifyframework.core.model.Model) HubEvent(com.amplifyframework.hub.HubEvent) ModelSyncedEvent(com.amplifyframework.datastore.events.ModelSyncedEvent) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) RandomString(com.amplifyframework.testutils.random.RandomString) Test(org.junit.Test)

Example 2 with Post

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);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) Post(com.amplifyframework.testmodels.commentsblog.Post) Model(com.amplifyframework.core.model.Model) ArrayList(java.util.ArrayList) SecureRandom(java.security.SecureRandom) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test)

Example 3 with Post

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);
}
Also used : Comment(com.amplifyframework.testmodels.commentsblog.Comment) ModelSchema(com.amplifyframework.core.model.ModelSchema) Post(com.amplifyframework.testmodels.commentsblog.Post) Test(org.junit.Test)

Example 4 with Post

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());
}
Also used : BeforeClass(org.junit.BeforeClass) Blog(com.amplifyframework.testmodels.commentsblog.Blog) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Model(com.amplifyframework.core.model.Model) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) StrictMode(com.amplifyframework.datastore.StrictMode) SynchronousStorageAdapter(com.amplifyframework.datastore.storage.SynchronousStorageAdapter) HashSet(java.util.HashSet) DataStoreException(com.amplifyframework.datastore.DataStoreException) List(java.util.List) TestObserver(io.reactivex.rxjava3.observers.TestObserver) After(org.junit.After) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) AmplifyModelProvider(com.amplifyframework.testmodels.commentsblog.AmplifyModelProvider) Post(com.amplifyframework.testmodels.commentsblog.Post) PostStatus(com.amplifyframework.testmodels.commentsblog.PostStatus) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) Before(org.junit.Before) Post(com.amplifyframework.testmodels.commentsblog.Post) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Blog(com.amplifyframework.testmodels.commentsblog.Blog) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 5 with Post

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));
}
Also used : Arrays(java.util.Arrays) BeforeClass(org.junit.BeforeClass) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) Blog(com.amplifyframework.testmodels.commentsblog.Blog) ArrayList(java.util.ArrayList) SynchronousStorageAdapter(com.amplifyframework.datastore.storage.SynchronousStorageAdapter) HashSet(java.util.HashSet) Consumer(com.amplifyframework.core.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) NoOpConsumer(com.amplifyframework.core.NoOpConsumer) PostStatus(com.amplifyframework.testmodels.commentsblog.PostStatus) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) Before(org.junit.Before) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Comment(com.amplifyframework.testmodels.commentsblog.Comment) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Action(com.amplifyframework.core.Action) StrictMode(com.amplifyframework.datastore.StrictMode) TimeUnit(java.util.concurrent.TimeUnit) DataStoreException(com.amplifyframework.datastore.DataStoreException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) Assert.assertFalse(org.junit.Assert.assertFalse) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) Comparator(java.util.Comparator) NoOpAction(com.amplifyframework.core.NoOpAction) AmplifyModelProvider(com.amplifyframework.testmodels.commentsblog.AmplifyModelProvider) Post(com.amplifyframework.testmodels.commentsblog.Post) Collections(java.util.Collections) QueryPredicate.not(com.amplifyframework.core.model.query.predicate.QueryPredicate.not) Assert.assertEquals(org.junit.Assert.assertEquals) DataStoreException(com.amplifyframework.datastore.DataStoreException) Action(com.amplifyframework.core.Action) NoOpAction(com.amplifyframework.core.NoOpAction) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) Post(com.amplifyframework.testmodels.commentsblog.Post) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) ArrayList(java.util.ArrayList) List(java.util.List) Blog(com.amplifyframework.testmodels.commentsblog.Blog) Cancelable(com.amplifyframework.core.async.Cancelable) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

Post (com.amplifyframework.testmodels.commentsblog.Post)16 Test (org.junit.Test)16 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)15 Blog (com.amplifyframework.testmodels.commentsblog.Blog)11 ArrayList (java.util.ArrayList)7 QueryPredicate (com.amplifyframework.core.model.query.predicate.QueryPredicate)6 DataStoreException (com.amplifyframework.datastore.DataStoreException)6 Comment (com.amplifyframework.testmodels.commentsblog.Comment)6 PostStatus (com.amplifyframework.testmodels.commentsblog.PostStatus)6 Collections (java.util.Collections)6 HashSet (java.util.HashSet)6 List (java.util.List)6 Assert.assertEquals (org.junit.Assert.assertEquals)6 Model (com.amplifyframework.core.model.Model)5 StrictMode (com.amplifyframework.datastore.StrictMode)5 SynchronousStorageAdapter (com.amplifyframework.datastore.storage.SynchronousStorageAdapter)5 AmplifyModelProvider (com.amplifyframework.testmodels.commentsblog.AmplifyModelProvider)5 Action (com.amplifyframework.core.Action)4 Consumer (com.amplifyframework.core.Consumer)4 NoOpAction (com.amplifyframework.core.NoOpAction)4