Search in sources :

Example 21 with SerializedModel

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

the class HybridAssociationSyncInstrumentationTest method associatedModelsAreSyncedUpToCloud.

/**
 * When we save {@link SerializedModel}s, we should find them in the cloud,
 * shortly there-after. Saving associated serialized models will work.
 * @throws AmplifyException For a variety of reasons, including failure to build schema,
 *                          or bad interaction with API or DataStore
 */
@Ignore("It passes. Not automating due to operational concerns as noted in class-level @Ignore.")
@Test
public void associatedModelsAreSyncedUpToCloud() throws AmplifyException {
    // First up, we're going to save a "leaf" model, a BlogOwner.
    String ownerModelName = BlogOwner.class.getSimpleName();
    ModelSchema ownerSchema = schemaProvider.modelSchemas().get(ownerModelName);
    assertNotNull(ownerSchema);
    BlogOwner owner = BlogOwner.builder().name("Guillermo Esteban").build();
    Map<String, Object> ownerData = new HashMap<>();
    ownerData.put("id", owner.getId());
    ownerData.put("name", owner.getName());
    SerializedModel serializedOwner = SerializedModel.builder().serializedData(ownerData).modelSchema(ownerSchema).build();
    // Setup an accumulator so we know when there has been a publication.
    HubAccumulator ownerAccumulator = HubAccumulator.create(HubChannel.DATASTORE, publicationOf(ownerModelName, owner.getId()), 1).start();
    hybridBehaviors.save(serializedOwner);
    ownerAccumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    // Validate that the Blog Owner was saved locally, and in the cloud.
    List<SerializedModel> allCurrentSerializedOwners = hybridBehaviors.list(ownerSchema.getName());
    assertTrue(allCurrentSerializedOwners.contains(serializedOwner));
    List<BlogOwner> allCurrentBlogOwners = normalBehaviors.list(BlogOwner.class);
    assertTrue(allCurrentBlogOwners.contains(owner));
    assertEquals(owner, api.get(BlogOwner.class, owner.getId()));
    // Now, we're going to save a type with a connection.
    // Build a blog, and its serialized form. Blog has association to a BlogOwner.
    Blog blog = Blog.builder().name("A wonderful blog").owner(owner).build();
    Map<String, Object> blogData = new HashMap<>();
    blogData.put("id", blog.getId());
    blogData.put("name", blog.getName());
    blogData.put("owner", SerializedModel.builder().serializedData(Collections.singletonMap("id", owner.getId())).modelSchema(null).build());
    String blogSchemaName = Blog.class.getSimpleName();
    ModelSchema blogSchema = schemaProvider.modelSchemas().get(blogSchemaName);
    assertNotNull(blogSchema);
    SerializedModel serializedBlog = SerializedModel.builder().serializedData(blogData).modelSchema(blogSchema).build();
    // Save the blog
    HubAccumulator blogAccumulator = HubAccumulator.create(HubChannel.DATASTORE, publicationOf(blogSchemaName, blog.getId()), 1).start();
    hybridBehaviors.save(serializedBlog);
    blogAccumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    // Validate that we find the blog locally, and on the remote system.
    List<SerializedModel> allCurrentSerializedBlogs = hybridBehaviors.list(blogSchema.getName());
    assertTrue(allCurrentSerializedBlogs.contains(serializedBlog));
    List<Blog> allCurrentBlogs = normalBehaviors.list(Blog.class);
    assertTrue(allCurrentBlogs.contains(blog));
    Blog foundBlog = api.get(Blog.class, blog.getId());
    assertEquals(blog, foundBlog);
    assertEquals(owner.getId(), foundBlog.getOwner().getId());
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) HashMap(java.util.HashMap) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) SerializedModel(com.amplifyframework.core.model.SerializedModel) Blog(com.amplifyframework.testmodels.commentsblog.Blog) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 22 with SerializedModel

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

the class HybridTemporalSyncInstrumentationTest method temporalTypesAreSyncedDownFromCloud.

/**
 * It is possible to receive a model with temporal types over a subscription.
 * After receiving such a model, we can query it locally and inspect its fields.
 * The temporal values should be the same as what was saved remotely.
 * @throws DataStoreException on failure to interact with AppSync
 */
@Ignore("It passes. Not automating due to operational concerns as noted in class-level @Ignore.")
@Test
public void temporalTypesAreSyncedDownFromCloud() throws DataStoreException {
    // Save a meeting, remotely. Wait for it to show up locally.
    Meeting meeting = createMeeting();
    HubAccumulator receiptAccumulator = HubAccumulator.create(HubChannel.DATASTORE, receiptOf(meeting.getId()), 1).start();
    appSync.create(meeting, modelSchema);
    receiptAccumulator.awaitFirst(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    // Look through the models that now exist locally.
    // One of them should be the thing we just saved to the backend.
    // Any others will have come in through the base sync in @Before.
    // When we find the clone, validate its fields.
    List<SerializedModel> clonedMeetings = hybridBehaviors.list(modelSchema.getName());
    SerializedModel clone = findById(clonedMeetings, meeting.getId());
    assertEquals(toMap(meeting), clone.getSerializedData());
}
Also used : Meeting(com.amplifyframework.testmodels.meeting.Meeting) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) SerializedModel(com.amplifyframework.core.model.SerializedModel) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 23 with SerializedModel

use of com.amplifyframework.core.model.SerializedModel 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)

Example 24 with SerializedModel

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

the class FieldFinderTest method extractsSerializedModelFieldValue.

/**
 * Extracts the field value for a serialized model.
 * @throws AmplifyException On failure to derive ModelSchema or to convert Java model to Map
 * @throws NoSuchFieldException If field name does not exist for model
 */
@Test
public void extractsSerializedModelFieldValue() throws AmplifyException, NoSuchFieldException {
    String username = "foo";
    User user = User.builder().username(username).build();
    ModelSchema modelSchema = ModelSchema.fromModelClass(User.class);
    Map<String, Object> map = ModelConverter.toMap(user, modelSchema);
    SerializedModel serializedModel = SerializedModel.builder().serializedData(map).modelSchema(modelSchema).build();
    Object extractedValue = FieldFinder.extractFieldValue(serializedModel, "username");
    Assert.assertEquals(username, extractedValue);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) User(com.amplifyframework.testmodels.ratingsblog.User) SerializedModel(com.amplifyframework.core.model.SerializedModel) Test(org.junit.Test)

Example 25 with SerializedModel

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

the class PersistentMutationOutboxTest method existingSerializedModelCreateIncomingUpdateMergesWithExistingMutation.

/**
 * When there is an existing SerializedModel create mutation, and a new SerializedModel update mutation comes in,
 * then we need to merge any existing mutations for that modelId and create the new one of type Create.
 * @throws AmplifyException On failure to find the serializedModel difference.
 * @throws InterruptedException If interrupted while awaiting terminal result in test observer
 */
@Test
public void existingSerializedModelCreateIncomingUpdateMergesWithExistingMutation() throws AmplifyException, InterruptedException {
    // Arrange an existing update mutation
    BlogOwner modelInSqlLite = BlogOwner.builder().name("Papa Tony").wea("Something").build();
    BlogOwner initialUpdate = BlogOwner.builder().name("Tony Jr").id(modelInSqlLite.getId()).build();
    PendingMutation<SerializedModel> initialUpdatePendingMutation = PendingMutation.creation(SerializedModel.difference(initialUpdate, modelInSqlLite, schema), schema);
    String existingUpdateId = initialUpdatePendingMutation.getMutationId().toString();
    mutationOutbox.enqueue(initialUpdatePendingMutation).blockingAwait();
    // Act: try to enqueue a new update mutation when there already is one
    BlogOwner incomingUpdatedModel = BlogOwner.builder().name("Papa Tony").wea("something else").id(modelInSqlLite.getId()).build();
    PendingMutation<SerializedModel> incomingUpdate = PendingMutation.update(SerializedModel.difference(incomingUpdatedModel, modelInSqlLite, schema), schema);
    String incomingUpdateId = incomingUpdate.getMutationId().toString();
    TestObserver<Void> enqueueObserver = mutationOutbox.enqueue(incomingUpdate).test();
    // Assert: OK. The new mutation is accepted
    enqueueObserver.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
    enqueueObserver.assertComplete();
    // Assert: the existing mutation has been removed
    assertRecordCountForMutationId(existingUpdateId, 0);
    // And the new one has been added to the queue
    assertRecordCountForMutationId(incomingUpdateId, 0);
    List<PersistentRecord> pendingMutationsFromStorage = getAllPendingMutationRecordFromStorage();
    for (PersistentRecord record : pendingMutationsFromStorage) {
        if (!record.getContainedModelId().equals(incomingUpdate.getMutatedItem().getId())) {
            pendingMutationsFromStorage.remove(record);
        }
    }
    // Ensure the new one is in storage.
    PendingMutation<SerializedModel> storedMutation = converter.fromRecord(pendingMutationsFromStorage.get(0));
    // This is the name from the second model, not the first!!
    assertEquals(initialUpdate.getName(), storedMutation.getMutatedItem().getSerializedData().get("name"));
    // wea got merged from existing model!!
    assertEquals(incomingUpdatedModel.getWea(), storedMutation.getMutatedItem().getSerializedData().get("wea"));
    assertEquals(PendingMutation.Type.CREATE, storedMutation.getMutationType());
}
Also used : BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) RandomString(com.amplifyframework.testutils.random.RandomString) SerializedModel(com.amplifyframework.core.model.SerializedModel) PersistentRecord(com.amplifyframework.datastore.syncengine.PendingMutation.PersistentRecord) Test(org.junit.Test)

Aggregations

SerializedModel (com.amplifyframework.core.model.SerializedModel)37 Test (org.junit.Test)21 HashMap (java.util.HashMap)18 ModelSchema (com.amplifyframework.core.model.ModelSchema)16 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)8 AmplifyException (com.amplifyframework.AmplifyException)7 Model (com.amplifyframework.core.model.Model)7 DataStoreException (com.amplifyframework.datastore.DataStoreException)6 ModelField (com.amplifyframework.core.model.ModelField)5 ArrayList (java.util.ArrayList)5 ModelAssociation (com.amplifyframework.core.model.ModelAssociation)4 SchemaRegistry (com.amplifyframework.core.model.SchemaRegistry)4 SerializedCustomType (com.amplifyframework.core.model.SerializedCustomType)4 StorageItemChange (com.amplifyframework.datastore.storage.StorageItemChange)4 Blog (com.amplifyframework.testmodels.commentsblog.Blog)4 HubAccumulator (com.amplifyframework.testutils.HubAccumulator)4 Map (java.util.Map)4 Ignore (org.junit.Ignore)4 Temporal (com.amplifyframework.core.model.temporal.Temporal)3 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)3