Search in sources :

Example 41 with DataStoreException

use of com.amplifyframework.datastore.DataStoreException in project amplify-android by aws-amplify.

the class SQLiteStorageAdapterObserveQueryTest method querySavedDataWithMultipleItems.

/**
 * Test querying the saved item in the SQLite database with observeQuery.
 *
 * @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 querySavedDataWithMultipleItems() throws DataStoreException, InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    final List<BlogOwner> savedModels = new ArrayList<>();
    final int numModels = 10;
    for (int counter = 0; counter < numModels; counter++) {
        final BlogOwner blogOwner = BlogOwner.builder().name("namePrefix:" + counter).build();
        adapter.save(blogOwner);
        savedModels.add(blogOwner);
    }
    Consumer<Cancelable> observationStarted = NoOpConsumer.create();
    Consumer<DataStoreQuerySnapshot<BlogOwner>> onQuerySnapshot = value -> {
        for (BlogOwner blogOwner : savedModels) {
            assertTrue(value.getItems().contains(blogOwner));
        }
        latch.countDown();
    };
    Consumer<DataStoreException> onObservationError = NoOpConsumer.create();
    Action onObservationComplete = NoOpAction.create();
    adapter.observeQuery(BlogOwner.class, new ObserveQueryOptions(null, null), observationStarted, onQuerySnapshot, onObservationError, onObservationComplete);
    assertTrue(latch.await(1, 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) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Cancelable(com.amplifyframework.core.async.Cancelable) Test(org.junit.Test)

Example 42 with DataStoreException

use of com.amplifyframework.datastore.DataStoreException in project amplify-android by aws-amplify.

the class SQLiteStorageAdapterQueryTest method queryWithOrderByRelatedModel.

/**
 * Test query with order by.  Validate that a list of Blog can be sorted by the names of BlogOwners.
 * @throws DataStoreException On failure to arrange items into store, or from the query action itself
 */
@Test
public void queryWithOrderByRelatedModel() throws DataStoreException {
    // Expect: Create BlogOwners and their respective blogs
    List<String> names = Arrays.asList("Joe", "Bob", "Dan", "Jane");
    List<Blog> blogs = new ArrayList<>();
    for (String name : names) {
        BlogOwner owner = BlogOwner.builder().name(name).build();
        adapter.save(owner);
        Blog blog = Blog.builder().name("").owner(owner).build();
        adapter.save(blog);
        blogs.add(blog);
    }
    // Act: Query Blogs sorted by owner's name
    List<Blog> result = adapter.query(Blog.class, Where.sorted(BlogOwner.NAME.ascending()));
    // Verify: Query result is sorted by owner's name
    List<Blog> sorted = new ArrayList<>(blogs);
    Collections.sort(sorted, Comparator.comparing(blog -> blog.getOwner().getName()));
    assertEquals(sorted, result);
}
Also used : Arrays(java.util.Arrays) BeforeClass(org.junit.BeforeClass) Blog(com.amplifyframework.testmodels.commentsblog.Blog) ArrayList(java.util.ArrayList) SynchronousStorageAdapter(com.amplifyframework.datastore.storage.SynchronousStorageAdapter) HashSet(java.util.HashSet) Observable(io.reactivex.rxjava3.core.Observable) After(org.junit.After) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) PostStatus(com.amplifyframework.testmodels.commentsblog.PostStatus) Before(org.junit.Before) Page(com.amplifyframework.core.model.query.Page) Phone(com.amplifyframework.testmodels.phonecall.Phone) Assert.assertNotNull(org.junit.Assert.assertNotNull) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Comment(com.amplifyframework.testmodels.commentsblog.Comment) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Where(com.amplifyframework.core.model.query.Where) StrictMode(com.amplifyframework.datastore.StrictMode) DataStoreException(com.amplifyframework.datastore.DataStoreException) List(java.util.List) Person(com.amplifyframework.testmodels.phonecall.Person) Temporal(com.amplifyframework.core.model.temporal.Temporal) Comparator(java.util.Comparator) AmplifyModelProvider(com.amplifyframework.testmodels.commentsblog.AmplifyModelProvider) Post(com.amplifyframework.testmodels.commentsblog.Post) Collections(java.util.Collections) QueryField.field(com.amplifyframework.core.model.query.predicate.QueryField.field) QueryPredicate.not(com.amplifyframework.core.model.query.predicate.QueryPredicate.not) Assert.assertEquals(org.junit.Assert.assertEquals) Call(com.amplifyframework.testmodels.phonecall.Call) ArrayList(java.util.ArrayList) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Blog(com.amplifyframework.testmodels.commentsblog.Blog) Test(org.junit.Test)

