Search in sources :

Example 11 with GraphQLResponse

use of com.amplifyframework.api.graphql.GraphQLResponse in project amplify-android by aws-amplify.

the class AWSApiPluginTest method requestUsesIamForAuth.

/**
 * Ensure the auth mode used for the request is AWS_IAM. We verify this by
 * @throws AmplifyException Not expected.
 * @throws InterruptedException Not expected.
 */
@Test
public void requestUsesIamForAuth() throws AmplifyException, InterruptedException {
    webServer.enqueue(new MockResponse().setBody(Resources.readAsString("blog-owners-query-results.json")));
    AppSyncGraphQLRequest<PaginatedResult<BlogOwner>> appSyncGraphQLRequest = createQueryRequestWithAuthMode(BlogOwner.class, AuthorizationType.AWS_IAM);
    GraphQLResponse<PaginatedResult<BlogOwner>> actualResponse = Await.<GraphQLResponse<PaginatedResult<BlogOwner>>, ApiException>result((onResult, onError) -> plugin.query(appSyncGraphQLRequest, onResult, onError));
    RecordedRequest recordedRequest = webServer.takeRequest();
    assertNull(recordedRequest.getHeader("x-api-key"));
    assertNotNull(recordedRequest.getHeader("authorization"));
    assertTrue(recordedRequest.getHeader("authorization").startsWith("AWS4-HMAC-SHA256"));
    assertEquals(Arrays.asList("Curly", "Moe", "Larry"), Observable.fromIterable(actualResponse.getData()).map(BlogOwner::getName).toList().blockingGet());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Example 12 with GraphQLResponse

use of com.amplifyframework.api.graphql.GraphQLResponse in project amplify-android by aws-amplify.

the class AWSApiPluginTest method requestUsesCognitoForAuth.

/**
 * If the auth mode is set for the individual request, ensure that the resulting request
 * to AppSync has the correct auth header.
 * @throws AmplifyException Not expected.
 * @throws InterruptedException Not expected.
 */
@Test
public void requestUsesCognitoForAuth() throws AmplifyException, InterruptedException {
    webServer.enqueue(new MockResponse().setBody(Resources.readAsString("blog-owners-query-results.json")));
    AppSyncGraphQLRequest<PaginatedResult<BlogOwner>> appSyncGraphQLRequest = createQueryRequestWithAuthMode(BlogOwner.class, AuthorizationType.AMAZON_COGNITO_USER_POOLS);
    GraphQLResponse<PaginatedResult<BlogOwner>> actualResponse = Await.<GraphQLResponse<PaginatedResult<BlogOwner>>, ApiException>result((onResult, onError) -> plugin.query(appSyncGraphQLRequest, onResult, onError));
    RecordedRequest recordedRequest = webServer.takeRequest();
    assertNull(recordedRequest.getHeader("x-api-key"));
    assertNotNull(recordedRequest.getHeader("authorization"));
    assertEquals("FAKE_TOKEN", recordedRequest.getHeader("authorization"));
    assertEquals(Arrays.asList("Curly", "Moe", "Larry"), Observable.fromIterable(actualResponse.getData()).map(BlogOwner::getName).toList().blockingGet());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Example 13 with GraphQLResponse

use of com.amplifyframework.api.graphql.GraphQLResponse 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 14 with GraphQLResponse

use of com.amplifyframework.api.graphql.GraphQLResponse in project amplify-android by aws-amplify.

the class GsonGraphQLResponseFactoryTest method errorResponseDeserializesExtensionsMap.

/**
 * This tests the GsonErrorDeserializer.  The test JSON response has 4 errors, which are all in
 * different formats, but are expected to be parsed into the same resulting object:
 * 1. Error contains errorType, errorInfo, data (AppSync specific fields) at root level
 * 2. Error contains errorType, errorInfo, data inside extensions object
 * 3. Error contains errorType, errorInfo, data at root AND inside extensions (fields inside
 * extensions take precedence)
 * 4. Error contains errorType at root, and errorInfo, data inside extensions (all should be
 * merged into extensions)
 *
 * @throws ApiException From API configuration
 */
@Test
public void errorResponseDeserializesExtensionsMap() throws ApiException {
    // Arrange some JSON string from a "server"
    final String partialResponseJson = Resources.readAsString("error-extensions-gql-response.json");
    // Act! Parse it into a model.
    Type responseType = TypeMaker.getParameterizedType(PaginatedResult.class, Todo.class);
    GraphQLRequest<PaginatedResult<Todo>> request = buildDummyRequest(responseType);
    final GraphQLResponse<PaginatedResult<Todo>> response = responseFactory.buildResponse(request, partialResponseJson);
    // Build the expected response.
    String message = "Conflict resolver rejects mutation.";
    List<GraphQLLocation> locations = Collections.singletonList(new GraphQLLocation(11, 3));
    List<GraphQLPathSegment> path = Arrays.asList(new GraphQLPathSegment("listTodos"), new GraphQLPathSegment("items"), new GraphQLPathSegment(0), new GraphQLPathSegment("name"));
    Map<String, Object> data = new HashMap<>();
    data.put("id", "EF48518C-92EB-4F7A-A64E-D1B9325205CF");
    data.put("title", "new3");
    data.put("content", "Original content from DataStoreEndToEndTests at 2020-03-26 21:55:47 " + "+0000");
    data.put("_version", 2);
    Map<String, Object> extensions = new HashMap<>();
    extensions.put("errorType", "ConflictUnhandled");
    extensions.put("errorInfo", null);
    extensions.put("data", data);
    GraphQLResponse.Error expectedError = new GraphQLResponse.Error(message, locations, path, extensions);
    GraphQLResponse<PaginatedResult<Todo>> expectedResponse = new GraphQLResponse<>(null, Arrays.asList(expectedError, expectedError, expectedError, expectedError));
    // Assert that the response is expected
    assertEquals(expectedResponse, response);
}
Also used : GraphQLLocation(com.amplifyframework.api.graphql.GraphQLLocation) HashMap(java.util.HashMap) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) GraphQLPathSegment(com.amplifyframework.api.graphql.GraphQLPathSegment) QueryType(com.amplifyframework.api.graphql.QueryType) Type(java.lang.reflect.Type) JSONObject(org.json.JSONObject) Test(org.junit.Test)

Example 15 with GraphQLResponse

use of com.amplifyframework.api.graphql.GraphQLResponse in project amplify-android by aws-amplify.

the class GsonGraphQLResponseFactoryTest method errorWithNullFieldsCanBeParsed.

/**
 * If an {@link GraphQLResponse} contains a non-null {@link GraphQLResponse.Error},
 * and if that error object itself contains some null-valued fields, the response factory
 * should be resilient to this, and continue to render a response, anyway, without
 * throwing an exception over the issue.
 * @throws ApiException On failure to build a response, perhaps because the null
 *                      valued items inside of the {@link GraphQLResponse.Error}
 *                      could not be parsed
 */
@Test
public void errorWithNullFieldsCanBeParsed() throws ApiException {
    // Arrange some JSON string from a "server"
    final String responseJson = Resources.readAsString("error-null-properties.json");
    // Act! Parse it into a model.
    Type responseType = TypeMaker.getParameterizedType(PaginatedResult.class, Todo.class);
    GraphQLRequest<PaginatedResult<Todo>> request = buildDummyRequest(responseType);
    final GraphQLResponse<PaginatedResult<Todo>> response = responseFactory.buildResponse(request, responseJson);
    // Build the expected response.
    Map<String, Object> extensions = new HashMap<>();
    extensions.put("errorType", null);
    extensions.put("errorInfo", null);
    extensions.put("data", null);
    GraphQLResponse.Error expectedError = new GraphQLResponse.Error("the message", null, null, extensions);
    GraphQLResponse<PaginatedResult<Todo>> expectedResponse = new GraphQLResponse<>(null, Collections.singletonList(expectedError));
    // Assert that the response is expected
    assertEquals(expectedResponse, response);
}
Also used : QueryType(com.amplifyframework.api.graphql.QueryType) Type(java.lang.reflect.Type) HashMap(java.util.HashMap) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) JSONObject(org.json.JSONObject) Test(org.junit.Test)

Aggregations

GraphQLResponse (com.amplifyframework.api.graphql.GraphQLResponse)30 Test (org.junit.Test)23 PaginatedResult (com.amplifyframework.api.graphql.PaginatedResult)14 Model (com.amplifyframework.core.model.Model)11 ApiException (com.amplifyframework.api.ApiException)10 Action (com.amplifyframework.core.Action)9 Consumer (com.amplifyframework.core.Consumer)9 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)9 JSONObject (org.json.JSONObject)9 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)8 GraphQLRequest (com.amplifyframework.api.graphql.GraphQLRequest)7 RandomString (com.amplifyframework.testutils.random.RandomString)7 AmplifyException (com.amplifyframework.AmplifyException)6 ModelSchema (com.amplifyframework.core.model.ModelSchema)6 ModelMetadata (com.amplifyframework.datastore.appsync.ModelMetadata)6 RandomModel (com.amplifyframework.testutils.random.RandomModel)6 HashMap (java.util.HashMap)6 QueryType (com.amplifyframework.api.graphql.QueryType)5 SubscriptionType (com.amplifyframework.api.graphql.SubscriptionType)5 Cancelable (com.amplifyframework.core.async.Cancelable)5