Search in sources :

Example 11 with HubAccumulator

use of com.amplifyframework.testutils.HubAccumulator in project amplify-android by aws-amplify.

the class BasicCloudSyncInstrumentationTest method syncUpToCloudIsWorking.

/**
 * Save a BlogOwner via DataStore, wait a bit, check API to see if the BlogOwner is there, remotely.
 * @throws DataStoreException On failure to save item into DataStore (first step)
 * @throws ApiException On failure to retrieve a valid response from API when checking
 *                      for remote presence of saved item
 * @throws AmplifyException On failure to arrange a {@link DataStoreCategory} via the
 *                          {@link DataStoreCategoryConfigurator}
 */
@Test
public void syncUpToCloudIsWorking() throws AmplifyException {
    // Start listening for model publication events on the Hub.
    BlogOwner localCharley = BlogOwner.builder().name("Charley Crockett").build();
    String modelName = BlogOwner.class.getSimpleName();
    HubAccumulator publishedMutationsAccumulator = HubAccumulator.create(HubChannel.DATASTORE, publicationOf(modelName, localCharley.getId()), 1).start();
    // Save Charley Crockett, a guy who has a blog, into the DataStore.
    dataStore.save(localCharley);
    // Wait for a Hub event telling us that our Charley model got published to the cloud.
    publishedMutationsAccumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    // Try to get Charley from the backend.
    BlogOwner remoteCharley = api.get(BlogOwner.class, localCharley.getId());
    // A Charley is a Charley is a Charley, right?
    assertEquals(localCharley.getId(), remoteCharley.getId());
    assertEquals(localCharley.getName(), remoteCharley.getName());
}
Also used : BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) Test(org.junit.Test)

Example 12 with HubAccumulator

use of com.amplifyframework.testutils.HubAccumulator in project amplify-android by aws-amplify.

the class BasicCloudSyncInstrumentationTest method createItemThenUpdateThenWaitThenUpdate.

/**
 * Create new item, then immediately update a different field.
 * Wait for sync round trip. Then update the first field.
 * @throws DataStoreException On failure to save or query items from DataStore.
 * @throws ApiException On failure to query the API.
 */
@Test
public void createItemThenUpdateThenWaitThenUpdate() throws DataStoreException, ApiException {
    // Setup
    BlogOwner owner = BlogOwner.builder().name("ownerName").build();
    BlogOwner updatedOwner = owner.copyOfBuilder().wea("pon").build();
    String modelName = BlogOwner.class.getSimpleName();
    HubAccumulator accumulator = HubAccumulator.create(HubChannel.DATASTORE, publicationOf(modelName, owner.getId()), 2).start();
    // Create new and then immediately update
    dataStore.save(owner);
    dataStore.save(updatedOwner);
    accumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    // Update the field
    BlogOwner diffFieldUpdated = updatedOwner.copyOfBuilder().name("ownerUpdatedName").build();
    accumulator = HubAccumulator.create(HubChannel.DATASTORE, publicationOf(modelName, diffFieldUpdated.getId()), 1).start();
    dataStore.save(diffFieldUpdated);
    accumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    BlogOwner localOwner = dataStore.get(BlogOwner.class, diffFieldUpdated.getId());
    ModelAssert.assertEqualsIgnoringTimestamps(diffFieldUpdated, localOwner);
    BlogOwner remoteOwner = api.get(BlogOwner.class, diffFieldUpdated.getId());
    ModelAssert.assertEqualsIgnoringTimestamps(diffFieldUpdated, remoteOwner);
}
Also used : BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) Test(org.junit.Test)

Example 13 with HubAccumulator

use of com.amplifyframework.testutils.HubAccumulator in project amplify-android by aws-amplify.

the class BasicCloudSyncInstrumentationTest method createWaitThenUpdate10TimesWithPredicate.

/**
 * The test is to test consecutive updates with predicate.
 * @throws DataStoreException On failure to save or query items from DataStore.
 * @throws ApiException On failure to query the API.
 */
