Search in sources :

Example 26 with Model

use of com.amplifyframework.core.model.Model in project amplify-android by aws-amplify.

the class RxDataStoreBindingTest method saveCompletesWhenBehaviorEmitsResult.

/**
 * When the DataStore behavior successfully saves a value, the Rx binding
 * for save should just complete.
 * @throws InterruptedException If interrupted while test observer is awaiting terminal event
 */
@Test
public void saveCompletesWhenBehaviorEmitsResult() throws InterruptedException {
    Model model = RandomModel.model();
    // Arrange: category returns notification of change when save is transacted
    doAnswer(invocation -> {
        // 0 = model, 1 = result consumer, 2 = failure consumer
        final int indexOfModel = 0;
        final int indexOfResultConsumer = 1;
        Model modelFromInvocation = invocation.getArgument(indexOfModel);
        Consumer<DataStoreItemChange<Model>> resultConsumer = invocation.getArgument(indexOfResultConsumer);
        resultConsumer.accept(DataStoreItemChange.builder().uuid(modelFromInvocation.getId()).type(Type.CREATE).itemClass(Model.class).initiator(Initiator.LOCAL).item(modelFromInvocation).build());
        return null;
    }).when(delegate).save(eq(model), anyConsumer(), anyConsumer());
    // Act: try to save something.
    TestObserver<Void> observer = rxDataStore.save(model).test();
    // Assert: operation completed
    observer.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    observer.assertComplete();
    // Assert: behavior was invoked
    verify(delegate).save(eq(model), anyConsumer(), anyConsumer());
}
Also used : DataStoreItemChange(com.amplifyframework.datastore.DataStoreItemChange) RandomModel(com.amplifyframework.testutils.random.RandomModel) Model(com.amplifyframework.core.model.Model) Test(org.junit.Test)

Example 27 with Model

use of com.amplifyframework.core.model.Model in project amplify-android by aws-amplify.

the class RxDataStoreBindingTest method observeQueryCompletesWhenCategoryBehaviorDoes.

/**
 * The Rx binding for the DataStore's observeQuery method is an Observable. It should
 * complete when the Rx binding's completion callback is triggered.
 * @throws InterruptedException If interrupted while test observer is awaiting terminal event
 */
@Test
public void observeQueryCompletesWhenCategoryBehaviorDoes() throws InterruptedException {
    // Category behavior is arranged to complete
    doAnswer(invocation -> {
        // 0 = clazz, 1 = options, 2 = start consumer, 3 = item consumer, 4 = failure consumer, 5 = onComplete
        final int positionOfOnStart = 3;
        Consumer<Cancelable> onStart = invocation.getArgument(positionOfOnStart);
        onStart.accept(new NoOpCancelable());
        final int positionOfOnComplete = 5;
        Action onComplete = invocation.getArgument(positionOfOnComplete);
        onComplete.call();
        // "void"
        return null;
    }).when(delegate).observeQuery(eq(Model.class), any(), anyConsumer(), anyConsumer(), anyConsumer(), anyAction());
    // Act: observe via Rx binding
    TestObserver<DataStoreQuerySnapshot<Model>> observer = rxDataStore.observeQuery(Model.class, new ObserveQueryOptions()).test();
    observer.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    observer.assertComplete();
    verify(delegate).observeQuery(eq(Model.class), any(), anyConsumer(), anyConsumer(), anyConsumer(), anyAction());
}
Also used : Matchers.anyAction(com.amplifyframework.rx.Matchers.anyAction) Action(com.amplifyframework.core.Action) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) RandomModel(com.amplifyframework.testutils.random.RandomModel) Model(com.amplifyframework.core.model.Model) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) Cancelable(com.amplifyframework.core.async.Cancelable) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) Test(org.junit.Test)

Example 28 with Model

use of com.amplifyframework.core.model.Model 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 29 with Model

use of com.amplifyframework.core.model.Model in project amplify-android by aws-amplify.

the class MultiAuthSyncEngineInstrumentationTest method verifyScenario.

