Search in sources :

Example 76 with ModelSchema

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

the class SQLCommandProcessorTest method rawQueryReturnsResults.

/**
 * Create and insert a BlogOwner, and then verify that a rawQuery returns a Cursor with one result, containing the
 * previously inserted BlogOwner.
 * @throws AmplifyException on failure to create ModelSchema from class
 */
@Test
public void rawQueryReturnsResults() throws AmplifyException {
    // Insert a BlogOwner
    ModelSchema blogOwnerSchema = ModelSchema.fromModelClass(BlogOwner.class);
    BlogOwner abigailMcGregor = BlogOwner.builder().name("Abigail McGregor").build();
    sqlCommandProcessor.execute(sqlCommandFactory.insertFor(blogOwnerSchema, abigailMcGregor));
    // Query for all BlogOwners, and verify that there is one result.
    SqlCommand queryCommand = sqlCommandFactory.queryFor(blogOwnerSchema, Where.matchesAll());
    Cursor cursor = sqlCommandProcessor.rawQuery(queryCommand);
    List<BlogOwner> results = new ArrayList<>();
    SQLiteModelFieldTypeConverter converter = new SQLiteModelFieldTypeConverter(blogOwnerSchema, schemaRegistry, GsonFactory.instance());
    if (cursor.moveToFirst()) {
        do {
            Map<String, Object> map = converter.buildMapForModel(cursor);
            String jsonString = gson.toJson(map);
            results.add(gson.fromJson(jsonString, BlogOwner.class));
        } while (cursor.moveToNext());
    }
    assertEquals(Arrays.asList(abigailMcGregor), results);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) ArrayList(java.util.ArrayList) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Cursor(android.database.Cursor) Test(org.junit.Test)

Example 77 with ModelSchema

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

the class SQLCommandProcessorTest method executeExistsReturnsTrueWhenItemExists.

/**
 * Create and insert a BlogOwner, and then verify that executeExists return true.
 * @throws AmplifyException on failure to create ModelSchema from class.
 */
@Test
public void executeExistsReturnsTrueWhenItemExists() throws AmplifyException {
    // Insert a BlogOwner
    ModelSchema blogOwnerSchema = ModelSchema.fromModelClass(BlogOwner.class);
    BlogOwner abigailMcGregor = BlogOwner.builder().name("Abigail McGregor").build();
    sqlCommandProcessor.execute(sqlCommandFactory.insertFor(blogOwnerSchema, abigailMcGregor));
    // Check that the BlogOwner exists
    QueryPredicate predicate = BlogOwner.ID.eq(abigailMcGregor.getId());
    SqlCommand existsCommand = sqlCommandFactory.existsFor(blogOwnerSchema, predicate);
    assertTrue(sqlCommandProcessor.executeExists(existsCommand));
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test)

Example 78 with ModelSchema

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

the class AppSyncClientTest method validateSyncQueryIsBuiltWithLimitLastSyncAndFilter.

/**
 * Validates sync query is constructed with all expected variables.
 * @throws AmplifyException On failure to build the sync request.
 * @throws JSONException from JSONAssert.assertEquals JSON parsing error
 */
@Test
public void validateSyncQueryIsBuiltWithLimitLastSyncAndFilter() throws AmplifyException, JSONException {
    ModelSchema modelSchema = ModelSchema.fromModelClass(BlogOwner.class);
    GraphQLRequest<PaginatedResult<ModelWithMetadata<BlogOwner>>> request = endpoint.buildSyncRequest(modelSchema, 123_412_341L, 342, BlogOwner.NAME.beginsWith("J"));
    JSONAssert.assertEquals(Resources.readAsString("sync-request-with-predicate.txt"), request.getContent(), true);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test)

Example 79 with ModelSchema

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

the class AppSyncClientInstrumentationTest method testAllOperations.

/**
 * Tests the operations in AppSyncClient.
 * @throws DataStoreException If any call to AppSync endpoint fails to return a response
 * @throws AmplifyException On failure to obtain ModelSchema
 */
