Search in sources :

Example 16 with BlogOwner

use of com.amplifyframework.testmodels.commentsblog.BlogOwner in project amplify-android by aws-amplify.

the class PersistentMutationOutboxTest method enqueueDoesNothingBeforeSubscription.

/**
 * The enqueue() returns a Completable, but that Completable doesn't actually invoke
 * any behavior until it is subscribed.
 * @throws DataStoreException On failure to query results, for assertions
 */
@Test
public void enqueueDoesNothingBeforeSubscription() throws DataStoreException {
    // Watch for notifications on the observe() API.
    TestObserver<OutboxEvent> testObserver = mutationOutbox.events().test();
    // Enqueue something, but don't subscribe to the observable just yet.
    BlogOwner tony = BlogOwner.builder().name("Tony Daniels").build();
    mutationOutbox.enqueue(PendingMutation.creation(tony, schema));
    // .subscribe() is NOT called on the enqueue() above!! This is the point!!!
    // Note that nothing has actually happened yet --
    // Nothing was put out on the observable ...
    testObserver.assertNoValues();
    testObserver.assertNotComplete();
    testObserver.dispose();
    // And nothing is in storage.
    assertTrue(storage.query(PersistentRecord.class).isEmpty());
    // And nothing is peek()ed.
    assertNull(mutationOutbox.peek());
}
Also used : BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) OutboxEvent(com.amplifyframework.datastore.syncengine.MutationOutbox.OutboxEvent) Test(org.junit.Test)

Example 17 with BlogOwner

use of com.amplifyframework.testmodels.commentsblog.BlogOwner in project amplify-android by aws-amplify.

the class PersistentMutationOutboxTest method hasPendingMutationReturnsFalseForItemNotInStore.

/**
 * When the mutation outbox is asked if there is a pending mutation, and there is no
 * corresponding mutation, then the mutation outbox shall say "heck no!".
 *
 * To throw a wrench in things, make sure the model is in storage -- just that there is
 * no pending mutation for it.
 *
 * @throws DataStoreException On failure to save the model item into storage
 */
@Test
public void hasPendingMutationReturnsFalseForItemNotInStore() throws DataStoreException {
    String joeId = RandomString.string();
    BlogOwner joe = BlogOwner.builder().name("Joe Swanson III").id(joeId).build();
    storage.save(joe);
    TimeBasedUuid mutationId = TimeBasedUuid.create();
    PendingMutation<BlogOwner> unrelatedMutation = PendingMutation.instance(mutationId, joe, schema, PendingMutation.Type.CREATE, QueryPredicates.all());
    storage.save(converter.toRecord(unrelatedMutation));
    assertFalse(mutationOutbox.hasPendingMutation(joeId));
    assertFalse(mutationOutbox.hasPendingMutation(mutationId.toString()));
}
Also used : BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) RandomString(com.amplifyframework.testutils.random.RandomString) Test(org.junit.Test)

Example 18 with BlogOwner

use of com.amplifyframework.testmodels.commentsblog.BlogOwner in project amplify-android by aws-amplify.

the class PersistentMutationOutboxTest method removeIsSynchronized.

/**
 * Attempting to remove an item from the queue which doesn't exist should throw an error.
 * @throws InterruptedException If interrupted while awaiting terminal result in test observer
 */
@Test
public void removeIsSynchronized() throws InterruptedException {
    // Enqueue and remove a mutation.
    BlogOwner tabby = BlogOwner.builder().name("Tabitha Stevens of Beaver Falls, Idaho").build();
    PendingMutation<BlogOwner> creation = PendingMutation.creation(tabby, schema);
    mutationOutbox.enqueue(creation).blockingAwait(TIMEOUT_MS, TimeUnit.MILLISECONDS);
    TestObserver<Void> observer = mutationOutbox.remove(creation.getMutationId()).andThen(mutationOutbox.remove(creation.getMutationId())).test();
    observer.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
    observer.assertError(DataStoreException.class).assertError(error -> error.getMessage() != null && error.getMessage().contains("there was no mutation with that ID in the outbox"));
}
Also used : DataStoreException(com.amplifyframework.datastore.DataStoreException) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test)

Example 19 with BlogOwner

use of com.amplifyframework.testmodels.commentsblog.BlogOwner in project amplify-android by aws-amplify.

the class SubscriptionProcessorTest method isDataMergedWhenBufferDrainedForBlogOwnerNamed.

/**
 * Return whether a response with a BlogOwner with the given name gets merged with the merger.
 * @param name name of the BlogOwner returned in the subscription
 * @return whether the data was merged
 * @throws DataStoreException On failure to arrange mocking
 * @throws InterruptedException On failure to await latch
 */
private boolean isDataMergedWhenBufferDrainedForBlogOwnerNamed(String name) throws DataStoreException, InterruptedException {
    // By default, start the subscriptions up.
    arrangeStartedSubscriptions(appSync, modelSchemas, SubscriptionType.values());
    // Arrange some subscription data
    BlogOwner model = BlogOwner.builder().name(name).build();
    ModelMetadata modelMetadata = new ModelMetadata(model.getId(), false, 1, Temporal.Timestamp.now());
    ModelWithMetadata<BlogOwner> modelWithMetadata = new ModelWithMetadata<>(model, modelMetadata);
    GraphQLResponse<ModelWithMetadata<BlogOwner>> response = new GraphQLResponse<>(modelWithMetadata, null);
    arrangeDataEmittingSubscription(appSync, schemaRegistry.getModelSchemaForModelInstance(model), SubscriptionType.ON_CREATE, response);
    // Merge will be invoked for the subcription data, when we start draining...
    CountDownLatch latch = new CountDownLatch(1);
    doAnswer(invocation -> {
        latch.countDown();
        return Completable.complete();
    }).when(merger).merge(eq(response.getData()));
    // Start draining....
    subscriptionProcessor.startSubscriptions();
    subscriptionProcessor.startDrainingMutationBuffer();
    // Was the data merged?
    return latch.await(OPERATION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
}
Also used : ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) CountDownLatch(java.util.concurrent.CountDownLatch) ModelMetadata(com.amplifyframework.datastore.appsync.ModelMetadata)

Example 20 with BlogOwner

use of com.amplifyframework.testmodels.commentsblog.BlogOwner 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)

Aggregations

BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)150 Test (org.junit.Test)146 DataStoreException (com.amplifyframework.datastore.DataStoreException)35 Blog (com.amplifyframework.testmodels.commentsblog.Blog)32 ModelSchema (com.amplifyframework.core.model.ModelSchema)31 Post (com.amplifyframework.testmodels.commentsblog.Post)31 ArrayList (java.util.ArrayList)29 QueryPredicate (com.amplifyframework.core.model.query.predicate.QueryPredicate)25 Assert.assertEquals (org.junit.Assert.assertEquals)25 ModelMetadata (com.amplifyframework.datastore.appsync.ModelMetadata)24 Collections (java.util.Collections)24 HashSet (java.util.HashSet)23 List (java.util.List)23 PostStatus (com.amplifyframework.testmodels.commentsblog.PostStatus)22 HubAccumulator (com.amplifyframework.testutils.HubAccumulator)22 Arrays (java.util.Arrays)22 TimeUnit (java.util.concurrent.TimeUnit)22 Consumer (com.amplifyframework.core.Consumer)21 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)21 Before (org.junit.Before)21