Search in sources :

Example 1 with HubEvent

use of com.amplifyframework.hub.HubEvent in project amplify-android by aws-amplify.

the class SyncProcessorTest method dataStoreHubEventsTriggered.

/**
 * During a base sync, there are a series of events that should be emitted.
 * This test verifies that these events are published via Amplify Hub depending
 * on actions takes for each available model.
 * @throws DataStoreException Not expected.
 * @throws InterruptedException Not expected.
 */
@Test
public void dataStoreHubEventsTriggered() throws DataStoreException, InterruptedException {
    // Arrange - BEGIN
    int expectedModelCount = Arrays.asList(Post.class, BlogOwner.class).size();
    // Collects one syncQueriesStarted event.
    HubAccumulator syncStartAccumulator = createAccumulator(syncQueryStartedForModels(modelCount), 1);
    // Collects one syncQueriesReady event.
    HubAccumulator syncQueryReadyAccumulator = createAccumulator(forEvent(DataStoreChannelEventName.SYNC_QUERIES_READY), 1);
    // Collects one modelSynced event for each model.
    HubAccumulator modelSyncedAccumulator = createAccumulator(forEvent(DataStoreChannelEventName.MODEL_SYNCED), expectedModelCount);
    // Add a couple of seed records so they can be deleted/updated.
    storageAdapter.save(DRUM_POST.getModel());
    storageAdapter.save(BLOGGER_ISLA.getModel());
    // Mock sync query results for a couple of models.
    AppSyncMocking.sync(appSync).mockSuccessResponse(Post.class, DELETED_DRUM_POST).mockSuccessResponse(BlogOwner.class, BLOGGER_ISLA, BLOGGER_JAMESON);
    // Start the accumulators.
    syncQueryReadyAccumulator.start();
    syncStartAccumulator.start();
    modelSyncedAccumulator.start();
    TestObserver<ModelWithMetadata<? extends Model>> hydrationObserver = TestObserver.create();
    // Arrange - END
    // Act: kickoff sync.
    syncProcessor.hydrate().subscribe(hydrationObserver);
    // Check - BEGIN
    // Verify that sync completes.
    assertTrue(hydrationObserver.await(OP_TIMEOUT_MS, TimeUnit.MILLISECONDS));
    hydrationObserver.assertNoErrors();
    hydrationObserver.assertComplete();
    // Verify that syncQueriesStarted was emitted once.
    assertEquals(1, syncStartAccumulator.await((int) OP_TIMEOUT_MS, TimeUnit.MILLISECONDS).size());
    // Verify that syncQueriesReady was emitted once.
    assertEquals(1, syncQueryReadyAccumulator.await((int) OP_TIMEOUT_MS, TimeUnit.MILLISECONDS).size());
    // Get the list of modelSynced events captured.
    List<HubEvent<?>> hubEvents = modelSyncedAccumulator.await((int) OP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    // Verify that [number of events] = [number of models]
    assertEquals(expectedModelCount, hubEvents.size());
    ModelSyncedEvent expectedBlogOwnerCounts = new ModelSyncedEvent("BlogOwner", true, 1, 1, 0);
    ModelSyncedEvent expectedPostCounts = new ModelSyncedEvent("Post", true, 0, 0, 1);
    // For each event (excluding system models), verify the desired count.
    for (HubEvent<?> event : hubEvents) {
        ModelSyncedEvent eventData = (ModelSyncedEvent) event.getData();
        assertTrue(eventData.isFullSync());
        assertFalse(eventData.isDeltaSync());
        String eventModel = eventData.getModel();
        switch(eventModel) {
            case "BlogOwner":
                // One BlogOwner added and one updated.
                assertEquals(expectedBlogOwnerCounts, eventData);
                break;
            case "Post":
                // One post deleted.
                assertEquals(expectedPostCounts, eventData);
                break;
            default:
                // Exclude system models
                if (!SYSTEM_MODEL_NAMES.contains(eventModel)) {
                    ModelSyncedEvent otherCounts = new ModelSyncedEvent(eventModel, true, 0, 0, 0);
                    assertEquals(otherCounts, eventData);
                }
        }
    }
// Check - END
}
Also used : ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) Post(com.amplifyframework.testmodels.commentsblog.Post) Model(com.amplifyframework.core.model.Model) HubEvent(com.amplifyframework.hub.HubEvent) ModelSyncedEvent(com.amplifyframework.datastore.events.ModelSyncedEvent) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) RandomString(com.amplifyframework.testutils.random.RandomString) Test(org.junit.Test)

Example 2 with HubEvent

use of com.amplifyframework.hub.HubEvent in project amplify-android by aws-amplify.

the class OrchestratorTest method itemsPlacedInStorageArePublishedToNetwork.

