Search in sources :

Example 26 with Consumer

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);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Arrays(java.util.Arrays) AmplifyException(com.amplifyframework.AmplifyException) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) ArrayList(java.util.ArrayList) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Consumer(com.amplifyframework.core.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PublishSubject(io.reactivex.rxjava3.subjects.PublishSubject) ModelSchema(com.amplifyframework.core.model.ModelSchema) Subject(io.reactivex.rxjava3.subjects.Subject) NoOpConsumer(com.amplifyframework.core.NoOpConsumer) PostStatus(com.amplifyframework.testmodels.commentsblog.PostStatus) ExecutorService(java.util.concurrent.ExecutorService) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) SerializedModel(com.amplifyframework.core.model.SerializedModel) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Model(com.amplifyframework.core.model.Model) Test(org.junit.Test) Action(com.amplifyframework.core.Action) UUID(java.util.UUID) Mockito.when(org.mockito.Mockito.when) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) DataStoreException(com.amplifyframework.datastore.DataStoreException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) Assert(org.junit.Assert) Comparator(java.util.Comparator) NoOpAction(com.amplifyframework.core.NoOpAction) Post(com.amplifyframework.testmodels.commentsblog.Post) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) DataStoreException(com.amplifyframework.datastore.DataStoreException) Action(com.amplifyframework.core.Action) NoOpAction(com.amplifyframework.core.NoOpAction) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) ExecutorService(java.util.concurrent.ExecutorService) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Cancelable(com.amplifyframework.core.async.Cancelable) Test(org.junit.Test)

Example 27 with Consumer

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));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Arrays(java.util.Arrays) AmplifyException(com.amplifyframework.AmplifyException) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) ArrayList(java.util.ArrayList) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Consumer(com.amplifyframework.core.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PublishSubject(io.reactivex.rxjava3.subjects.PublishSubject) ModelSchema(com.amplifyframework.core.model.ModelSchema) Subject(io.reactivex.rxjava3.subjects.Subject) NoOpConsumer(com.amplifyframework.core.NoOpConsumer) PostStatus(com.amplifyframework.testmodels.commentsblog.PostStatus) ExecutorService(java.util.concurrent.ExecutorService) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) SerializedModel(com.amplifyframework.core.model.SerializedModel) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Model(com.amplifyframework.core.model.Model) Test(org.junit.Test) Action(com.amplifyframework.core.Action) UUID(java.util.UUID) Mockito.when(org.mockito.Mockito.when) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) DataStoreException(com.amplifyframework.datastore.DataStoreException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) Assert(org.junit.Assert) Comparator(java.util.Comparator) NoOpAction(com.amplifyframework.core.NoOpAction) Post(com.amplifyframework.testmodels.commentsblog.Post) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) DataStoreException(com.amplifyframework.datastore.DataStoreException) Action(com.amplifyframework.core.Action) NoOpAction(com.amplifyframework.core.NoOpAction) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) ExecutorService(java.util.concurrent.ExecutorService) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Cancelable(com.amplifyframework.core.async.Cancelable) Test(org.junit.Test)

Example 28 with Consumer

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;
}
Also used : GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Action(com.amplifyframework.core.Action) Consumer(com.amplifyframework.core.Consumer) ApiCategory(com.amplifyframework.api.ApiCategory) ApiException(com.amplifyframework.api.ApiException)

Example 29 with Consumer

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;
}
Also used : ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) Action(com.amplifyframework.core.Action) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) RandomString(com.amplifyframework.testutils.random.RandomString) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Consumer(com.amplifyframework.core.Consumer) ApiEndpointStatusChangeEvent(com.amplifyframework.api.events.ApiEndpointStatusChangeEvent) ApiCategory(com.amplifyframework.api.ApiCategory) ApiCategoryConfiguration(com.amplifyframework.api.ApiCategoryConfiguration)

Example 30 with Consumer

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;
}
Also used : ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Consumer(com.amplifyframework.core.Consumer) ApiEndpointStatusChangeEvent(com.amplifyframework.api.events.ApiEndpointStatusChangeEvent) ApiCategory(com.amplifyframework.api.ApiCategory) ApiCategoryConfiguration(com.amplifyframework.api.ApiCategoryConfiguration)

Aggregations

Consumer (com.amplifyframework.core.Consumer)35 Action (com.amplifyframework.core.Action)28 DataStoreException (com.amplifyframework.datastore.DataStoreException)28 ArrayList (java.util.ArrayList)26 List (java.util.List)26 Test (org.junit.Test)26 Cancelable (com.amplifyframework.core.async.Cancelable)25 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)25 TimeUnit (java.util.concurrent.TimeUnit)24 Collections (java.util.Collections)23 CountDownLatch (java.util.concurrent.CountDownLatch)22 Assert.assertEquals (org.junit.Assert.assertEquals)21 NoOpConsumer (com.amplifyframework.core.NoOpConsumer)20 ObserveQueryOptions (com.amplifyframework.core.model.query.ObserveQueryOptions)20 DataStoreQuerySnapshot (com.amplifyframework.datastore.DataStoreQuerySnapshot)20 Arrays (java.util.Arrays)20 NoOpAction (com.amplifyframework.core.NoOpAction)19 QuerySortBy (com.amplifyframework.core.model.query.QuerySortBy)19 Post (com.amplifyframework.testmodels.commentsblog.Post)19 PostStatus (com.amplifyframework.testmodels.commentsblog.PostStatus)19