use of com.amplifyframework.core.Consumer in project amplify-android by aws-amplify.
the class ObserveQueryExecutorTest method observeQueryCancelsTheOperationOnQueryError.
/**
* testing cancel on observe query.
* @throws DataStoreException DataStoreException
*/
@Test
public void observeQueryCancelsTheOperationOnQueryError() throws DataStoreException {
Consumer<DataStoreQuerySnapshot<BlogOwner>> onQuerySnapshot = NoOpConsumer.create();
Consumer<DataStoreException> onObservationError = NoOpConsumer.create();
Action onObservationComplete = NoOpAction.create();
SQLCommandProcessor sqlCommandProcessor = mock(SQLCommandProcessor.class);
when(sqlCommandProcessor.rawQuery(any())).thenThrow(new DataStoreException("test", "test"));
SqlQueryProcessor sqlQueryProcessor = new SqlQueryProcessor(sqlCommandProcessor, mock(SQLiteCommandFactory.class), mock(SchemaRegistry.class));
Subject<StorageItemChange<? extends Model>> subject = PublishSubject.<StorageItemChange<? extends Model>>create().toSerialized();
ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 5);
ObserveQueryExecutor<BlogOwner> observeQueryExecutor = new ObserveQueryExecutor<>(subject, sqlQueryProcessor, threadPool, mock(SyncStatus.class), new ModelSorter<>(), DataStoreConfiguration.defaults());
Consumer<Cancelable> observationStarted = value -> {
value.cancel();
Assert.assertTrue(observeQueryExecutor.getIsCancelled());
assertEquals(0, observeQueryExecutor.getCompleteMap().size());
assertEquals(0, observeQueryExecutor.getChangeList().size());
subject.test().assertNoErrors().isDisposed();
};
observeQueryExecutor.observeQuery(BlogOwner.class, new ObserveQueryOptions(null, null), observationStarted, onQuerySnapshot, onObservationError, onObservationComplete);
}
use of com.amplifyframework.core.Consumer in project amplify-android by aws-amplify.
the class ObserveQueryExecutorTest method observeQueryReturnsRecordsBasedOnMaxRecords.
/**
* observe Query Returns Records Based On Max Records.
* @throws InterruptedException InterruptedException
* @throws DataStoreException DataStoreException
* @throws AmplifyException AmplifyException
*/
@Test
public void observeQueryReturnsRecordsBasedOnMaxRecords() throws InterruptedException, AmplifyException {
CountDownLatch latch = new CountDownLatch(1);
CountDownLatch changeLatch = new CountDownLatch(3);
AtomicInteger count = new AtomicInteger();
BlogOwner blogOwner = BlogOwner.builder().name("Alan Turing").build();
List<BlogOwner> datastoreResultList = new ArrayList<>();
int maxRecords = 2;
datastoreResultList.add(blogOwner);
Consumer<Cancelable> observationStarted = NoOpConsumer.create();
SyncStatus mockSyncStatus = mock(SyncStatus.class);
when(mockSyncStatus.get(any(), any())).thenReturn(false).thenReturn(true).thenReturn(true);
Subject<StorageItemChange<? extends Model>> subject = PublishSubject.<StorageItemChange<? extends Model>>create().toSerialized();
Consumer<DataStoreQuerySnapshot<BlogOwner>> onQuerySnapshot = value -> {
if (count.get() == 0) {
Assert.assertTrue(value.getItems().contains(blogOwner));
latch.countDown();
} else if (count.get() == 1) {
Assert.assertEquals(3, value.getItems().size());
Assert.assertTrue(value.getIsSynced());
changeLatch.countDown();
} else if (count.get() == 2) {
Assert.assertEquals(4, value.getItems().size());
changeLatch.countDown();
} else {
Assert.assertEquals(5, value.getItems().size());
changeLatch.countDown();
}
count.getAndIncrement();
};
Consumer<DataStoreException> onObservationError = NoOpConsumer.create();
Action onObservationComplete = NoOpAction.create();
SqlQueryProcessor mockSqlQueryProcessor = mock(SqlQueryProcessor.class);
when(mockSqlQueryProcessor.queryOfflineData(eq(BlogOwner.class), any(), any())).thenReturn(datastoreResultList);
when(mockSqlQueryProcessor.modelExists(any(), any())).thenReturn(true);
ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 5);
ObserveQueryExecutor<BlogOwner> observeQueryExecutor = new ObserveQueryExecutor<>(subject, mockSqlQueryProcessor, threadPool, mockSyncStatus, new ModelSorter<>(), maxRecords, maxRecords);
observeQueryExecutor.observeQuery(BlogOwner.class, new ObserveQueryOptions(null, null), observationStarted, onQuerySnapshot, onObservationError, onObservationComplete);
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
for (int i = 0; i < 5; i++) {
BlogOwner itemChange = BlogOwner.builder().name("Alan Turing" + i).build();
subject.onNext(StorageItemChange.<BlogOwner>builder().changeId(UUID.randomUUID().toString()).initiator(StorageItemChange.Initiator.SYNC_ENGINE).item(itemChange).patchItem(SerializedModel.create(itemChange, ModelSchema.fromModelClass(BlogOwner.class))).modelSchema(ModelSchema.fromModelClass(BlogOwner.class)).predicate(QueryPredicates.all()).type(StorageItemChange.Type.UPDATE).build());
}
Assert.assertTrue(changeLatch.await(7, TimeUnit.SECONDS));
}
use of com.amplifyframework.core.Consumer in project amplify-android by aws-amplify.
the class AWSDataStorePluginTest method mockApiPluginWithExceptions.
/**
* Almost the same as mockApiCategoryWithGraphQlApi, but it calls the onError callback instead.
*
* @return A mock version of the API Category.
* @throws AmplifyException Throw if an error happens when adding the plugin.
*/
@SuppressWarnings("unchecked")
private static ApiCategory mockApiPluginWithExceptions() throws AmplifyException {
ApiCategory mockApiCategory = spy(ApiCategory.class);
ApiPlugin<?> mockApiPlugin = mock(ApiPlugin.class);
when(mockApiPlugin.getPluginKey()).thenReturn(MOCK_API_PLUGIN_NAME);
when(mockApiPlugin.getCategoryType()).thenReturn(CategoryType.API);
doAnswer(invocation -> {
int indexOfErrorConsumer = 2;
Consumer<ApiException> onError = invocation.getArgument(indexOfErrorConsumer);
onError.accept(new ApiException("Fake exception thrown from the API.query method", "Just retry"));
return null;
}).when(mockApiPlugin).query(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class));
doAnswer(invocation -> {
int indexOfErrorConsumer = 2;
Consumer<ApiException> onError = invocation.getArgument(indexOfErrorConsumer);
onError.accept(new ApiException("Fake exception thrown from the API.mutate method", "Just retry"));
return null;
}).when(mockApiPlugin).mutate(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class));
doAnswer(invocation -> {
int indexOfErrorConsumer = 3;
Consumer<ApiException> onError = invocation.getArgument(indexOfErrorConsumer);
ApiException apiException = new ApiException("Fake exception thrown from the API.subscribe method", "Just retry");
onError.accept(apiException);
return null;
}).when(mockApiPlugin).subscribe(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class), any(Consumer.class), any(Action.class));
mockApiCategory.addPlugin(mockApiPlugin);
return mockApiCategory;
}
use of com.amplifyframework.core.Consumer in project amplify-android by aws-amplify.
the class AWSDataStorePluginTest method mockApiCategoryWithGraphQlApi.
@SuppressWarnings("unchecked")
private ApiCategory mockApiCategoryWithGraphQlApi() throws AmplifyException {
ApiCategory mockApiCategory = spy(ApiCategory.class);
ApiPlugin<?> mockApiPlugin = mock(ApiPlugin.class);
when(mockApiPlugin.getPluginKey()).thenReturn(MOCK_API_PLUGIN_NAME);
when(mockApiPlugin.getCategoryType()).thenReturn(CategoryType.API);
ApiEndpointStatusChangeEvent eventData = new ApiEndpointStatusChangeEvent(ApiEndpointStatusChangeEvent.ApiEndpointStatus.REACHABLE, ApiEndpointStatusChangeEvent.ApiEndpointStatus.UNKOWN);
HubEvent<ApiEndpointStatusChangeEvent> hubEvent = HubEvent.create(ApiChannelEventName.API_ENDPOINT_STATUS_CHANGED, eventData);
// Make believe that queries return response immediately
doAnswer(invocation -> {
// Mock the API emitting an ApiEndpointStatusChangeEvent event.
Amplify.Hub.publish(HubChannel.API, hubEvent);
int indexOfResponseConsumer = 1;
Consumer<GraphQLResponse<PaginatedResult<ModelWithMetadata<Person>>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
PaginatedResult<ModelWithMetadata<Person>> data = new PaginatedResult<>(Collections.emptyList(), null);
onResponse.accept(new GraphQLResponse<>(data, Collections.emptyList()));
return null;
}).when(mockApiPlugin).query(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class));
// Make believe that subscriptions return response immediately
doAnswer(invocation -> {
int indexOfStartConsumer = 1;
Consumer<String> onStart = invocation.getArgument(indexOfStartConsumer);
GraphQLOperation<?> mockOperation = mock(GraphQLOperation.class);
doAnswer(opAnswer -> {
this.subscriptionCancelledCounter.incrementAndGet();
return null;
}).when(mockOperation).cancel();
this.subscriptionStartedCounter.incrementAndGet();
// Trigger the subscription start event.
onStart.accept(RandomString.string());
return mockOperation;
}).when(mockApiPlugin).subscribe(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class), any(Consumer.class), any(Action.class));
mockApiCategory.addPlugin(mockApiPlugin);
mockApiCategory.configure(new ApiCategoryConfiguration(), getApplicationContext());
mockApiCategory.initialize(getApplicationContext());
return mockApiCategory;
}
use of com.amplifyframework.core.Consumer in project amplify-android by aws-amplify.
the class ConflictResolverIntegrationTest method mockApiCategoryWithGraphQlApi.
@SuppressWarnings("unchecked")
private ApiCategory mockApiCategoryWithGraphQlApi() throws AmplifyException {
ApiCategory mockApiCategory = spy(ApiCategory.class);
ApiPlugin<?> mockApiPlugin = mock(ApiPlugin.class);
when(mockApiPlugin.getPluginKey()).thenReturn(MOCK_API_PLUGIN_NAME);
when(mockApiPlugin.getCategoryType()).thenReturn(CategoryType.API);
ApiEndpointStatusChangeEvent eventData = new ApiEndpointStatusChangeEvent(ApiEndpointStatusChangeEvent.ApiEndpointStatus.REACHABLE, ApiEndpointStatusChangeEvent.ApiEndpointStatus.UNKOWN);
HubEvent<ApiEndpointStatusChangeEvent> hubEvent = HubEvent.create(ApiChannelEventName.API_ENDPOINT_STATUS_CHANGED, eventData);
// Make believe that queries return response immediately
doAnswer(invocation -> {
// Mock the API emitting an ApiEndpointStatusChangeEvent event.
Amplify.Hub.publish(HubChannel.API, hubEvent);
int indexOfResponseConsumer = 1;
Consumer<GraphQLResponse<PaginatedResult<ModelWithMetadata<Person>>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
PaginatedResult<ModelWithMetadata<Person>> data = new PaginatedResult<>(Collections.emptyList(), null);
onResponse.accept(new GraphQLResponse<>(data, Collections.emptyList()));
return null;
}).when(mockApiPlugin).query(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class));
mockApiCategory.addPlugin(mockApiPlugin);
mockApiCategory.configure(new ApiCategoryConfiguration(), getApplicationContext());
mockApiCategory.initialize(getApplicationContext());
return mockApiCategory;
}
Aggregations