/**
 * When an item is placed into storage, a cascade of
 * things happen which should ultimately result in a mutation call
 * to the API category, with an {@link MutationType} corresponding to the type of
 * modification that was made to the storage.
 * @throws AmplifyException On failure to load model schema into registry
 */
// Casting ? in HubEvent<?> to PendingMutation<? extends Model>
@SuppressWarnings("unchecked")
@Test
public void itemsPlacedInStorageArePublishedToNetwork() throws AmplifyException {
    // Arrange: orchestrator is running
    orchestrator.start().test();
    orchestratorInitObserver.await(10, TimeUnit.SECONDS);
    HubAccumulator accumulator = HubAccumulator.create(HubChannel.DATASTORE, isProcessed(susan), 1).start();
    // Act: Put BlogOwner into storage, and wait for it to complete.
    SynchronousStorageAdapter.delegatingTo(localStorageAdapter).save(susan);
    // Assert that the event is published out to the API
    assertEquals(Collections.singletonList(susan), Observable.fromIterable(accumulator.await(10, TimeUnit.SECONDS)).map(HubEvent::getData).map(data -> (OutboxMutationEvent<BlogOwner>) data).map(OutboxMutationEvent::getElement).map(OutboxMutationEvent.OutboxMutationEventElement::getModel).toList().blockingGet());
    assertTrue(orchestrator.stop().blockingAwait(5, TimeUnit.SECONDS));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) AmplifyException(com.amplifyframework.AmplifyException) MutationType(com.amplifyframework.api.graphql.MutationType) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) ModelProvider(com.amplifyframework.core.model.ModelProvider) DataStoreChannelEventName(com.amplifyframework.datastore.DataStoreChannelEventName) RunWith(org.junit.runner.RunWith) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) SynchronousStorageAdapter(com.amplifyframework.datastore.storage.SynchronousStorageAdapter) Observable(io.reactivex.rxjava3.core.Observable) TestHubEventFilters.isProcessed(com.amplifyframework.datastore.syncengine.TestHubEventFilters.isProcessed) ModelMetadata(com.amplifyframework.datastore.appsync.ModelMetadata) HubEvent(com.amplifyframework.hub.HubEvent) Before(org.junit.Before) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) Amplify(com.amplifyframework.core.Amplify) HubChannel(com.amplifyframework.hub.HubChannel) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) AppSyncClient(com.amplifyframework.datastore.appsync.AppSyncClient) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Completable(io.reactivex.rxjava3.core.Completable) Mockito.times(org.mockito.Mockito.times) Logger(com.amplifyframework.logging.Logger) Mockito.verify(org.mockito.Mockito.verify) RobolectricTestRunner(org.robolectric.RobolectricTestRunner) TimeUnit(java.util.concurrent.TimeUnit) GraphQLBehavior(com.amplifyframework.api.graphql.GraphQLBehavior) InMemoryStorageAdapter(com.amplifyframework.datastore.storage.InMemoryStorageAdapter) Temporal(com.amplifyframework.core.model.temporal.Temporal) ShadowLog(org.robolectric.shadows.ShadowLog) ApiMocking(com.amplifyframework.testutils.mocks.ApiMocking) Collections(java.util.Collections) SimpleModelProvider(com.amplifyframework.datastore.model.SimpleModelProvider) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) HubEvent(com.amplifyframework.hub.HubEvent) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) Test(org.junit.Test)

Example 3 with HubEvent

use of com.amplifyframework.hub.HubEvent 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 4 with HubEvent

use of com.amplifyframework.hub.HubEvent in project amplify-android by aws-amplify.

the class AWSS3StorageDownloadTest method testDownloadFileIsResumable.

/**
 * Tests that file download operation can be paused and resumed
 * while the transfer hasn't completed yet.
 *
 * @throws Exception if download is not paused, resumed, and
 *                   completed successfully before timeout
 */