@Test
@SuppressWarnings("MethodLength")
public void testAllOperations() throws AmplifyException {
    ModelSchema blogOwnerSchema = ModelSchema.fromModelClass(BlogOwner.class);
    ModelSchema postSchema = ModelSchema.fromModelClass(Post.class);
    ModelSchema blogSchema = ModelSchema.fromModelClass(Blog.class);
    long startTimeSeconds = TimeUnit.MILLISECONDS.toSeconds(new Date().getTime());
    // Create simple model with no relationship
    BlogOwner owner = BlogOwner.builder().name("David").build();
    ModelWithMetadata<BlogOwner> blogOwnerCreateResult = create(owner, blogOwnerSchema);
    BlogOwner actual = blogOwnerCreateResult.getModel();
    ModelAssert.assertEqualsIgnoringTimestamps(owner, actual);
    assertEquals(new Integer(1), blogOwnerCreateResult.getSyncMetadata().getVersion());
    // TODO: BE AWARE THAT THE DELETED PROPERTY RETURNS NULL INSTEAD OF FALSE
    assertNull(blogOwnerCreateResult.getSyncMetadata().isDeleted());
    assertTrue(blogOwnerCreateResult.getSyncMetadata().getId().endsWith(owner.getId()));
    // Subscribe to Blog creations
    Observable<GraphQLResponse<ModelWithMetadata<Blog>>> blogCreations = onCreate(blogSchema);
    // Now, actually create a Blog
    Blog blog = Blog.builder().name("Create test").owner(owner).build();
    ModelWithMetadata<Blog> blogCreateResult = create(blog, blogSchema);
    // Currently cannot do BlogOwner.justId because it will assign the id to the name field.
    // This is being fixed
    assertEquals(blog.getId(), blogCreateResult.getModel().getId());
    assertEquals(blog.getName(), blogCreateResult.getModel().getName());
    assertEquals(blog.getOwner().getId(), blogCreateResult.getModel().getOwner().getId());
    assertEquals(new Integer(1), blogCreateResult.getSyncMetadata().getVersion());
    assertNull(blogCreateResult.getSyncMetadata().isDeleted());
    Temporal.Timestamp createdBlogLastChangedAt = blogCreateResult.getSyncMetadata().getLastChangedAt();
    assertNotNull(createdBlogLastChangedAt);
    assertTrue(createdBlogLastChangedAt.getSecondsSinceEpoch() > startTimeSeconds);
    assertTrue(blogCreateResult.getSyncMetadata().getId().endsWith(blog.getId()));
    // TODO: Subscriptions are currently failing.  More investigation required to fix this part of the test.
    // Validate that subscription picked up the mutation and end the subscription since we're done with.
    // TestObserver<ModelWithMetadata<Blog>> blogCreationSubscriber = TestObserver.create();
    // blogCreations
    // .map(GraphQLResponse::getData)
    // .subscribe(blogCreationSubscriber);
    // blogCreationSubscriber.assertValue(blogCreateResult);
    // Create Posts which Blog hasMany of
    Post post1 = Post.builder().title("Post 1").status(PostStatus.ACTIVE).rating(4).blog(blog).build();
    Post post2 = Post.builder().title("Post 2").status(PostStatus.INACTIVE).rating(-1).blog(blog).build();
    Post post1ModelResult = create(post1, postSchema).getModel();
    Post post2ModelResult = create(post2, postSchema).getModel();
    // Results only have blog ID so strip out other information from the original post blog
    ModelAssert.assertEqualsIgnoringTimestamps(post1.copyOfBuilder().blog(Blog.justId(blog.getId())).build(), post1ModelResult);
    ModelAssert.assertEqualsIgnoringTimestamps(post2.copyOfBuilder().blog(Blog.justId(blog.getId())).build(), post2ModelResult);
    // Update model
    Blog updatedBlog = blog.copyOfBuilder().name("Updated blog").build();
    long updateBlogStartTimeSeconds = TimeUnit.MILLISECONDS.toSeconds(new Date().getTime());
    ModelWithMetadata<Blog> blogUpdateResult = update(updatedBlog, blogSchema, 1);
    assertEquals(updatedBlog.getName(), blogUpdateResult.getModel().getName());
    assertEquals(updatedBlog.getOwner().getId(), blogUpdateResult.getModel().getOwner().getId());
    assertEquals(updatedBlog.getId(), blogUpdateResult.getModel().getId());
    assertEquals(2, blogUpdateResult.getModel().getPosts().size());
    assertEquals(new Integer(2), blogUpdateResult.getSyncMetadata().getVersion());
    assertNull(blogUpdateResult.getSyncMetadata().isDeleted());
    Temporal.Timestamp updatedBlogLastChangedAt = blogUpdateResult.getSyncMetadata().getLastChangedAt();
    assertNotNull(updatedBlogLastChangedAt);
    assertTrue(updatedBlogLastChangedAt.getSecondsSinceEpoch() > updateBlogStartTimeSeconds);
    // Delete one of the posts
    ModelWithMetadata<Post> post1DeleteResult = delete(post1, postSchema, 1);
    ModelAssert.assertEqualsIgnoringTimestamps(post1.copyOfBuilder().blog(Blog.justId(blog.getId())).build(), post1DeleteResult.getModel());
    Boolean isDeleted = post1DeleteResult.getSyncMetadata().isDeleted();
    assertEquals(Boolean.TRUE, isDeleted);
    // Try to delete a post with a bad version number
    List<GraphQLResponse.Error> post2DeleteErrors = deleteExpectingResponseErrors(post2, postSchema, 0);
    assertEquals("Conflict resolver rejects mutation.", post2DeleteErrors.get(0).getMessage());
    // Run sync on Blogs
    // TODO: This is currently a pretty worthless test - mainly for setting a debug point and manually inspecting
    // When you call sync with a null lastSync it gives only one entry per object (the latest state)
    Iterable<ModelWithMetadata<Blog>> blogSyncResult = sync(api.buildSyncRequest(blogSchema, null, 1000, QueryPredicates.all()));
    assertTrue(blogSyncResult.iterator().hasNext());
    // Run sync on Posts
    // TODO: This is currently a pretty worthless test - mainly for setting a debug point and manually inspecting
    // When you call sync with a lastSyncTime it gives you one entry per version of that object which was created
    // since that time.
    Iterable<ModelWithMetadata<Post>> postSyncResult = sync(api.buildSyncRequest(postSchema, startTimeSeconds, 1000, QueryPredicates.all()));
    assertTrue(postSyncResult.iterator().hasNext());
}
Also used : ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) Post(com.amplifyframework.testmodels.commentsblog.Post) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) Date(java.util.Date) ModelSchema(com.amplifyframework.core.model.ModelSchema) Temporal(com.amplifyframework.core.model.temporal.Temporal) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Blog(com.amplifyframework.testmodels.commentsblog.Blog) Test(org.junit.Test)