Example 43 with DataStoreException

use of com.amplifyframework.datastore.DataStoreException in project amplify-android by aws-amplify.

the class TestStorageAdapter method create.

/**
 * Creates an instance of the {@link SynchronousStorageAdapter}, which has been initialized
 * so that it can be used with the given models. The {@link SynchronousStorageAdapter}
 * is backed by an {@link SQLiteStorageAdapter}. The caller of this method
 * should do due diligence to ensure that any resources created by
 * {@link SQLiteStorageAdapter#initialize(Context, Consumer, Consumer)} have been cleaned up.
 * @return An initialized instance of the {@link SynchronousStorageAdapter}
 */
static SynchronousStorageAdapter create(ModelProvider modelProvider) {
    SchemaRegistry schemaRegistry = SchemaRegistry.instance();
    schemaRegistry.clear();
    try {
        schemaRegistry.register(modelProvider.models());
    } catch (AmplifyException modelSchemaLoadingFailure) {
        throw new RuntimeException(modelSchemaLoadingFailure);
    }
    SQLiteStorageAdapter sqLiteStorageAdapter = SQLiteStorageAdapter.forModels(schemaRegistry, modelProvider);
    SynchronousStorageAdapter synchronousStorageAdapter = SynchronousStorageAdapter.delegatingTo(sqLiteStorageAdapter);
    Context context = ApplicationProvider.getApplicationContext();
    try {
        synchronousStorageAdapter.initialize(context);
    } catch (DataStoreException initializationFailure) {
        throw new RuntimeException(initializationFailure);
    }
    return synchronousStorageAdapter;
}
Also used : Context(android.content.Context) DataStoreException(com.amplifyframework.datastore.DataStoreException) AmplifyException(com.amplifyframework.AmplifyException) SynchronousStorageAdapter(com.amplifyframework.datastore.storage.SynchronousStorageAdapter) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry)

Example 44 with DataStoreException

use of com.amplifyframework.datastore.DataStoreException in project amplify-android by aws-amplify.

the class PersistentMutationOutboxTest method existingDeletionIncomingCreationYieldsError.

/**
 * When there is an existing deletion for a model, and a new creation for that
 * model comes in, an error should be returned. Even though the model may be staged
 * for deletion, that deletion hasn't happened yet. So, it doesn't make sense to create()
 * something that currently already exists. That's like an "update."
 * @throws DataStoreException On failure to query which mutation is present in storage
 * @throws InterruptedException If interrupted while awaiting terminal result in test observer
 */
@Test
public void existingDeletionIncomingCreationYieldsError() throws DataStoreException, InterruptedException {
    // Arrange an existing deletion mutation
    BlogOwner modelInExistingMutation = BlogOwner.builder().name("Papa Tony").build();
    PendingMutation<BlogOwner> existingDeletion = PendingMutation.deletion(modelInExistingMutation, schema);
    String existingDeletionId = existingDeletion.getMutationId().toString();
    mutationOutbox.enqueue(existingDeletion).blockingAwait(TIMEOUT_MS, TimeUnit.MILLISECONDS);
    // Act: try to create tony, but wait -- if we're already deleting him...
    BlogOwner modelInIncomingMutation = modelInExistingMutation.copyOfBuilder().name("Tony Jr.").build();
    PendingMutation<BlogOwner> incomingCreation = PendingMutation.creation(modelInIncomingMutation, schema);
    String incomingCreationId = incomingCreation.getMutationId().toString();
    TestObserver<Void> enqueueObserver = mutationOutbox.enqueue(incomingCreation).test();
    // Assert: caused a failure.
    enqueueObserver.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
    enqueueObserver.assertError(throwable -> throwable instanceof DataStoreException);
    // Assert: original mutation is present, but the new one isn't.
    PendingMutation.PersistentRecord storedMutation = storage.query(PersistentRecord.class, Where.id(existingDeletionId)).get(0);
    assertEquals(modelInExistingMutation, converter.fromRecord(storedMutation).getMutatedItem());
    assertTrue(storage.query(PersistentRecord.class, Where.id(incomingCreationId)).isEmpty());
    // Existing mutation still attainable as next mutation (right now, its the ONLY mutation in outbox)
    assertTrue(mutationOutbox.hasPendingMutation(modelInExistingMutation.getId()));
    assertEquals(existingDeletion, mutationOutbox.peek());
}
Also used : DataStoreException(com.amplifyframework.datastore.DataStoreException) PersistentRecord(com.amplifyframework.datastore.syncengine.PendingMutation.PersistentRecord) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) RandomString(com.amplifyframework.testutils.random.RandomString) PersistentRecord(com.amplifyframework.datastore.syncengine.PendingMutation.PersistentRecord) Test(org.junit.Test)

