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
}
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));
}
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());
}
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);
}
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());
}
Aggregations