Example 80 with ModelSchema

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

the class MutationPersistenceInstrumentationTest method saveIsObservedForPersistentRecord.

/**
 * When {@link LocalStorageAdapter#save(Model, StorageItemChange.Initiator, QueryPredicate, Consumer, Consumer)}
 * is called to save a {@link PendingMutation.PersistentRecord}, we should see an event emitted on the
 * {@link LocalStorageAdapter#observe(Consumer, Consumer, Action)}'s item consumer.
 * @throws DataStoreException On failure to convert received value out of record format, or
 *                            on failure to manipulate data in/out of DataStore
 */
@Test
public void saveIsObservedForPersistentRecord() throws DataStoreException {
    // Start watching observe().
    // The storage adapter emits StorageItemChange.
    TestObserver<StorageItemChange<? extends Model>> saveObserver = storage.observe().test();
    // Save something ..
    BlogOwner juan = BlogOwner.builder().name("Juan Gonzales").build();
    ModelSchema schema = schemaRegistry.getModelSchemaForModelClass(BlogOwner.class);
    PendingMutation<BlogOwner> change = PendingMutation.creation(juan, schema);
    PendingMutation.PersistentRecord thingWeSaved = converter.toRecord(change);
    // Wait for it to save...
    storage.save(thingWeSaved);
    // Assert that our observer got the item;
    // The observed change makes reference to an item. That referred item is our
    // PendingMutation.PersistentRecord. It should be identical to the item that we saved.
    assertEquals(thingWeSaved, saveObserver.awaitCount(1).values().get(0).item());
    saveObserver.dispose();
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) Model(com.amplifyframework.core.model.Model) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test)

Aggregations

ModelSchema (com.amplifyframework.core.model.ModelSchema)109 Test (org.junit.Test)69 SerializedModel (com.amplifyframework.core.model.SerializedModel)34 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)30 Model (com.amplifyframework.core.model.Model)28 DataStoreException (com.amplifyframework.datastore.DataStoreException)26 HashMap (java.util.HashMap)23 ArrayList (java.util.ArrayList)22 SchemaRegistry (com.amplifyframework.core.model.SchemaRegistry)21 AmplifyException (com.amplifyframework.AmplifyException)19 Consumer (com.amplifyframework.core.Consumer)19 List (java.util.List)17 NonNull (androidx.annotation.NonNull)14 Cancelable (com.amplifyframework.core.async.Cancelable)14 TimeUnit (java.util.concurrent.TimeUnit)14 QueryPredicate (com.amplifyframework.core.model.query.predicate.QueryPredicate)13 Action (com.amplifyframework.core.Action)12 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)12 Collections (java.util.Collections)12 ModelProvider (com.amplifyframework.core.model.ModelProvider)11