@Test
public void createWaitThenUpdate10TimesWithPredicate() throws DataStoreException, ApiException {
    // Setup
    BlogOwner owner = BlogOwner.builder().name("Blogger").wea("ryt").build();
    String modelName = BlogOwner.class.getSimpleName();
    QueryPredicate predicate = BlogOwner.WEA.beginsWith("r");
    // Setup 10 updates
    List<String> weas = Arrays.asList("ron", "rth", "rer", "rly", "ren", "rel", "ral", "rec", "rin", "reh");
    List<BlogOwner> owners = new ArrayList<>();
    for (int i = 0; i < weas.size(); i++) {
        BlogOwner updatedOwner = owner.copyOfBuilder().wea(weas.get(i)).build();
        owners.add(updatedOwner);
    }
    HubAccumulator accumulator = HubAccumulator.create(HubChannel.DATASTORE, publicationOf(modelName, owner.getId()), 1).start();
    // Create an item.
    dataStore.save(owner);
    // Wait for the sync.
    accumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    // Make 10 consecutive updates with predicate
    HubAccumulator updateAccumulator = HubAccumulator.create(HubChannel.DATASTORE, publicationOf(modelName, owner.getId()), 10).start();
    for (int i = 0; i < weas.size(); i++) {
        dataStore.save(owners.get(i), predicate);
    }
    updateAccumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    BlogOwner lastUpdate = owners.get(owners.size() - 1);
    BlogOwner localOwner = dataStore.get(BlogOwner.class, lastUpdate.getId());
    ModelAssert.assertEqualsIgnoringTimestamps(lastUpdate, localOwner);
    BlogOwner remoteOwner = api.get(BlogOwner.class, lastUpdate.getId());
    ModelAssert.assertEqualsIgnoringTimestamps(lastUpdate, remoteOwner);
}
Also used : QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) ArrayList(java.util.ArrayList) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) Test(org.junit.Test)

Example 14 with HubAccumulator

use of com.amplifyframework.testutils.HubAccumulator in project amplify-android by aws-amplify.

the class AWSApiPluginTest method graphQlMutationGetsResponse.

/**
 * It should be possible to perform a successful call to
 * {@link AWSApiPlugin#mutate(GraphQLRequest, Consumer, Consumer)}.
 * When the server returns a valid response, then the mutate methods should
 * emit content via their value consumer.
 * @throws ApiException If call to mutate(...) itself emits such an exception
 * @throws JSONException On failure to arrange response JSON
 */
@Test
public void graphQlMutationGetsResponse() throws JSONException, ApiException {
    HubAccumulator networkStatusObserver = HubAccumulator.create(HubChannel.API, ApiChannelEventName.API_ENDPOINT_STATUS_CHANGED, 1).start();
    // Arrange a response from the "server"
    String expectedName = RandomString.string();
    webServer.enqueue(new MockResponse().setBody(new JSONObject().put("data", new JSONObject().put("createBlogOwner", new JSONObject().put("name", expectedName))).toString()));
    // Try to perform a mutation.
    BlogOwner tony = BlogOwner.builder().name(expectedName).build();
    GraphQLResponse<BlogOwner> actualResponse = Await.<GraphQLResponse<BlogOwner>, ApiException>result(((onResult, onError) -> plugin.mutate(ModelMutation.create(tony), onResult, onError)));
    // Assert that the expected response was received
    assertEquals(expectedName, actualResponse.getData().getName());
    // Verify that the expected hub event fired.
    HubEvent<?> event = networkStatusObserver.awaitFirst();
    assertNotNull(event);
    assertTrue(event.getData() instanceof ApiEndpointStatusChangeEvent);
    ApiEndpointStatusChangeEvent eventData = (ApiEndpointStatusChangeEvent) event.getData();
    assertEquals(ApiEndpointStatusChangeEvent.ApiEndpointStatus.REACHABLE, eventData.getCurrentStatus());
}
Also used : Arrays(java.util.Arrays) AmplifyException(com.amplifyframework.AmplifyException) ApplicationProvider(androidx.test.core.app.ApplicationProvider) ApiChannelEventName(com.amplifyframework.api.events.ApiChannelEventName) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) After(org.junit.After) Map(java.util.Map) MockWebServer(okhttp3.mockwebserver.MockWebServer) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) AWSCredentials(com.amazonaws.auth.AWSCredentials) ResponseBody(okhttp3.ResponseBody) HubEvent(com.amplifyframework.hub.HubEvent) Request(okhttp3.Request) HubChannel(com.amplifyframework.hub.HubChannel) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ModelPagination(com.amplifyframework.api.graphql.model.ModelPagination) RobolectricTestRunner(org.robolectric.RobolectricTestRunner) Type(java.lang.reflect.Type) Await(com.amplifyframework.testutils.Await) RandomString(com.amplifyframework.testutils.random.RandomString) ModelQuery(com.amplifyframework.api.graphql.model.ModelQuery) HttpUrl(okhttp3.HttpUrl) MockResponse(okhttp3.mockwebserver.MockResponse) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) RunWith(org.junit.runner.RunWith) Resources(com.amplifyframework.testutils.Resources) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) ApiException(com.amplifyframework.api.ApiException) Consumer(com.amplifyframework.core.Consumer) TypeMaker(com.amplifyframework.util.TypeMaker) Observable(io.reactivex.rxjava3.core.Observable) ApiEndpointStatusChangeEvent(com.amplifyframework.api.events.ApiEndpointStatusChangeEvent) AWSCredentialsProvider(com.amazonaws.auth.AWSCredentialsProvider) Response(okhttp3.Response) CognitoUserPoolsAuthProvider(com.amplifyframework.api.aws.sigv4.CognitoUserPoolsAuthProvider) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) Before(org.junit.Before) BasicAWSCredentials(com.amazonaws.auth.BasicAWSCredentials) Assert.assertNotNull(org.junit.Assert.assertNotNull) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) QueryType(com.amplifyframework.api.graphql.QueryType) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) Assert.assertNull(org.junit.Assert.assertNull) ModelMutation(com.amplifyframework.api.graphql.model.ModelMutation) Assert.assertEquals(org.junit.Assert.assertEquals) MockResponse(okhttp3.mockwebserver.MockResponse) JSONObject(org.json.JSONObject) ApiEndpointStatusChangeEvent(com.amplifyframework.api.events.ApiEndpointStatusChangeEvent) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) RandomString(com.amplifyframework.testutils.random.RandomString) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Example 15 with HubAccumulator

