diff --git a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/aot/DatastoreCoreRuntimeHints.java b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/aot/DatastoreCoreRuntimeHints.java index c39bdbc9f3..eaa31c6700 100644 --- a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/aot/DatastoreCoreRuntimeHints.java +++ b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/aot/DatastoreCoreRuntimeHints.java @@ -29,8 +29,7 @@ public void registerHints(RuntimeHints hints, ClassLoader classLoader) { hints .reflection() .registerTypes( - Arrays.asList( - TypeReference.of(java.util.HashMap.class)), + Arrays.asList(TypeReference.of(java.util.HashMap.class)), hint -> hint.withMembers( MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, diff --git a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/aot/DatastoreQueryRuntimeHints.java b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/aot/DatastoreQueryRuntimeHints.java index 34f6bc3c1d..837af66a71 100644 --- a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/aot/DatastoreQueryRuntimeHints.java +++ b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/aot/DatastoreQueryRuntimeHints.java @@ -30,8 +30,7 @@ public void registerHints(RuntimeHints hints, ClassLoader classLoader) { hints .reflection() .registerTypes( - Arrays.asList( - TypeReference.of(DatastorePageable.class)), + Arrays.asList(TypeReference.of(DatastorePageable.class)), hint -> hint.withMembers( MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, diff --git a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/DatastoreOperations.java b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/DatastoreOperations.java index f04799c441..dc096e485d 100644 --- a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/DatastoreOperations.java +++ b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/DatastoreOperations.java @@ -73,8 +73,8 @@ public interface DatastoreOperations { Iterable saveAll(Iterable entities, Key... ancestors); /** - * Inserts an instance of an object to Cloud Datastore. Throws a DatastoreException if an entry with same ID - * already exists. Ancestors can be added only to entries with Key ids. + * Inserts an instance of an object to Cloud Datastore. Throws a DatastoreException if an entry + * with same ID already exists. Ancestors can be added only to entries with Key ids. * * @param instance the instance to save. * @param ancestors ancestors that should be added to the entry @@ -85,8 +85,8 @@ public interface DatastoreOperations { T insert(T instance, Key... ancestors); /** - * Saves multiple instances of objects to Cloud Datastore. Throws a DatastoreException if any entry with one of - * the IDs already exists. Ancestors can be added only to entries with Key ids. + * Saves multiple instances of objects to Cloud Datastore. Throws a DatastoreException if any + * entry with one of the IDs already exists. Ancestors can be added only to entries with Key ids. * * @param entities the objects to save. * @param ancestors ancestors that should be added to each entry diff --git a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplate.java b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplate.java index afe0818728..8bcfc098ed 100644 --- a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplate.java +++ b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplate.java @@ -176,7 +176,8 @@ public Iterable insertAll(final Iterable entities, final Key... ancest return entities; } - private void insertOrSaveEntities(Iterable iterable, Key[] ancestors, Consumer[]> consumer) { + private void insertOrSaveEntities( + Iterable iterable, Key[] ancestors, Consumer[]> consumer) { List instances; if (iterable instanceof List) { instances = (List) iterable; @@ -255,16 +256,17 @@ private void performDelete(Key[] keys, Iterable ids, Iterable entities, Class en @Override public long count(Class entityClass) { - KeyQuery baseQuery = Query.newKeyQueryBuilder() - .setKind(getPersistentEntity(entityClass).kindName()) - .build(); + KeyQuery baseQuery = + Query.newKeyQueryBuilder().setKind(getPersistentEntity(entityClass).kindName()).build(); - AggregationQuery countAggregationQuery = Query.newAggregationQueryBuilder() - .over(baseQuery) - .addAggregation(Aggregation.count().as("total_count")) - .build(); + AggregationQuery countAggregationQuery = + Query.newAggregationQueryBuilder() + .over(baseQuery) + .addAggregation(Aggregation.count().as("total_count")) + .build(); - AggregationResults aggregationResults = getDatastoreReadWriter().runAggregation(countAggregationQuery); + AggregationResults aggregationResults = + getDatastoreReadWriter().runAggregation(countAggregationQuery); maybeEmitEvent(new AfterQueryEvent(aggregationResults, countAggregationQuery)); AggregationResult aggregationResult = Iterables.getOnlyElement(aggregationResults); return aggregationResult.get("total_count"); diff --git a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/convert/DefaultDatastoreEntityConverter.java b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/convert/DefaultDatastoreEntityConverter.java index 8f9f18c2e7..6f350ae4fa 100644 --- a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/convert/DefaultDatastoreEntityConverter.java +++ b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/convert/DefaultDatastoreEntityConverter.java @@ -226,8 +226,7 @@ public void write(Object source, @NonNull BaseEntity.Builder sink) { List discriminationValues = persistentEntity.getCompatibleDiscriminationValues(); if (!discriminationValues.isEmpty() || discriminationFieldName != null) { sink.set( - discriminationFieldName, - discriminationValues.stream().map(StringValue::of).toList()); + discriminationFieldName, discriminationValues.stream().map(StringValue::of).toList()); } PersistentPropertyAccessor accessor = persistentEntity.getPropertyAccessor(source); persistentEntity.doWithColumnBackedProperties( @@ -269,8 +268,7 @@ private Value setExcludeFromIndexes(Value convertedVal) { } else if (convertedVal.getClass().equals(ListValue.class)) { return ListValue.of( (List) - ((ListValue) convertedVal) - .get().stream().map(this::setExcludeFromIndexes).toList()); + ((ListValue) convertedVal).get().stream().map(this::setExcludeFromIndexes).toList()); } else { return convertedVal.toBuilder().setExcludeFromIndexes(true).build(); } diff --git a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/convert/TwoStepsConversions.java b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/convert/TwoStepsConversions.java index 144f1c5ff6..ded3a9b173 100644 --- a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/convert/TwoStepsConversions.java +++ b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/convert/TwoStepsConversions.java @@ -138,16 +138,18 @@ private T convertOnRead( if (val == null) { return null; } - BiFunction, ?> readConverter = switch (embeddedType) { - case EMBEDDED_MAP -> (x, typeInformation) -> - convertOnReadSingleEmbeddedMap( - x, - Objects.requireNonNull(typeInformation.getComponentType()).getType(), - typeInformation.getMapValueType(), - targetComponentType); - case EMBEDDED_ENTITY -> this::convertOnReadSingleEmbedded; - case NOT_EMBEDDED -> this::convertOnReadSingle; - }; + BiFunction, ?> readConverter = + switch (embeddedType) { + case EMBEDDED_MAP -> + (x, typeInformation) -> + convertOnReadSingleEmbeddedMap( + x, + Objects.requireNonNull(typeInformation.getComponentType()).getType(), + typeInformation.getMapValueType(), + targetComponentType); + case EMBEDDED_ENTITY -> this::convertOnReadSingleEmbedded; + case NOT_EMBEDDED -> this::convertOnReadSingle; + }; if (ValueUtil.isCollectionLike(val.getClass()) && targetCollectionType != null @@ -191,8 +193,7 @@ private T convertOnReadSingleEmbedded( Object value, TypeInformation targetTypeInformation) { Assert.notNull(value, "Cannot convert a null value."); if (value instanceof BaseEntity baseEntity) { - return (T) - this.datastoreEntityConverter.read(targetTypeInformation.getType(), baseEntity); + return (T) this.datastoreEntityConverter.read(targetTypeInformation.getType(), baseEntity); } throw new DatastoreDataException( "Embedded entity was expected, but " + value.getClass() + " found"); @@ -261,12 +262,15 @@ private Value convertOnWrite( Function writeConverter = this::convertOnWriteSingle; if (proppertyVal != null) { - writeConverter = switch (embeddedType) { - case EMBEDDED_MAP -> x -> convertOnWriteSingleEmbeddedMap(x, fieldName, - typeInformation.getMapValueType()); - case EMBEDDED_ENTITY -> x -> convertOnWriteSingleEmbedded(x, fieldName); - case NOT_EMBEDDED -> this::convertOnWriteSingle; - }; + writeConverter = + switch (embeddedType) { + case EMBEDDED_MAP -> + x -> + convertOnWriteSingleEmbeddedMap( + x, fieldName, typeInformation.getMapValueType()); + case EMBEDDED_ENTITY -> x -> convertOnWriteSingleEmbedded(x, fieldName); + case NOT_EMBEDDED -> this::convertOnWriteSingle; + }; } val = ValueUtil.toListIfArray(val); @@ -289,16 +293,16 @@ private EntityValue applyEntityValueBuilder( builder = FullEntity.newBuilder(); } else { /* The following does 3 sequential null checks. We only want an ID value if the object isn't null, - has an ID property, and the ID property isn't null. - */ + has an ID property, and the ID property isn't null. + */ Optional idProp = Optional.ofNullable(val) .map(v -> this.datastoreMappingContext.getPersistentEntity(v.getClass())) .map(PersistentEntity::getIdProperty) .map( id -> - Objects.requireNonNull(this.datastoreMappingContext - .getPersistentEntity(val.getClass())) + Objects.requireNonNull( + this.datastoreMappingContext.getPersistentEntity(val.getClass())) .getPropertyAccessor(val) .getProperty(id)); @@ -321,8 +325,7 @@ private EntityValue convertOnWriteSingleEmbeddedMap( for (Map.Entry e : ((Map) val).entrySet()) { String field = convertOnReadSingle( - convertOnWriteSingle(e.getKey()).get(), - TypeInformation.of(String.class)); + convertOnWriteSingle(e.getKey()).get(), TypeInformation.of(String.class)); builder.set( field, convertOnWrite( @@ -412,8 +415,7 @@ public void registerEntityConverter(DatastoreEntityConverter datastoreEntityConv this.datastoreEntityConverter = datastoreEntityConverter; } - private record TypeTargets(Class firstStepTarget, - Class secondStepTarget) { + private record TypeTargets(Class firstStepTarget, Class secondStepTarget) { Class getFirstStepTarget() { return this.firstStepTarget; diff --git a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/util/SliceUtil.java b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/util/SliceUtil.java index a71c8cf335..bf5d04ad19 100644 --- a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/util/SliceUtil.java +++ b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/util/SliceUtil.java @@ -20,7 +20,7 @@ import java.util.function.Consumer; /** - * @since 1.2 + * @since 1.2 */ public final class SliceUtil { diff --git a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/config/DatastoreAuditingRegistrar.java b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/config/DatastoreAuditingRegistrar.java index 617e96c941..64321f08c0 100644 --- a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/config/DatastoreAuditingRegistrar.java +++ b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/config/DatastoreAuditingRegistrar.java @@ -59,7 +59,7 @@ protected BeanDefinitionBuilder getAuditHandlerBeanDefinitionBuilder( AuditingConfiguration configuration) { return configureDefaultAuditHandlerAttributes( configuration, BeanDefinitionBuilder.rootBeanDefinition(AuditingHandler.class)) - .addConstructorArgValue(PersistentEntities.of(new DatastoreMappingContext())); + .addConstructorArgValue(PersistentEntities.of(new DatastoreMappingContext())); } @Override diff --git a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/query/GqlDatastoreQuery.java b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/query/GqlDatastoreQuery.java index ce49d16720..6358ed263a 100644 --- a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/query/GqlDatastoreQuery.java +++ b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/query/GqlDatastoreQuery.java @@ -56,11 +56,8 @@ import org.springframework.data.repository.query.ParameterAccessor; import org.springframework.data.repository.query.Parameters; import org.springframework.data.repository.query.ParametersParameterAccessor; -import org.springframework.data.repository.query.SpelEvaluator; -import org.springframework.data.repository.query.SpelQueryContext; import org.springframework.data.repository.query.ValueExpressionDelegate; import org.springframework.data.repository.query.ValueExpressionQueryRewriter; -import org.springframework.expression.spel.standard.SpelCompiler; import org.springframework.util.StringUtils; /** @@ -86,7 +83,8 @@ public class GqlDatastoreQuery extends AbstractDatastoreQuery { private final ValueExpressionDelegate valueExpressionDelegate; - private ValueExpressionQueryRewriter.EvaluatingValueExpressionQueryRewriter valueExpressionQueryRewriter; + private ValueExpressionQueryRewriter.EvaluatingValueExpressionQueryRewriter + valueExpressionQueryRewriter; /** * Constructor. @@ -316,16 +314,19 @@ private void setGqlResolvedEntityClassName() { private void setEvaluatingSpelQueryContext() { Set originalTags = new HashSet<>(GqlDatastoreQuery.this.originalParamTags); - GqlDatastoreQuery.this.valueExpressionQueryRewriter = ValueExpressionQueryRewriter.of(valueExpressionDelegate, - (counter, spelExpression) -> { - String newTag; - do { - counter++; - newTag = "@SpELtag" + counter; - } while (originalTags.contains(newTag)); - originalTags.add(newTag); - return newTag; - }, String::concat) + GqlDatastoreQuery.this.valueExpressionQueryRewriter = + ValueExpressionQueryRewriter.of( + valueExpressionDelegate, + (counter, spelExpression) -> { + String newTag; + do { + counter++; + newTag = "@SpELtag" + counter; + } while (originalTags.contains(newTag)); + originalTags.add(newTag); + return newTag; + }, + String::concat) .withEvaluationContextAccessor(valueExpressionDelegate.getEvaluationContextAccessor()); } diff --git a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactory.java b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactory.java index 26e71c7db3..be484bef0e 100644 --- a/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactory.java +++ b/spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactory.java @@ -25,21 +25,14 @@ import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import org.springframework.context.expression.BeanFactoryAccessor; -import org.springframework.context.expression.BeanFactoryResolver; import org.springframework.data.mapping.MappingException; import org.springframework.data.repository.core.EntityInformation; import org.springframework.data.repository.core.RepositoryInformation; import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.core.support.RepositoryFactorySupport; -import org.springframework.data.repository.query.Parameters; import org.springframework.data.repository.query.QueryLookupStrategy; import org.springframework.data.repository.query.QueryLookupStrategy.Key; -import org.springframework.data.repository.query.QueryMethodEvaluationContextProvider; import org.springframework.data.repository.query.ValueExpressionDelegate; -import org.springframework.data.spel.ExpressionDependencies; -import org.springframework.expression.EvaluationContext; -import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.lang.Nullable; import org.springframework.util.Assert; @@ -103,9 +96,7 @@ protected Optional getQueryLookupStrategy( return Optional.of( new DatastoreQueryLookupStrategy( - this.datastoreMappingContext, - this.datastoreOperations, - valueExpressionDelegate)); + this.datastoreMappingContext, this.datastoreOperations, valueExpressionDelegate)); } @Override diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/aot/TestRuntimeHints.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/aot/TestRuntimeHints.java index 62210a6c4c..34b2303e2e 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/aot/TestRuntimeHints.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/aot/TestRuntimeHints.java @@ -38,9 +38,7 @@ import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.aot.hint.TypeReference; -/** - * Runtime hints for integration test. - */ +/** Runtime hints for integration test. */ public class TestRuntimeHints implements RuntimeHintsRegistrar { @Override @@ -65,12 +63,24 @@ public void registerHints(RuntimeHints hints, ClassLoader classLoader) { TypeReference.of(ServiceConfiguration.class), TypeReference.of(SubEntity.class), TypeReference.of(TreeCollection.class), - TypeReference.of(com.google.cloud.spring.data.datastore.it.subclasses.references.testdomains.EntityA.class), - TypeReference.of(com.google.cloud.spring.data.datastore.it.subclasses.references.testdomains.EntityB.class), - TypeReference.of(com.google.cloud.spring.data.datastore.it.subclasses.references.testdomains.EntityC.class), - TypeReference.of(com.google.cloud.spring.data.datastore.it.subclasses.descendants.testdomains.EntityA.class), - TypeReference.of(com.google.cloud.spring.data.datastore.it.subclasses.descendants.testdomains.EntityB.class), - TypeReference.of(com.google.cloud.spring.data.datastore.it.subclasses.descendants.testdomains.EntityC.class)), + TypeReference.of( + com.google.cloud.spring.data.datastore.it.subclasses.references.testdomains + .EntityA.class), + TypeReference.of( + com.google.cloud.spring.data.datastore.it.subclasses.references.testdomains + .EntityB.class), + TypeReference.of( + com.google.cloud.spring.data.datastore.it.subclasses.references.testdomains + .EntityC.class), + TypeReference.of( + com.google.cloud.spring.data.datastore.it.subclasses.descendants.testdomains + .EntityA.class), + TypeReference.of( + com.google.cloud.spring.data.datastore.it.subclasses.descendants.testdomains + .EntityB.class), + TypeReference.of( + com.google.cloud.spring.data.datastore.it.subclasses.descendants.testdomains + .EntityC.class)), hint -> hint.withMembers( MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplateAuditingTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplateAuditingTests.java index b109fa68be..03a23c08ad 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplateAuditingTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplateAuditingTests.java @@ -155,7 +155,6 @@ private static class TestEntity { @LastModifiedBy String lastUser; - @LastModifiedDate - Instant lastTouched; + @LastModifiedDate Instant lastTouched; } } diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplateTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplateTests.java index b2c8b40431..5e2343711e 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplateTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTemplateTests.java @@ -584,8 +584,7 @@ void saveOrInsertReferenceLoopTest(SaveOrInsertMethod method) { datastorePutOrAddAll(method, ArgumentMatchers.any()), Collections.singletonList(this.e1)); - assertThat(saveOrInsert(method, referenceTestEntity)) - .isInstanceOf(ReferenceTestEntity.class); + assertThat(saveOrInsert(method, referenceTestEntity)).isInstanceOf(ReferenceTestEntity.class); Entity writtenEntity = Entity.newBuilder(this.key1).set("sibling", this.key1).build(); @@ -642,23 +641,24 @@ void saveOrInsertTestCommon(SaveOrInsertMethod method, TestEntity parent, boolea Entity writtenChildEntity7 = Entity.newBuilder(this.childKey7).build(); when(datastorePutOrAddAll(method, ArgumentMatchers.any())) - .thenAnswer(invocation -> { - Object[] arguments = invocation.getArguments(); - assertThat(arguments).contains(writtenEntity); - assertThat(arguments).contains(writtenChildEntity2); - assertThat(arguments).contains(writtenChildEntity3); - assertThat(arguments).contains(writtenChildEntity4); - assertThat(arguments).contains(writtenChildEntity5); - assertThat(arguments).contains(writtenChildEntity6); - if (lazy) { - assertThat(arguments).hasSize(6); - } else { - assertThat(arguments).contains(writtenChildEntity7); - assertThat(arguments).hasSize(7); - } - - return null; - }); + .thenAnswer( + invocation -> { + Object[] arguments = invocation.getArguments(); + assertThat(arguments).contains(writtenEntity); + assertThat(arguments).contains(writtenChildEntity2); + assertThat(arguments).contains(writtenChildEntity3); + assertThat(arguments).contains(writtenChildEntity4); + assertThat(arguments).contains(writtenChildEntity5); + assertThat(arguments).contains(writtenChildEntity6); + if (lazy) { + assertThat(arguments).hasSize(6); + } else { + assertThat(arguments).contains(writtenChildEntity7); + assertThat(arguments).hasSize(7); + } + + return null; + }); assertThat(saveOrInsert(method, parent)).isInstanceOf(TestEntity.class); verifyPutOrAdd(method, times(1)); @@ -702,7 +702,6 @@ void saveOrInsertTestNonKeyId(SaveOrInsertMethod method) { assertThatThrownBy(() -> saveOrInsert(method, this.ob1, testKey)) .isInstanceOf(DatastoreDataException.class) .hasMessage("Only Key types are allowed for descendants id"); - } @ParameterizedTest @@ -787,18 +786,19 @@ void saveOrInsertAndAllocateIdTest(SaveOrInsertMethod method) { Entity writtenChildEntity7 = Entity.newBuilder(this.childKey7).build(); when(datastorePutOrAddAll(method, ArgumentMatchers.any())) - .thenAnswer(invocation -> { - assertThat(invocation.getArguments()) - .containsExactlyInAnyOrder( - writtenChildEntity2, - writtenChildEntity3, - writtenChildEntity4, - writtenChildEntity5, - writtenChildEntity6, - writtenEntity1, - writtenChildEntity7); - return null; - }); + .thenAnswer( + invocation -> { + assertThat(invocation.getArguments()) + .containsExactlyInAnyOrder( + writtenChildEntity2, + writtenChildEntity3, + writtenChildEntity4, + writtenChildEntity5, + writtenChildEntity6, + writtenEntity1, + writtenChildEntity7); + return null; + }); assertThat(saveOrInsert(method, this.ob1)).isInstanceOf(TestEntity.class); verifyPutOrAdd(method, times(1)); @@ -828,19 +828,20 @@ void saveOrInsertAllTest(SaveOrInsertMethod method) { Entity writtenChildEntity7 = Entity.newBuilder(this.childKey7).build(); when(datastorePutOrAddAll(method, ArgumentMatchers.any())) - .thenAnswer(invocation -> { - assertThat(invocation.getArguments()) - .containsExactlyInAnyOrder( - writtenChildEntity2, - writtenChildEntity3, - writtenChildEntity4, - writtenChildEntity5, - writtenChildEntity6, - writtenEntity1, - writtenEntity2, - writtenChildEntity7); - return null; - }); + .thenAnswer( + invocation -> { + assertThat(invocation.getArguments()) + .containsExactlyInAnyOrder( + writtenChildEntity2, + writtenChildEntity3, + writtenChildEntity4, + writtenChildEntity5, + writtenChildEntity6, + writtenEntity1, + writtenEntity2, + writtenChildEntity7); + return null; + }); List expected = Arrays.asList( @@ -902,12 +903,13 @@ void saveOrInsertAllMaxWriteSizeTest(SaveOrInsertMethod method) { writtenEntity1, writtenEntity2)); when(datastorePutOrAddAll(method, ArgumentMatchers.any())) - .thenAnswer(invocation -> { - assertThat(invocation.getArguments()).hasSize(1); - assertThat(entities).contains((Entity) invocation.getArguments()[0]); - entities.remove(invocation.getArguments()[0]); - return null; - }); + .thenAnswer( + invocation -> { + assertThat(invocation.getArguments()).hasSize(1); + assertThat(entities).contains((Entity) invocation.getArguments()[0]); + entities.remove(invocation.getArguments()[0]); + return null; + }); List expected = Arrays.asList( @@ -949,8 +951,8 @@ private T saveOrInsert(SaveOrInsertMethod method, T instance, Key... ancesto } } - private Iterable saveOrInsertAll(SaveOrInsertMethod method, Iterable entities, - Key... ancestors) { + private Iterable saveOrInsertAll( + SaveOrInsertMethod method, Iterable entities, Key... ancestors) { if (SaveOrInsertMethod.SAVE == method) { return this.datastoreTemplate.saveAll(entities, ancestors); } else { @@ -975,7 +977,8 @@ private void verifyPutOrAdd(SaveOrInsertMethod method, VerificationMode verifica } private enum SaveOrInsertMethod { - SAVE, INSERT; + SAVE, + INSERT; } @Test @@ -1055,10 +1058,11 @@ void countTest() { when(aggregationResults.iterator()).thenReturn(List.of(aggregationResult).iterator()); KeyQuery baseQuery = Query.newKeyQueryBuilder().setKind("custom_test_kind").build(); - AggregationQuery countAggregationQuery = Query.newAggregationQueryBuilder() - .over(baseQuery) - .addAggregation(Aggregation.count().as("total_count")) - .build(); + AggregationQuery countAggregationQuery = + Query.newAggregationQueryBuilder() + .over(baseQuery) + .addAggregation(Aggregation.count().as("total_count")) + .build(); when(this.datastore.runAggregation(argThat(equalsTo(countAggregationQuery)))) .thenReturn(aggregationResults); @@ -1068,7 +1072,9 @@ void countTest() { private ArgumentMatcher equalsTo(AggregationQuery expectedAggregationQuery) { return actualAggregationQuery -> expectedAggregationQuery.getAggregations().equals(actualAggregationQuery.getAggregations()) - && expectedAggregationQuery.getNestedStructuredQuery().equals(actualAggregationQuery.getNestedStructuredQuery()); + && expectedAggregationQuery + .getNestedStructuredQuery() + .equals(actualAggregationQuery.getNestedStructuredQuery()); } @Test @@ -1318,10 +1324,11 @@ void queryByExampleIgnoreFieldTest() { @Test void queryByExampleDeepPathTest() { - Example testExample = Example.of(new SimpleTestEntity(), ExampleMatcher.matching().withIgnorePaths("intField.a")); + Example testExample = + Example.of(new SimpleTestEntity(), ExampleMatcher.matching().withIgnorePaths("intField.a")); assertThatThrownBy(() -> this.datastoreTemplate.queryByExample(testExample, null)) - .hasMessage("Ignored paths deeper than 1 are not supported") - .isInstanceOf(DatastoreDataException.class); + .hasMessage("Ignored paths deeper than 1 are not supported") + .isInstanceOf(DatastoreDataException.class); } @Test @@ -1354,19 +1361,23 @@ void queryByExampleNoNullValuesTest() { @Test void queryByExampleExactMatchTest() { - Example testExample = Example.of(new SimpleTestEntity(), ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.REGEX)); + Example testExample = + Example.of( + new SimpleTestEntity(), + ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.REGEX)); assertThatThrownBy(() -> this.datastoreTemplate.queryByExample(testExample, null)) - .hasMessage("Unsupported StringMatcher. Only EXACT and DEFAULT are supported") - .isInstanceOf(DatastoreDataException.class); + .hasMessage("Unsupported StringMatcher. Only EXACT and DEFAULT are supported") + .isInstanceOf(DatastoreDataException.class); } @Test void queryByExampleIgnoreCaseTest() { - Example testExample = Example.of(new SimpleTestEntity(), ExampleMatcher.matching().withIgnoreCase()); + Example testExample = + Example.of(new SimpleTestEntity(), ExampleMatcher.matching().withIgnoreCase()); assertThatThrownBy(() -> this.datastoreTemplate.queryByExample(testExample, null)) - .hasMessage("Ignore case matching is not supported") - .isInstanceOf(DatastoreDataException.class); + .hasMessage("Ignore case matching is not supported") + .isInstanceOf(DatastoreDataException.class); } @Test @@ -1374,42 +1385,44 @@ void queryByExampleAllMatchTest() { Example testExample = Example.of(new SimpleTestEntity(), ExampleMatcher.matchingAny()); assertThatThrownBy(() -> this.datastoreTemplate.queryByExample(testExample, null)) - .hasMessage("Unsupported MatchMode. Only MatchMode.ALL is supported") - .isInstanceOf(DatastoreDataException.class); + .hasMessage("Unsupported MatchMode. Only MatchMode.ALL is supported") + .isInstanceOf(DatastoreDataException.class); } @Test void queryByExamplePropertyMatchersTest() { - Example testExample = Example.of( + Example testExample = + Example.of( new SimpleTestEntity(), ExampleMatcher.matching() - .withMatcher( - "id", - ExampleMatcher.GenericPropertyMatcher.of(ExampleMatcher.StringMatcher.REGEX))); - assertThatThrownBy(() -> this.datastoreTemplate.queryByExample(testExample, null)) - .hasMessage("Property matchers are not supported") - .isInstanceOf(DatastoreDataException.class); + .withMatcher( + "id", + ExampleMatcher.GenericPropertyMatcher.of(ExampleMatcher.StringMatcher.REGEX))); + assertThatThrownBy(() -> this.datastoreTemplate.queryByExample(testExample, null)) + .hasMessage("Property matchers are not supported") + .isInstanceOf(DatastoreDataException.class); } @Test void queryByExampleCaseSensitiveTest() { - Example testExample = Example.of( + Example testExample = + Example.of( new SimpleTestEntity(), ExampleMatcher.matching() - .withMatcher("id", ExampleMatcher.GenericPropertyMatcher::caseSensitive)); + .withMatcher("id", ExampleMatcher.GenericPropertyMatcher::caseSensitive)); assertThatThrownBy(() -> this.datastoreTemplate.queryByExample(testExample, null)) - .hasMessage("Property matchers are not supported") - .isInstanceOf(DatastoreDataException.class); + .hasMessage("Property matchers are not supported") + .isInstanceOf(DatastoreDataException.class); } @Test void queryByExampleNullTest() { assertThatThrownBy(() -> this.datastoreTemplate.queryByExample(null, null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A non-null example is expected"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-null example is expected"); } @Test @@ -1481,8 +1494,7 @@ private static class TestEntity { @Reference LinkedList multipleReference; - @LazyReference - List lazyMultipleReference; + @LazyReference List lazyMultipleReference; @Override public boolean equals(Object o) { diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTransactionManagerTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTransactionManagerTests.java index f357a3eb50..4efb0b31b2 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTransactionManagerTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTransactionManagerTests.java @@ -107,9 +107,9 @@ void testDoCommitFailure() { this.tx.setTransaction(this.transaction); assertThatThrownBy(() -> this.manager.doCommit(this.status)) - .isInstanceOf(TransactionSystemException.class) - .hasMessage("Cloud Datastore transaction failed to commit.") - .hasCause(exception); + .isInstanceOf(TransactionSystemException.class) + .hasMessage("Cloud Datastore transaction failed to commit.") + .hasCause(exception); } @Test @@ -136,9 +136,9 @@ void testDoRollbackFailure() { this.tx.setTransaction(this.transaction); assertThatThrownBy(() -> this.manager.doRollback(this.status)) - .isInstanceOf(TransactionSystemException.class) - .hasMessage("Cloud Datastore transaction failed to rollback.") - .hasCause(exception); + .isInstanceOf(TransactionSystemException.class) + .hasMessage("Cloud Datastore transaction failed to rollback.") + .hasCause(exception); } @Test diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTransactionTemplateTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTransactionTemplateTests.java index d2149d1fec..c7ab00cb2f 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTransactionTemplateTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/DatastoreTransactionTemplateTests.java @@ -144,18 +144,20 @@ void doWithoutTransactionTest() { void unsupportedIsolationTest() { assertThatThrownBy(() -> this.transactionalService.doNothingUnsupportedIsolation()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("DatastoreTransactionManager supports only " - + "isolation level TransactionDefinition.ISOLATION_DEFAULT or ISOLATION_SERIALIZABLE"); + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "DatastoreTransactionManager supports only " + + "isolation level TransactionDefinition.ISOLATION_DEFAULT or ISOLATION_SERIALIZABLE"); } @Test void unsupportedPropagationTest() { assertThatThrownBy(() -> this.transactionalService.doNothingUnsupportedPropagation()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("DatastoreTransactionManager supports only " - + "propagation behavior TransactionDefinition.PROPAGATION_REQUIRED"); + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "DatastoreTransactionManager supports only " + + "propagation behavior TransactionDefinition.PROPAGATION_REQUIRED"); } /** Spring config for the tests. */ diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/DatastoreServiceObjectToKeyFactoryTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/DatastoreServiceObjectToKeyFactoryTests.java index 0bf821c6a9..e609f4b17a 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/DatastoreServiceObjectToKeyFactoryTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/DatastoreServiceObjectToKeyFactoryTests.java @@ -68,9 +68,10 @@ void getKeyFromIdLongTest() { @Test void getKeyFromIdExceptionTest() { when(this.datastore.newKeyFactory()).thenReturn(new KeyFactory("p").setKind("k")); - assertThatThrownBy(() -> this.datastoreServiceObjectToKeyFactory.getKeyFromId(true, "custom_test_kind")) - .isInstanceOf(DatastoreDataException.class) - .hasMessage("Keys can only be created using String or long values."); + assertThatThrownBy( + () -> this.datastoreServiceObjectToKeyFactory.getKeyFromId(true, "custom_test_kind")) + .isInstanceOf(DatastoreDataException.class) + .hasMessage("Keys can only be created using String or long values."); } @Test @@ -90,14 +91,17 @@ void getKeyTest() { @Test void getKeyNoIdTest() { - DatastorePersistentEntity dpeTest = this.datastoreMappingContext.getPersistentEntity(TestEntityNoId.class); + DatastorePersistentEntity dpeTest = + this.datastoreMappingContext.getPersistentEntity(TestEntityNoId.class); Object entity = new TestEntityNoId(); - assertThatThrownBy(() -> this.datastoreServiceObjectToKeyFactory.getKeyFromObject(entity, dpeTest)) - .isInstanceOf(DatastoreDataException.class) - .hasMessage("An ID property was required but does not exist for the type: " - + "class com.google.cloud.spring.data.datastore.core.convert." - + "DatastoreServiceObjectToKeyFactoryTests$TestEntityNoId"); + assertThatThrownBy( + () -> this.datastoreServiceObjectToKeyFactory.getKeyFromObject(entity, dpeTest)) + .isInstanceOf(DatastoreDataException.class) + .hasMessage( + "An ID property was required but does not exist for the type: " + + "class com.google.cloud.spring.data.datastore.core.convert." + + "DatastoreServiceObjectToKeyFactoryTests$TestEntityNoId"); } @Test @@ -155,13 +159,17 @@ void allocateIdForObjectNonKeyIdTest() { KeyFactory keyFactory = new KeyFactory("project").setKind("kind"); Key testKey = keyFactory.newKey("ancestor"); - DatastorePersistentEntity dpeTest = this.datastoreMappingContext.getPersistentEntity(testEntityWithId.getClass()); + DatastorePersistentEntity dpeTest = + this.datastoreMappingContext.getPersistentEntity(testEntityWithId.getClass()); when(this.datastore.newKeyFactory()).thenReturn(keyFactory); - assertThatThrownBy(() -> this.datastoreServiceObjectToKeyFactory.allocateKeyForObject(testEntityWithId, dpeTest, testKey)) - .isInstanceOf(DatastoreDataException.class) - .hasMessage("Only Key types are allowed for descendants id"); + assertThatThrownBy( + () -> + this.datastoreServiceObjectToKeyFactory.allocateKeyForObject( + testEntityWithId, dpeTest, testKey)) + .isInstanceOf(DatastoreDataException.class) + .hasMessage("Only Key types are allowed for descendants id"); } @Test @@ -171,12 +179,17 @@ void allocateIdForObjectUnsupportedKeyTypeIdTest() { KeyFactory keyFactory = new KeyFactory("project").setKind("kind"); Key testKey = keyFactory.newKey("key"); when(this.datastore.newKeyFactory()).thenReturn(keyFactory); - DatastorePersistentEntity dpeTest = this.datastoreMappingContext.getPersistentEntity(testEntityWithStringId.getClass()); - - assertThatThrownBy(() -> this.datastoreServiceObjectToKeyFactory.allocateKeyForObject(testEntityWithStringId, dpeTest, testKey)) - .isInstanceOf(DatastoreDataException.class) - .hasMessage("Cloud Datastore can only allocate IDs for Long and Key properties. " - + "Cannot allocate for type: class java.lang.String"); + DatastorePersistentEntity dpeTest = + this.datastoreMappingContext.getPersistentEntity(testEntityWithStringId.getClass()); + + assertThatThrownBy( + () -> + this.datastoreServiceObjectToKeyFactory.allocateKeyForObject( + testEntityWithStringId, dpeTest, testKey)) + .isInstanceOf(DatastoreDataException.class) + .hasMessage( + "Cloud Datastore can only allocate IDs for Long and Key properties. " + + "Cannot allocate for type: class java.lang.String"); } @com.google.cloud.spring.data.datastore.core.mapping.Entity(name = "custom_test_kind") diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/DefaultDatastoreEntityConverterTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/DefaultDatastoreEntityConverterTests.java index a6d14b2906..8b8d31347c 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/DefaultDatastoreEntityConverterTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/DefaultDatastoreEntityConverterTests.java @@ -197,8 +197,10 @@ void conflictingDiscriminationTest() { .build(); assertThatThrownBy(() -> ENTITY_CONVERTER.read(DiscrimEntityY.class, entityY)) - .isInstanceOf(DatastoreDataException.class) - .hasMessageContaining("More than one class in an inheritance hierarchy " + "has the same DiscriminatorValue: "); + .isInstanceOf(DatastoreDataException.class) + .hasMessageContaining( + "More than one class in an inheritance hierarchy " + + "has the same DiscriminatorValue: "); } @Test @@ -225,13 +227,16 @@ void readNullTest() { @Test void testWrongTypeReadException() { - Entity entity = getEntityBuilder().set("stringField", "string value").set("boolField", 123L).build(); + Entity entity = + getEntityBuilder().set("stringField", "string value").set("boolField", 123L).build(); assertThatThrownBy(() -> ENTITY_CONVERTER.read(TestDatastoreItem.class, entity)) - .isInstanceOf(DatastoreDataException.class) - .hasMessageContaining("Unable to read " - + "com.google.cloud.spring.data.datastore.core.convert.TestDatastoreItem entity") - .hasStackTraceContaining("Unable to read property boolField") - .hasStackTraceContaining("Unable to convert class java.lang.Long to class java.lang.Boolean"); + .isInstanceOf(DatastoreDataException.class) + .hasMessageContaining( + "Unable to read " + + "com.google.cloud.spring.data.datastore.core.convert.TestDatastoreItem entity") + .hasStackTraceContaining("Unable to read property boolField") + .hasStackTraceContaining( + "Unable to convert class java.lang.Long to class java.lang.Boolean"); } @Test @@ -241,8 +246,8 @@ void testObjectEntityException() { getEntityBuilder().set("stringField", "string value").set("boolField", 123L).build(); assertThatThrownBy(() -> ENTITY_CONVERTER.read(Object.class, entity)) - .isInstanceOf(DatastoreDataException.class) - .hasMessage("Unable to convert Datastore Entity to class java.lang.Object"); + .isInstanceOf(DatastoreDataException.class) + .hasMessage("Unable to convert Datastore Entity to class java.lang.Object"); } @Test @@ -255,12 +260,14 @@ void testWrongTypeReadExceptionList() { .build(); assertThatThrownBy(() -> ENTITY_CONVERTER.read(TestDatastoreItem.class, entity)) - .isInstanceOf(DatastoreDataException.class) - .hasMessageContaining("Unable to read " - + "com.google.cloud.spring.data.datastore.core.convert.TestDatastoreItem entity") - .hasStackTraceContaining("Unable to read property boolField") - .hasStackTraceContaining("Unable to convert class " - + "com.google.common.collect.SingletonImmutableList to class java.lang.Boolean"); + .isInstanceOf(DatastoreDataException.class) + .hasMessageContaining( + "Unable to read " + + "com.google.cloud.spring.data.datastore.core.convert.TestDatastoreItem entity") + .hasStackTraceContaining("Unable to read property boolField") + .hasStackTraceContaining( + "Unable to convert class " + + "com.google.common.collect.SingletonImmutableList to class java.lang.Boolean"); } @Test @@ -363,11 +370,12 @@ void testUnsupportedTypeWriteException() { Entity.Builder builder = getEntityBuilder(); assertThatThrownBy(() -> ENTITY_CONVERTER.write(item, builder)) - .isInstanceOf(DatastoreDataException.class) - .hasMessageContaining("Unable to write testItemUnsupportedFields.unsupportedField") - .hasStackTraceContaining("Unable to convert class " - + "com.google.cloud.spring.data.datastore.core.convert." - + "TestItemUnsupportedFields$NewType to Datastore supported type."); + .isInstanceOf(DatastoreDataException.class) + .hasMessageContaining("Unable to write testItemUnsupportedFields.unsupportedField") + .hasStackTraceContaining( + "Unable to convert class " + + "com.google.cloud.spring.data.datastore.core.convert." + + "TestItemUnsupportedFields$NewType to Datastore supported type."); } @Test @@ -402,7 +410,8 @@ void testUnsupportedTypeWrite() { @Test void testCollectionFieldsUnsupportedCollection() { - ComparableBeanContextSupport comparableBeanContextSupport = new ComparableBeanContextSupport<>(); + ComparableBeanContextSupport comparableBeanContextSupport = + new ComparableBeanContextSupport<>(); comparableBeanContextSupport.add("this implementation of Collection"); comparableBeanContextSupport.add("is unsupported out of the box!"); @@ -420,13 +429,15 @@ void testCollectionFieldsUnsupportedCollection() { Entity entity = builder.build(); assertThatThrownBy(() -> ENTITY_CONVERTER.read(TestDatastoreItemCollections.class, entity)) - .isInstanceOf(DatastoreDataException.class) - .hasMessageContaining("Unable to read" - + " com.google.cloud.spring.data.datastore.core.convert.TestDatastoreItemCollections" - + " entity") - .hasStackTraceContaining("Unable to read property beanContext") - .hasStackTraceContaining("Failed to convert from type [java.util.ImmutableCollections$ListN] to type" - + " [com.google.cloud.spring.data.datastore.core.convert.TestDatastoreItemCollections$ComparableBeanContextSupport]"); + .isInstanceOf(DatastoreDataException.class) + .hasMessageContaining( + "Unable to read" + + " com.google.cloud.spring.data.datastore.core.convert.TestDatastoreItemCollections" + + " entity") + .hasStackTraceContaining("Unable to read property beanContext") + .hasStackTraceContaining( + "Failed to convert from type [java.util.ImmutableCollections$ListN] to type" + + " [com.google.cloud.spring.data.datastore.core.convert.TestDatastoreItemCollections$ComparableBeanContextSupport]"); } @Test @@ -548,11 +559,12 @@ void testCollectionFieldsUnsupported() { Entity.Builder builder = getEntityBuilder(); assertThatThrownBy(() -> ENTITY_CONVERTER.write(item, builder)) - .isInstanceOf(DatastoreDataException.class) - .hasMessageContaining("Unable to write collectionOfUnsupportedTypes.unsupportedElts") - .hasStackTraceContaining("Unable to convert " - + "class com.google.cloud.spring.data.datastore.core.convert." - + "TestItemUnsupportedFields$NewType to Datastore supported type."); + .isInstanceOf(DatastoreDataException.class) + .hasMessageContaining("Unable to write collectionOfUnsupportedTypes.unsupportedElts") + .hasStackTraceContaining( + "Unable to convert " + + "class com.google.cloud.spring.data.datastore.core.convert." + + "TestItemUnsupportedFields$NewType to Datastore supported type."); } @Test @@ -582,7 +594,8 @@ void testCollectionFieldsUnsupportedWriteOnly() { @Test void testCollectionFieldsUnsupportedWriteReadException() { - TestItemUnsupportedFields.CollectionOfUnsupportedTypes item = getCollectionOfUnsupportedTypesItem(); + TestItemUnsupportedFields.CollectionOfUnsupportedTypes item = + getCollectionOfUnsupportedTypesItem(); DatastoreEntityConverter entityConverter = new DefaultDatastoreEntityConverter( @@ -600,14 +613,16 @@ void testCollectionFieldsUnsupportedWriteReadException() { Class parameter = TestItemUnsupportedFields.CollectionOfUnsupportedTypes.class; assertThatThrownBy(() -> entityConverter.read(parameter, entity)) - .hasStackTraceContaining("Unable to read property unsupportedElts") - .hasStackTraceContaining("Unable process elements of a collection") - .hasStackTraceContaining("No converter found capable of converting from type [java.lang.Integer] " - + "to type [com.google.cloud.spring.data.datastore.core.convert." - + "TestItemUnsupportedFields$NewType]") - .hasStackTraceContaining("Unable to read com.google.cloud.spring.data.datastore.core.convert." - + "TestItemUnsupportedFields$CollectionOfUnsupportedTypes entity") - .isInstanceOf(DatastoreDataException.class); + .hasStackTraceContaining("Unable to read property unsupportedElts") + .hasStackTraceContaining("Unable process elements of a collection") + .hasStackTraceContaining( + "No converter found capable of converting from type [java.lang.Integer] " + + "to type [com.google.cloud.spring.data.datastore.core.convert." + + "TestItemUnsupportedFields$NewType]") + .hasStackTraceContaining( + "Unable to read com.google.cloud.spring.data.datastore.core.convert." + + "TestItemUnsupportedFields$CollectionOfUnsupportedTypes entity") + .isInstanceOf(DatastoreDataException.class); } @Test @@ -892,21 +907,25 @@ void privateCustomMapExceptionTest() { @Test void testMismatchedStringIdLongProperty() { - Entity testEntity = Entity.newBuilder(this.datastore.newKeyFactory().setKind("aKind").newKey("a")).build(); + Entity testEntity = + Entity.newBuilder(this.datastore.newKeyFactory().setKind("aKind").newKey("a")).build(); assertThatThrownBy(() -> ENTITY_CONVERTER.read(LongIdEntity.class, testEntity)) - .isInstanceOf(ConversionFailedException.class) - .hasStackTraceContaining("The given key doesn't have a numeric ID but a conversion to Long was attempted"); + .isInstanceOf(ConversionFailedException.class) + .hasStackTraceContaining( + "The given key doesn't have a numeric ID but a conversion to Long was attempted"); } @Test void testMismatchedLongIdStringProperty() { - Entity testEntity = Entity.newBuilder(this.datastore.newKeyFactory().setKind("aKind").newKey(1)).build(); + Entity testEntity = + Entity.newBuilder(this.datastore.newKeyFactory().setKind("aKind").newKey(1)).build(); assertThatThrownBy(() -> ENTITY_CONVERTER.read(StringIdEntity.class, testEntity)) - .isInstanceOf(ConversionFailedException.class) - .hasStackTraceContaining("The given key doesn't have a String name value but a conversion to String was attempted"); + .isInstanceOf(ConversionFailedException.class) + .hasStackTraceContaining( + "The given key doesn't have a String name value but a conversion to String was attempted"); } private Entity.Builder getEntityBuilder() { diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/EntityPropertyValueProviderTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/EntityPropertyValueProviderTests.java index 19c91d5cc8..99b3152e9b 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/EntityPropertyValueProviderTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/convert/EntityPropertyValueProviderTests.java @@ -126,8 +126,9 @@ void testException() { DatastorePersistentProperty testDpe = this.persistentEntity.getPersistentProperty("boolField"); assertThatThrownBy(() -> provider.getPropertyValue(testDpe)) - .isInstanceOf(DatastoreDataException.class) - .hasMessageContaining("Unable to read property boolField") - .hasStackTraceContaining("Unable to convert class java.lang.Long to class java.lang.Boolean"); + .isInstanceOf(DatastoreDataException.class) + .hasMessageContaining("Unable to read property boolField") + .hasStackTraceContaining( + "Unable to convert class java.lang.Long to class java.lang.Boolean"); } } diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/mapping/DatastorePersistentEntityImplTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/mapping/DatastorePersistentEntityImplTests.java index e15f6a51ad..787c391c50 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/mapping/DatastorePersistentEntityImplTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/mapping/DatastorePersistentEntityImplTests.java @@ -46,8 +46,7 @@ void testTableName() { @Test void testRawTableName() { DatastorePersistentEntityImpl entity = - new DatastorePersistentEntityImpl<>( - TypeInformation.of(EntityNoCustomName.class), null); + new DatastorePersistentEntityImpl<>(TypeInformation.of(EntityNoCustomName.class), null); assertThat(entity.kindName()).isEqualTo("entityNoCustomName"); } @@ -55,8 +54,7 @@ void testRawTableName() { @Test void testEmptyCustomTableName() { DatastorePersistentEntityImpl entity = - new DatastorePersistentEntityImpl<>( - TypeInformation.of(EntityEmptyCustomName.class), null); + new DatastorePersistentEntityImpl<>(TypeInformation.of(EntityEmptyCustomName.class), null); assertThat(entity.kindName()).isEqualTo("entityEmptyCustomName"); } @@ -64,19 +62,17 @@ void testEmptyCustomTableName() { @Test void testExpressionResolutionWithoutApplicationContext() { DatastorePersistentEntityImpl entity = - new DatastorePersistentEntityImpl<>( - TypeInformation.of(EntityWithExpression.class), null); + new DatastorePersistentEntityImpl<>(TypeInformation.of(EntityWithExpression.class), null); assertThatThrownBy(entity::kindName) - .isInstanceOf(SpelEvaluationException.class) - .hasMessageContaining("Property or field 'kindPostfix' cannot be found on null"); + .isInstanceOf(SpelEvaluationException.class) + .hasMessageContaining("Property or field 'kindPostfix' cannot be found on null"); } @Test void testExpressionResolutionFromApplicationContext() { DatastorePersistentEntityImpl entity = - new DatastorePersistentEntityImpl<>( - TypeInformation.of(EntityWithExpression.class), null); + new DatastorePersistentEntityImpl<>(TypeInformation.of(EntityWithExpression.class), null); ApplicationContext applicationContext = mock(ApplicationContext.class); when(applicationContext.getBean("kindPostfix")).thenReturn("something"); @@ -102,15 +98,15 @@ void testHasNoIdProperty() { @Test void testGetIdPropertyOrFail() { - DatastorePersistentEntity testEntity = new DatastoreMappingContext().getPersistentEntity(EntityWithNoId.class); + DatastorePersistentEntity testEntity = + new DatastoreMappingContext().getPersistentEntity(EntityWithNoId.class); assertThatThrownBy(testEntity::getIdPropertyOrFail) - .isInstanceOf(DatastoreDataException.class) - .hasMessage("An ID property was required but does not exist for the type: " - + "class com.google.cloud.spring.data.datastore.core.mapping." - + "DatastorePersistentEntityImplTests$EntityWithNoId"); - - + .isInstanceOf(DatastoreDataException.class) + .hasMessage( + "An ID property was required but does not exist for the type: " + + "class com.google.cloud.spring.data.datastore.core.mapping." + + "DatastorePersistentEntityImplTests$EntityWithNoId"); } @Test @@ -164,25 +160,27 @@ void testDiscriminationMetadata() { void testConflictingDiscriminationFieldNames() { assertThatThrownBy(() -> this.datastoreMappingContext.getPersistentEntity(DiscrimEntityB.class)) - .isInstanceOf(DatastoreDataException.class) - .hasMessageContaining("This class and its super class both have " - + "discrimination fields but they are different fields: "); - + .isInstanceOf(DatastoreDataException.class) + .hasMessageContaining( + "This class and its super class both have " + + "discrimination fields but they are different fields: "); } @Test void testEntityMissingDiscriminationSuperclass() { - DatastorePersistentEntity dpe = this.datastoreMappingContext.getPersistentEntity(TestEntityNoSuperclass.class); + DatastorePersistentEntity dpe = + this.datastoreMappingContext.getPersistentEntity(TestEntityNoSuperclass.class); assertThatThrownBy(() -> dpe.kindName()) - .isInstanceOf(DatastoreDataException.class) - .hasMessageContaining("This class expects a discrimination field but none are designated"); + .isInstanceOf(DatastoreDataException.class) + .hasMessageContaining("This class expects a discrimination field but none are designated"); } @Test void testInterfaceProperty() { - DatastorePersistentEntity persistentEntity = new DatastoreMappingContext().getPersistentEntity(EntityWithInterface.class); + DatastorePersistentEntity persistentEntity = + new DatastoreMappingContext().getPersistentEntity(EntityWithInterface.class); assertThat(persistentEntity).isNotNull(); assertThat(persistentEntity.getPersistentProperty("text")).isNotNull(); } diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/mapping/DatastorePersistentPropertyImplTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/mapping/DatastorePersistentPropertyImplTests.java index 7504c5ddc1..957156d807 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/mapping/DatastorePersistentPropertyImplTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/core/mapping/DatastorePersistentPropertyImplTests.java @@ -89,38 +89,52 @@ void testAssociations() { @Test void referenceDescendantAnnotatedTest() { - assertThatThrownBy(() -> this.datastoreMappingContext.getPersistentEntity(DescendantReferenceAnnotatedEntity.class)) - .isInstanceOf(DatastoreDataException.class) - .hasMessage("Property cannot be annotated both @Descendants and " + "@Reference: subEntity"); + assertThatThrownBy( + () -> + this.datastoreMappingContext.getPersistentEntity( + DescendantReferenceAnnotatedEntity.class)) + .isInstanceOf(DatastoreDataException.class) + .hasMessage( + "Property cannot be annotated both @Descendants and " + "@Reference: subEntity"); } @Test void fieldDescendantAnnotatedTest() { - assertThatThrownBy(() -> this.datastoreMappingContext.getPersistentEntity(DescendantFieldAnnotatedEntity.class)) - .isInstanceOf(DatastoreDataException.class) - .hasMessage("Property cannot be annotated as @Field if it is " - + "annotated @Descendants or @Reference: name"); + assertThatThrownBy( + () -> + this.datastoreMappingContext.getPersistentEntity( + DescendantFieldAnnotatedEntity.class)) + .isInstanceOf(DatastoreDataException.class) + .hasMessage( + "Property cannot be annotated as @Field if it is " + + "annotated @Descendants or @Reference: name"); } @Test void fieldReferenceAnnotatedTest() { - assertThatThrownBy(() -> this.datastoreMappingContext.getPersistentEntity(FieldReferenceAnnotatedEntity.class)) - .isInstanceOf(DatastoreDataException.class) - .hasMessage("Property cannot be annotated as @Field if it is " - + "annotated @Descendants or @Reference: name"); - + assertThatThrownBy( + () -> + this.datastoreMappingContext.getPersistentEntity( + FieldReferenceAnnotatedEntity.class)) + .isInstanceOf(DatastoreDataException.class) + .hasMessage( + "Property cannot be annotated as @Field if it is " + + "annotated @Descendants or @Reference: name"); } @Test void fieldReferencedAnnotatedTest() { - assertThatThrownBy(() -> this.datastoreMappingContext.getPersistentEntity(FieldReferencedAnnotatedEntity.class)) - .isInstanceOf(DatastoreDataException.class) - .hasMessage("Property cannot be annotated as @Field if it is " - + "annotated @Descendants or @Reference: name"); - + assertThatThrownBy( + () -> + this.datastoreMappingContext.getPersistentEntity( + FieldReferencedAnnotatedEntity.class)) + .isInstanceOf(DatastoreDataException.class) + .hasMessage( + "Property cannot be annotated as @Field if it is " + + "annotated @Descendants or @Reference: name"); } @Entity(name = "custom_test_kind") diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/DatastoreIntegrationTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/DatastoreIntegrationTests.java index 9fabfdc68a..b960b7f92b 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/DatastoreIntegrationTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/DatastoreIntegrationTests.java @@ -693,7 +693,8 @@ void ancestorsTest() { void referenceTest() { ReferenceEntity parent = saveReferenceEntitiesGraph(); - ReferenceEntity loadedParent = this.datastoreTemplate.findById(parent.id, ReferenceEntity.class); + ReferenceEntity loadedParent = + this.datastoreTemplate.findById(parent.id, ReferenceEntity.class); assertThat(loadedParent).isEqualTo(parent); parent.name = "parent updated"; @@ -718,7 +719,8 @@ void referenceTest() { void lazyReferenceCollectionTest() { ReferenceLazyEntity parent = saveEntitiesGraph(); - ReferenceLazyEntity lazyParent = this.datastoreTemplate.findById(parent.id, ReferenceLazyEntity.class); + ReferenceLazyEntity lazyParent = + this.datastoreTemplate.findById(parent.id, ReferenceLazyEntity.class); // Saving an entity with not loaded lazy field this.datastoreTemplate.save(lazyParent); @@ -766,7 +768,8 @@ void lazyReferenceTransactionTest() { // Exception should be produced if a lazy loaded property accessed outside of the initial // transaction - ReferenceLazyEntity finalLoadedParent = this.transactionalTemplateService.findByIdLazy(parent.id); + ReferenceLazyEntity finalLoadedParent = + this.transactionalTemplateService.findByIdLazy(parent.id); assertThatThrownBy(() -> finalLoadedParent.children.size()) .isInstanceOf(DatastoreDataException.class) .hasMessage("Lazy load should be invoked within the same transaction"); @@ -1016,8 +1019,6 @@ void sameClassDescendantsTest() { assertThat(readCompany.leaders.get(0).id).isEqualTo(entity1.id); } - - @Test void testPageableGqlEntityProjectionsPage() { Page page = diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/ParallelDatastoreIntegrationTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/ParallelDatastoreIntegrationTests.java index 1fe39482fe..278e544b86 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/ParallelDatastoreIntegrationTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/ParallelDatastoreIntegrationTests.java @@ -40,8 +40,7 @@ class ParallelDatastoreIntegrationTests extends AbstractDatastoreIntegrationTest private static final int PARALLEL_OPERATIONS = 10; - @Autowired - TestEntityRepository testEntityRepository; + @Autowired TestEntityRepository testEntityRepository; @AfterEach void deleteAll() { @@ -51,9 +50,9 @@ void deleteAll() { @Test void testParallelOperations() { performOperation( - x -> - this.testEntityRepository.save( - new TestEntity((long) x, "color", (long) x, null, null))); + x -> + this.testEntityRepository.save( + new TestEntity((long) x, "color", (long) x, null, null))); waitUntilTrue(() -> this.testEntityRepository.count() == PARALLEL_OPERATIONS - 1); diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/descendants/testdomains/EntityA.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/descendants/testdomains/EntityA.java index 8b47edf6ec..259bf9713a 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/descendants/testdomains/EntityA.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/descendants/testdomains/EntityA.java @@ -24,8 +24,7 @@ @Entity(name = "A") @DiscriminatorField(field = "type") public abstract class EntityA { - @Id - private Key id; + @Id private Key id; public Key getId() { return id; diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/AncestorEntity.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/AncestorEntity.java index 21bb8a255d..d9195b5b0c 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/AncestorEntity.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/AncestorEntity.java @@ -25,13 +25,11 @@ /** An ancestor entity for integration tests. */ public class AncestorEntity { - @Id - public Long id; + @Id public Long id; String name; - @Descendants - public List descendants; + @Descendants public List descendants; public AncestorEntity(String name, List descendants) { this.name = name; diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/Event.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/Event.java index fd713d594f..560d160923 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/Event.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/Event.java @@ -23,8 +23,7 @@ @Entity public class Event { - @Id - private String eventName; + @Id private String eventName; private Map preferences; diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/LazyEntity.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/LazyEntity.java index 75e738cc05..c7a1ddc757 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/LazyEntity.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/LazyEntity.java @@ -23,8 +23,7 @@ @Entity public class LazyEntity { - @Id - public Long id; + @Id public Long id; @LazyReference LazyEntity lazyChild; diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/ReferenceLazyEntity.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/ReferenceLazyEntity.java index 5470c1d3cb..0dbaf03f1a 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/ReferenceLazyEntity.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/testdomains/ReferenceLazyEntity.java @@ -34,7 +34,8 @@ public class ReferenceLazyEntity { @LazyReference public List children; - public ReferenceLazyEntity(String name, ReferenceLazyEntity sibling, List children) { + public ReferenceLazyEntity( + String name, ReferenceLazyEntity sibling, List children) { this.name = name; this.sibling = sibling; this.children = children; diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/DatastoreQueryLookupStrategyTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/DatastoreQueryLookupStrategyTests.java index 5ee49ebbae..5b9e709e50 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/DatastoreQueryLookupStrategyTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/DatastoreQueryLookupStrategyTests.java @@ -87,7 +87,8 @@ void resolveSqlQueryTest() { when(namedQueries.hasQuery(queryName)).thenReturn(true); when(namedQueries.getQuery(queryName)).thenReturn(query); - when(valueExpressionDelegate.getEvaluationContextAccessor()).thenReturn(mock(QueryMethodValueEvaluationContextAccessor.class)); + when(valueExpressionDelegate.getEvaluationContextAccessor()) + .thenReturn(mock(QueryMethodValueEvaluationContextAccessor.class)); this.datastoreQueryLookupStrategy.resolveQuery(null, null, null, namedQueries); diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/GqlDatastoreQueryTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/GqlDatastoreQueryTests.java index cf50260495..ff7ea3c998 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/GqlDatastoreQueryTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/GqlDatastoreQueryTests.java @@ -105,7 +105,8 @@ void initMocks() { .thenReturn(this.datastoreEntityConverter); when(this.datastoreEntityConverter.getConversions()).thenReturn(this.readWriteConversions); this.valueExpressionDelegate = mock(ValueExpressionDelegate.class); - when(valueExpressionDelegate.getEvaluationContextAccessor()).thenReturn(mock(QueryMethodValueEvaluationContextAccessor.class)); + when(valueExpressionDelegate.getEvaluationContextAccessor()) + .thenReturn(mock(QueryMethodValueEvaluationContextAccessor.class)); } private GqlDatastoreQuery createQuery( diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/PartTreeDatastoreQueryTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/PartTreeDatastoreQueryTests.java index f7a180bd73..f4290426c9 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/PartTreeDatastoreQueryTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/PartTreeDatastoreQueryTests.java @@ -83,14 +83,14 @@ class PartTreeDatastoreQueryTests { private static final Object[] EMPTY_PARAMETERS = new Object[0]; private static final DatastoreResultsIterable EMPTY_RESPONSE = - new DatastoreResultsIterable<>(Collections.emptyIterator(), null); + new DatastoreResultsIterable<>(Collections.emptyIterator(), null); static final CompositeFilter FILTER = - CompositeFilter.and( - PropertyFilter.eq("action", "BUY"), - PropertyFilter.eq("ticker", "abcd"), - PropertyFilter.lt("price", 8.88), - PropertyFilter.ge("price", 3.33), - PropertyFilter.isNull("__key__")); + CompositeFilter.and( + PropertyFilter.eq("action", "BUY"), + PropertyFilter.eq("ticker", "abcd"), + PropertyFilter.lt("price", 8.88), + PropertyFilter.ge("price", 3.33), + PropertyFilter.isNull("__key__")); private DatastoreTemplate datastoreTemplate; @@ -112,36 +112,36 @@ void initMocks() { this.datastoreMappingContext = new DatastoreMappingContext(); this.datastoreEntityConverter = mock(DatastoreEntityConverter.class); this.readWriteConversions = - new TwoStepsConversions( - new DatastoreCustomConversions(), null, this.datastoreMappingContext); + new TwoStepsConversions( + new DatastoreCustomConversions(), null, this.datastoreMappingContext); when(this.datastoreTemplate.getDatastoreEntityConverter()) - .thenReturn(this.datastoreEntityConverter); + .thenReturn(this.datastoreEntityConverter); when(this.datastoreEntityConverter.getConversions()).thenReturn(this.readWriteConversions); } private PartTreeDatastoreQuery createQuery( - boolean isPageQuery, boolean isSliceQuery, ProjectionInformation projectionInformation) { + boolean isPageQuery, boolean isSliceQuery, ProjectionInformation projectionInformation) { ProjectionFactory projectionFactory = mock(ProjectionFactory.class); doReturn(projectionInformation != null ? projectionInformation : getProjectionInformationMock()) - .when(projectionFactory) - .getProjectionInformation(any()); + .when(projectionFactory) + .getProjectionInformation(any()); PartTreeDatastoreQuery tradePartTreeDatastoreQuery = - new PartTreeDatastoreQuery<>( - this.queryMethod, - this.datastoreTemplate, - this.datastoreMappingContext, - Trade.class, - projectionFactory); + new PartTreeDatastoreQuery<>( + this.queryMethod, + this.datastoreTemplate, + this.datastoreMappingContext, + Trade.class, + projectionFactory); PartTreeDatastoreQuery spy = spy(tradePartTreeDatastoreQuery); doReturn(isPageQuery).when(spy).isPageQuery(); doReturn(isSliceQuery).when(spy).isSliceQuery(); doAnswer(invocation -> invocation.getArguments()[0]) - .when(spy) - .processRawObjectForProjection(any()); + .when(spy) + .processRawObjectForProjection(any()); doAnswer(invocation -> invocation.getArguments()[0]) - .when(spy) - .convertResultCollection(any(), isNotNull()); + .when(spy) + .convertResultCollection(any(), isNotNull()); return spy; } @@ -155,19 +155,19 @@ private ProjectionInformation getProjectionInformationMock() { @Test void compoundNameConventionTest() throws NoSuchMethodException { queryWithMockResult( - "findTop333ByActionAndSymbolAndPriceLessThan" - + "AndPriceGreaterThanEqual" - + "AndEmbeddedEntityStringFieldEquals" - + "AndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - String.class)); + "findTop333ByActionAndSymbolAndPriceLessThan" + + "AndPriceGreaterThanEqual" + + "AndEmbeddedEntityStringFieldEquals" + + "AndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + String.class)); Object[] params = new Object[] { @@ -180,29 +180,29 @@ void compoundNameConventionTest() throws NoSuchMethodException { }; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); - - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter( - CompositeFilter.and( - PropertyFilter.eq("action", "BUY"), - PropertyFilter.eq("ticker", "abcd"), - PropertyFilter.lt("price", 8L), - PropertyFilter.ge("price", 3.33), - PropertyFilter.eq("embeddedEntity.stringField", "abc"), - PropertyFilter.isNull("__key__"))) - .setKind("trades") - .setOrderBy(OrderBy.desc("__key__")) - .setLimit(333) - .build(); - - assertThat(statement).isEqualTo(expected); - - return EMPTY_RESPONSE; - }); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); + + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter( + CompositeFilter.and( + PropertyFilter.eq("action", "BUY"), + PropertyFilter.eq("ticker", "abcd"), + PropertyFilter.lt("price", 8L), + PropertyFilter.ge("price", 3.33), + PropertyFilter.eq("embeddedEntity.stringField", "abc"), + PropertyFilter.isNull("__key__"))) + .setKind("trades") + .setOrderBy(OrderBy.desc("__key__")) + .setLimit(333) + .build(); + + assertThat(statement).isEqualTo(expected); + + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -211,65 +211,68 @@ void compoundNameConventionTest() throws NoSuchMethodException { } @Test - void compoundNameConventionProjectionTest() - throws NoSuchMethodException, IntrospectionException { + void compoundNameConventionProjectionTest() throws NoSuchMethodException, IntrospectionException { ProjectionInformation projectionInformation = mock(ProjectionInformation.class); doReturn(TradeProjection.class).when(projectionInformation).getType(); doReturn(true).when(projectionInformation).isClosed(); doReturn( Arrays.asList( - new PropertyDescriptor("id", null, null), - new PropertyDescriptor("symbol", null, null))) - .when(projectionInformation) - .getInputProperties(); + new PropertyDescriptor("id", null, null), + new PropertyDescriptor("symbol", null, null))) + .when(projectionInformation) + .getInputProperties(); queryWithMockResult( - "findTop333ByActionAndSymbolAndPriceLessThan" - + "AndPriceGreaterThanEqual" - + "AndEmbeddedEntityStringFieldEquals" - + "AndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethodProjection", - String.class, - String.class, - double.class, - double.class, - String.class), - projectionInformation); + "findTop333ByActionAndSymbolAndPriceLessThan" + + "AndPriceGreaterThanEqual" + + "AndEmbeddedEntityStringFieldEquals" + + "AndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethodProjection", + String.class, + String.class, + double.class, + double.class, + String.class), + projectionInformation); Object[] params = - new Object[] {"BUY", "abcd", - // this int param requires custom conversion - 8, 3.33, "abc" - }; + new Object[] { + "BUY", + "abcd", + // this int param requires custom conversion + 8, + 3.33, + "abc" + }; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - StructuredQuery statement = invocation.getArgument(0); - - StructuredQuery expected = - StructuredQuery.newProjectionEntityQueryBuilder() - .addProjection("__key__", "ticker") - .setFilter( - CompositeFilter.and( - PropertyFilter.eq("action", "BUY"), - PropertyFilter.eq("ticker", "abcd"), - PropertyFilter.lt("price", 8L), - PropertyFilter.ge("price", 3.33), - PropertyFilter.eq("embeddedEntity.stringField", "abc"), - PropertyFilter.isNull("__key__"))) - .setKind("trades") - .setOrderBy(OrderBy.desc("__key__")) - .setLimit(333) - .build(); - - assertThat(statement).isEqualTo(expected); - - return EMPTY_RESPONSE; - }); + .thenAnswer( + invocation -> { + StructuredQuery statement = invocation.getArgument(0); + + StructuredQuery expected = + StructuredQuery.newProjectionEntityQueryBuilder() + .addProjection("__key__", "ticker") + .setFilter( + CompositeFilter.and( + PropertyFilter.eq("action", "BUY"), + PropertyFilter.eq("ticker", "abcd"), + PropertyFilter.lt("price", 8L), + PropertyFilter.ge("price", 3.33), + PropertyFilter.eq("embeddedEntity.stringField", "abc"), + PropertyFilter.isNull("__key__"))) + .setKind("trades") + .setOrderBy(OrderBy.desc("__key__")) + .setLimit(333) + .build(); + + assertThat(statement).isEqualTo(expected); + + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -280,40 +283,41 @@ void compoundNameConventionProjectionTest() @Test void ambiguousSortPageableParam() throws NoSuchMethodException { queryWithMockResult( - "findTop333ByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findTop333ByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 444, Sort.Direction.ASC, "price") - }; + new Object[] { + "BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 444, Sort.Direction.ASC, "price") + }; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOffset(444) - .setLimit(444) - .setOrderBy(OrderBy.desc("__key__"), OrderBy.asc("price")) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOffset(444) + .setLimit(444) + .setOrderBy(OrderBy.desc("__key__"), OrderBy.asc("price")) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - return EMPTY_RESPONSE; - }); + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -324,37 +328,37 @@ void ambiguousSortPageableParam() throws NoSuchMethodException { @Test void nullPageable() throws NoSuchMethodException { queryWithMockResult( - "findTop333ByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findTop333ByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); Object[] params = new Object[] {"BUY", "abcd", 8.88, 3.33, null}; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setLimit(333) - .setOrderBy(OrderBy.desc("__key__")) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setLimit(333) + .setOrderBy(OrderBy.desc("__key__")) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - return EMPTY_RESPONSE; - }); + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -365,32 +369,32 @@ void nullPageable() throws NoSuchMethodException { @Test void ambiguousSort() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Direction.ASC, "price")}; + new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Direction.ASC, "price")}; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOrderBy(OrderBy.desc("__key__"), OrderBy.asc("price")) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOrderBy(OrderBy.desc("__key__"), OrderBy.asc("price")) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - return EMPTY_RESPONSE; - }); + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -401,31 +405,31 @@ void ambiguousSort() throws NoSuchMethodException { @Test void nullSort() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); Object[] params = new Object[] {"BUY", "abcd", 8.88, 3.33, null}; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOrderBy(OrderBy.desc("__key__")) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOrderBy(OrderBy.desc("__key__")) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - return EMPTY_RESPONSE; - }); + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -436,74 +440,73 @@ void nullSort() throws NoSuchMethodException { @Test void caseInsensitiveSort() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Order.by("price").ignoreCase())}; + new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Order.by("price").ignoreCase())}; assertThatThrownBy(() -> this.partTreeDatastoreQuery.execute(params)) - .hasMessage("Datastore doesn't support sorting ignoring case"); + .hasMessage("Datastore doesn't support sorting ignoring case"); } @Test void caseNullHandlingSort() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Order.by("price").nullsFirst())}; - + new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Order.by("price").nullsFirst())}; assertThatThrownBy(() -> this.partTreeDatastoreQuery.execute(params)) - .hasMessage("Datastore supports only NullHandling.NATIVE null handling"); + .hasMessage("Datastore supports only NullHandling.NATIVE null handling"); } @Test void pageableParam() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 444, Sort.Direction.DESC, "id")}; + new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 444, Sort.Direction.DESC, "id")}; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOffset(444) - .setOrderBy(OrderBy.desc("__key__")) - .setLimit(444) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOffset(444) + .setOrderBy(OrderBy.desc("__key__")) + .setLimit(444) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - return EMPTY_RESPONSE; - }); + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -514,21 +517,21 @@ void pageableParam() throws NoSuchMethodException { @Test void pageableQuery() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); this.partTreeDatastoreQuery = createQuery(true, false, null); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 2, Sort.Direction.DESC, "id")}; + new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 2, Sort.Direction.DESC, "id")}; preparePageResults(2, 2, null, Arrays.asList(3, 4), Arrays.asList(1, 2, 3, 4)); @@ -547,23 +550,23 @@ void pageableQuery() throws NoSuchMethodException { @Test void pageableQueryNextPage() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); this.partTreeDatastoreQuery = createQuery(true, false, null); PageRequest pageRequest = PageRequest.of(1, 2, Sort.Direction.DESC, "id"); Cursor cursor = Cursor.copyFrom("abc".getBytes()); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, DatastorePageable.from(pageRequest, cursor, 99L)}; + new Object[] {"BUY", "abcd", 8.88, 3.33, DatastorePageable.from(pageRequest, cursor, 99L)}; preparePageResults(2, 2, cursor, Arrays.asList(3, 4), Arrays.asList(1, 2, 3, 4)); @@ -580,11 +583,11 @@ void pageableQueryNextPage() throws NoSuchMethodException { @Test void pageableQueryMissingPageableParamReturnsAllResults() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod("tradeMethod", String.class, String.class, double.class, double.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod("tradeMethod", String.class, String.class, double.class, double.class)); this.partTreeDatastoreQuery = createQuery(true, false, null); @@ -606,21 +609,21 @@ void pageableQueryMissingPageableParamReturnsAllResults() throws NoSuchMethodExc @Test void sliceQueryLast() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); this.partTreeDatastoreQuery = createQuery(false, true, null); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 2, Sort.Direction.DESC, "id")}; + new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 2, Sort.Direction.DESC, "id")}; prepareSliceResults(2, 2, true); @@ -635,11 +638,11 @@ void sliceQueryLast() throws NoSuchMethodException { @Test void sliceQueryNoPageableParam() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod("tradeMethod", String.class, String.class, double.class, double.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod("tradeMethod", String.class, String.class, double.class, double.class)); this.partTreeDatastoreQuery = createQuery(false, true, null); @@ -653,27 +656,27 @@ void sliceQueryNoPageableParam() throws NoSuchMethodException { assertThat(result.hasNext()).isFalse(); verify(this.datastoreTemplate, times(1)) - .queryEntitiesSlice(isA(EntityQuery.class), any(), any()); + .queryEntitiesSlice(isA(EntityQuery.class), any(), any()); } @Test void sliceQuery() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); this.partTreeDatastoreQuery = createQuery(false, true, null); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(0, 2, Sort.Direction.DESC, "id")}; + new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(0, 2, Sort.Direction.DESC, "id")}; prepareSliceResults(0, 2, false); @@ -683,80 +686,80 @@ void sliceQuery() throws NoSuchMethodException { assertThat(result.hasNext()).isFalse(); verify(this.datastoreTemplate, times(1)) - .queryEntitiesSlice(isA(EntityQuery.class), any(), any()); + .queryEntitiesSlice(isA(EntityQuery.class), any(), any()); } private void preparePageResults( - int offset, - Integer limit, - Cursor cursor, - List pageResults, - List fullResults) { + int offset, + Integer limit, + Cursor cursor, + List pageResults, + List fullResults) { when(this.datastoreTemplate.queryKeysOrEntities(isA(EntityQuery.class), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setStartCursor(cursor) - .setOffset(cursor != null ? 0 : offset) - .setOrderBy(OrderBy.desc("__key__")) - .setLimit(limit) - .build(); - - assertThat(statement).isEqualTo(expected); - return new DatastoreResultsIterable( - pageResults.iterator(), Cursor.copyFrom("abc".getBytes())); - }); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setStartCursor(cursor) + .setOffset(cursor != null ? 0 : offset) + .setOrderBy(OrderBy.desc("__key__")) + .setLimit(limit) + .build(); + + assertThat(statement).isEqualTo(expected); + return new DatastoreResultsIterable( + pageResults.iterator(), Cursor.copyFrom("abc".getBytes())); + }); when(this.datastoreTemplate.queryKeysOrEntities(isA(KeyQuery.class), any())) - .thenAnswer( - invocation -> { - KeyQuery statement = invocation.getArgument(0); - KeyQuery expected = - StructuredQuery.newKeyQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOrderBy(OrderBy.desc("__key__")) - .build(); - - assertThat(statement).isEqualTo(expected); - return new DatastoreResultsIterable( - fullResults.iterator(), Cursor.copyFrom("def".getBytes())); - }); + .thenAnswer( + invocation -> { + KeyQuery statement = invocation.getArgument(0); + KeyQuery expected = + StructuredQuery.newKeyQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOrderBy(OrderBy.desc("__key__")) + .build(); + + assertThat(statement).isEqualTo(expected); + return new DatastoreResultsIterable( + fullResults.iterator(), Cursor.copyFrom("def".getBytes())); + }); } private void prepareSliceResults(int offset, Integer queryLimit, Boolean hasNext) { Cursor cursor = Cursor.copyFrom("abc".getBytes()); List datastoreMatchingRecords = Arrays.asList(3, 4, 5); when(this.datastoreTemplate.queryEntitiesSlice(isA(EntityQuery.class), any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOffset(offset) - .setOrderBy(OrderBy.desc("__key__")) - .setLimit(queryLimit) - .build(); - - assertThat(statement).isEqualTo(expected); - return new SliceImpl( - new DatastoreResultsIterable(datastoreMatchingRecords.iterator(), cursor) - .toList(), - Pageable.unpaged(), - hasNext); - }); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOffset(offset) + .setOrderBy(OrderBy.desc("__key__")) + .setLimit(queryLimit) + .build(); + + assertThat(statement).isEqualTo(expected); + return new SliceImpl( + new DatastoreResultsIterable(datastoreMatchingRecords.iterator(), cursor) + .toList(), + Pageable.unpaged(), + hasNext); + }); } @Test void deleteTest() throws NoSuchMethodException { queryWithMockResult( - "deleteByAction", null, getClass().getMethod("countByAction", String.class)); + "deleteByAction", null, getClass().getMethod("countByAction", String.class)); this.partTreeDatastoreQuery = createQuery(false, false, null); @@ -778,7 +781,7 @@ void deleteTest() throws NoSuchMethodException { @Test void deleteReturnCollectionTest() throws NoSuchMethodException { queryWithMockResult( - "deleteByAction", null, getClass().getMethod("countByAction", String.class)); + "deleteByAction", null, getClass().getMethod("countByAction", String.class)); this.partTreeDatastoreQuery = createQuery(false, false, null); @@ -802,39 +805,40 @@ private void prepareDeleteResults(boolean isCollection) { Cursor cursor = Cursor.copyFrom("abc".getBytes()); List datastoreMatchingRecords = Arrays.asList(3, 4, 5); when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - StructuredQuery statement = invocation.getArgument(0); - StructuredQuery.Builder builder = - isCollection - ? StructuredQuery.newEntityQueryBuilder() - : StructuredQuery.newKeyQueryBuilder(); - StructuredQuery expected = - builder.setFilter(PropertyFilter.eq("action", "BUY")).setKind("trades").build(); - - assertThat(statement).isEqualTo(expected); - return new DatastoreResultsIterable(datastoreMatchingRecords.iterator(), cursor); - }); + .thenAnswer( + invocation -> { + StructuredQuery statement = invocation.getArgument(0); + StructuredQuery.Builder builder = + isCollection + ? StructuredQuery.newEntityQueryBuilder() + : StructuredQuery.newKeyQueryBuilder(); + StructuredQuery expected = + builder.setFilter(PropertyFilter.eq("action", "BUY")).setKind("trades").build(); + + assertThat(statement).isEqualTo(expected); + return new DatastoreResultsIterable(datastoreMatchingRecords.iterator(), cursor); + }); } @Test void unspecifiedParametersTest() throws NoSuchMethodException { queryWithMockResult( - "countByTraderIdBetween", null, getClass().getMethod("countByAction", String.class)); + "countByTraderIdBetween", null, getClass().getMethod("countByAction", String.class)); when(this.queryMethod.getName()) - .thenReturn( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc"); + .thenReturn( + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc"); this.partTreeDatastoreQuery = createQuery(false, false, null); // There are too few params specified, so the exception will occur. Object[] params = new Object[] {"BUY"}; assertThatThrownBy(() -> this.partTreeDatastoreQuery.execute(params)) - .hasMessage("Too few parameters are provided for query method: " - + "findByActionAndSymbolAndPriceLessThanAndPriceGreaterThanEqualAndIdIsNullOrderByIdDesc"); + .hasMessage( + "Too few parameters are provided for query method: " + + "findByActionAndSymbolAndPriceLessThanAndPriceGreaterThanEqualAndIdIsNullOrderByIdDesc"); } @Test @@ -846,10 +850,11 @@ void unsupportedParamTypeTest() throws NoSuchMethodException { Object[] params = new Object[] {new Trade()}; - assertThatThrownBy(() -> this.partTreeDatastoreQuery.execute(params)) - .hasMessage("Unable to convert class " - + "com.google.cloud.spring.data.datastore.repository.query." - + "PartTreeDatastoreQueryTests$Trade to Datastore supported type."); + assertThatThrownBy(() -> this.partTreeDatastoreQuery.execute(params)) + .hasMessage( + "Unable to convert class " + + "com.google.cloud.spring.data.datastore.repository.query." + + "PartTreeDatastoreQueryTests$Trade to Datastore supported type."); } @Test @@ -859,17 +864,17 @@ void unSupportedPredicateTest() throws NoSuchMethodException { this.partTreeDatastoreQuery = createQuery(false, false, null); assertThatThrownBy(() -> this.partTreeDatastoreQuery.execute(EMPTY_PARAMETERS)) - .hasMessageContaining("Unsupported predicate keyword: BETWEEN"); - - + .hasMessageContaining("Unsupported predicate keyword: BETWEEN"); } @Test void unSupportedOrTest() { - //PartTreeDatastoreQuery constructor will fail as part of queryWithMockResult setup - assertThatThrownBy(() -> queryWithMockResult("countByTraderIdOrPrice", null, getClass().getMethod("traderAndPrice"))) - .hasMessage("Cloud Datastore only supports multiple filters combined with AND."); - + // PartTreeDatastoreQuery constructor will fail as part of queryWithMockResult setup + assertThatThrownBy( + () -> + queryWithMockResult( + "countByTraderIdOrPrice", null, getClass().getMethod("traderAndPrice"))) + .hasMessage("Cloud Datastore only supports multiple filters combined with AND."); } @Test @@ -878,12 +883,14 @@ void countTest() throws NoSuchMethodException { results.add(new Trade()); queryWithMockResult( - "countByAction", results, getClass().getMethod("countByAction", String.class)); + "countByAction", results, getClass().getMethod("countByAction", String.class)); PartTreeDatastoreQuery spyQuery = this.partTreeDatastoreQuery; Object[] params = - new Object[] {"BUY", }; + new Object[] { + "BUY", + }; assertThat(spyQuery.execute(params)).isEqualTo(1L); } @@ -893,34 +900,38 @@ void existShouldBeTrueWhenResultSetIsNotEmpty() throws NoSuchMethodException { results.add(new Trade()); queryWithMockResult( - "existsByAction", results, getClass().getMethod("countByAction", String.class)); + "existsByAction", results, getClass().getMethod("countByAction", String.class)); PartTreeDatastoreQuery spyQuery = this.partTreeDatastoreQuery; doAnswer(invocation -> invocation.getArgument(0)) - .when(spyQuery) - .processRawObjectForProjection(any()); + .when(spyQuery) + .processRawObjectForProjection(any()); Object[] params = - new Object[] {"BUY", }; + new Object[] { + "BUY", + }; assertThat((boolean) spyQuery.execute(params)).isTrue(); } @Test void existShouldBeFalseWhenResultSetIsEmpty() throws NoSuchMethodException { queryWithMockResult( - "existsByAction", - Collections.emptyList(), - getClass().getMethod("countByAction", String.class)); + "existsByAction", + Collections.emptyList(), + getClass().getMethod("countByAction", String.class)); PartTreeDatastoreQuery spyQuery = this.partTreeDatastoreQuery; doAnswer(invocation -> invocation.getArgument(0)) - .when(spyQuery) - .processRawObjectForProjection(any()); + .when(spyQuery) + .processRawObjectForProjection(any()); Object[] params = - new Object[] {"BUY", }; + new Object[] { + "BUY", + }; assertThat((boolean) spyQuery.execute(params)).isFalse(); } @@ -928,28 +939,30 @@ void existShouldBeFalseWhenResultSetIsEmpty() throws NoSuchMethodException { void nonCollectionReturnType() throws NoSuchMethodException { Trade trade = new Trade(); queryWithMockResult( - "findByAction", null, getClass().getMethod("findByAction", String.class), true, null); + "findByAction", null, getClass().getMethod("findByAction", String.class), true, null); Object[] params = - new Object[] {"BUY", }; + new Object[] { + "BUY", + }; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(PropertyFilter.eq("action", "BUY")) - .setKind("trades") - .setLimit(1) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(PropertyFilter.eq("action", "BUY")) + .setKind("trades") + .setLimit(1) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - List results = Collections.singletonList(trade); - return new DatastoreResultsIterable(results.iterator(), null); - }); + List results = Collections.singletonList(trade); + return new DatastoreResultsIterable(results.iterator(), null); + }); assertThat(this.partTreeDatastoreQuery.execute(params)).isEqualTo(trade); } @@ -958,41 +971,41 @@ void nonCollectionReturnType() throws NoSuchMethodException { void usingIdField() throws NoSuchMethodException { Trade trade = new Trade(); queryWithMockResult( - "findByActionAndId", - null, - getClass().getMethod("findByActionAndId", String.class, String.class), - true, - null); + "findByActionAndId", + null, + getClass().getMethod("findByActionAndId", String.class, String.class), + true, + null); Object[] params = new Object[] {"BUY", "id1"}; when(this.datastoreTemplate.createKey("trades", "id1")) - .thenAnswer( - invocation -> - Key.newBuilder("project", invocation.getArgument(0), invocation.getArgument(1)) - .build()); + .thenAnswer( + invocation -> + Key.newBuilder("project", invocation.getArgument(0), invocation.getArgument(1)) + .build()); when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); - - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter( - CompositeFilter.and( - PropertyFilter.eq("action", "BUY"), - PropertyFilter.eq( - "__key__", - KeyValue.of(Key.newBuilder("project", "trades", "id1").build())))) - .setKind("trades") - .setLimit(1) - .build(); - - assertThat(statement).isEqualTo(expected); - - List results = Collections.singletonList(trade); - return new DatastoreResultsIterable(results.iterator(), null); - }); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); + + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter( + CompositeFilter.and( + PropertyFilter.eq("action", "BUY"), + PropertyFilter.eq( + "__key__", + KeyValue.of(Key.newBuilder("project", "trades", "id1").build())))) + .setKind("trades") + .setLimit(1) + .build(); + + assertThat(statement).isEqualTo(expected); + + List results = Collections.singletonList(trade); + return new DatastoreResultsIterable(results.iterator(), null); + }); assertThat(this.partTreeDatastoreQuery.execute(params)).isEqualTo(trade); } @@ -1000,28 +1013,32 @@ void usingIdField() throws NoSuchMethodException { @Test void nonCollectionReturnTypeNoResultsNullable() throws NoSuchMethodException { queryWithMockResult( - "findByAction", - Collections.emptyList(), - getClass().getMethod("findByActionNullable", String.class), - true, - null); + "findByAction", + Collections.emptyList(), + getClass().getMethod("findByActionNullable", String.class), + true, + null); Object[] params = - new Object[] {"BUY", }; + new Object[] { + "BUY", + }; assertThat(this.partTreeDatastoreQuery.execute(params)).isNull(); } @Test void nonCollectionReturnTypeNoResultsOptional() throws NoSuchMethodException { queryWithMockResult( - "findByAction", - Collections.emptyList(), - getClass().getMethod("findByActionOptional", String.class), - true, - null); + "findByAction", + Collections.emptyList(), + getClass().getMethod("findByActionOptional", String.class), + true, + null); Object[] params = - new Object[] {"BUY", }; + new Object[] { + "BUY", + }; assertThat((Optional) this.partTreeDatastoreQuery.execute(params)).isNotPresent(); } @@ -1032,19 +1049,21 @@ void streamResultTest() throws NoSuchMethodException { Trade tradeB = new Trade(); tradeB.id = "b"; queryWithMockResult( - "findStreamByAction", - Arrays.asList(tradeA, tradeB), - getClass().getMethod("findStreamByAction", String.class)); + "findStreamByAction", + Arrays.asList(tradeA, tradeB), + getClass().getMethod("findStreamByAction", String.class)); when(this.queryMethod.isStreamQuery()).thenReturn(true); Object[] params = - new Object[] {"BUY", }; + new Object[] { + "BUY", + }; Object result = this.partTreeDatastoreQuery.execute(params); assertThat(result).isInstanceOf(Stream.class); assertThat((Stream) result).hasSize(2).contains(tradeA, tradeB); } private void queryWithMockResult( - String queryName, List results, Method m, ProjectionInformation projectionInformation) { + String queryName, List results, Method m, ProjectionInformation projectionInformation) { queryWithMockResult(queryName, results, m, false, projectionInformation); } @@ -1053,11 +1072,11 @@ private void queryWithMockResult(String queryName, List results, Method m) { } private void queryWithMockResult( - String queryName, - List results, - Method m, - boolean mockOptionalNullable, - ProjectionInformation projectionInformation) { + String queryName, + List results, + Method m, + boolean mockOptionalNullable, + ProjectionInformation projectionInformation) { when(this.queryMethod.getName()).thenReturn(queryName); doReturn(new DefaultParameters(ParametersSource.of(m))).when(this.queryMethod).getParameters(); if (mockOptionalNullable) { @@ -1066,18 +1085,18 @@ private void queryWithMockResult( doReturn(TypeInformation.fromReturnTypeOf(m)).when(mockMetadata).getReturnType(m); doReturn(TypeInformation.fromReturnTypeOf(m)).when(mockMetadata).getDomainTypeInformation(); DatastoreQueryMethod datastoreQueryMethod = - new DatastoreQueryMethod(m, mockMetadata, mock(SpelAwareProxyProjectionFactory.class)); + new DatastoreQueryMethod(m, mockMetadata, mock(SpelAwareProxyProjectionFactory.class)); doReturn(datastoreQueryMethod.isOptionalReturnType()) - .when(this.queryMethod) - .isOptionalReturnType(); + .when(this.queryMethod) + .isOptionalReturnType(); doReturn(datastoreQueryMethod.isNullable()).when(this.queryMethod).isNullable(); } this.partTreeDatastoreQuery = createQuery(false, false, projectionInformation); when(this.datastoreTemplate.queryKeysOrEntities(any(), Mockito.>any())) - .thenReturn( - new DatastoreResultsIterable<>( - results != null ? results.iterator() : Collections.emptyIterator(), null)); + .thenReturn( + new DatastoreResultsIterable<>( + results != null ? results.iterator() : Collections.emptyIterator(), null)); } public Trade findByAction(String action) { @@ -1103,12 +1122,12 @@ public Optional findByActionOptional(String action) { } public List tradeMethod( - String action, String symbol, double pless, double pgreater, String embeddedProperty) { + String action, String symbol, double pless, double pgreater, String embeddedProperty) { return null; } public List tradeMethodProjection( - String action, String symbol, double pless, double pgreater, String embeddedProperty) { + String action, String symbol, double pless, double pgreater, String embeddedProperty) { return null; } @@ -1117,12 +1136,12 @@ public List tradeMethod(String action, String symbol, double pless, doubl } public List tradeMethod( - String action, String symbol, double pless, double pgreater, Pageable pageable) { + String action, String symbol, double pless, double pgreater, Pageable pageable) { return null; } public List tradeMethod( - String action, String symbol, double pless, double pgreater, Sort sort) { + String action, String symbol, double pless, double pgreater, Sort sort) { return null; } diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactoryTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactoryTests.java index 02cf66b353..aaf1374e27 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactoryTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactoryTests.java @@ -66,9 +66,10 @@ void getEntityInformationNotAvailableTest() { new DatastoreRepositoryFactory(mock(DatastoreMappingContext.class), this.datastoreTemplate); assertThatThrownBy(() -> factory.getEntityInformation(TestEntity.class)) - .isInstanceOf(MappingException.class) - .hasMessage("Could not lookup mapping metadata for domain class: com.google.cloud.spring.data.datastore.repository.support." - + "DatastoreRepositoryFactoryTests$TestEntity"); + .isInstanceOf(MappingException.class) + .hasMessage( + "Could not lookup mapping metadata for domain class: com.google.cloud.spring.data.datastore.repository.support." + + "DatastoreRepositoryFactoryTests$TestEntity"); } @Test diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/SimpleDatastoreRepositoryTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/SimpleDatastoreRepositoryTests.java index 3cce9a9723..1f50128f80 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/SimpleDatastoreRepositoryTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/SimpleDatastoreRepositoryTests.java @@ -304,12 +304,11 @@ void findAllByExamplePageCursor() { @Test void findAllByExamplePageNull() { - Example example = Example.of(new Object()); - - assertThatThrownBy(() -> this.simpleDatastoreRepository.findAll(example, (Pageable) null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A non-null pageable is required."); + Example example = Example.of(new Object()); + assertThatThrownBy(() -> this.simpleDatastoreRepository.findAll(example, (Pageable) null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-null pageable is required."); } @Test @@ -496,15 +495,19 @@ void findByExampleFluentQueryAsUnsupported() { Example example = Example.of(new Object()); - assertThatThrownBy(() -> this.simpleDatastoreRepository.findBy(example, q -> q.as(Object.class).all())) - .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> this.simpleDatastoreRepository.findBy(example, q -> q.as(Object.class).all())) + .isInstanceOf(UnsupportedOperationException.class); } @Test void findByExampleFluentQueryProjectUnsupported() { Example example = Example.of(new Object()); - assertThatThrownBy(() -> this.simpleDatastoreRepository.findBy(example, q -> q.project("firstProperty").all())) - .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + this.simpleDatastoreRepository.findBy( + example, q -> q.project("firstProperty").all())) + .isInstanceOf(UnsupportedOperationException.class); } } diff --git a/spring-cloud-gcp-data-datastore/src/test/resources/index.yaml b/spring-cloud-gcp-data-datastore/src/test/resources/index.yaml index 7165b73e09..135030d329 100644 --- a/spring-cloud-gcp-data-datastore/src/test/resources/index.yaml +++ b/spring-cloud-gcp-data-datastore/src/test/resources/index.yaml @@ -1,13 +1,13 @@ # For running the ITs in local setups: `cd` into this folder and run `gcloud datastore indexes create index.yaml` indexes: -- kind: test_entities_ci - properties: - - name: size - - name: color + - kind: test_entities_ci + properties: + - name: size + - name: color -- kind: test_entities_ci - properties: - - name: color - - name: __key__ - direction: desc \ No newline at end of file + - kind: test_entities_ci + properties: + - name: color + - name: __key__ + direction: desc \ No newline at end of file diff --git a/spring-cloud-gcp-data-datastore/src/test/resources/logback-test.xml b/spring-cloud-gcp-data-datastore/src/test/resources/logback-test.xml index 5535de3c96..b36b736af4 100644 --- a/spring-cloud-gcp-data-datastore/src/test/resources/logback-test.xml +++ b/spring-cloud-gcp-data-datastore/src/test/resources/logback-test.xml @@ -1,14 +1,14 @@ - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + - - - + + + diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/SpannerMutationFactoryImpl.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/SpannerMutationFactoryImpl.java index d9faf41745..0f5752f85c 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/SpannerMutationFactoryImpl.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/SpannerMutationFactoryImpl.java @@ -164,7 +164,8 @@ private void verifyChildHasParentId( Iterator childKeyParts = this.spannerSchemaUtils.getKey(childObject).getParts().iterator(); int partNum = 1; while (parentKeyParts.hasNext()) { - if (!childKeyParts.hasNext() || !Objects.equals(parentKeyParts.next(), childKeyParts.next())) { + if (!childKeyParts.hasNext() + || !Objects.equals(parentKeyParts.next(), childKeyParts.next())) { throw new SpannerDataException( "A child entity's common primary key parts with its parent must " + "have the same values. Primary key component " diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/admin/SpannerDatabaseAdminTemplate.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/admin/SpannerDatabaseAdminTemplate.java index efc0184629..ecf835d821 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/admin/SpannerDatabaseAdminTemplate.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/admin/SpannerDatabaseAdminTemplate.java @@ -43,7 +43,7 @@ public class SpannerDatabaseAdminTemplate { private static final String TABLE_SCHEMA_COL_NAME = "table_schema"; - + private static final String TABLE_NAME_COL_NAME = "table_name"; private static final String PARENT_TABLE_NAME_COL_NAME = "parent_table_name"; @@ -158,8 +158,7 @@ public Map getChildParentTablesMap() { Struct row = results.getCurrentRowAsStruct(); relationships.put( getQualifiedTableName( - row.getString(TABLE_SCHEMA_COL_NAME), - row.getString(TABLE_NAME_COL_NAME)), + row.getString(TABLE_SCHEMA_COL_NAME), row.getString(TABLE_NAME_COL_NAME)), row.isNull(PARENT_TABLE_NAME_COL_NAME) ? null : getQualifiedTableName( @@ -171,14 +170,14 @@ public Map getChildParentTablesMap() { return relationships; } } - + private String getQualifiedTableName(String schema, String table) { if (schema == null || Objects.equals(schema, getDefaultSchemaName())) { return table; } return schema + "." + table; } - + private String getDefaultSchemaName() { // TODO: Get the default schema directly from the dialect when this is supported in the Spanner // Java client. diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/ConverterAwareMappingSpannerEntityReader.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/ConverterAwareMappingSpannerEntityReader.java index ed42f46fd4..71d5e3e6e0 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/ConverterAwareMappingSpannerEntityReader.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/ConverterAwareMappingSpannerEntityReader.java @@ -70,7 +70,8 @@ public R read( SpannerPersistentEntity persistentEntity = (SpannerPersistentEntity) this.spannerMappingContext.getPersistentEntityOrFail(type); - StructAccessor structAccessor = new StructAccessor(source, this.spannerMappingContext.getGson()); + StructAccessor structAccessor = + new StructAccessor(source, this.spannerMappingContext.getGson()); StructPropertyValueProvider propertyValueProvider = new StructPropertyValueProvider(structAccessor, this.converter, this, allowMissingColumns); diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/ConverterAwareMappingSpannerEntityWriter.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/ConverterAwareMappingSpannerEntityWriter.java index 1dc3685ebf..2435a48668 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/ConverterAwareMappingSpannerEntityWriter.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/ConverterAwareMappingSpannerEntityWriter.java @@ -327,7 +327,6 @@ private boolean attemptSetIterableValue( boolean valueSet = false; - if (spannerPersistentProperty.getAnnotatedColumnItemType() == Type.Code.JSON) { // if column annotated with JSON, convert directly valueBinder.toJsonArray(this.convertIterableJsonToValue(value)); diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/SpannerConverters.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/SpannerConverters.java index 3bd09a243a..6ad40c68ec 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/SpannerConverters.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/SpannerConverters.java @@ -140,6 +140,7 @@ public java.util.Date convert(Timestamp timestamp) { return timestamp.toDate(); } }; + /** A converter from {@link Instant} to the Spanner instantaneous time type. */ public static final Converter INSTANT_TIMESTAMP_CONVERTER = new CommitTimestampDecorator( diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/StructAccessor.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/StructAccessor.java index 72c09fadaf..e6017fbd2a 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/StructAccessor.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/StructAccessor.java @@ -171,26 +171,24 @@ List getListJsonValue(String colName, Class colType) { } List jsonStringList = this.struct.getJsonList(colName); List result = new ArrayList<>(); - jsonStringList.forEach(item -> - result.add(gson.fromJson(item, colType))); + jsonStringList.forEach(item -> result.add(gson.fromJson(item, colType))); return result; } - public Object getJsonValue(int colIndex, Class colType) { + public Object getJsonValue(int colIndex, Class colType) { if (this.struct.getColumnType(colIndex).getCode() != Code.ARRAY) { return getSingleJsonValue(colIndex, colType); } return getListJsonValue(colIndex, colType); } - private List getListJsonValue(int colIndex, Class colType) { + private List getListJsonValue(int colIndex, Class colType) { if (this.struct.getColumnType(colIndex).getCode() != Code.ARRAY) { throw new SpannerDataException(EXCEPTION_COL_NOT_ARRAY + colIndex); } List jsonStringList = this.struct.getJsonList(colIndex); List result = new ArrayList<>(); - jsonStringList.forEach(item -> - result.add(gson.fromJson(item, colType))); + jsonStringList.forEach(item -> result.add(gson.fromJson(item, colType))); return result; } @@ -225,8 +223,8 @@ T getSingleJsonValue(String colName, Class colType) { return gson.fromJson(jsonString, colType); } - //TODO: change this to private in next major release - public T getSingleJsonValue(int colIndex, Class colType) { + // TODO: change this to private in next major release + public T getSingleJsonValue(int colIndex, Class colType) { if (this.struct.getColumnType(colIndex).getCode() != Code.JSON) { throw new SpannerDataException("Column of index " + colIndex + " not an JSON type."); } diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/StructPropertyValueProvider.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/StructPropertyValueProvider.java index fe201b764f..1d2fd76a1c 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/StructPropertyValueProvider.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/convert/StructPropertyValueProvider.java @@ -127,8 +127,9 @@ private Iterable readIterableWithConversion( String colName = spannerPersistentProperty.getColumnName(); Type.Code spannerColumnType = spannerPersistentProperty.getAnnotatedColumnItemType(); if (spannerColumnType == Type.Code.JSON) { - return (List) this.structAccessor.getListJsonValue(colName, - spannerPersistentProperty.getColumnInnerType()); + return (List) + this.structAccessor.getListJsonValue( + colName, spannerPersistentProperty.getColumnInnerType()); } List listValue = this.structAccessor.getListValue(colName); return listValue.stream() diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentPropertyImpl.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentPropertyImpl.java index 8de60840ab..15640e3af9 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentPropertyImpl.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentPropertyImpl.java @@ -71,7 +71,8 @@ public class SpannerPersistentPropertyImpl @Override @NonNull public Iterable> getPersistentEntityTypeInformation() { - return StreamUtils.createStreamFromIterator(super.getPersistentEntityTypeInformation().iterator()) + return StreamUtils.createStreamFromIterator( + super.getPersistentEntityTypeInformation().iterator()) .filter(typeInfo -> typeInfo.getType().isAnnotationPresent(Table.class)) .toList(); } diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/SpannerRepository.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/SpannerRepository.java index 1bf6c4aaaa..56b441637a 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/SpannerRepository.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/SpannerRepository.java @@ -28,8 +28,8 @@ * @param the id type of the entity * @since 1.1 */ -public interface SpannerRepository extends PagingAndSortingRepository, - CrudRepository { +public interface SpannerRepository + extends PagingAndSortingRepository, CrudRepository { /** * Gets a {@link SpannerOperations}, which allows more-direct access to Google Cloud Spanner diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/config/SpannerAuditingRegistrar.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/config/SpannerAuditingRegistrar.java index 1ce60ddb0b..3980038b4f 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/config/SpannerAuditingRegistrar.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/config/SpannerAuditingRegistrar.java @@ -59,7 +59,7 @@ protected BeanDefinitionBuilder getAuditHandlerBeanDefinitionBuilder( AuditingConfiguration configuration) { return configureDefaultAuditHandlerAttributes( configuration, BeanDefinitionBuilder.rootBeanDefinition(AuditingHandler.class)) - .addConstructorArgValue(PersistentEntities.of(new SpannerMappingContext())); + .addConstructorArgValue(PersistentEntities.of(new SpannerMappingContext())); } @Override diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/query/SpannerStatementQueryExecutor.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/query/SpannerStatementQueryExecutor.java index 35ad72da9a..b4d38bd383 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/query/SpannerStatementQueryExecutor.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/query/SpannerStatementQueryExecutor.java @@ -114,7 +114,8 @@ private static Map preparePartTreeSqlTagParameterMap( // query. // They are processed separately in applySort and buildLimit methods. if (param.getType() != Pageable.class && param.getType() != Sort.class) { - paramMetadataMap.put(sqlStringAndPlaceholders.getPlaceholders().get(nextPlaceholderIdx++), param); + paramMetadataMap.put( + sqlStringAndPlaceholders.getPlaceholders().get(nextPlaceholderIdx++), param); } } return paramMetadataMap; diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/query/SqlSpannerQuery.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/query/SqlSpannerQuery.java index 4c6376a413..ae1a7ba64c 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/query/SqlSpannerQuery.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/query/SqlSpannerQuery.java @@ -159,8 +159,12 @@ private void resolveSpelTags(QueryTagValue queryTagValue) { StringBuilder sb = new StringBuilder(); Map valueToTag = new HashMap<>(); int tagNum = 0; - EvaluationContext evaluationContext = this.valueExpressionDelegate.getEvaluationContextAccessor().create(this.queryMethod.getParameters()) - .getEvaluationContext(queryTagValue.rawParams).getEvaluationContext(); + EvaluationContext evaluationContext = + this.valueExpressionDelegate + .getEvaluationContextAccessor() + .create(this.queryMethod.getParameters()) + .getEvaluationContext(queryTagValue.rawParams) + .getEvaluationContext(); for (Expression expression : expressions) { if (expression instanceof LiteralExpression) { sb.append(expression.getValue(String.class)); @@ -240,11 +244,13 @@ private List executeReadSql(Pageable pageable, Sort sort, QueryTagValue queryTag return this.spannerTemplate.query( struct -> new StructAccessor(struct).getSingleValue(0), statement, spannerQueryOptions); } - // check if returnedType is a field annotated as json or is inner-type of a field annotated as json + // check if returnedType is a field annotated as json or is inner-type of a field annotated as + // json if (isJsonFieldType(returnedType)) { return this.spannerTemplate.query( - struct -> new StructAccessor(struct, - this.spannerMappingContext.getGson()).getJsonValue(0, returnedType), + struct -> + new StructAccessor(struct, this.spannerMappingContext.getGson()) + .getJsonValue(0, returnedType), statement, spannerQueryOptions); } diff --git a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/support/SpannerRepositoryFactory.java b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/support/SpannerRepositoryFactory.java index fc31c4bccd..e1d3bbe7c5 100644 --- a/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/support/SpannerRepositoryFactory.java +++ b/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/support/SpannerRepositoryFactory.java @@ -117,35 +117,36 @@ protected Optional getQueryLookupStrategy( private QueryMethodEvaluationContextProvider delegateContextProvider( ValueExpressionDelegate evaluationContextProvider) { return null; -// return new QueryMethodEvaluationContextProvider() { -// @Override -// public > EvaluationContext getEvaluationContext( -// T parameters, Object[] parameterValues) { -// StandardEvaluationContext evaluationContext = -// (StandardEvaluationContext) -// evaluationContextProvider.getEvaluationContext(parameters, parameterValues); -// evaluationContext.setRootObject(SpannerRepositoryFactory.this.applicationContext); -// evaluationContext.addPropertyAccessor(new BeanFactoryAccessor()); -// evaluationContext.setBeanResolver( -// new BeanFactoryResolver(SpannerRepositoryFactory.this.applicationContext)); -// return evaluationContext; -// } -// -// @Override -// public > EvaluationContext getEvaluationContext( -// T parameters, Object[] parameterValues, ExpressionDependencies expressionDependencies) { -// StandardEvaluationContext evaluationContext = -// (StandardEvaluationContext) -// evaluationContextProvider.getEvaluationContext( -// parameters, parameterValues, expressionDependencies); -// -// evaluationContext.setRootObject(SpannerRepositoryFactory.this.applicationContext); -// evaluationContext.addPropertyAccessor(new BeanFactoryAccessor()); -// evaluationContext.setBeanResolver( -// new BeanFactoryResolver(SpannerRepositoryFactory.this.applicationContext)); -// return evaluationContext; -// } -// }; + // return new QueryMethodEvaluationContextProvider() { + // @Override + // public > EvaluationContext getEvaluationContext( + // T parameters, Object[] parameterValues) { + // StandardEvaluationContext evaluationContext = + // (StandardEvaluationContext) + // evaluationContextProvider.getEvaluationContext(parameters, parameterValues); + // evaluationContext.setRootObject(SpannerRepositoryFactory.this.applicationContext); + // evaluationContext.addPropertyAccessor(new BeanFactoryAccessor()); + // evaluationContext.setBeanResolver( + // new BeanFactoryResolver(SpannerRepositoryFactory.this.applicationContext)); + // return evaluationContext; + // } + // + // @Override + // public > EvaluationContext getEvaluationContext( + // T parameters, Object[] parameterValues, ExpressionDependencies + // expressionDependencies) { + // StandardEvaluationContext evaluationContext = + // (StandardEvaluationContext) + // evaluationContextProvider.getEvaluationContext( + // parameters, parameterValues, expressionDependencies); + // + // evaluationContext.setRootObject(SpannerRepositoryFactory.this.applicationContext); + // evaluationContext.addPropertyAccessor(new BeanFactoryAccessor()); + // evaluationContext.setBeanResolver( + // new BeanFactoryResolver(SpannerRepositoryFactory.this.applicationContext)); + // return evaluationContext; + // } + // }; } @Override diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/aot/SpannerSchemaUtilsRuntimeHintsTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/aot/SpannerSchemaUtilsRuntimeHintsTests.java index 3c7b2bffeb..da04526ad0 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/aot/SpannerSchemaUtilsRuntimeHintsTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/aot/SpannerSchemaUtilsRuntimeHintsTests.java @@ -28,8 +28,6 @@ void registerString() { RuntimeHints runtimeHints = new RuntimeHints(); SpannerSchemaUtilsRuntimeHints registrar = new SpannerSchemaUtilsRuntimeHints(); registrar.registerHints(runtimeHints, null); - assertThat(runtimeHints) - .matches( - reflection().onType(String.class)); + assertThat(runtimeHints).matches(reflection().onType(String.class)); } } diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerMutationFactoryImplTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerMutationFactoryImplTests.java index 93f7d85907..5f146da69c 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerMutationFactoryImplTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerMutationFactoryImplTests.java @@ -150,12 +150,13 @@ void insertChildrenMismatchIdTest() { // throws exception because child entity's id column does not match that of its // parent. assertThatThrownBy(() -> this.spannerMutationFactory.insert(t)) - .isInstanceOf(SpannerDataException.class) - .hasMessage("A child entity's common primary key parts with its parent must have the same values." - + " Primary key component 1 does not match for entities: class" - + " com.google.cloud.spring.data.spanner.core.SpannerMutationFactoryImplTests$TestEntity" - + " class" - + " com.google.cloud.spring.data.spanner.core.SpannerMutationFactoryImplTests$ChildEntity"); + .isInstanceOf(SpannerDataException.class) + .hasMessage( + "A child entity's common primary key parts with its parent must have the same values." + + " Primary key component 1 does not match for entities: class" + + " com.google.cloud.spring.data.spanner.core.SpannerMutationFactoryImplTests$TestEntity" + + " class" + + " com.google.cloud.spring.data.spanner.core.SpannerMutationFactoryImplTests$ChildEntity"); } @Test @@ -286,23 +287,18 @@ private static class EmbeddedKeyComponents { @Table private static class Parent { - @PrimaryKey - @Column - String keyOne; + @PrimaryKey @Column String keyOne; @PrimaryKey(keyOrder = 2) @Column Long keyTwo; - @Interleaved - List children; + @Interleaved List children; } @Table private static class Child { - @PrimaryKey - @Column - String keyOne; + @PrimaryKey @Column String keyOne; @PrimaryKey(keyOrder = 2) @Column diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerReadOptionsTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerReadOptionsTests.java index 99a8ad7055..f6a1c6dd3c 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerReadOptionsTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerReadOptionsTests.java @@ -35,8 +35,8 @@ class SpannerReadOptionsTests { void addNullReadOptionTest() { SpannerReadOptions testSpannerReadOptions = new SpannerReadOptions(); assertThatThrownBy(() -> testSpannerReadOptions.addReadOption(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Valid read option is required!"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Valid read option is required!"); } @Test @@ -64,8 +64,8 @@ void convertReadToQueryOptionTest_throwIfNotSupported() { ReadOption r1 = mock(ReadOption.class); spannerReadOptions.addReadOption(r1); assertThatThrownBy(spannerReadOptions::toQueryOptions) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Can't convert"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Can't convert"); } @Test diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerSortPageQueryOptionsTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerSortPageQueryOptionsTests.java index 73d0647f29..c08442bedd 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerSortPageQueryOptionsTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerSortPageQueryOptionsTests.java @@ -34,8 +34,8 @@ void addNullQueryOptionTest() { SpannerQueryOptions testSpannerQueryOptions = new SpannerQueryOptions(); assertThatThrownBy(() -> testSpannerQueryOptions.addQueryOption(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Valid query option is required!"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Valid query option is required!"); } @Test diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerTemplateTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerTemplateTests.java index 4ab8561d1a..f4ae511d92 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerTemplateTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerTemplateTests.java @@ -353,7 +353,6 @@ void readOnlyTransactionTest() { verify(readOnlyTransaction, times(2)).read(eq("custom_test_table"), any(), any()); } - @Test void readOnlyTransactionDmlTest() { @@ -363,15 +362,19 @@ void readOnlyTransactionDmlTest() { TimestampBound.ofReadTimestamp(Timestamp.ofTimeMicroseconds(333)))) .thenReturn(readOnlyTransaction); - SpannerReadOptions testSpannerReadOptions = new SpannerReadOptions().setTimestamp(Timestamp.ofTimeMicroseconds(333)); - Function testSpannerOperations = spannerOperations -> { - spannerOperations.executeDmlStatement(Statement.of("fail")); - return null; - }; + SpannerReadOptions testSpannerReadOptions = + new SpannerReadOptions().setTimestamp(Timestamp.ofTimeMicroseconds(333)); + Function testSpannerOperations = + spannerOperations -> { + spannerOperations.executeDmlStatement(Statement.of("fail")); + return null; + }; - assertThatThrownBy(() -> this.spannerTemplate.performReadOnlyTransaction( - testSpannerOperations, testSpannerReadOptions)) - .hasMessage("A read-only transaction template cannot execute DML."); + assertThatThrownBy( + () -> + this.spannerTemplate.performReadOnlyTransaction( + testSpannerOperations, testSpannerReadOptions)) + .hasMessage("A read-only transaction template cannot execute DML."); } @Test @@ -382,15 +385,19 @@ void readOnlyTransactionPartitionedDmlTest() { TimestampBound.ofReadTimestamp(Timestamp.ofTimeMicroseconds(333)))) .thenReturn(readOnlyTransaction); - SpannerReadOptions testSpannerReadOptions = new SpannerReadOptions().setTimestamp(Timestamp.ofTimeMicroseconds(333)); - Function testSpannerOperations = spannerOperations -> { - spannerOperations.executePartitionedDmlStatement(Statement.of("fail")); - return null; - }; + SpannerReadOptions testSpannerReadOptions = + new SpannerReadOptions().setTimestamp(Timestamp.ofTimeMicroseconds(333)); + Function testSpannerOperations = + spannerOperations -> { + spannerOperations.executePartitionedDmlStatement(Statement.of("fail")); + return null; + }; - assertThatThrownBy(() -> this.spannerTemplate.performReadOnlyTransaction( - testSpannerOperations, testSpannerReadOptions)) - .hasMessage("A read-only transaction template cannot execute partitioned DML."); + assertThatThrownBy( + () -> + this.spannerTemplate.performReadOnlyTransaction( + testSpannerOperations, testSpannerReadOptions)) + .hasMessage("A read-only transaction template cannot execute partitioned DML."); } @Test @@ -407,49 +414,75 @@ void readWriteTransactionPartitionedDmlTest() { TransactionCallable transactionCallable = invocation.getArgument(0); return transactionCallable.run(transactionContext); }); - Function testSpannerOperations = spannerTemplate -> { - spannerTemplate.executePartitionedDmlStatement(Statement.of("DML statement here")); - return "all done"; - }; + Function testSpannerOperations = + spannerTemplate -> { + spannerTemplate.executePartitionedDmlStatement(Statement.of("DML statement here")); + return "all done"; + }; - assertThatThrownBy(() -> this.spannerTemplate.performReadWriteTransaction(testSpannerOperations)) - .hasMessage("A read-write transaction template cannot execute partitioned" + " DML."); + assertThatThrownBy( + () -> this.spannerTemplate.performReadWriteTransaction(testSpannerOperations)) + .hasMessage("A read-write transaction template cannot execute partitioned" + " DML."); } @Test void nullDatabaseClientTest() { - assertThatThrownBy(() -> new SpannerTemplate( - null, this.mappingContext, this.objectMapper, this.mutationFactory, this.schemaUtils)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A valid database client for Spanner is required."); + assertThatThrownBy( + () -> + new SpannerTemplate( + null, + this.mappingContext, + this.objectMapper, + this.mutationFactory, + this.schemaUtils)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A valid database client for Spanner is required."); } @Test void nullMappingContextTest() { - assertThatThrownBy(() -> new SpannerTemplate( - () -> this.databaseClient, null, this.objectMapper, this.mutationFactory, this.schemaUtils)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A valid mapping context for Spanner is required."); + assertThatThrownBy( + () -> + new SpannerTemplate( + () -> this.databaseClient, + null, + this.objectMapper, + this.mutationFactory, + this.schemaUtils)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A valid mapping context for Spanner is required."); } @Test void nullObjectMapperTest() { - assertThatThrownBy(() -> new SpannerTemplate( - () -> this.databaseClient, this.mappingContext, null, this.mutationFactory, this.schemaUtils)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A valid entity processor for Spanner is required."); + assertThatThrownBy( + () -> + new SpannerTemplate( + () -> this.databaseClient, + this.mappingContext, + null, + this.mutationFactory, + this.schemaUtils)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A valid entity processor for Spanner is required."); } @Test void nullMutationFactoryTest() { - assertThatThrownBy(() -> new SpannerTemplate( - () -> this.databaseClient, this.mappingContext, this.objectMapper, null, this.schemaUtils)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A valid Spanner mutation factory is required."); + assertThatThrownBy( + () -> + new SpannerTemplate( + () -> this.databaseClient, + this.mappingContext, + this.objectMapper, + null, + this.schemaUtils)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A valid Spanner mutation factory is required."); } @Test @@ -524,9 +557,9 @@ void findKeySetTestEagerConvertedOptions() { SpannerTemplate spyTemplate = spy(this.spannerTemplate); KeySet keys = KeySet.newBuilder().addKey(Key.of("key1")).addKey(Key.of("key2")).build(); SpannerReadOptions options = - new SpannerReadOptions() - .addReadOption(mock(Options.ReadAndQueryOption.class)) - .addReadOption(mock(Options.ReadQueryUpdateTransactionOption.class)); + new SpannerReadOptions() + .addReadOption(mock(Options.ReadAndQueryOption.class)) + .addReadOption(mock(Options.ReadQueryUpdateTransactionOption.class)); spyTemplate.read(ParentEntity.class, keys, options); verify(spyTemplate).read(eq(ParentEntity.class), same(keys), eq(options)); verify(this.databaseClient, times(1)).singleUse(); @@ -1008,8 +1041,7 @@ private void verifyAfterEvents( @Table(name = "test_table_embedded_pk") private static class TestEntityEmbeddedPrimaryKey { - @Embedded @PrimaryKey - EmbeddedPrimaryKey key; + @Embedded @PrimaryKey EmbeddedPrimaryKey key; } private static class EmbeddedPrimaryKey { diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerTemplateTransactionManagerTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerTemplateTransactionManagerTests.java index 2755c50792..4c13fd02b6 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerTemplateTransactionManagerTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/SpannerTemplateTransactionManagerTests.java @@ -210,25 +210,25 @@ void doWithoutTransaction() { @Test void readOnlySaveTest() { assertThatThrownBy(() -> this.transactionalService.writingInReadOnly(new TestEntity())) - .hasMessage("Spanner transaction cannot apply mutations because it is in readonly mode"); + .hasMessage("Spanner transaction cannot apply mutations because it is in readonly mode"); } @Test void readOnlyDeleteTest() { assertThatThrownBy(() -> this.transactionalService.deleteInReadOnly(new TestEntity())) - .hasMessage("Spanner transaction cannot apply mutations because it is in readonly mode"); + .hasMessage("Spanner transaction cannot apply mutations because it is in readonly mode"); } @Test void readOnlyDmlTest() { assertThatThrownBy(() -> this.transactionalService.dmlInReadOnly()) - .hasMessage("Spanner transaction cannot execute DML because it is in readonly mode"); + .hasMessage("Spanner transaction cannot execute DML because it is in readonly mode"); } @Test void partitionedDmlInTransactionTest() { assertThatThrownBy(() -> this.transactionalService.partitionedDmlInTransaction()) - .hasMessage("Cannot execute partitioned DML in a transaction."); + .hasMessage("Cannot execute partitioned DML in a transaction."); } /** Spring config for the tests. */ diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/admin/SpannerDatabaseAdminTemplateTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/admin/SpannerDatabaseAdminTemplateTests.java index 0c91520226..52b1fd3576 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/admin/SpannerDatabaseAdminTemplateTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/admin/SpannerDatabaseAdminTemplateTests.java @@ -77,8 +77,7 @@ void setup() { @Test void getTableRelationshipsTest() { when(this.mockDatabasePage.getValues()) - .thenReturn( - List.of(new Database(this.databaseId, State.READY, this.databaseAdminClient))); + .thenReturn(List.of(new Database(this.databaseId, State.READY, this.databaseAdminClient))); ReadContext readContext = mock(ReadContext.class); Struct s1 = @@ -223,17 +222,16 @@ void getTableRelationshipsTest() { assertThat(this.spannerDatabaseAdminTemplate.isInterleaved("parent_b", "child")) .as("verify not parent-child relationship") .isFalse(); - - assertThat(this.spannerDatabaseAdminTemplate - .isInterleaved("my_schema.grandpa", "my_schema.dad")) + + assertThat( + this.spannerDatabaseAdminTemplate.isInterleaved("my_schema.grandpa", "my_schema.dad")) .as("verify my-schema grand-child relationship") .isTrue(); - assertThat(this.spannerDatabaseAdminTemplate - .isInterleaved("my_schema.grandpa", "my_schema.child")) + assertThat( + this.spannerDatabaseAdminTemplate.isInterleaved("my_schema.grandpa", "my_schema.child")) .as("verify my-schema grand-child relationship") .isTrue(); - assertThat(this.spannerDatabaseAdminTemplate - .isInterleaved("my_schema.grandpa", "child")) + assertThat(this.spannerDatabaseAdminTemplate.isInterleaved("my_schema.grandpa", "child")) .as("verify not my-schema grand-child relationship") .isFalse(); } diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/admin/SpannerSchemaUtilsTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/admin/SpannerSchemaUtilsTests.java index 02fa5d67e3..dd6b3b77f4 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/admin/SpannerSchemaUtilsTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/admin/SpannerSchemaUtilsTests.java @@ -175,7 +175,11 @@ void createDdlForJson() { assertColumnDdl( JsonColumn.class, null, "jsonCol", Type.Code.JSON, OptionalLong.empty(), "jsonCol JSON"); assertColumnDdl( - List.class, JsonColumn.class, "arrayJsonCol", Type.Code.JSON, OptionalLong.empty(), + List.class, + JsonColumn.class, + "arrayJsonCol", + Type.Code.JSON, + OptionalLong.empty(), "arrayJsonCol ARRAY"); } diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/convert/KeyConversionTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/convert/KeyConversionTests.java index 508688f501..0977a7c7b3 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/convert/KeyConversionTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/convert/KeyConversionTests.java @@ -32,7 +32,6 @@ import org.junit.jupiter.params.provider.MethodSource; /** Tests for converting Spanner keys. */ - class KeyConversionTests { private final SpannerWriteConverter writeConverter; diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/convert/SpannerWriteMethodCoverageTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/convert/SpannerWriteMethodCoverageTests.java index ae0c4513db..c2908f142d 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/convert/SpannerWriteMethodCoverageTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/convert/SpannerWriteMethodCoverageTests.java @@ -37,9 +37,9 @@ void allKnownMappingTypesTest() throws NoSuchFieldException { // TODO: https://github.com/GoogleCloudPlatform/spring-cloud-gcp/issues/2574 // Until this is implemented, ignore the new column types by ignoring the methods // that have the new column types as a parameter - if (Arrays.stream(method.getParameterTypes()).map(Class::getName) - .anyMatch(x -> x.contains("ProtocolMessageEnum") - || x.contains("AbstractMessage"))) { + if (Arrays.stream(method.getParameterTypes()) + .map(Class::getName) + .anyMatch(x -> x.contains("ProtocolMessageEnum") || x.contains("AbstractMessage"))) { continue; } diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/it/SpannerTemplateIntegrationTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/it/SpannerTemplateIntegrationTests.java index 18330cc429..5081fe7b76 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/it/SpannerTemplateIntegrationTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/it/SpannerTemplateIntegrationTests.java @@ -188,17 +188,18 @@ void readOnlyTransactionTest() { Trade trade = Trade.makeTrade(); - Function operation = transactionOperations -> { - // cannot do mutate in a read-only transaction - transactionOperations.insert(trade); - return null; - }; + Function operation = + transactionOperations -> { + // cannot do mutate in a read-only transaction + transactionOperations.insert(trade); + return null; + }; SpannerReadOptions readOptions = new SpannerReadOptions(); - assertThatThrownBy(() -> this.spannerOperations.performReadOnlyTransaction(operation, readOptions)) - .isInstanceOf(SpannerDataException.class) - .hasMessage("A read-only transaction template cannot perform mutations."); - + assertThatThrownBy( + () -> this.spannerOperations.performReadOnlyTransaction(operation, readOptions)) + .isInstanceOf(SpannerDataException.class) + .hasMessage("A read-only transaction template cannot perform mutations."); } /** a transactional service for testing annotated transaction methods. */ diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerKeyPropertyTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerKeyPropertyTests.java index 8d94ebe2dd..41f8682782 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerKeyPropertyTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerKeyPropertyTests.java @@ -44,18 +44,18 @@ void setup() { @Test void nullSpannerPersistentEntityTest() { - assertThatThrownBy(() -> new SpannerCompositeKeyProperty(null, new SpannerPersistentProperty[] {})) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A valid Cloud Spanner persistent entity is required."); + assertThatThrownBy( + () -> new SpannerCompositeKeyProperty(null, new SpannerPersistentProperty[] {})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A valid Cloud Spanner persistent entity is required."); } @Test void nullPropertiesTest() { assertThatThrownBy(() -> new SpannerCompositeKeyProperty(this.spannerPersistentEntity, null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A valid array of primary key properties is required."); - + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A valid array of primary key properties is required."); } @Test diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentEntityImplTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentEntityImplTests.java index 207a39f784..c2556f1371 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentEntityImplTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentEntityImplTests.java @@ -47,15 +47,17 @@ class SpannerPersistentEntityImplTests { SpannerPersistentEntityImplTests() { this.spannerMappingContext = new SpannerMappingContext(); - this.spannerEntityProcessor = new ConverterAwareMappingSpannerEntityProcessor( - this.spannerMappingContext); + this.spannerEntityProcessor = + new ConverterAwareMappingSpannerEntityProcessor(this.spannerMappingContext); } @Test void testTableName() { SpannerPersistentEntityImpl entity = - new SpannerPersistentEntityImpl<>(TypeInformation.of(TestEntity.class), - this.spannerMappingContext, this.spannerEntityProcessor); + new SpannerPersistentEntityImpl<>( + TypeInformation.of(TestEntity.class), + this.spannerMappingContext, + this.spannerEntityProcessor); assertThat(entity.tableName()).isEqualTo("custom_test_table"); } @@ -63,8 +65,10 @@ void testTableName() { @Test void testRawTableName() { SpannerPersistentEntityImpl entity = - new SpannerPersistentEntityImpl<>(TypeInformation.of(EntityNoCustomName.class), - this.spannerMappingContext, this.spannerEntityProcessor); + new SpannerPersistentEntityImpl<>( + TypeInformation.of(EntityNoCustomName.class), + this.spannerMappingContext, + this.spannerEntityProcessor); assertThat(entity.tableName()).isEqualTo("entityNoCustomName"); } @@ -72,8 +76,10 @@ void testRawTableName() { @Test void testEmptyCustomTableName() { SpannerPersistentEntityImpl entity = - new SpannerPersistentEntityImpl<>(TypeInformation.of(EntityEmptyCustomName.class), - this.spannerMappingContext, this.spannerEntityProcessor); + new SpannerPersistentEntityImpl<>( + TypeInformation.of(EntityEmptyCustomName.class), + this.spannerMappingContext, + this.spannerEntityProcessor); assertThat(entity.tableName()).isEqualTo("entityEmptyCustomName"); } @@ -88,19 +94,24 @@ void testColumns() { void testExpressionResolutionWithoutApplicationContext() { SpannerPersistentEntityImpl entity = - new SpannerPersistentEntityImpl<>(TypeInformation.of(EntityWithExpression.class), - this.spannerMappingContext, this.spannerEntityProcessor); + new SpannerPersistentEntityImpl<>( + TypeInformation.of(EntityWithExpression.class), + this.spannerMappingContext, + this.spannerEntityProcessor); assertThatThrownBy(entity::tableName) .isInstanceOf(SpannerDataException.class) .hasMessage("Error getting table name for EntityWithExpression") - .hasStackTraceContaining("EL1007E: Property or field 'tablePostfix' cannot be found on null"); + .hasStackTraceContaining( + "EL1007E: Property or field 'tablePostfix' cannot be found on null"); } @Test void testExpressionResolutionFromApplicationContext() { SpannerPersistentEntityImpl entity = - new SpannerPersistentEntityImpl<>(TypeInformation.of(EntityWithExpression.class), - this.spannerMappingContext, this.spannerEntityProcessor); + new SpannerPersistentEntityImpl<>( + TypeInformation.of(EntityWithExpression.class), + this.spannerMappingContext, + this.spannerEntityProcessor); ApplicationContext applicationContext = mock(ApplicationContext.class); when(applicationContext.getBean("tablePostfix")).thenReturn("something"); @@ -114,9 +125,12 @@ void testExpressionResolutionFromApplicationContext() { void testDuplicatePrimaryKeyOrder() { SpannerMappingContext spannerMappingContext = new SpannerMappingContext(); - assertThatThrownBy(() -> spannerMappingContext.getPersistentEntity(EntityWithDuplicatePrimaryKeyOrder.class)) - .isInstanceOf(SpannerDataException.class) - .hasMessage("Two properties were annotated with the same primary key order: id2 and id in EntityWithDuplicatePrimaryKeyOrder."); + assertThatThrownBy( + () -> + spannerMappingContext.getPersistentEntity(EntityWithDuplicatePrimaryKeyOrder.class)) + .isInstanceOf(SpannerDataException.class) + .hasMessage( + "Two properties were annotated with the same primary key order: id2 and id in EntityWithDuplicatePrimaryKeyOrder."); } @Test @@ -124,10 +138,11 @@ void testInvalidPrimaryKeyOrder() { SpannerMappingContext spannerMappingContext = new SpannerMappingContext(); - assertThatThrownBy(() -> spannerMappingContext.getPersistentEntity(EntityWithWronglyOrderedKeys.class)) - .isInstanceOf(SpannerDataException.class) - .hasMessage("The primary key columns were not given a consecutive order. There is no property annotated with order 2 in EntityWithWronglyOrderedKeys."); - + assertThatThrownBy( + () -> spannerMappingContext.getPersistentEntity(EntityWithWronglyOrderedKeys.class)) + .isInstanceOf(SpannerDataException.class) + .hasMessage( + "The primary key columns were not given a consecutive order. There is no property annotated with order 2 in EntityWithWronglyOrderedKeys."); } @Test @@ -178,8 +193,8 @@ void testSetIdPropertyLongerKey() { Key testKey = Key.of("blah", 123L, 123.45D, "abc"); assertThatThrownBy(() -> propertyAccessor.setProperty(idProperty, testKey)) - .isInstanceOf(SpannerDataException.class) - .hasMessage("The number of key parts is not equal to the number of primary key properties"); + .isInstanceOf(SpannerDataException.class) + .hasMessage("The number of key parts is not equal to the number of primary key properties"); } @Test @@ -194,9 +209,8 @@ void testSetIdPropertyNullKey() { PersistentPropertyAccessor propertyAccessor = entity.getPropertyAccessor(t); assertThatThrownBy(() -> propertyAccessor.setProperty(idProperty, null)) - .isInstanceOf(SpannerDataException.class) - .hasMessage("The number of key parts is not equal to the number of primary key properties"); - + .isInstanceOf(SpannerDataException.class) + .hasMessage("The number of key parts is not equal to the number of primary key properties"); } @Test @@ -216,8 +230,10 @@ void testIgnoredProperty() { void testInvalidTableName() { SpannerPersistentEntityImpl entity = - new SpannerPersistentEntityImpl<>(TypeInformation.of(EntityBadName.class), - this.spannerMappingContext, this.spannerEntityProcessor); + new SpannerPersistentEntityImpl<>( + TypeInformation.of(EntityBadName.class), + this.spannerMappingContext, + this.spannerEntityProcessor); assertThatThrownBy(entity::tableName) .isInstanceOf(SpannerDataException.class) @@ -230,8 +246,10 @@ void testInvalidTableName() { void testSpelInvalidName() { SpannerPersistentEntityImpl entity = - new SpannerPersistentEntityImpl<>(TypeInformation.of(EntityWithExpression.class), - this.spannerMappingContext, this.spannerEntityProcessor); + new SpannerPersistentEntityImpl<>( + TypeInformation.of(EntityWithExpression.class), + this.spannerMappingContext, + this.spannerEntityProcessor); ApplicationContext applicationContext = mock(ApplicationContext.class); when(applicationContext.getBean("tablePostfix")).thenReturn("; DROP TABLE your_table;"); @@ -245,18 +263,17 @@ void testSpelInvalidName() { .hasStackTraceContaining( "Only letters, numbers, and underscores are allowed in table names: " + "table_; DROP TABLE your_table;"); - - } @Test void testDuplicateEmbeddedColumnName() { - - assertThatThrownBy(() -> this.spannerMappingContext.getPersistentEntity(EmbeddedParentDuplicateColumn.class)) - .isInstanceOf(SpannerDataException.class) - .hasMessage("Two properties resolve to the same column name: other in EmbeddedParentDuplicateColumn"); - + assertThatThrownBy( + () -> + this.spannerMappingContext.getPersistentEntity(EmbeddedParentDuplicateColumn.class)) + .isInstanceOf(SpannerDataException.class) + .hasMessage( + "Two properties resolve to the same column name: other in EmbeddedParentDuplicateColumn"); } @Test @@ -297,9 +314,10 @@ void testEmbeddedParentKeys() { @Test void testEmbeddedCollection() { - assertThatThrownBy(() -> this.spannerMappingContext.getPersistentEntity(ChildCollectionEmbedded.class)) - .isInstanceOf(SpannerDataException.class) - .hasMessageContaining("Embedded properties cannot be collections: "); + assertThatThrownBy( + () -> this.spannerMappingContext.getPersistentEntity(ChildCollectionEmbedded.class)) + .isInstanceOf(SpannerDataException.class) + .hasMessageContaining("Embedded properties cannot be collections: "); } @Test @@ -328,10 +346,14 @@ void doWithChildrenCollectionsTest() { @Test void testParentChildPkNamesMismatch() { - assertThatThrownBy(() -> this.spannerMappingContext.getPersistentEntity(ParentInRelationshipMismatchedKeyName.class)) - .isInstanceOf(SpannerDataException.class) - .hasMessage("The child primary key column (ChildBinRelationship.id) at position 1 does not match that " - + "of its parent (ParentInRelationshipMismatchedKeyName.idNameDifferentThanChildren)."); + assertThatThrownBy( + () -> + this.spannerMappingContext.getPersistentEntity( + ParentInRelationshipMismatchedKeyName.class)) + .isInstanceOf(SpannerDataException.class) + .hasMessage( + "The child primary key column (ChildBinRelationship.id) at position 1 does not match that " + + "of its parent (ParentInRelationshipMismatchedKeyName.idNameDifferentThanChildren)."); } @Test diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentPropertyImplTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentPropertyImplTests.java index 3dcdcddf14..bce2eb8a6f 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentPropertyImplTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/SpannerPersistentPropertyImplTests.java @@ -37,7 +37,7 @@ class SpannerPersistentPropertyImplTests { @Test void testGetColumn() { assertThat(new SpannerMappingContext().getPersistentEntity(TestEntity.class).columns()) - .containsExactlyInAnyOrder("id", "custom_col", "other", "doubleList"); + .containsExactlyInAnyOrder("id", "custom_col", "other", "doubleList"); } @Test @@ -49,58 +49,59 @@ void testNullColumnName() { context.setFieldNamingStrategy(namingStrat); assertThatThrownBy(() -> context.getPersistentEntity(TestEntity.class)) - .hasMessageContaining("Invalid (null or empty) field name returned for " - + "property @com.google.cloud.spring.data.spanner.core.mapping.PrimaryKey") - .hasMessageContaining("keyOrder=1") - .hasMessageContaining("value=1") - .hasMessageContaining("java.lang.String com.google.cloud.spring.data.spanner.core.mapping." - + "SpannerPersistentPropertyImplTests$TestEntity.id by class " - + "org.springframework.data.mapping.model.FieldNamingStrategy$MockitoMock$"); + .hasMessageContaining( + "Invalid (null or empty) field name returned for " + + "property @com.google.cloud.spring.data.spanner.core.mapping.PrimaryKey") + .hasMessageContaining("keyOrder=1") + .hasMessageContaining("value=1") + .hasMessageContaining( + "java.lang.String com.google.cloud.spring.data.spanner.core.mapping." + + "SpannerPersistentPropertyImplTests$TestEntity.id by class " + + "org.springframework.data.mapping.model.FieldNamingStrategy$MockitoMock$"); } - @Test void testAssociations() { new SpannerMappingContext() - .getPersistentEntity(TestEntity.class) - .doWithProperties( - (PropertyHandler) - prop -> { - assertThat( - ((SpannerPersistentPropertyImpl) prop).createAssociation().getInverse()) - .isSameAs(prop); - assertThat( - ((SpannerPersistentPropertyImpl) prop).createAssociation().getObverse()) - .isNull(); - }); + .getPersistentEntity(TestEntity.class) + .doWithProperties( + (PropertyHandler) + prop -> { + assertThat( + ((SpannerPersistentPropertyImpl) prop).createAssociation().getInverse()) + .isSameAs(prop); + assertThat( + ((SpannerPersistentPropertyImpl) prop).createAssociation().getObverse()) + .isNull(); + }); } @Test void testColumnInnerType() { assertThat( new SpannerMappingContext() - .getPersistentEntity(TestEntity.class) - .getPersistentProperty("doubleList") - .getColumnInnerType()) - .isEqualTo(Double.class); + .getPersistentEntity(TestEntity.class) + .getPersistentProperty("doubleList") + .getColumnInnerType()) + .isEqualTo(Double.class); } @Test void testNoPojoIdProperties() { new SpannerMappingContext() - .getPersistentEntity(TestEntity.class) - .doWithProperties( - (PropertyHandler) - prop -> assertThat(prop.isIdProperty()).isFalse()); + .getPersistentEntity(TestEntity.class) + .doWithProperties( + (PropertyHandler) + prop -> assertThat(prop.isIdProperty()).isFalse()); } @Test void testIgnoredProperty() { new SpannerMappingContext() - .getPersistentEntity(TestEntity.class) - .doWithProperties( - (PropertyHandler) - prop -> assertThat(prop.getColumnName()).isNotEqualTo("not_mapped")); + .getPersistentEntity(TestEntity.class) + .doWithProperties( + (PropertyHandler) + prop -> assertThat(prop.getColumnName()).isNotEqualTo("not_mapped")); } @Table(name = "custom_test_table") diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/typeadapter/InstantTypeAdapterTest.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/typeadapter/InstantTypeAdapterTest.java index b110d9aade..eabf00bbc8 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/typeadapter/InstantTypeAdapterTest.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/core/mapping/typeadapter/InstantTypeAdapterTest.java @@ -22,7 +22,6 @@ public void writeInstantTest_epochSecond0() throws IOException { instantTypeAdapter.write(jsonWriter, instant); assertThat(stringWriter.toString()).isEqualTo("\"1970-01-01T00:00:00Z\""); - } @Test diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/it/SpannerRepositoryInsertIntegrationTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/it/SpannerRepositoryInsertIntegrationTests.java index beaeba1d7c..7fa63d0af6 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/it/SpannerRepositoryInsertIntegrationTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/it/SpannerRepositoryInsertIntegrationTests.java @@ -35,7 +35,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; /** Integration tests for Spanner Repository. */ - @EnabledIfSystemProperty(named = "it.spanner", matches = "true") @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = {IntegrationTestConfiguration.class}) diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SpannerQueryMethodTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SpannerQueryMethodTests.java index 5f256691b4..ecc020461c 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SpannerQueryMethodTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SpannerQueryMethodTests.java @@ -39,7 +39,8 @@ void setUp() throws Exception { this.mockMetadata = mock(RepositoryMetadata.class); this.mockProjectionFactory = mock(ProjectionFactory.class); doReturn(TypeInformation.fromReturnTypeOf(Example.class.getMethod("someAnnotatedMethod"))) - .when(mockMetadata).getReturnType(any()); + .when(mockMetadata) + .getReturnType(any()); doAnswer(a -> String.class).when(mockMetadata).getReturnedDomainClass(any()); } diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SpannerStatementQueryTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SpannerStatementQueryTests.java index 7f44d391ec..3e8da8a722 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SpannerStatementQueryTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SpannerStatementQueryTests.java @@ -174,7 +174,9 @@ void compoundNameConventionTest() throws NoSuchMethodException { List.class, BigDecimal.class); when(this.queryMethod.getQueryMethod()).thenReturn(method); - doReturn(new DefaultParameters(ParametersSource.of(method))).when(this.queryMethod).getParameters(); + doReturn(new DefaultParameters(ParametersSource.of(method))) + .when(this.queryMethod) + .getParameters(); this.partTreeSpannerQuery.execute(params); verify(this.spannerTemplate, times(1)).query((Class) any(), any(), any()); @@ -222,7 +224,9 @@ void compoundNameConventionCountTest() throws NoSuchMethodException { Object.class, Object.class, Object.class); - doReturn(new DefaultParameters(ParametersSource.of(method))).when(this.queryMethod).getParameters(); + doReturn(new DefaultParameters(ParametersSource.of(method))) + .when(this.queryMethod) + .getParameters(); when(this.spannerTemplate.query((Function) any(), any(), any())) .thenAnswer( @@ -296,7 +300,9 @@ private void runPageableOrSortTest(Object[] params, Method method, String expect when(this.spannerTemplate.query((Function) any(), any(), any())) .thenReturn(Collections.singletonList(1L)); - doReturn(new DefaultParameters(ParametersSource.of(method))).when(this.queryMethod).getParameters(); + doReturn(new DefaultParameters(ParametersSource.of(method))) + .when(this.queryMethod) + .getParameters(); when(this.spannerTemplate.query((Class) any(), any(), any())) .thenAnswer( @@ -325,7 +331,9 @@ void pageableNotLastParameterTest() throws NoSuchMethodException { // Test that preparePartTreeSqlTagParameterMap() can process cases // where Pageable is not the last parameter Object[] params = new Object[] {"BUY", PageRequest.of(1, 10, Sort.by("traderId")), "STOCK1"}; - Method method = QueryHolder.class.getMethod("repositoryMethod7", String.class, Pageable.class, String.class); + Method method = + QueryHolder.class.getMethod( + "repositoryMethod7", String.class, Pageable.class, String.class); when(this.queryMethod.getQueryMethod()).thenReturn(method); String expectedSql = @@ -334,14 +342,15 @@ void pageableNotLastParameterTest() throws NoSuchMethodException { + "WHERE ( action=@tag0 AND ticker=@tag1 ) " + "ORDER BY trader_id ASC LIMIT 10 OFFSET 10"; - when(this.queryMethod.getName()).thenReturn("findByActionAndSymbol"); this.partTreeSpannerQuery = spy(createQuery()); when(this.spannerTemplate.query((Function) any(), any(), any())) .thenReturn(Collections.singletonList(1L)); - doReturn(new DefaultParameters(ParametersSource.of(method))).when(this.queryMethod).getParameters(); + doReturn(new DefaultParameters(ParametersSource.of(method))) + .when(this.queryMethod) + .getParameters(); when(this.spannerTemplate.query((Class) any(), any(), any())) .thenAnswer( @@ -378,7 +387,9 @@ void unspecifiedParametersTest() throws NoSuchMethodException { this.partTreeSpannerQuery = createQuery(); Method method = QueryHolder.class.getMethod("repositoryMethod4", Object.class, Object.class, Object.class); - doReturn(new DefaultParameters(ParametersSource.of(method))).when(this.queryMethod).getParameters(); + doReturn(new DefaultParameters(ParametersSource.of(method))) + .when(this.queryMethod) + .getParameters(); // There are too few params specified, so the exception will occur. Object[] params = @@ -387,8 +398,8 @@ void unspecifiedParametersTest() throws NoSuchMethodException { }; assertThatThrownBy(() -> this.partTreeSpannerQuery.execute(params)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The number of tags does not match the number of params."); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The number of tags does not match the number of params."); } @Test @@ -409,7 +420,9 @@ void unsupportedParamTypeTest() throws NoSuchMethodException { Trade.class, Object.class); - doReturn(new DefaultParameters(ParametersSource.of(method))).when(this.queryMethod).getParameters(); + doReturn(new DefaultParameters(ParametersSource.of(method))) + .when(this.queryMethod) + .getParameters(); // This parameter is an unsupported type for Spanner SQL. Object[] params = @@ -418,22 +431,25 @@ void unsupportedParamTypeTest() throws NoSuchMethodException { }; assertThatThrownBy(() -> this.partTreeSpannerQuery.execute(params)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("is not a supported type: class com.google." - + "cloud.spring.data.spanner.repository.query.SpannerStatementQueryTests$Trade"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "is not a supported type: class com.google." + + "cloud.spring.data.spanner.repository.query.SpannerStatementQueryTests$Trade"); } @Test void unSupportedPredicateTest() throws NoSuchMethodException { when(this.queryMethod.getName()).thenReturn("countByTraderIdBetween"); Method method = Object.class.getMethod("toString"); - doReturn(new DefaultParameters(ParametersSource.of(method))).when(this.queryMethod).getParameters(); + doReturn(new DefaultParameters(ParametersSource.of(method))) + .when(this.queryMethod) + .getParameters(); this.partTreeSpannerQuery = createQuery(); assertThatThrownBy(() -> this.partTreeSpannerQuery.execute(EMPTY_PARAMETERS)) - .isInstanceOf(UnsupportedOperationException.class) - .hasMessage("The statement type: BETWEEN (2): [IsBetween, " + "Between] is not supported."); + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("The statement type: BETWEEN (2): [IsBetween, " + "Between] is not supported."); } @Table(name = "trades") diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SqlSpannerQueryTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SqlSpannerQueryTests.java index 5806913683..850b5796b2 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SqlSpannerQueryTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/query/SqlSpannerQueryTests.java @@ -153,12 +153,13 @@ void noPageableParamQueryTest() throws NoSuchMethodException { when(queryMethod.isCollectionQuery()).thenReturn(false); when(queryMethod.getReturnedObjectType()).thenReturn(toReturn); - ValueEvaluationContextProvider evaluationContextProvider = mock(ValueEvaluationContextProvider.class); - ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); - when(this.valueExpressionDelegate.createValueContextProvider(any())) - .thenReturn(evaluationContextProvider); - when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); - when(valueEvaluationContext.getEvaluationContext()).thenReturn(mock(EvaluationContext.class)); + ValueEvaluationContextProvider evaluationContextProvider = + mock(ValueEvaluationContextProvider.class); + ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); + when(this.valueExpressionDelegate.createValueContextProvider(any())) + .thenReturn(evaluationContextProvider); + when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); + when(valueEvaluationContext.getEvaluationContext()).thenReturn(mock(EvaluationContext.class)); SqlSpannerQuery sqlSpannerQuery = createQuery(sql, toReturn, false); @@ -216,12 +217,13 @@ void pageableParamQueryTest() throws NoSuchMethodException { for (int i = 0; i < params.length; i++) { evaluationContext.setVariable(paramNames[i], params[i]); } - ValueEvaluationContextProvider evaluationContextProvider = mock(ValueEvaluationContextProvider.class); + ValueEvaluationContextProvider evaluationContextProvider = + mock(ValueEvaluationContextProvider.class); ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); - when(this.valueExpressionDelegate.createValueContextProvider(any())) - .thenReturn(evaluationContextProvider); - when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); - when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); + when(this.valueExpressionDelegate.createValueContextProvider(any())) + .thenReturn(evaluationContextProvider); + when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); + when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); SqlSpannerQuery sqlSpannerQuery = createQuery(sql, Child.class, false); @@ -283,12 +285,13 @@ void sortParamQueryTest() throws NoSuchMethodException { for (int i = 0; i < params.length; i++) { evaluationContext.setVariable(paramNames[i], params[i]); } - ValueEvaluationContextProvider evaluationContextProvider = mock(ValueEvaluationContextProvider.class); - ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); - when(this.valueExpressionDelegate.createValueContextProvider(any())) - .thenReturn(evaluationContextProvider); - when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); - when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); + ValueEvaluationContextProvider evaluationContextProvider = + mock(ValueEvaluationContextProvider.class); + ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); + when(this.valueExpressionDelegate.createValueContextProvider(any())) + .thenReturn(evaluationContextProvider); + when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); + when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); SqlSpannerQuery sqlSpannerQuery = createQuery(sql, Child.class, false); @@ -351,12 +354,13 @@ void sortAndPageableQueryTest() throws NoSuchMethodException { for (int i = 0; i < params.length; i++) { evaluationContext.setVariable(paramNames[i], params[i]); } - ValueEvaluationContextProvider evaluationContextProvider = mock(ValueEvaluationContextProvider.class); - ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); - when(this.valueExpressionDelegate.createValueContextProvider(any())) - .thenReturn(evaluationContextProvider); - when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); - when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); + ValueEvaluationContextProvider evaluationContextProvider = + mock(ValueEvaluationContextProvider.class); + ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); + when(this.valueExpressionDelegate.createValueContextProvider(any())) + .thenReturn(evaluationContextProvider); + when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); + when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); SqlSpannerQuery sqlSpannerQuery = createQuery(sql, Child.class, false); @@ -461,12 +465,13 @@ void compoundNameConventionTest() throws NoSuchMethodException { for (int i = 0; i < params.length; i++) { evaluationContext.setVariable(paramNames[i], params[i]); } - ValueEvaluationContextProvider evaluationContextProvider = mock(ValueEvaluationContextProvider.class); - ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); - when(this.valueExpressionDelegate.createValueContextProvider(any())) - .thenReturn(evaluationContextProvider); - when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); - when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); + ValueEvaluationContextProvider evaluationContextProvider = + mock(ValueEvaluationContextProvider.class); + ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); + when(this.valueExpressionDelegate.createValueContextProvider(any())) + .thenReturn(evaluationContextProvider); + when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); + when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); SqlSpannerQuery sqlSpannerQuery = createQuery(sql, Trade.class, false); @@ -535,12 +540,13 @@ void dmlTest() throws NoSuchMethodException { TransactionRunner transactionRunner = mock(TransactionRunner.class); when(this.databaseClient.readWriteTransaction()).thenReturn(transactionRunner); - ValueEvaluationContextProvider evaluationContextProvider = mock(ValueEvaluationContextProvider.class); - ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); - when(this.valueExpressionDelegate.createValueContextProvider(any())) - .thenReturn(evaluationContextProvider); - when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); - when(valueEvaluationContext.getEvaluationContext()).thenReturn(mock(EvaluationContext.class)); + ValueEvaluationContextProvider evaluationContextProvider = + mock(ValueEvaluationContextProvider.class); + ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); + when(this.valueExpressionDelegate.createValueContextProvider(any())) + .thenReturn(evaluationContextProvider); + when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); + when(valueEvaluationContext.getEvaluationContext()).thenReturn(mock(EvaluationContext.class)); when(transactionRunner.run(any())) .thenAnswer( @@ -584,12 +590,13 @@ void sqlCountWithWhereTest() throws NoSuchMethodException { for (int i = 0; i < params.length; i++) { evaluationContext.setVariable(paramNames[i], params[i]); } - ValueEvaluationContextProvider evaluationContextProvider = mock(ValueEvaluationContextProvider.class); - ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); - when(this.valueExpressionDelegate.createValueContextProvider(any())) - .thenReturn(evaluationContextProvider); - when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); - when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); + ValueEvaluationContextProvider evaluationContextProvider = + mock(ValueEvaluationContextProvider.class); + ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); + when(this.valueExpressionDelegate.createValueContextProvider(any())) + .thenReturn(evaluationContextProvider); + when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); + when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); SqlSpannerQuery sqlSpannerQuery = createQuery(sql, long.class, false); @@ -652,12 +659,13 @@ void sqlReturnTypeIsJsonFieldTest() throws NoSuchMethodException { EvaluationContext evaluationContext = new StandardEvaluationContext(); evaluationContext.setVariable(paramNames[0], params[0]); - ValueEvaluationContextProvider evaluationContextProvider = mock(ValueEvaluationContextProvider.class); - ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); - when(this.valueExpressionDelegate.createValueContextProvider(any())) - .thenReturn(evaluationContextProvider); - when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); - when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); + ValueEvaluationContextProvider evaluationContextProvider = + mock(ValueEvaluationContextProvider.class); + ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); + when(this.valueExpressionDelegate.createValueContextProvider(any())) + .thenReturn(evaluationContextProvider); + when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); + when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); SqlSpannerQuery sqlSpannerQuery = createQuery(sql, Singer.class, false); @@ -706,8 +714,8 @@ void sqlReturnTypeIsJsonFieldTest() throws NoSuchMethodException { void sqlReturnTypeIsArrayJsonFieldTest() throws NoSuchMethodException { String sql = "SELECT detailsList from singer where stageName = @stageName"; - Object[] params = new Object[]{"STAGENAME"}; - String[] paramNames = new String[]{"stageName"}; + Object[] params = new Object[] {"STAGENAME"}; + String[] paramNames = new String[] {"stageName"}; when(queryMethod.isCollectionQuery()).thenReturn(true); ResultProcessor resultProcessor = mock(ResultProcessor.class); @@ -719,24 +727,25 @@ void sqlReturnTypeIsArrayJsonFieldTest() throws NoSuchMethodException { EvaluationContext evaluationContext = new StandardEvaluationContext(); evaluationContext.setVariable(paramNames[0], params[0]); - ValueEvaluationContextProvider evaluationContextProvider = mock(ValueEvaluationContextProvider.class); - ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); - when(this.valueExpressionDelegate.createValueContextProvider(any())) - .thenReturn(evaluationContextProvider); - when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); - when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); + ValueEvaluationContextProvider evaluationContextProvider = + mock(ValueEvaluationContextProvider.class); + ValueEvaluationContext valueEvaluationContext = mock(ValueEvaluationContext.class); + when(this.valueExpressionDelegate.createValueContextProvider(any())) + .thenReturn(evaluationContextProvider); + when(evaluationContextProvider.getEvaluationContext(any())).thenReturn(valueEvaluationContext); + when(valueEvaluationContext.getEvaluationContext()).thenReturn(evaluationContext); SqlSpannerQuery sqlSpannerQuery = createQuery(sql, Singer.class, false); doAnswer( - invocation -> { - Statement statement = invocation.getArgument(1); - assertThat(statement.getSql()).isEqualTo(sql); - Map paramMap = statement.getParameters(); - assertThat(paramMap.get("stageName").getString()).isEqualTo(params[0]); - - return null; - }) + invocation -> { + Statement statement = invocation.getArgument(1); + assertThat(statement.getSql()).isEqualTo(sql); + Map paramMap = statement.getParameters(); + assertThat(paramMap.get("stageName").getString()).isEqualTo(params[0]); + + return null; + }) .when(this.spannerTemplate) .query((Function) any(), any(), any()); @@ -757,17 +766,22 @@ void sqlReturnTypeIsArrayJsonFieldTest() throws NoSuchMethodException { Struct row = mock(Struct.class); when(row.getType()) - .thenReturn(Type.struct( - Arrays.asList(Type.StructField.of("detailsList", Type.array(Type.json()))))); + .thenReturn( + Type.struct( + Arrays.asList(Type.StructField.of("detailsList", Type.array(Type.json()))))); when(row.getColumnType(0)).thenReturn(Type.array(Type.json())); - when(row.getJsonList(0)).thenReturn(Arrays.asList("{\"p1\":\"address line\",\"p2\":\"5\"}", - "{\"p1\":\"address line 2\",\"p2\":\"6\"}")); + when(row.getJsonList(0)) + .thenReturn( + Arrays.asList( + "{\"p1\":\"address line\",\"p2\":\"5\"}", + "{\"p1\":\"address line 2\",\"p2\":\"6\"}")); when(row.getColumnType("detailsList")).thenReturn(Type.array(Type.json())); Object result = rowFunc.apply(row); assertThat(result).isInstanceOf(List.class); - assertThat((List) result).hasSize(2) + assertThat((List) result) + .hasSize(2) .containsExactly(new Detail("address line", "5"), new Detail("address line 2", "6")); } @@ -802,8 +816,7 @@ public boolean equals(Object o) { return false; } Detail detail = (Detail) o; - return Objects.equal(p1, detail.p1) - && Objects.equal(p2, detail.p2); + return Objects.equal(p1, detail.p1) && Objects.equal(p2, detail.p2); } @Override diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/support/SimpleSpannerRepositoryTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/support/SimpleSpannerRepositoryTests.java index 018d5e040f..28beef7d94 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/support/SimpleSpannerRepositoryTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/support/SimpleSpannerRepositoryTests.java @@ -62,16 +62,16 @@ void setup() { void constructorNullSpannerOperationsTest() { assertThatThrownBy(() -> new SimpleSpannerRepository(null, Object.class)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A valid SpannerTemplate object is required."); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A valid SpannerTemplate object is required."); } @Test void constructorNullEntityTypeTest() { assertThatThrownBy(() -> new SimpleSpannerRepository(this.template, null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A valid entity type is required."); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A valid entity type is required."); } @Test @@ -84,74 +84,77 @@ void getSpannerOperationsTest() { @Test void saveNullObjectTest() { - SimpleSpannerRepository spannerRepository = new SimpleSpannerRepository(this.template, Object.class); + SimpleSpannerRepository spannerRepository = + new SimpleSpannerRepository(this.template, Object.class); assertThatThrownBy(() -> spannerRepository.save(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A non-null entity is required for saving."); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-null entity is required for saving."); } @Test void findNullIdTest() { - SimpleSpannerRepository spannerRepository = new SimpleSpannerRepository(this.template, Object.class); + SimpleSpannerRepository spannerRepository = + new SimpleSpannerRepository(this.template, Object.class); assertThatThrownBy(() -> spannerRepository.findById(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A non-null ID is required."); - - + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-null ID is required."); } @Test void existsNullIdTest() { - SimpleSpannerRepository spannerRepository = new SimpleSpannerRepository(this.template, Object.class); + SimpleSpannerRepository spannerRepository = + new SimpleSpannerRepository(this.template, Object.class); assertThatThrownBy(() -> spannerRepository.existsById(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A non-null ID is required."); - + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-null ID is required."); } @Test void deleteNullIdTest() { - SimpleSpannerRepository spannerRepository = new SimpleSpannerRepository(this.template, Object.class); + SimpleSpannerRepository spannerRepository = + new SimpleSpannerRepository(this.template, Object.class); assertThatThrownBy(() -> spannerRepository.deleteById(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A non-null ID is required."); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-null ID is required."); } @Test void deleteNullEntityTest() { - SimpleSpannerRepository spannerRepository = new SimpleSpannerRepository(this.template, Object.class); + SimpleSpannerRepository spannerRepository = + new SimpleSpannerRepository(this.template, Object.class); assertThatThrownBy(() -> spannerRepository.delete(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A non-null entity is required."); - + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-null entity is required."); } @Test void deleteAllNullEntityTest() { - SimpleSpannerRepository spannerRepository = new SimpleSpannerRepository(this.template, Object.class); + SimpleSpannerRepository spannerRepository = + new SimpleSpannerRepository(this.template, Object.class); assertThatThrownBy(() -> spannerRepository.deleteAll(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A non-null list of entities is required."); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-null list of entities is required."); } @Test void saveAllNullEntityTest() { - SimpleSpannerRepository spannerRepository = new SimpleSpannerRepository(this.template, Object.class); + SimpleSpannerRepository spannerRepository = + new SimpleSpannerRepository(this.template, Object.class); assertThatThrownBy(() -> spannerRepository.saveAll(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A non-null list of entities is required for saving."); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-null list of entities is required for saving."); } @Test @@ -188,13 +191,13 @@ void findByIdTest() { void findByIdKeyWritingThrowsAnException() { when(this.entityProcessor.convertToKey(any())).thenThrow(SpannerDataException.class); - SimpleSpannerRepository spannerRepository = new SimpleSpannerRepository(this.template, Object.class); + SimpleSpannerRepository spannerRepository = + new SimpleSpannerRepository(this.template, Object.class); assertThatThrownBy(() -> spannerRepository.findById(new Object[] {})) - .isInstanceOf(SpannerDataException.class); + .isInstanceOf(SpannerDataException.class); } - @Test void existsByIdTestFound() { when(this.entityProcessor.convertToKey(A_KEY)).thenReturn(A_KEY); @@ -285,8 +288,7 @@ void findAllById_failsOnNull() { void findAllById_shortcutsToEmptyReturn() { SimpleSpannerRepository repo = new SimpleSpannerRepository<>(this.template, Object.class); - assertThat(repo.findAllById(new ArrayList<>())) - .isEmpty(); + assertThat(repo.findAllById(new ArrayList<>())).isEmpty(); verifyNoInteractions(this.template); } diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/support/SpannerRepositoryFactoryTests.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/support/SpannerRepositoryFactoryTests.java index aab77e3191..d68592e77a 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/support/SpannerRepositoryFactoryTests.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/repository/support/SpannerRepositoryFactoryTests.java @@ -73,10 +73,11 @@ void getEntityInformationNotAvailableTest() { new SpannerRepositoryFactory(mock(SpannerMappingContext.class), this.spannerTemplate); assertThatThrownBy(() -> factory.getEntityInformation(TestEntity.class)) - .isInstanceOf(MappingException.class) - .hasMessage("Could not lookup mapping metadata for domain " - + "class com.google.cloud.spring.data.spanner.repository.support." - + "SpannerRepositoryFactoryTests$TestEntity!"); + .isInstanceOf(MappingException.class) + .hasMessage( + "Could not lookup mapping metadata for domain " + + "class com.google.cloud.spring.data.spanner.repository.support." + + "SpannerRepositoryFactoryTests$TestEntity!"); } @Test diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/SingerRepository.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/SingerRepository.java index 4c0a1b1498..75c4ab5d34 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/SingerRepository.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/SingerRepository.java @@ -26,5 +26,8 @@ public interface SingerRepository extends SpannerRepository { value = "INSERT INTO singers_list (singerId, firstName, lastName) VALUES (@singerId, @firstName," + " @lastName)") - void insert(@Param("singerId") Integer singerId, @Param("firstName") String firstName, @Param("lastName") String lastName); + void insert( + @Param("singerId") Integer singerId, + @Param("firstName") String firstName, + @Param("lastName") String lastName); } diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/Trade.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/Trade.java index 3e211cd337..c768292482 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/Trade.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/Trade.java @@ -325,8 +325,7 @@ public List
getAdditionalDetails() { return additionalDetails; } - public void setAdditionalDetails( - List
additionalDetails) { + public void setAdditionalDetails(List
additionalDetails) { this.additionalDetails = additionalDetails; } diff --git a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/TradeRepository.java b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/TradeRepository.java index aa75ab52a6..3391f983c3 100644 --- a/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/TradeRepository.java +++ b/spring-cloud-gcp-data-spanner/src/test/java/com/google/cloud/spring/data/spanner/test/domain/TradeRepository.java @@ -152,6 +152,7 @@ public interface TradeRepository extends SpannerRepository { @NonNull Trade getByAction(String s); - @Query("SELECT symbol from :com.google.cloud.spring.data.spanner.test.domain.Trade: where id = @id") + @Query( + "SELECT symbol from :com.google.cloud.spring.data.spanner.test.domain.Trade: where id = @id") Optional getSymbolById(@Param("id") String id); } diff --git a/spring-cloud-gcp-data-spanner/src/test/resources/logback-test.xml b/spring-cloud-gcp-data-spanner/src/test/resources/logback-test.xml index e1d2038170..842c0b5cf0 100644 --- a/spring-cloud-gcp-data-spanner/src/test/resources/logback-test.xml +++ b/spring-cloud-gcp-data-spanner/src/test/resources/logback-test.xml @@ -1,16 +1,16 @@ - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + - + - - - + + +