use of com.amplifyframework.api.ApiCategory in project amplify-android by aws-amplify.
the class ConflictResolverIntegrationTest method setupApiMock.
@SuppressWarnings("unchecked")
private Person setupApiMock(CountDownLatch latch, ApiCategory mockApiCategory) {
Person person1 = createPerson("Test", "Dummy I");
// Mock success on subscription.
doAnswer(invocation -> {
int indexOfStartConsumer = 1;
Consumer<String> onStart = invocation.getArgument(indexOfStartConsumer);
GraphQLOperation<?> mockOperation = mock(GraphQLOperation.class);
doAnswer(opAnswer -> {
return null;
}).when(mockOperation).cancel();
// Trigger the subscription start event.
onStart.accept(RandomString.string());
return mockOperation;
}).when(mockApiCategory).subscribe(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class), any(Consumer.class), any(Action.class));
// When mutate is called on the appsync for the first time unhandled conflict error is returned.
doAnswer(invocation -> {
int indexOfResponseConsumer = 1;
Consumer<GraphQLResponse<ModelWithMetadata<Person>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
List<GraphQLLocation> locations = new ArrayList<>();
locations.add(new GraphQLLocation(2, 3));
List<GraphQLPathSegment> path = new ArrayList<>();
path.add(new GraphQLPathSegment("updatePost"));
Map<String, Object> serverModelData = new HashMap<>();
serverModelData.put("id", "5c895eae-88ef-4ce8-9d58-e27d0c7cbe99");
serverModelData.put("createdAt", "2022-02-04T19:41:05.973Z");
serverModelData.put("first_name", "test");
serverModelData.put("last_name", "server last");
serverModelData.put("_version", 92);
serverModelData.put("_deleted", false);
serverModelData.put("_lastChangedAt", 1_000);
Map<String, Object> extensions = new HashMap<>();
extensions.put("errorInfo", null);
extensions.put("data", serverModelData);
extensions.put("errorType", "ConflictUnhandled");
ArrayList<GraphQLResponse.Error> errorList = new ArrayList<>();
errorList.add(new GraphQLResponse.Error("Conflict resolver rejects mutation.", locations, path, extensions));
onResponse.accept(new GraphQLResponse<>(null, errorList));
// latch makes sure conflict unhandled response is returned.
latch.countDown();
return mock(GraphQLOperation.class);
}).doAnswer(invocation -> {
// When mutate is called on the appsync for the second time success response is returned
int indexOfResponseConsumer = 1;
Consumer<GraphQLResponse<ModelWithMetadata<Person>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
ModelMetadata modelMetadata = new ModelMetadata(person1.getId(), false, 1, Temporal.Timestamp.now());
ModelWithMetadata<Person> modelWithMetadata = new ModelWithMetadata<>(person1, modelMetadata);
onResponse.accept(new GraphQLResponse<>(modelWithMetadata, Collections.emptyList()));
verify(mockApiCategory, atLeast(2)).mutate(argThat(getMatcherFor(person1)), any(), any());
// latch makes sure success response is returned.
latch.countDown();
return mock(GraphQLOperation.class);
}).when(mockApiCategory).mutate(any(), any(), any());
// Setup to mimic successful sync
doAnswer(invocation -> {
int indexOfResponseConsumer = 1;
ModelMetadata modelMetadata = new ModelMetadata(person1.getId(), false, 1, Temporal.Timestamp.now());
ModelWithMetadata<Person> modelWithMetadata = new ModelWithMetadata<>(person1, modelMetadata);
// Mock the API emitting an ApiEndpointStatusChangeEvent event.
Consumer<GraphQLResponse<PaginatedResult<ModelWithMetadata<Person>>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
PaginatedResult<ModelWithMetadata<Person>> data = new PaginatedResult<>(Collections.singletonList(modelWithMetadata), null);
onResponse.accept(new GraphQLResponse<>(data, Collections.emptyList()));
latch.countDown();
return mock(GraphQLOperation.class);
}).doAnswer(invocation -> {
int indexOfResponseConsumer = 1;
Car car = Car.builder().build();
ModelMetadata modelMetadata = new ModelMetadata(car.getId(), false, 1, Temporal.Timestamp.now());
ModelWithMetadata<Car> modelWithMetadata = new ModelWithMetadata<>(car, modelMetadata);
Consumer<GraphQLResponse<PaginatedResult<ModelWithMetadata<Car>>>> onResponse = invocation.getArgument(indexOfResponseConsumer);
PaginatedResult<ModelWithMetadata<Car>> data = new PaginatedResult<>(Collections.singletonList(modelWithMetadata), null);
onResponse.accept(new GraphQLResponse<>(data, Collections.emptyList()));
latch.countDown();
return mock(GraphQLOperation.class);
}).when(mockApiCategory).query(any(), any(), any());
return person1;
}
use of com.amplifyframework.api.ApiCategory in project amplify-android by aws-amplify.
the class RxApiBindingTest method createBindingInFrontOfMockPlugin.
/**
* To test the binding, we construct a category that has been configured
* with a mock plugin. The binding delegates to the category.
* @throws AmplifyException On failure to add plugin or configure category
*/
@Before
public void createBindingInFrontOfMockPlugin() throws AmplifyException {
// Mock plugin on which we will simulate API responses/failures
this.delegate = mock(ApiPlugin.class);
when(delegate.getPluginKey()).thenReturn(RandomString.string());
// Build a category, add the mock plugin, configure and init the category.
final ApiCategory apiCategory = new ApiCategory();
apiCategory.addPlugin(delegate);
apiCategory.configure(new ApiCategoryConfiguration(), mock(Context.class));
apiCategory.initialize(mock(Context.class));
// Provide that category as a backing to our binding.
this.rxApi = new RxApiBinding(apiCategory);
}
use of com.amplifyframework.api.ApiCategory in project amplify-android by aws-amplify.
the class HybridAssociationSyncInstrumentationTest method setup.
/**
* DataStore is configured with a real AppSync endpoint. API and AppSync clients
* are used to arrange/validate state before/after exercising the DataStore. The {@link Amplify}
* facade is intentionally *not* used, since we don't want to pollute the instrumentation
* test process with global state. We need an *instance* of the DataStore.
* @throws AmplifyException On failure to configure Amplify, API/DataStore categories.
*/
@Ignore("It passes. Not automating due to operational concerns as noted in class-level @Ignore.")
@Before
public void setup() throws AmplifyException {
Amplify.addPlugin(new AndroidLoggingPlugin(LogLevel.VERBOSE));
StrictMode.enable();
Context context = getApplicationContext();
@RawRes int configResourceId = Resources.getRawResourceId(context, "amplifyconfiguration");
// Setup an API
CategoryConfiguration apiCategoryConfiguration = AmplifyConfiguration.fromConfigFile(context, configResourceId).forCategoryType(CategoryType.API);
ApiCategory apiCategory = new ApiCategory();
apiCategory.addPlugin(new AWSApiPlugin());
apiCategory.configure(apiCategoryConfiguration, context);
// To arrange and verify state, we need to access the supporting AppSync API
api = SynchronousApi.delegatingTo(apiCategory);
appSync = SynchronousAppSync.using(AppSyncClient.via(apiCategory));
schemaProvider = SchemaLoader.loadFromAssetsDirectory("schemas/commentsblog");
DataStoreCategory dataStoreCategory = DataStoreCategoryConfigurator.begin().api(apiCategory).clearDatabase(true).context(context).modelProvider(schemaProvider).resourceId(configResourceId).timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS).finish();
AWSDataStorePlugin plugin = (AWSDataStorePlugin) dataStoreCategory.getPlugin("awsDataStorePlugin");
normalBehaviors = SynchronousDataStore.delegatingTo(dataStoreCategory);
hybridBehaviors = SynchronousHybridBehaviors.delegatingTo(plugin);
}
use of com.amplifyframework.api.ApiCategory in project amplify-android by aws-amplify.
the class HybridTemporalSyncInstrumentationTest method setup.
/**
* DataStore is configured with a real AppSync endpoint. API and AppSync clients
* are used to arrange/validate state before/after exercising the DataStore. The {@link Amplify}
* facade is intentionally *not* used, since we don't want to pollute the instrumentation
* test process with global state. We need an *instance* of the DataStore.
* @throws AmplifyException On failure to configure Amplify, API/DataStore categories.
*/
@Ignore("It passes. Not automating due to operational concerns as noted in class-level @Ignore.")
@Before
public void setup() throws AmplifyException {
Amplify.addPlugin(new AndroidLoggingPlugin(LogLevel.VERBOSE));
StrictMode.enable();
Context context = getApplicationContext();
@RawRes int configResourceId = Resources.getRawResourceId(context, "amplifyconfiguration");
// Setup an API
CategoryConfiguration apiCategoryConfiguration = AmplifyConfiguration.fromConfigFile(context, configResourceId).forCategoryType(CategoryType.API);
ApiCategory apiCategory = new ApiCategory();
apiCategory.addPlugin(new AWSApiPlugin());
apiCategory.configure(apiCategoryConfiguration, context);
// To arrange and verify state, we need to access the supporting AppSync API
api = SynchronousApi.delegatingTo(apiCategory);
appSync = SynchronousAppSync.using(AppSyncClient.via(apiCategory));
SchemaProvider schemaProvider = SchemaLoader.loadFromAssetsDirectory("schemas/meeting");
DataStoreCategory dataStoreCategory = DataStoreCategoryConfigurator.begin().api(apiCategory).clearDatabase(true).context(context).modelProvider(schemaProvider).resourceId(configResourceId).timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS).finish();
AWSDataStorePlugin plugin = (AWSDataStorePlugin) dataStoreCategory.getPlugin("awsDataStorePlugin");
hybridBehaviors = SynchronousHybridBehaviors.delegatingTo(plugin);
// Get a handle to the Meeting model schema that we loaded into the DataStore in @Before.
String modelName = Meeting.class.getSimpleName();
modelSchema = schemaProvider.modelSchemas().get(modelName);
}
use of com.amplifyframework.api.ApiCategory in project amplify-android by aws-amplify.
the class MultiAuthSyncEngineInstrumentationTest method configure.
/**
* Method used to configure each scenario.
* @param modelType The model type.
* @param signInToCognito Does the test scenario require the user to be logged in with user pools.
* @param signInWithOidc Does the test scenario require the user to be logged in with an OIDC provider.
* @param expectedAuthType The auth type that should succeed for the test.
* @throws AmplifyException No expected.
* @throws IOException Not expected.
*/
private void configure(Class<? extends Model> modelType, boolean signInToCognito, boolean signInWithOidc, AuthorizationType expectedAuthType) throws AmplifyException, IOException {
Amplify.addPlugin(new AndroidLoggingPlugin(LogLevel.VERBOSE));
String tag = modelType.getSimpleName();
MultiAuthTestModelProvider modelProvider = MultiAuthTestModelProvider.getInstance(Collections.singletonList(modelType));
SchemaRegistry schemaRegistry = SchemaRegistry.instance();
ModelSchema modelSchema = ModelSchema.fromModelClass(modelType);
schemaRegistry.register(modelType.getSimpleName(), modelSchema);
StrictMode.enable();
Context context = getApplicationContext();
@RawRes int configResourceId = Resources.getRawResourceId(context, "amplifyconfiguration");
AmplifyConfiguration amplifyConfiguration = AmplifyConfiguration.fromConfigFile(context, configResourceId);
readCredsFromConfig(context);
// Setup an auth plugin
CategoryConfiguration authCategoryConfiguration = amplifyConfiguration.forCategoryType(CategoryType.AUTH);
// Turn off persistence so the mobile client's state for one test does not interfere with the others.
try {
authCategoryConfiguration.getPluginConfig("awsCognitoAuthPlugin").getJSONObject("Auth").getJSONObject("Default").put("Persistence", false);
} catch (JSONException exception) {
exception.printStackTrace();
fail();
return;
}
AuthCategory authCategory = new AuthCategory();
AWSCognitoAuthPlugin authPlugin = new AWSCognitoAuthPlugin();
authCategory.addPlugin(authPlugin);
authCategory.configure(authCategoryConfiguration, context);
auth = SynchronousAuth.delegatingTo(authCategory);
if (signInToCognito) {
Log.v(tag, "Test requires signIn.");
AuthSignInResult authSignInResult = auth.signIn(cognitoUser, cognitoPassword);
if (!authSignInResult.isSignInComplete()) {
fail("Unable to complete initial sign-in");
}
}
if (signInWithOidc) {
oidcLogin();
if (token.get() == null) {
fail("Unable to autenticate with OIDC provider");
}
}
// Setup an API
DefaultCognitoUserPoolsAuthProvider cognitoProvider = new DefaultCognitoUserPoolsAuthProvider(authPlugin.getEscapeHatch());
CategoryConfiguration apiCategoryConfiguration = amplifyConfiguration.forCategoryType(CategoryType.API);
ApiAuthProviders apiAuthProviders = ApiAuthProviders.builder().cognitoUserPoolsAuthProvider(cognitoProvider).awsCredentialsProvider(authPlugin.getEscapeHatch()).oidcAuthProvider(token::get).build();
ApiCategory apiCategory = new ApiCategory();
requestInterceptor = new HttpRequestInterceptor(expectedAuthType);
apiCategory.addPlugin(AWSApiPlugin.builder().configureClient("DataStoreIntegTestsApi", okHttpClientBuilder -> okHttpClientBuilder.addInterceptor(requestInterceptor)).apiAuthProviders(apiAuthProviders).build());
apiCategory.configure(apiCategoryConfiguration, context);
api = SynchronousApi.delegatingTo(apiCategory);
// Setup DataStore
DataStoreConfiguration dsConfig = DataStoreConfiguration.builder().errorHandler(exception -> Log.e(tag, "DataStore error handler received an error.", exception)).syncExpression(modelSchema.getName(), () -> Where.id("FAKE_ID").getQueryPredicate()).build();
CategoryConfiguration dataStoreCategoryConfiguration = AmplifyConfiguration.fromConfigFile(context, configResourceId).forCategoryType(CategoryType.DATASTORE);
String databaseName = "IntegTest" + modelType.getSimpleName() + ".db";
SQLiteStorageAdapter sqLiteStorageAdapter = TestStorageAdapter.create(schemaRegistry, modelProvider, databaseName);
AWSDataStorePlugin awsDataStorePlugin = AWSDataStorePlugin.builder().storageAdapter(sqLiteStorageAdapter).modelProvider(modelProvider).apiCategory(apiCategory).authModeStrategy(AuthModeStrategyType.MULTIAUTH).schemaRegistry(schemaRegistry).dataStoreConfiguration(dsConfig).build();
DataStoreCategory dataStoreCategory = new DataStoreCategory();
dataStoreCategory.addPlugin(awsDataStorePlugin);
dataStoreCategory.configure(dataStoreCategoryConfiguration, context);
dataStoreCategory.initialize(context);
dataStore = SynchronousDataStore.delegatingTo(dataStoreCategory);
}
Aggregations