use of com.amplifyframework.testutils.HubAccumulator in project amplify-android by aws-amplify.

the class HybridAssociationSyncInstrumentationTest method associatedModelAreSyncedDownFromCloud.

/**
 * When the cloud sees an update to its data, the new data should be reflected in the
 * local store. What's more, we should be able to query for the updated data by its model names,
 * and expect to see the result, that way. This should hold for associated models, too.
 * @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 associatedModelAreSyncedDownFromCloud() throws AmplifyException {
    // Create a BlogOwner on the remote system,
    // and wait for it to trickle back to the client.
    BlogOwner owner = BlogOwner.builder().name("Agent Texas").build();
    String ownerModelName = BlogOwner.class.getSimpleName();
    ModelSchema ownerSchema = schemaProvider.modelSchemas().get(ownerModelName);
    assertNotNull(ownerSchema);
    HubAccumulator ownerAccumulator = HubAccumulator.create(HubChannel.DATASTORE, receiptOf(owner.getId()), 1).start();
    appSync.create(owner, ownerSchema);
    ownerAccumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    // Now, validate that we see the data locally, when we query for serialized models
    // and by Java BlogOwners.
    Map<String, Object> expectedOwnerData = new HashMap<>();
    expectedOwnerData.put("id", owner.getId());
    expectedOwnerData.put("name", owner.getName());
    List<SerializedModel> actualSerializedOwners = hybridBehaviors.list(ownerSchema.getName());
    assertTrue(actualSerializedOwners.contains(SerializedModel.builder().serializedData(expectedOwnerData).modelSchema(ownerSchema).build()));
    assertTrue(normalBehaviors.list(BlogOwner.class).contains(owner));
    // Now, remotely save a model that has an association to the owner above.
    Blog blog = Blog.builder().name("Blog about Texas").owner(owner).build();
    String blogModelName = Blog.class.getSimpleName();
    ModelSchema blogSchema = schemaProvider.modelSchemas().get(blogModelName);
    assertNotNull(blogSchema);
    HubAccumulator blogAccumulator = HubAccumulator.create(HubChannel.DATASTORE, receiptOf(blog.getId()), 1).start();
    appSync.create(blog, blogSchema);
    blogAccumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    // Validate that we can find the newly associated model locally, now.
    Map<String, Object> expectedBlogData = new HashMap<>();
    expectedBlogData.put("id", blog.getId());
    expectedBlogData.put("name", blog.getName());
    expectedBlogData.put("owner", SerializedModel.builder().serializedData(Collections.singletonMap("id", owner.getId())).modelSchema(null).build());
    List<SerializedModel> expectedSerializedBlogs = hybridBehaviors.list(blogSchema.getName());
    assertTrue(expectedSerializedBlogs.contains(SerializedModel.builder().serializedData(expectedBlogData).modelSchema(blogSchema).build()));
    assertTrue(normalBehaviors.list(Blog.class).contains(blog));
}
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)

Aggregations

HubAccumulator (com.amplifyframework.testutils.HubAccumulator)30 Test (org.junit.Test)27 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)21 ModelSchema (com.amplifyframework.core.model.ModelSchema)7 SerializedModel (com.amplifyframework.core.model.SerializedModel)5 ModelMetadata (com.amplifyframework.datastore.appsync.ModelMetadata)5 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)5 JSONObject (org.json.JSONObject)5 Ignore (org.junit.Ignore)5 ApiCategory (com.amplifyframework.api.ApiCategory)4 SynchronousDataStore (com.amplifyframework.testutils.sync.SynchronousDataStore)4 GraphQLResponse (com.amplifyframework.api.graphql.GraphQLResponse)3 HubEvent (com.amplifyframework.hub.HubEvent)3 Blog (com.amplifyframework.testmodels.commentsblog.Blog)3 RandomString (com.amplifyframework.testutils.random.RandomString)3 Before (org.junit.Before)3 AmplifyException (com.amplifyframework.AmplifyException)2 Model (com.amplifyframework.core.model.Model)2 HubChannel (com.amplifyframework.hub.HubChannel)2 Person (com.amplifyframework.testmodels.personcar.Person)2