@Ignore("Contains tests that hang, or hang the suite overall.")
@SuppressWarnings("unchecked")
public void testDownloadFileIsResumable() throws Exception {
    final CountDownLatch completed = new CountDownLatch(1);
    final CountDownLatch resumed = new CountDownLatch(1);
    final AtomicReference<Resumable> opContainer = new AtomicReference<>();
    final AtomicReference<Throwable> errorContainer = new AtomicReference<>();
    // Listen to Hub events to resume when operation has been paused
    SubscriptionToken resumeToken = Amplify.Hub.subscribe(HubChannel.STORAGE, hubEvent -> {
        if (StorageChannelEventName.DOWNLOAD_STATE.toString().equals(hubEvent.getName())) {
            HubEvent<String> stateEvent = (HubEvent<String>) hubEvent;
            TransferState state = TransferState.getState(stateEvent.getData());
            if (TransferState.PAUSED.equals(state)) {
                opContainer.get().resume();
                resumed.countDown();
            }
        }
    });
    subscriptions.add(resumeToken);
    // Begin downloading a large file
    StorageDownloadFileOperation<?> op = storageCategory.downloadFile(LARGE_FILE_NAME, downloadFile, options, progress -> {
        if (progress.getCurrentBytes() > 0 && resumed.getCount() > 0) {
            opContainer.get().pause();
        }
    }, result -> completed.countDown(), errorContainer::set);
    opContainer.set(op);
    // Assert that all the required conditions have been met
    assertTrue(resumed.await(EXTENDED_TIMEOUT_MS, TimeUnit.MILLISECONDS));
    assertTrue(completed.await(EXTENDED_TIMEOUT_MS, TimeUnit.MILLISECONDS));
    assertNull(errorContainer.get());
    FileAssert.assertEquals(largeFile, downloadFile);
}
Also used : HubEvent(com.amplifyframework.hub.HubEvent) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) TransferState(com.amazonaws.mobileconnectors.s3.transferutility.TransferState) Resumable(com.amplifyframework.core.async.Resumable) SubscriptionToken(com.amplifyframework.hub.SubscriptionToken) Ignore(org.junit.Ignore)

Example 5 with HubEvent

use of com.amplifyframework.hub.HubEvent in project amplify-android by aws-amplify.

the class AWSS3StorageDownloadTest method testDownloadFileIsCancelable.

/**
 * Tests that file download operation can be canceled while the
 * transfer hasn't completed yet.
 *
 * @throws Exception if download is not canceled successfully
 *                   before timeout
 */
@Ignore("Contains tests that hang, or hang the suite overall.")
@SuppressWarnings("unchecked")
public void testDownloadFileIsCancelable() throws Exception {
    final CountDownLatch canceled = new CountDownLatch(1);
    final AtomicReference<Cancelable> opContainer = new AtomicReference<>();
    final AtomicReference<Throwable> errorContainer = new AtomicReference<>();
    // Listen to Hub events for cancel
    SubscriptionToken cancelToken = Amplify.Hub.subscribe(HubChannel.STORAGE, hubEvent -> {
        if (StorageChannelEventName.DOWNLOAD_STATE.toString().equals(hubEvent.getName())) {
            HubEvent<String> stateEvent = (HubEvent<String>) hubEvent;
            TransferState state = TransferState.getState(stateEvent.getData());
            if (TransferState.CANCELED.equals(state)) {
                canceled.countDown();
            }
        }
    });
    subscriptions.add(cancelToken);
    // Begin downloading a large file
    StorageDownloadFileOperation<?> op = storageCategory.downloadFile(LARGE_FILE_NAME, downloadFile, options, progress -> {
        if (progress.getCurrentBytes() > 0 && canceled.getCount() > 0) {
            opContainer.get().cancel();
        }
    }, result -> errorContainer.set(new RuntimeException("Download completed without canceling.")), errorContainer::set);
    opContainer.set(op);
    // Assert that the required conditions have been met
    assertTrue(canceled.await(EXTENDED_TIMEOUT_MS, TimeUnit.MILLISECONDS));
    assertNull(errorContainer.get());
}
Also used : HubEvent(com.amplifyframework.hub.HubEvent) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) TransferState(com.amazonaws.mobileconnectors.s3.transferutility.TransferState) SubscriptionToken(com.amplifyframework.hub.SubscriptionToken) Cancelable(com.amplifyframework.core.async.Cancelable) Ignore(org.junit.Ignore)

Aggregations

HubEvent (com.amplifyframework.hub.HubEvent)7 TransferState (com.amazonaws.mobileconnectors.s3.transferutility.TransferState)4 SubscriptionToken (com.amplifyframework.hub.SubscriptionToken)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 Ignore (org.junit.Ignore)4 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)3 HubAccumulator (com.amplifyframework.testutils.HubAccumulator)3 Test (org.junit.Test)3 AmplifyException (com.amplifyframework.AmplifyException)2 Cancelable (com.amplifyframework.core.async.Cancelable)2 Resumable (com.amplifyframework.core.async.Resumable)2 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)2 HubChannel (com.amplifyframework.hub.HubChannel)2 RandomString (com.amplifyframework.testutils.random.RandomString)2 RandomTempFile (com.amplifyframework.testutils.random.RandomTempFile)2 Observable (io.reactivex.rxjava3.core.Observable)2 File (java.io.File)2 TimeUnit (java.util.concurrent.TimeUnit)2 Assert.assertEquals (org.junit.Assert.assertEquals)2