Search in sources :

Example 31 with Action

use of com.amplifyframework.core.Action in project amplify-android by aws-amplify.

the class AppSyncClient method subscription.

private <T extends Model> Cancelable subscription(SubscriptionType subscriptionType, ModelSchema modelSchema, Consumer<String> onSubscriptionStarted, Consumer<GraphQLResponse<ModelWithMetadata<T>>> onNextResponse, Consumer<DataStoreException> onSubscriptionFailure, Action onSubscriptionCompleted) {
    final GraphQLRequest<ModelWithMetadata<T>> request;
    try {
        request = AppSyncRequestFactory.buildSubscriptionRequest(modelSchema, subscriptionType, authModeStrategyType);
    } catch (DataStoreException requestGenerationException) {
        onSubscriptionFailure.accept(requestGenerationException);
        return new NoOpCancelable();
    }
    final Consumer<GraphQLResponse<ModelWithMetadata<T>>> responseConsumer = response -> {
        if (response.hasErrors()) {
            onSubscriptionFailure.accept(new DataStoreException.GraphQLResponseException("Subscription error for " + modelSchema.getName() + ": " + response.getErrors(), response.getErrors()));
        } else {
            onNextResponse.accept(response);
        }
    };
    final Consumer<ApiException> failureConsumer = failure -> onSubscriptionFailure.accept(new DataStoreException("Error during subscription.", failure, "Evaluate details."));
    final Cancelable cancelable = api.subscribe(request, onSubscriptionStarted, responseConsumer, failureConsumer, onSubscriptionCompleted);
    if (cancelable != null) {
        return cancelable;
    }
    return new NoOpCancelable();
}
Also used : Amplify(com.amplifyframework.core.Amplify) AmplifyException(com.amplifyframework.AmplifyException) NonNull(androidx.annotation.NonNull) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Model(com.amplifyframework.core.model.Model) Action(com.amplifyframework.core.Action) ApiException(com.amplifyframework.api.ApiException) Logger(com.amplifyframework.logging.Logger) GraphQLBehavior(com.amplifyframework.api.graphql.GraphQLBehavior) DataStoreException(com.amplifyframework.datastore.DataStoreException) Consumer(com.amplifyframework.core.Consumer) Nullable(androidx.annotation.Nullable) Cancelable(com.amplifyframework.core.async.Cancelable) SubscriptionType(com.amplifyframework.api.graphql.SubscriptionType) AuthModeStrategyType(com.amplifyframework.api.aws.AuthModeStrategyType) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) ModelSchema(com.amplifyframework.core.model.ModelSchema) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) ApiCategoryBehavior(com.amplifyframework.api.ApiCategoryBehavior) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) DataStoreException(com.amplifyframework.datastore.DataStoreException) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) Cancelable(com.amplifyframework.core.async.Cancelable) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) ApiException(com.amplifyframework.api.ApiException)

Example 32 with Action

use of com.amplifyframework.core.Action in project amplify-android by aws-amplify.

the class RxApiBindingTest method subscribeStartsAndGetsCancelled.

/**
 * Verify that the subscription starts and is cancelled gracefully.
 * @throws InterruptedException Not expected.
 */
@SuppressWarnings("rawtypes")
@Test
public void subscribeStartsAndGetsCancelled() throws InterruptedException {
    // Arrange a category behavior which emits an expected sequence of callback events
    String token = RandomString.string();
    GraphQLRequest<Model> request = createMockSubscriptionRequest(Model.class);
    ConnectionStateEvent expectedConnectionStateEvent = new ConnectionStateEvent(ConnectionState.CONNECTED, token);
    doAnswer(invocation -> {
        final int onStartPosition = 1;
        final int onCompletePosition = 4;
        Consumer<String> onStart = invocation.getArgument(onStartPosition);
        Action onComplete = invocation.getArgument(onCompletePosition);
        onStart.accept(token);
        GraphQLOperation mockApiOperation = mock(GraphQLOperation.class);
        doAnswer(apiCancelInvocation -> {
            onComplete.call();
            return null;
        }).when(mockApiOperation).cancel();
        return mockApiOperation;
    }).when(delegate).subscribe(eq(request), anyConsumer(), anyConsumer(), anyConsumer(), anyAction());
    // Act: subscribe via binding
    RxSubscriptionOperation<GraphQLResponse<Model>> rxOperation = rxApi.subscribe(request);
    // Act: subscribe via binding
    TestObserver<GraphQLResponse<Model>> dataObserver = rxOperation.observeSubscriptionData().test();
    TestObserver<ConnectionStateEvent> startObserver = rxOperation.observeConnectionState().test();
    startObserver.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    startObserver.assertValue(expectedConnectionStateEvent);
    startObserver.assertNoErrors();
    // Act: cancel the subscription
    Completable.timer(1, TimeUnit.SECONDS).andThen(Completable.fromAction(rxOperation::cancel)).subscribe();
    dataObserver.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    dataObserver.assertNoValues();
    dataObserver.assertNoErrors();
    dataObserver.assertComplete();
    startObserver.assertComplete();
}
Also used : Matchers.anyAction(com.amplifyframework.rx.Matchers.anyAction) Action(com.amplifyframework.core.Action) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) RandomString(com.amplifyframework.testutils.random.RandomString) ConnectionStateEvent(com.amplifyframework.rx.RxOperations.RxSubscriptionOperation.ConnectionStateEvent) GraphQLOperation(com.amplifyframework.api.graphql.GraphQLOperation) RandomModel(com.amplifyframework.testutils.random.RandomModel) Model(com.amplifyframework.core.model.Model) Test(org.junit.Test)