private void verifyScenario(Class<? extends Model> modelType, boolean signInToCognito, boolean signInWithOidc, AuthorizationType expectedAuthType) throws AmplifyException, IOException {
    configure(modelType, signInToCognito, signInWithOidc, expectedAuthType);
    String modelId = UUID.randomUUID().toString();
    Model testRecord = createRecord(modelType, modelId);
    HubAccumulator expectedEventAccumulator = null;
    if (expectedAuthType != null) {
        expectedEventAccumulator = HubAccumulator.create(HubChannel.DATASTORE, publicationOf(modelType.getSimpleName(), testRecord.getId()), 1).start();
    } else {
        expectedEventAccumulator = HubAccumulator.create(HubChannel.DATASTORE, networkStatusFailure(), 1).start();
    }
    dataStore.start();
    dataStore.save(testRecord);
    expectedEventAccumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    assertFalse(requestInterceptor.hasUnexpectedRequests());
    // Sign the user out if sign-in was required.
    if (signInToCognito) {
        auth.signOut(AuthSignOutOptions.builder().build());
    }
}
Also used : SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) RandomString(com.amplifyframework.testutils.random.RandomString) HubAccumulator(com.amplifyframework.testutils.HubAccumulator)

Example 30 with Model

use of com.amplifyframework.core.model.Model in project amplify-android by aws-amplify.

the class SQLiteStorageAdapterSaveTest method patchItemOnlyHasAllFields.

/**
 * Verify that saving an item that already exists emits a StorageItemChange event with a patchItem that only
 * contains the fields that are different.
 *
 * @throws AmplifyException On failure to obtain ModelSchema from model class.
 * @throws InterruptedException If interrupted while awaiting terminal result in test observer
 */
@Test
public void patchItemOnlyHasAllFields() throws AmplifyException, InterruptedException {
    // Create a BlogOwner.
    final BlogOwner johnSmith = BlogOwner.builder().name("John Smith").wea("ther").build();
    adapter.save(johnSmith);
    // Start observing for changes
    TestObserver<StorageItemChange<? extends Model>> observer = adapter.observe().test();
    // Update one field on the BlogOwner.
    BlogOwner johnAdams = johnSmith.copyOfBuilder().name("John Adams").build();
    adapter.save(johnAdams);
    // Observe that the StorageItemChange contains an item with only the fields that changed (`id`, and `name`, but
    // not `wea`)
    Map<String, Object> serializedData = new HashMap<>();
    serializedData.put("id", johnAdams.getId());
    serializedData.put("name", "John Adams");
    serializedData.put("wea", johnAdams.getWea());
    serializedData.put("createdAt", johnAdams.getCreatedAt());
    serializedData.put("updatedAt", johnAdams.getUpdatedAt());
    SerializedModel expectedItem = SerializedModel.builder().serializedData(serializedData).modelSchema(ModelSchema.fromModelClass(BlogOwner.class)).build();
    observer.await(1, TimeUnit.SECONDS);
    observer.assertValueCount(1);
    observer.assertValueAt(0, storageItemChange -> storageItemChange.patchItem().equals(expectedItem));
}
Also used : HashMap(java.util.HashMap) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) SerializedModel(com.amplifyframework.core.model.SerializedModel) Test(org.junit.Test)

Aggregations

Model (com.amplifyframework.core.model.Model)62 Test (org.junit.Test)37 DataStoreException (com.amplifyframework.datastore.DataStoreException)34 ModelSchema (com.amplifyframework.core.model.ModelSchema)32 SerializedModel (com.amplifyframework.core.model.SerializedModel)30 AmplifyException (com.amplifyframework.AmplifyException)23 Cancelable (com.amplifyframework.core.async.Cancelable)22 Action (com.amplifyframework.core.Action)19 Consumer (com.amplifyframework.core.Consumer)19 StorageItemChange (com.amplifyframework.datastore.storage.StorageItemChange)19 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)19 ArrayList (java.util.ArrayList)19 List (java.util.List)19 SchemaRegistry (com.amplifyframework.core.model.SchemaRegistry)18 RandomModel (com.amplifyframework.testutils.random.RandomModel)17 GraphQLResponse (com.amplifyframework.api.graphql.GraphQLResponse)16 QueryPredicates (com.amplifyframework.core.model.query.predicate.QueryPredicates)16 TimeUnit (java.util.concurrent.TimeUnit)16 Collections (java.util.Collections)15 ObserveQueryOptions (com.amplifyframework.core.model.query.ObserveQueryOptions)13