Example 45 with DataStoreException

use of com.amplifyframework.datastore.DataStoreException in project amplify-android by aws-amplify.

the class PersistentMutationOutboxTest method existingDeletionIncomingUpdateYieldsError.

/**
 * If there is a pending deletion, enqueuing an update will fail, since the thing being
 * updated is not meant to exist.
 * @throws DataStoreException On failure to query storage, for the purpose of asserting the
 *                            state of mutations after the test action
 * @throws InterruptedException If interrupted while awaiting terminal result in test observer
 */
@Test
public void existingDeletionIncomingUpdateYieldsError() throws DataStoreException, InterruptedException {
    // Arrange an existing deletion mutation
    BlogOwner modelInExistingMutation = BlogOwner.builder().name("Papa Tony").build();
    PendingMutation<BlogOwner> existingDeletion = PendingMutation.deletion(modelInExistingMutation, schema);
    String existingDeletionId = existingDeletion.getMutationId().toString();
    mutationOutbox.enqueue(existingDeletion).blockingAwait(TIMEOUT_MS, TimeUnit.MILLISECONDS);
    // Act: try to update tony, but wait ... aren't we deleting tony?
    BlogOwner modelInIncomingMutation = modelInExistingMutation.copyOfBuilder().name("Tony Jr.").build();
    PendingMutation<BlogOwner> incomingUpdate = PendingMutation.update(modelInIncomingMutation, schema);
    String incomingUpdateId = incomingUpdate.getMutationId().toString();
    TestObserver<Void> enqueueObserver = mutationOutbox.enqueue(incomingUpdate).test();
    // Assert: caused a failure.
    enqueueObserver.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
    enqueueObserver.assertError(throwable -> throwable instanceof DataStoreException);
    // Assert: original mutation is present, but the new one isn't.
    PendingMutation.PersistentRecord storedMutation = storage.query(PersistentRecord.class, Where.id(existingDeletionId)).get(0);
    assertEquals(modelInExistingMutation, converter.fromRecord(storedMutation).getMutatedItem());
    assertTrue(storage.query(PersistentRecord.class, Where.id(incomingUpdateId)).isEmpty());
    // Existing mutation still attainable as next mutation (right now, its the ONLY mutation in outbox)
    assertTrue(mutationOutbox.hasPendingMutation(modelInExistingMutation.getId()));
    assertEquals(existingDeletion, mutationOutbox.peek());
}
Also used : DataStoreException(com.amplifyframework.datastore.DataStoreException) PersistentRecord(com.amplifyframework.datastore.syncengine.PendingMutation.PersistentRecord) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) RandomString(com.amplifyframework.testutils.random.RandomString) PersistentRecord(com.amplifyframework.datastore.syncengine.PendingMutation.PersistentRecord) Test(org.junit.Test)

Aggregations

DataStoreException (com.amplifyframework.datastore.DataStoreException)89 Test (org.junit.Test)52 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)36 Consumer (com.amplifyframework.core.Consumer)32 List (java.util.List)32 Cancelable (com.amplifyframework.core.async.Cancelable)31 Model (com.amplifyframework.core.model.Model)31 ArrayList (java.util.ArrayList)31 AmplifyException (com.amplifyframework.AmplifyException)29 ModelSchema (com.amplifyframework.core.model.ModelSchema)28 Collections (java.util.Collections)28 Action (com.amplifyframework.core.Action)27 QueryPredicate (com.amplifyframework.core.model.query.predicate.QueryPredicate)27 TimeUnit (java.util.concurrent.TimeUnit)25 Post (com.amplifyframework.testmodels.commentsblog.Post)23 PostStatus (com.amplifyframework.testmodels.commentsblog.PostStatus)23 Arrays (java.util.Arrays)23 Assert.assertEquals (org.junit.Assert.assertEquals)23 ObserveQueryOptions (com.amplifyframework.core.model.query.ObserveQueryOptions)22 DataStoreQuerySnapshot (com.amplifyframework.datastore.DataStoreQuerySnapshot)21