Example 33 with Action

use of com.amplifyframework.core.Action in project amplify-android by aws-amplify.

the class RxAuthBindingTest method testUpdatePasswordSucceeds.

/**
 * Tests that a successful request to update a user's password will propagate a completion
 * back through the binding.
 * @throws InterruptedException If test observer is interrupted while awaiting terminal event
 */
@Test
public void testUpdatePasswordSucceeds() throws InterruptedException {
    String oldPassword = RandomString.string();
    String newPassword = RandomString.string();
    // Arrange an invocation of the success Action
    doAnswer(invocation -> {
        // 0 = old pass, 1 = new pass, 2 = onComplete, 3 = onFailure
        int positionOfCompletionAction = 2;
        Action onCompletion = invocation.getArgument(positionOfCompletionAction);
        onCompletion.call();
        return null;
    }).when(delegate).updatePassword(eq(oldPassword), eq(newPassword), anyAction(), anyConsumer());
    // Act: call the binding
    TestObserver<Void> observer = auth.updatePassword(oldPassword, newPassword).test();
    // Assert: Completable completes with success
    observer.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    observer.assertNoErrors().assertComplete();
}
Also used : Matchers.anyAction(com.amplifyframework.rx.Matchers.anyAction) Action(com.amplifyframework.core.Action) RandomString(com.amplifyframework.testutils.random.RandomString) Test(org.junit.Test)

Example 34 with Action

use of com.amplifyframework.core.Action in project amplify-android by aws-amplify.

the class RxAuthBindingTest method testRememberDevice.

/**
 * Tests that a successful request to remember current auth device will propagate a completion
 * back through the binding.
 * @throws InterruptedException If test observer is interrupted while awaiting terminal event
 */
@Test
public void testRememberDevice() throws InterruptedException {
    // Arrange an invocation of the success Action
    doAnswer(invocation -> {
        // 0 = onComplete, 1 = onFailure
        Action onCompletion = invocation.getArgument(0);
        onCompletion.call();
        return null;
    }).when(delegate).rememberDevice(anyAction(), anyConsumer());
    // Act: call the binding
    TestObserver<Void> observer = auth.rememberDevice().test();
    // Assert: Completable completes with success
    observer.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    observer.assertNoErrors().assertComplete();
}
Also used : Matchers.anyAction(com.amplifyframework.rx.Matchers.anyAction) Action(com.amplifyframework.core.Action) Test(org.junit.Test)

Example 35 with Action

use of com.amplifyframework.core.Action in project amplify-android by aws-amplify.

the class RxAuthBindingTest method testConfirmUserAttribute.

/**
 * Validates that a successful request to confirm user attribute will propagate up into the binding.
 * @throws InterruptedException If test observer is interrupted while awaiting terminal event
 */
@Test
public void testConfirmUserAttribute() throws InterruptedException {
    // Arrange an invocation of the success Action
    AuthUserAttributeKey attributeKey = AuthUserAttributeKey.custom(ATTRIBUTE_KEY);
    doAnswer(invocation -> {
        Action onComplete = invocation.getArgument(2);
        onComplete.call();
        return null;
    }).when(delegate).confirmUserAttribute(any(), any(), anyAction(), anyConsumer());
    // Act: call the binding
    TestObserver<Void> observer = auth.confirmUserAttribute(attributeKey, CONFIRMATION_CODE).test();
    // Assert: Completable completes successfully
    observer.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    observer.assertNoErrors().assertComplete();
}
Also used : Matchers.anyAction(com.amplifyframework.rx.Matchers.anyAction) Action(com.amplifyframework.core.Action) AuthUserAttributeKey(com.amplifyframework.auth.AuthUserAttributeKey) Test(org.junit.Test)

Aggregations

Action (com.amplifyframework.core.Action)36 Test (org.junit.Test)34 Cancelable (com.amplifyframework.core.async.Cancelable)23 Consumer (com.amplifyframework.core.Consumer)21 DataStoreException (com.amplifyframework.datastore.DataStoreException)21 ObserveQueryOptions (com.amplifyframework.core.model.query.ObserveQueryOptions)20 DataStoreQuerySnapshot (com.amplifyframework.datastore.DataStoreQuerySnapshot)20 Arrays (java.util.Arrays)20 List (java.util.List)20 TimeUnit (java.util.concurrent.TimeUnit)20 NoOpAction (com.amplifyframework.core.NoOpAction)19 NoOpConsumer (com.amplifyframework.core.NoOpConsumer)19 QuerySortBy (com.amplifyframework.core.model.query.QuerySortBy)19 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)19 Post (com.amplifyframework.testmodels.commentsblog.Post)19 PostStatus (com.amplifyframework.testmodels.commentsblog.PostStatus)19 ArrayList (java.util.ArrayList)19 Collections (java.util.Collections)19 Comparator (java.util.Comparator)19 CountDownLatch (java.util.concurrent.CountDownLatch)19