use of com.amplifyframework.testmodels.commentsblog.BlogOwner in project amplify-android by aws-amplify.
the class ObserveQueryExecutorTest method observeQueryReturnsSortedListOfTotalItems.
/**
* observe Query Returns Sorted List Of Total Items.
* @throws InterruptedException InterruptedException
* @throws DataStoreException DataStoreException
*/
@Test
public void observeQueryReturnsSortedListOfTotalItems() throws InterruptedException, DataStoreException {
CountDownLatch latch = new CountDownLatch(1);
CountDownLatch changeLatch = new CountDownLatch(1);
AtomicInteger count = new AtomicInteger();
List<String> names = Arrays.asList("John", "Jacob", "Joe", "Bob", "Bobby", "Bobb", "Dan", "Dany", "Daniel");
List<String> weas = Arrays.asList("pon", "lth", "ver", "kly", "ken", "sel", "ner", "rer", "ned");
List<BlogOwner> owners = new ArrayList<>();
for (int i = 0; i < names.size() / 2; i++) {
BlogOwner owner = BlogOwner.builder().name(names.get(i)).wea(weas.get(i)).build();
owners.add(owner);
}
int maxRecords = 50;
Consumer<Cancelable> observationStarted = NoOpConsumer.create();
SyncStatus mockSyncStatus = mock(SyncStatus.class);
when(mockSyncStatus.get(any(), any())).thenReturn(false);
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(owners.get(0)));
latch.countDown();
} else if (count.get() == 1) {
List<BlogOwner> sorted = new ArrayList<>(owners);
Collections.sort(sorted, Comparator.comparing(BlogOwner::getName).reversed().thenComparing(BlogOwner::getWea));
assertEquals(sorted, value.getItems());
Assert.assertEquals(8, value.getItems().size());
changeLatch.countDown();
}
count.getAndIncrement();
};
Consumer<DataStoreException> onObservationError = NoOpConsumer.create();
Action onObservationComplete = () -> {
};
SqlQueryProcessor mockSqlQueryProcessor = mock(SqlQueryProcessor.class);
when(mockSqlQueryProcessor.queryOfflineData(eq(BlogOwner.class), any(), any())).thenReturn(owners);
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, 1);
List<QuerySortBy> sortBy = new ArrayList<>();
sortBy.add(BlogOwner.NAME.descending());
sortBy.add(BlogOwner.WEA.ascending());
observeQueryExecutor.observeQuery(BlogOwner.class, new ObserveQueryOptions(null, sortBy), observationStarted, onQuerySnapshot, onObservationError, onObservationComplete);
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
for (int i = (names.size() / 2) + 1; i < names.size(); i++) {
BlogOwner itemChange = BlogOwner.builder().name(names.get(i)).wea(weas.get(i)).build();
owners.add(itemChange);
try {
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.CREATE).build());
} catch (AmplifyException exception) {
exception.printStackTrace();
}
}
Assert.assertTrue(changeLatch.await(7, TimeUnit.SECONDS));
}
use of com.amplifyframework.testmodels.commentsblog.BlogOwner in project amplify-android by aws-amplify.
the class SQLCommandProcessorTest method executeExistsReturnsFalseWhenItemDoesntExist.
/**
* Create a BlogOwner, but don't insert it. Then verify that executeExists returns false.
* @throws AmplifyException on failure to create ModelSchema from class.
*/
@Test
public void executeExistsReturnsFalseWhenItemDoesntExist() throws AmplifyException {
// Create a BlogOwner, but don't insert it
ModelSchema blogOwnerSchema = ModelSchema.fromModelClass(BlogOwner.class);
BlogOwner abigailMcGregor = BlogOwner.builder().name("Abigail McGregor").build();
QueryPredicate predicate = BlogOwner.ID.eq(abigailMcGregor.getId());
SqlCommand existsCommand = sqlCommandFactory.existsFor(blogOwnerSchema, predicate);
assertFalse(sqlCommandProcessor.executeExists(existsCommand));
}
use of com.amplifyframework.testmodels.commentsblog.BlogOwner in project amplify-android by aws-amplify.
the class VersionRepositoryTest method emitsErrorForNoMetadataInRepo.
/**
* When you try to get a model version, but there's no metadata for that model,
* this should fail with an {@link DataStoreException}.
* @throws InterruptedException If interrupted while awaiting terminal result in test observer
*/
@Test
public void emitsErrorForNoMetadataInRepo() throws InterruptedException {
// Arrange: no metadata is in the repo.
BlogOwner blogOwner = BlogOwner.builder().name("Jameson Williams").build();
// Note that this line is NOT executed in arrangement.
// ModelMetadata metadata = new ModelMetadata(blogOwner.getId(), false, 1, Time.now());
// putInStore(blogOwner blogOwner);
// Act: try to lookup the metadata. Is it going to work? Duh.
TestObserver<Integer> observer = versionRepository.findModelVersion(blogOwner).test();
assertTrue(observer.await(REASONABLE_WAIT_TIME, TimeUnit.MILLISECONDS));
// Assert: this failed. There was no version available.
observer.assertError(error -> {
if (!(error instanceof DataStoreException)) {
return false;
}
String expectedMessage = String.format(Locale.US, "Wanted 1 metadata for item with id = %s, but had 0.", blogOwner.getId());
return expectedMessage.equals(error.getMessage());
});
}
use of com.amplifyframework.testmodels.commentsblog.BlogOwner in project amplify-android by aws-amplify.
the class VersionRepositoryTest method emitsSuccessWithValueWhenVersionInStore.
/**
* When there is metadata for a model in the store, and that metadata includes a version -
* for heaven's sake, man - do please emit the dang thing.
* @throws DataStoreException On failure to arrange data into store
* @throws InterruptedException If interrupted while awaiting terminal result in test observer
*/
@Test
public void emitsSuccessWithValueWhenVersionInStore() throws DataStoreException, InterruptedException {
// Arrange versioning info into the store.
BlogOwner owner = BlogOwner.builder().name("Jameson").build();
final int maxRandomVersion = 1_000;
int expectedVersion = new Random().nextInt(maxRandomVersion);
storageAdapter.save(new ModelMetadata(owner.getModelName() + "|" + owner.getId(), false, expectedVersion, Temporal.Timestamp.now()));
// Act! Try to obtain it via the Versioning Repository.
TestObserver<Integer> observer = versionRepository.findModelVersion(owner).test();
assertTrue(observer.await(REASONABLE_WAIT_TIME, TimeUnit.MILLISECONDS));
// Assert: we got a version.
observer.assertNoErrors().assertComplete().assertValue(expectedVersion);
}
use of com.amplifyframework.testmodels.commentsblog.BlogOwner in project amplify-android by aws-amplify.
the class ModelWithMetadataAdapterTest method adapterCanSerializeMwm.
/**
* The Gson adapter can be used to serialize a ModelWithMetadata to JSON.
* @throws JSONException From JSONAssert.assert(...) call, if invalid JSON
* is provided in either position
*/
@Test
public void adapterCanSerializeMwm() throws JSONException {
Temporal.Timestamp lastChangedAt = Temporal.Timestamp.now();
String modelId = UUID.randomUUID().toString();
ModelMetadata metadata = new ModelMetadata(modelId, false, 4, lastChangedAt);
BlogOwner model = BlogOwner.builder().name("Blog Owner").build();
ModelWithMetadata<BlogOwner> mwm = new ModelWithMetadata<>(model, metadata);
String expected = new JSONObject().put("id", model.getId()).put("name", model.getName()).put("_lastChangedAt", metadata.getLastChangedAt().getSecondsSinceEpoch()).put("_deleted", metadata.isDeleted()).put("_version", metadata.getVersion()).toString();
String actual = gson.toJson(mwm);
JSONAssert.assertEquals(expected, actual, true);
}
Aggregations