collectionToUse = prepareCollection(collection, writeConcernToUse);
-
+ InsertManyOptions insertManyOptions =new InsertManyOptions();
+ insertManyOptions.ordered(false);
documents.addAll(toDocuments(dbDocList));
-
- return collectionToUse.insertMany(documents);
+ return collectionToUse.insertMany(documents, insertManyOptions);
}).flatMap(s -> {
diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoRepositoryFactory.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoRepositoryFactory.java
index 699e7b158d..5a023b2b09 100644
--- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoRepositoryFactory.java
+++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoRepositoryFactory.java
@@ -39,7 +39,6 @@
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryComposition.RepositoryFragments;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
-import org.springframework.data.repository.core.support.RepositoryFragment;
import org.springframework.data.repository.query.QueryLookupStrategy;
import org.springframework.data.repository.query.QueryLookupStrategy.Key;
import org.springframework.data.repository.query.QueryMethodEvaluationContextProvider;
@@ -92,8 +91,21 @@ protected Class> getRepositoryBaseClass(RepositoryMetadata metadata) {
*/
@Override
protected RepositoryFragments getRepositoryFragments(RepositoryMetadata metadata) {
+ return getRepositoryFragments(metadata, operations);
+ }
- RepositoryFragments fragments = RepositoryFragments.empty();
+ /**
+ * Creates {@link RepositoryFragments} based on {@link RepositoryMetadata} to add Mongo-specific extensions. Typically
+ * adds a {@link QuerydslMongoPredicateExecutor} if the repository interface uses Querydsl.
+ *
+ * Can be overridden by subclasses to customize {@link RepositoryFragments}.
+ *
+ * @param metadata repository metadata.
+ * @param operations the MongoDB operations manager.
+ * @return
+ * @since 3.2.1
+ */
+ protected RepositoryFragments getRepositoryFragments(RepositoryMetadata metadata, MongoOperations operations) {
boolean isQueryDslRepository = QUERY_DSL_PRESENT
&& QuerydslPredicateExecutor.class.isAssignableFrom(metadata.getRepositoryInterface());
@@ -105,14 +117,11 @@ protected RepositoryFragments getRepositoryFragments(RepositoryMetadata metadata
"Cannot combine Querydsl and reactive repository support in a single interface");
}
- MongoEntityInformation, Serializable> entityInformation = getEntityInformation(metadata.getDomainType(),
- metadata);
-
- fragments = fragments.append(RepositoryFragment.implemented(
- getTargetRepositoryViaReflection(QuerydslMongoPredicateExecutor.class, entityInformation, operations)));
+ return RepositoryFragments
+ .just(new QuerydslMongoPredicateExecutor<>(getEntityInformation(metadata.getDomainType()), operations));
}
- return fragments;
+ return RepositoryFragments.empty();
}
/*
diff --git a/spring-data-mongodb/src/test/java/ConfigClassInDefaultPackage.java b/spring-data-mongodb/src/test/java/ConfigClassInDefaultPackage.java
deleted file mode 100644
index 01816ff4f9..0000000000
--- a/spring-data-mongodb/src/test/java/ConfigClassInDefaultPackage.java
+++ /dev/null
@@ -1,57 +0,0 @@
-
-/*
- * Copyright 2014-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.util.Collections;
-import java.util.Set;
-
-import org.springframework.context.annotation.Configuration;
-import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
-
-import com.mongodb.client.MongoClient;
-import com.mongodb.client.MongoClients;
-
-/**
- * Sample configuration class in default package.
- *
- * @author Oliver Gierke
- */
-@Configuration
-public class ConfigClassInDefaultPackage extends AbstractMongoClientConfiguration {
-
- /*
- * (non-Javadoc)
- * @see org.springframework.data.mongodb.config.AbstractMongoClientConfiguration#getDatabaseName()
- */
- @Override
- protected String getDatabaseName() {
- return "default";
- }
-
- /*
- * (non-Javadoc)
- * @see org.springframework.data.mongodb.config.AbstractMongoClientConfiguration#mongoClient()
- */
- @Override
- public MongoClient mongoClient() {
- return MongoClients.create();
- }
-
- @Override
- protected Set> getInitialEntitySet() throws ClassNotFoundException {
- return Collections.emptySet();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/ConfigClassInDefaultPackageUnitTests.java b/spring-data-mongodb/src/test/java/ConfigClassInDefaultPackageUnitTests.java
deleted file mode 100644
index 7f59a436d7..0000000000
--- a/spring-data-mongodb/src/test/java/ConfigClassInDefaultPackageUnitTests.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright 2014-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import org.junit.jupiter.api.Test;
-
-import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-
-/**
- * Unit test for {@link ConfigClassInDefaultPackage}.
- *
- * @author Oliver Gierke
- */
-public class ConfigClassInDefaultPackageUnitTests {
-
- @Test // DATAMONGO-877
- public void loadsConfigClassFromDefaultPackage() {
- new AnnotationConfigApplicationContext(ConfigClassInDefaultPackage.class).close();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/example/first/First.java b/spring-data-mongodb/src/test/java/example/first/First.java
deleted file mode 100644
index 2cd7cda056..0000000000
--- a/spring-data-mongodb/src/test/java/example/first/First.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright 2016-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package example.first;
-
-import org.springframework.data.mongodb.core.mapping.Document;
-
-/**
- * @author Oliver Gierke
- */
-@Document
-public class First {
-
-}
diff --git a/spring-data-mongodb/src/test/java/example/second/Second.java b/spring-data-mongodb/src/test/java/example/second/Second.java
deleted file mode 100644
index 851f2fca7f..0000000000
--- a/spring-data-mongodb/src/test/java/example/second/Second.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright 2016-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package example.second;
-
-import org.springframework.data.mongodb.core.mapping.Document;
-
-/**
- * @author Oliver Gierke
- */
-@Document
-public class Second {
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/DependencyTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/DependencyTests.java
deleted file mode 100644
index 9294c83555..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/DependencyTests.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright 2017-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb;
-
-import static de.schauderhaft.degraph.check.JCheck.*;
-import static org.hamcrest.MatcherAssert.*;
-
-import de.schauderhaft.degraph.configuration.NamedPattern;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests package dependency constraints.
- *
- * @author Jens Schauder
- * @author Oliver Gierke
- */
-class DependencyTests {
-
- @Test
- void noInternalPackageCycles() {
-
- assertThat(classpath() //
- .noJars() //
- .including("org.springframework.data.mongodb.**") //
- .filterClasspath("*target/classes") //
- .printOnFailure("degraph.graphml"), //
- violationFree() //
- );
- }
-
- @Test
- void onlyConfigMayUseRepository() {
-
- assertThat(classpath() //
- .including("org.springframework.data.**") //
- .filterClasspath("*target/classes") //
- .printOnFailure("onlyConfigMayUseRepository.graphml") //
- .withSlicing("slices", //
- "**.(config).**", //
- new NamedPattern("**.cdi.**", "config"), //
- "**.(repository).**", //
- new NamedPattern("**", "other"))
- .allow("config", "repository", "other"), //
- violationFree() //
- );
- }
-
- @Test
- void commonsInternaly() {
-
- assertThat(classpath() //
- .noJars() //
- .including("org.springframework.data.**") //
- .excluding("org.springframework.data.mongodb.**") //
- .filterClasspath("*target/classes") //
- .printTo("commons.graphml"), //
- violationFree() //
- );
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/MongoDatabaseUtilsUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/MongoDatabaseUtilsUnitTests.java
deleted file mode 100644
index 8cb222f0e6..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/MongoDatabaseUtilsUnitTests.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Copyright 2018-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.ArgumentMatchers.*;
-import static org.mockito.Mockito.*;
-
-import javax.transaction.Status;
-import javax.transaction.UserTransaction;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.transaction.TransactionStatus;
-import org.springframework.transaction.jta.JtaTransactionManager;
-import org.springframework.transaction.support.TransactionCallbackWithoutResult;
-import org.springframework.transaction.support.TransactionSynchronizationManager;
-import org.springframework.transaction.support.TransactionTemplate;
-
-import com.mongodb.client.ClientSession;
-import com.mongodb.client.MongoDatabase;
-import com.mongodb.session.ServerSession;
-
-/**
- * @author Christoph Strobl
- */
-@ExtendWith(MockitoExtension.class)
-class MongoDatabaseUtilsUnitTests {
-
- @Mock ClientSession session;
- @Mock ServerSession serverSession;
- @Mock MongoDatabaseFactory dbFactory;
- @Mock MongoDatabase db;
-
- @Mock UserTransaction userTransaction;
-
- @AfterEach
- void verifyTransactionSynchronizationManagerState() {
-
- assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue();
- assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
- assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull();
- assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
- assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()).isNull();
- assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
- }
-
- @Test // DATAMONGO-2130
- void isTransactionActiveShouldDetectTxViaFactory() {
-
- when(dbFactory.isTransactionActive()).thenReturn(true);
-
- assertThat(MongoDatabaseUtils.isTransactionActive(dbFactory)).isTrue();
- }
-
- @Test // DATAMONGO-2130
- void isTransactionActiveShouldReturnFalseIfNoTxActive() {
-
- when(dbFactory.isTransactionActive()).thenReturn(false);
-
- assertThat(MongoDatabaseUtils.isTransactionActive(dbFactory)).isFalse();
- }
-
- @Test // DATAMONGO-2130
- void isTransactionActiveShouldLookupTxForActiveTransactionSynchronizationViaTxManager() {
-
- when(dbFactory.getSession(any())).thenReturn(session);
- when(session.getServerSession()).thenReturn(serverSession);
- when(session.hasActiveTransaction()).thenReturn(true);
- when(serverSession.isClosed()).thenReturn(false);
-
- when(dbFactory.isTransactionActive()).thenReturn(false);
-
- MongoTransactionManager txManager = new MongoTransactionManager(dbFactory);
- TransactionTemplate txTemplate = new TransactionTemplate(txManager);
-
- txTemplate.execute(new TransactionCallbackWithoutResult() {
-
- @Override
- protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
- assertThat(MongoDatabaseUtils.isTransactionActive(dbFactory)).isTrue();
- }
- });
- }
-
- @Test // DATAMONGO-1920
- void shouldNotStartSessionWhenNoTransactionOngoing() {
-
- MongoDatabaseUtils.getDatabase(dbFactory, SessionSynchronization.ON_ACTUAL_TRANSACTION);
-
- verify(dbFactory, never()).getSession(any());
- verify(dbFactory, never()).withSession(any(ClientSession.class));
- }
-
- @Test // DATAMONGO-1920
- void shouldParticipateInOngoingJtaTransactionWithCommitWhenSessionSychronizationIsAny() throws Exception {
-
- when(dbFactory.getSession(any())).thenReturn(session);
- when(dbFactory.withSession(session)).thenReturn(dbFactory);
- when(dbFactory.getMongoDatabase()).thenReturn(db);
- when(session.getServerSession()).thenReturn(serverSession);
- when(session.hasActiveTransaction()).thenReturn(true);
- when(serverSession.isClosed()).thenReturn(false);
-
- when(userTransaction.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
- Status.STATUS_ACTIVE);
-
- JtaTransactionManager txManager = new JtaTransactionManager(userTransaction);
- TransactionTemplate txTemplate = new TransactionTemplate(txManager);
-
- txTemplate.execute(new TransactionCallbackWithoutResult() {
-
- @Override
- protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
-
- assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
- assertThat(transactionStatus.isNewTransaction()).isTrue();
- assertThat(TransactionSynchronizationManager.hasResource(dbFactory)).isFalse();
-
- MongoDatabaseUtils.getDatabase(dbFactory, SessionSynchronization.ALWAYS);
-
- assertThat(TransactionSynchronizationManager.hasResource(dbFactory)).isTrue();
- }
- });
-
- verify(userTransaction).begin();
-
- verify(session).startTransaction();
- verify(session).commitTransaction();
- verify(session).close();
- }
-
- @Test // DATAMONGO-1920
- void shouldParticipateInOngoingJtaTransactionWithRollbackWhenSessionSychronizationIsAny() throws Exception {
-
- when(dbFactory.getSession(any())).thenReturn(session);
- when(dbFactory.withSession(session)).thenReturn(dbFactory);
- when(dbFactory.getMongoDatabase()).thenReturn(db);
- when(session.getServerSession()).thenReturn(serverSession);
- when(session.hasActiveTransaction()).thenReturn(true);
- when(serverSession.isClosed()).thenReturn(false);
-
- when(userTransaction.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
- Status.STATUS_ACTIVE);
-
- JtaTransactionManager txManager = new JtaTransactionManager(userTransaction);
- TransactionTemplate txTemplate = new TransactionTemplate(txManager);
-
- txTemplate.execute(new TransactionCallbackWithoutResult() {
-
- @Override
- protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
-
- assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
- assertThat(transactionStatus.isNewTransaction()).isTrue();
- assertThat(TransactionSynchronizationManager.hasResource(dbFactory)).isFalse();
-
- MongoDatabaseUtils.getDatabase(dbFactory, SessionSynchronization.ALWAYS);
-
- assertThat(TransactionSynchronizationManager.hasResource(dbFactory)).isTrue();
-
- transactionStatus.setRollbackOnly();
- }
- });
-
- verify(userTransaction).rollback();
-
- verify(session).startTransaction();
- verify(session).abortTransaction();
- verify(session).close();
- }
-
- @Test // DATAMONGO-1920
- void shouldNotParticipateInOngoingJtaTransactionWithRollbackWhenSessionSychronizationIsNative() throws Exception {
-
- when(userTransaction.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
- Status.STATUS_ACTIVE);
-
- JtaTransactionManager txManager = new JtaTransactionManager(userTransaction);
- TransactionTemplate txTemplate = new TransactionTemplate(txManager);
-
- txTemplate.execute(new TransactionCallbackWithoutResult() {
-
- @Override
- protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
-
- assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
- assertThat(transactionStatus.isNewTransaction()).isTrue();
- assertThat(TransactionSynchronizationManager.hasResource(dbFactory)).isFalse();
-
- MongoDatabaseUtils.getDatabase(dbFactory, SessionSynchronization.ON_ACTUAL_TRANSACTION);
-
- assertThat(TransactionSynchronizationManager.hasResource(dbFactory)).isFalse();
-
- transactionStatus.setRollbackOnly();
- }
- });
-
- verify(userTransaction).rollback();
-
- verify(session, never()).startTransaction();
- verify(session, never()).abortTransaction();
- verify(session, never()).close();
- }
-
- @Test // DATAMONGO-1920
- void shouldParticipateInOngoingMongoTransactionWhenSessionSychronizationIsNative() {
-
- when(dbFactory.getSession(any())).thenReturn(session);
- when(dbFactory.withSession(session)).thenReturn(dbFactory);
- when(dbFactory.getMongoDatabase()).thenReturn(db);
- when(session.getServerSession()).thenReturn(serverSession);
- when(serverSession.isClosed()).thenReturn(false);
-
- MongoTransactionManager txManager = new MongoTransactionManager(dbFactory);
- TransactionTemplate txTemplate = new TransactionTemplate(txManager);
-
- txTemplate.execute(new TransactionCallbackWithoutResult() {
-
- @Override
- protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
-
- assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
- assertThat(transactionStatus.isNewTransaction()).isTrue();
- assertThat(TransactionSynchronizationManager.hasResource(dbFactory)).isTrue();
-
- MongoDatabaseUtils.getDatabase(dbFactory, SessionSynchronization.ON_ACTUAL_TRANSACTION);
-
- transactionStatus.setRollbackOnly();
- }
- });
-
- verify(session).startTransaction();
- verify(session).abortTransaction();
- verify(session).close();
- }
-
- @Test // DATAMONGO-1920
- void shouldParticipateInOngoingMongoTransactionWhenSessionSynchronizationIsAny() {
-
- when(dbFactory.getSession(any())).thenReturn(session);
- when(dbFactory.withSession(session)).thenReturn(dbFactory);
- when(dbFactory.getMongoDatabase()).thenReturn(db);
- when(session.getServerSession()).thenReturn(serverSession);
- when(serverSession.isClosed()).thenReturn(false);
-
- MongoTransactionManager txManager = new MongoTransactionManager(dbFactory);
- TransactionTemplate txTemplate = new TransactionTemplate(txManager);
-
- txTemplate.execute(new TransactionCallbackWithoutResult() {
-
- @Override
- protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
-
- assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
- assertThat(transactionStatus.isNewTransaction()).isTrue();
- assertThat(TransactionSynchronizationManager.hasResource(dbFactory)).isTrue();
-
- MongoDatabaseUtils.getDatabase(dbFactory, SessionSynchronization.ALWAYS);
-
- transactionStatus.setRollbackOnly();
- }
- });
-
- verify(session).startTransaction();
- verify(session).abortTransaction();
- verify(session).close();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/MongoTransactionManagerUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/MongoTransactionManagerUnitTests.java
deleted file mode 100644
index dfb48fdbb1..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/MongoTransactionManagerUnitTests.java
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * Copyright 2018-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.data.mongodb.core.MongoTemplate;
-import org.springframework.transaction.TransactionDefinition;
-import org.springframework.transaction.TransactionStatus;
-import org.springframework.transaction.UnexpectedRollbackException;
-import org.springframework.transaction.support.DefaultTransactionDefinition;
-import org.springframework.transaction.support.TransactionCallbackWithoutResult;
-import org.springframework.transaction.support.TransactionSynchronizationManager;
-import org.springframework.transaction.support.TransactionTemplate;
-
-import com.mongodb.client.ClientSession;
-import com.mongodb.client.MongoDatabase;
-import com.mongodb.session.ServerSession;
-
-/**
- * @author Christoph Strobl
- */
-@ExtendWith(MockitoExtension.class)
-public class MongoTransactionManagerUnitTests {
-
- @Mock ClientSession session;
- @Mock ClientSession session2;
- @Mock ServerSession serverSession;
- @Mock MongoDatabaseFactory dbFactory;
- @Mock MongoDatabaseFactory dbFactory2;
- @Mock MongoDatabase db;
- @Mock MongoDatabase db2;
-
- @BeforeEach
- public void setUp() {
-
- when(dbFactory.getSession(any())).thenReturn(session, session2);
- when(dbFactory.withSession(session)).thenReturn(dbFactory);
- when(dbFactory.getMongoDatabase()).thenReturn(db);
- when(session.getServerSession()).thenReturn(serverSession);
- }
-
- @AfterEach
- public void verifyTransactionSynchronizationManager() {
-
- assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue();
- assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
- }
-
- @Test // DATAMONGO-1920
- public void triggerCommitCorrectly() {
-
- MongoTransactionManager txManager = new MongoTransactionManager(dbFactory);
- TransactionStatus txStatus = txManager.getTransaction(new DefaultTransactionDefinition());
-
- MongoTemplate template = new MongoTemplate(dbFactory);
-
- template.execute(db -> {
- db.drop();
- return null;
- });
-
- verify(dbFactory).withSession(eq(session));
-
- txManager.commit(txStatus);
-
- verify(session).startTransaction();
- verify(session).commitTransaction();
- verify(session).close();
- }
-
- @Test // DATAMONGO-1920
- public void participateInOnGoingTransactionWithCommit() {
-
- MongoTransactionManager txManager = new MongoTransactionManager(dbFactory);
- TransactionStatus txStatus = txManager.getTransaction(new DefaultTransactionDefinition());
-
- MongoTemplate template = new MongoTemplate(dbFactory);
-
- template.execute(db -> {
- db.drop();
- return null;
- });
-
- TransactionTemplate txTemplate = new TransactionTemplate(txManager);
- txTemplate.execute(new TransactionCallbackWithoutResult() {
-
- @Override
- protected void doInTransactionWithoutResult(TransactionStatus status) {
-
- template.execute(db -> {
- db.drop();
- return null;
- });
- }
- });
-
- verify(dbFactory, times(2)).withSession(eq(session));
-
- txManager.commit(txStatus);
-
- verify(session).startTransaction();
- verify(session).commitTransaction();
- verify(session).close();
- }
-
- @Test // DATAMONGO-1920
- public void participateInOnGoingTransactionWithRollbackOnly() {
-
- MongoTransactionManager txManager = new MongoTransactionManager(dbFactory);
- TransactionStatus txStatus = txManager.getTransaction(new DefaultTransactionDefinition());
-
- MongoTemplate template = new MongoTemplate(dbFactory);
-
- template.execute(db -> {
- db.drop();
- return null;
- });
-
- TransactionTemplate txTemplate = new TransactionTemplate(txManager);
- txTemplate.execute(new TransactionCallbackWithoutResult() {
-
- @Override
- protected void doInTransactionWithoutResult(TransactionStatus status) {
-
- template.execute(db -> {
- db.drop();
- return null;
- });
-
- status.setRollbackOnly();
- }
- });
-
- verify(dbFactory, times(2)).withSession(eq(session));
-
- assertThatExceptionOfType(UnexpectedRollbackException.class).isThrownBy(() -> txManager.commit(txStatus));
-
- verify(session).startTransaction();
- verify(session).abortTransaction();
- verify(session).close();
- }
-
- @Test // DATAMONGO-1920
- public void triggerRollbackCorrectly() {
-
- MongoTransactionManager txManager = new MongoTransactionManager(dbFactory);
- TransactionStatus txStatus = txManager.getTransaction(new DefaultTransactionDefinition());
-
- MongoTemplate template = new MongoTemplate(dbFactory);
-
- template.execute(db -> {
- db.drop();
- return null;
- });
-
- verify(dbFactory).withSession(eq(session));
-
- txManager.rollback(txStatus);
-
- verify(session).startTransaction();
- verify(session).abortTransaction();
- verify(session).close();
- }
-
- @Test // DATAMONGO-1920
- public void suspendTransactionWhilePropagationNotSupported() {
-
- MongoTransactionManager txManager = new MongoTransactionManager(dbFactory);
- TransactionStatus txStatus = txManager.getTransaction(new DefaultTransactionDefinition());
-
- MongoTemplate template = new MongoTemplate(dbFactory);
-
- template.execute(db -> {
- db.drop();
- return null;
- });
-
- TransactionTemplate txTemplate = new TransactionTemplate(txManager);
- txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
- txTemplate.execute(new TransactionCallbackWithoutResult() {
-
- @Override
- protected void doInTransactionWithoutResult(TransactionStatus status) {
-
- template.execute(db -> {
- db.drop();
- return null;
- });
- }
- });
-
- template.execute(MongoDatabase::listCollections);
- txManager.commit(txStatus);
-
- verify(session).startTransaction();
- verify(session2, never()).startTransaction();
-
- verify(dbFactory, times(2)).withSession(eq(session));
- verify(dbFactory, never()).withSession(eq(session2));
-
- verify(db, times(2)).drop();
- verify(db).listCollections();
-
- verify(session).close();
- verify(session2, never()).close();
- }
-
- @Test // DATAMONGO-1920
- public void suspendTransactionWhilePropagationRequiresNew() {
-
- when(dbFactory.withSession(session2)).thenReturn(dbFactory2);
- when(dbFactory2.getMongoDatabase()).thenReturn(db2);
- when(session2.getServerSession()).thenReturn(serverSession);
- when(serverSession.isClosed()).thenReturn(false);
-
- MongoTransactionManager txManager = new MongoTransactionManager(dbFactory);
- TransactionStatus txStatus = txManager.getTransaction(new DefaultTransactionDefinition());
-
- MongoTemplate template = new MongoTemplate(dbFactory);
-
- template.execute(db -> {
- db.drop();
- return null;
- });
-
- TransactionTemplate txTemplate = new TransactionTemplate(txManager);
- txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
- txTemplate.execute(new TransactionCallbackWithoutResult() {
-
- @Override
- protected void doInTransactionWithoutResult(TransactionStatus status) {
-
- template.execute(db -> {
- db.drop();
- return null;
- });
- }
- });
-
- template.execute(MongoDatabase::listCollections);
- txManager.commit(txStatus);
-
- verify(session).startTransaction();
- verify(session2).startTransaction();
-
- verify(dbFactory, times(2)).withSession(eq(session));
- verify(dbFactory).withSession(eq(session2));
-
- verify(db).drop();
- verify(db2).drop();
- verify(db).listCollections();
-
- verify(session).close();
- verify(session2).close();
- }
-
- @Test // DATAMONGO-1920
- public void readonlyShouldInitiateASessionStartAndCommitTransaction() {
-
- MongoTransactionManager txManager = new MongoTransactionManager(dbFactory);
-
- DefaultTransactionDefinition readonlyTxDefinition = new DefaultTransactionDefinition();
- readonlyTxDefinition.setReadOnly(true);
-
- TransactionStatus txStatus = txManager.getTransaction(readonlyTxDefinition);
-
- MongoTemplate template = new MongoTemplate(dbFactory);
-
- template.execute(db -> {
- db.drop();
- return null;
- });
-
- verify(dbFactory).withSession(eq(session));
-
- txManager.commit(txStatus);
-
- verify(session).startTransaction();
- verify(session).commitTransaction();
- verify(session).close();
- }
-
- @Test // DATAMONGO-1920
- public void readonlyShouldInitiateASessionStartAndRollbackTransaction() {
-
- MongoTransactionManager txManager = new MongoTransactionManager(dbFactory);
-
- DefaultTransactionDefinition readonlyTxDefinition = new DefaultTransactionDefinition();
- readonlyTxDefinition.setReadOnly(true);
-
- TransactionStatus txStatus = txManager.getTransaction(readonlyTxDefinition);
-
- MongoTemplate template = new MongoTemplate(dbFactory);
-
- template.execute(db -> {
- db.drop();
- return null;
- });
-
- verify(dbFactory).withSession(eq(session));
-
- txManager.rollback(txStatus);
-
- verify(session).startTransaction();
- verify(session).abortTransaction();
- verify(session).close();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/ReactiveMongoDatabaseUtilsUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/ReactiveMongoDatabaseUtilsUnitTests.java
deleted file mode 100644
index 60a7ff9a47..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/ReactiveMongoDatabaseUtilsUnitTests.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.ArgumentMatchers.*;
-import static org.mockito.Mockito.*;
-
-import reactor.core.publisher.Mono;
-import reactor.test.StepVerifier;
-
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.transaction.reactive.TransactionSynchronizationManager;
-import org.springframework.transaction.reactive.TransactionalOperator;
-import org.springframework.transaction.support.DefaultTransactionDefinition;
-
-import com.mongodb.reactivestreams.client.ClientSession;
-import com.mongodb.reactivestreams.client.MongoDatabase;
-import com.mongodb.session.ServerSession;
-
-/**
- * Unit tests for {@link ReactiveMongoDatabaseUtils}.
- *
- * @author Mark Paluch
- * @author Christoph Strobl
- * @author Mathieu Ouellet
- */
-@ExtendWith(MockitoExtension.class)
-class ReactiveMongoDatabaseUtilsUnitTests {
-
- @Mock ClientSession session;
- @Mock ServerSession serverSession;
- @Mock ReactiveMongoDatabaseFactory databaseFactory;
- @Mock MongoDatabase db;
-
- @Test // DATAMONGO-2265
- void isTransactionActiveShouldDetectTxViaFactory() {
-
- when(databaseFactory.isTransactionActive()).thenReturn(true);
-
- ReactiveMongoDatabaseUtils.isTransactionActive(databaseFactory) //
- .as(StepVerifier::create) //
- .expectNext(true).verifyComplete();
- }
-
- @Test // DATAMONGO-2265
- void isTransactionActiveShouldReturnFalseIfNoTxActive() {
-
- when(databaseFactory.isTransactionActive()).thenReturn(false);
-
- ReactiveMongoDatabaseUtils.isTransactionActive(databaseFactory) //
- .as(StepVerifier::create) //
- .expectNext(false).verifyComplete();
- }
-
- @Test // DATAMONGO-2265
- void isTransactionActiveShouldLookupTxForActiveTransactionSynchronizationViaTxManager() {
-
- when(session.getServerSession()).thenReturn(serverSession);
- when(session.hasActiveTransaction()).thenReturn(true);
- when(databaseFactory.getSession(any())).thenReturn(Mono.just(session));
- when(databaseFactory.isTransactionActive()).thenReturn(false);
- when(session.commitTransaction()).thenReturn(Mono.empty());
-
- ReactiveMongoTransactionManager txManager = new ReactiveMongoTransactionManager(databaseFactory);
- TransactionalOperator operator = TransactionalOperator.create(txManager, new DefaultTransactionDefinition());
-
- operator.execute(tx -> {
-
- return ReactiveMongoDatabaseUtils.isTransactionActive(databaseFactory);
- }).as(StepVerifier::create).expectNext(true).verifyComplete();
- }
-
- @Test // DATAMONGO-2265
- void shouldNotStartSessionWhenNoTransactionOngoing() {
-
- when(databaseFactory.getMongoDatabase()).thenReturn(Mono.just(db));
-
- ReactiveMongoDatabaseUtils.getDatabase(databaseFactory, SessionSynchronization.ON_ACTUAL_TRANSACTION) //
- .as(StepVerifier::create) //
- .expectNextCount(1) //
- .verifyComplete();
-
- verify(databaseFactory, never()).getSession(any());
- verify(databaseFactory, never()).withSession(any(ClientSession.class));
- }
-
- @Test // DATAMONGO-2265
- void shouldParticipateInOngoingMongoTransactionWhenSessionSychronizationIsNative() {
-
- when(session.getServerSession()).thenReturn(serverSession);
- when(databaseFactory.getSession(any())).thenReturn(Mono.just(session));
-
- ReactiveMongoTransactionManager txManager = new ReactiveMongoTransactionManager(databaseFactory);
- when(session.abortTransaction()).thenReturn(Mono.empty());
-
- TransactionalOperator operator = TransactionalOperator.create(txManager, new DefaultTransactionDefinition());
-
- operator.execute(tx -> {
-
- return TransactionSynchronizationManager.forCurrentTransaction().doOnNext(synchronizationManager -> {
-
- assertThat(synchronizationManager.isSynchronizationActive()).isTrue();
- assertThat(tx.isNewTransaction()).isTrue();
-
- assertThat(synchronizationManager.hasResource(databaseFactory)).isTrue();
-
- }).then(Mono.fromRunnable(tx::setRollbackOnly));
- }).as(StepVerifier::create).verifyComplete();
-
- verify(session).startTransaction();
- verify(session).abortTransaction();
- verify(session).close();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/ReactiveMongoTransactionManagerUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/ReactiveMongoTransactionManagerUnitTests.java
deleted file mode 100644
index cf20421309..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/ReactiveMongoTransactionManagerUnitTests.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb;
-
-import static org.mockito.Mockito.*;
-
-import reactor.core.publisher.Mono;
-import reactor.test.StepVerifier;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
-import org.springframework.transaction.TransactionDefinition;
-import org.springframework.transaction.reactive.TransactionalOperator;
-import org.springframework.transaction.support.DefaultTransactionDefinition;
-
-import com.mongodb.reactivestreams.client.ClientSession;
-import com.mongodb.reactivestreams.client.MongoDatabase;
-import com.mongodb.session.ServerSession;
-
-/**
- * Unit tests for {@link ReactiveMongoTransactionManager}.
- *
- * @author Mark Paluch
- * @author Christoph Strobl
- * @author Mathieu Ouellet
- */
-@ExtendWith(MockitoExtension.class)
-class ReactiveMongoTransactionManagerUnitTests {
-
- @Mock ClientSession session;
- @Mock ClientSession session2;
- @Mock ServerSession serverSession;
- @Mock ReactiveMongoDatabaseFactory databaseFactory;
- @Mock ReactiveMongoDatabaseFactory databaseFactory2;
- @Mock MongoDatabase db;
- @Mock MongoDatabase db2;
-
- @BeforeEach
- void setUp() {
- when(databaseFactory.getSession(any())).thenReturn(Mono.just(session), Mono.just(session2));
- when(databaseFactory.withSession(session)).thenReturn(databaseFactory);
- when(databaseFactory.getMongoDatabase()).thenReturn(Mono.just(db));
- when(session.getServerSession()).thenReturn(serverSession);
- }
-
- @Test // DATAMONGO-2265
- void triggerCommitCorrectly() {
-
- ReactiveMongoTransactionManager txManager = new ReactiveMongoTransactionManager(databaseFactory);
- ReactiveMongoTemplate template = new ReactiveMongoTemplate(databaseFactory);
- when(session.commitTransaction()).thenReturn(Mono.empty());
-
- TransactionalOperator operator = TransactionalOperator.create(txManager, new DefaultTransactionDefinition());
-
- template.execute(db -> {
- db.drop();
- return Mono.empty();
-
- }).as(operator::transactional) //
- .as(StepVerifier::create) //
- .verifyComplete();
-
- verify(databaseFactory).withSession(eq(session));
-
- verify(session).startTransaction();
- verify(session).commitTransaction();
-
- verify(session).close();
- }
-
- @Test // DATAMONGO-2265
- void participateInOnGoingTransactionWithCommit() {
-
- ReactiveMongoTransactionManager txManager = new ReactiveMongoTransactionManager(databaseFactory);
- ReactiveMongoTemplate template = new ReactiveMongoTemplate(databaseFactory);
- when(session.commitTransaction()).thenReturn(Mono.empty());
-
- TransactionalOperator operator = TransactionalOperator.create(txManager, new DefaultTransactionDefinition());
-
- template.execute(db -> {
- db.drop();
- return Mono.empty();
- }).as(StepVerifier::create).verifyComplete();
-
- template.execute(db -> {
- db.drop();
- return Mono.empty();
- }).as(operator::transactional) //
- .as(StepVerifier::create) //
- .verifyComplete();
-
- verify(databaseFactory, times(1)).withSession(eq(session));
-
- verify(session).startTransaction();
- verify(session).commitTransaction();
- verify(session).close();
- }
-
- @Test // DATAMONGO-2265
- void participateInOnGoingTransactionWithRollbackOnly() {
-
- ReactiveMongoTransactionManager txManager = new ReactiveMongoTransactionManager(databaseFactory);
- ReactiveMongoTemplate template = new ReactiveMongoTemplate(databaseFactory);
- when(session.abortTransaction()).thenReturn(Mono.empty());
-
- TransactionalOperator operator = TransactionalOperator.create(txManager, new DefaultTransactionDefinition());
-
- operator.execute(tx -> {
-
- return template.execute(db -> {
- db.drop();
- tx.setRollbackOnly();
- return Mono.empty();
- });
- }).as(StepVerifier::create).verifyComplete();
-
- verify(databaseFactory, times(1)).withSession(eq(session));
-
- verify(session).startTransaction();
- verify(session).abortTransaction();
- verify(session).close();
- }
-
- @Test // DATAMONGO-2265
- void suspendTransactionWhilePropagationNotSupported() {
-
- ReactiveMongoTransactionManager txManager = new ReactiveMongoTransactionManager(databaseFactory);
- ReactiveMongoTemplate template = new ReactiveMongoTemplate(databaseFactory);
- when(session.commitTransaction()).thenReturn(Mono.empty());
-
- TransactionalOperator outer = TransactionalOperator.create(txManager, new DefaultTransactionDefinition());
-
- DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
- definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
- TransactionalOperator inner = TransactionalOperator.create(txManager, definition);
-
- outer.execute(tx1 -> {
-
- return template.execute(db -> {
-
- db.drop();
-
- return inner.execute(tx2 -> {
- return template.execute(db2 -> {
- db2.drop();
- return Mono.empty();
- });
- });
- });
- }).as(StepVerifier::create).verifyComplete();
-
- verify(session).startTransaction();
- verify(session2, never()).startTransaction();
-
- verify(databaseFactory, times(1)).withSession(eq(session));
- verify(databaseFactory, never()).withSession(eq(session2));
-
- verify(db, times(2)).drop();
-
- verify(session2, never()).close();
- }
-
- @Test // DATAMONGO-2265
- void suspendTransactionWhilePropagationRequiresNew() {
-
- when(databaseFactory.withSession(session2)).thenReturn(databaseFactory2);
- when(databaseFactory2.getMongoDatabase()).thenReturn(Mono.just(db2));
- when(session2.getServerSession()).thenReturn(serverSession);
-
- ReactiveMongoTransactionManager txManager = new ReactiveMongoTransactionManager(databaseFactory);
- ReactiveMongoTemplate template = new ReactiveMongoTemplate(databaseFactory);
- when(session.commitTransaction()).thenReturn(Mono.empty());
- when(session2.commitTransaction()).thenReturn(Mono.empty());
-
- TransactionalOperator outer = TransactionalOperator.create(txManager, new DefaultTransactionDefinition());
-
- DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
- definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
- TransactionalOperator inner = TransactionalOperator.create(txManager, definition);
-
- outer.execute(tx1 -> {
-
- return template.execute(db -> {
-
- db.drop();
-
- return inner.execute(tx2 -> {
- return template.execute(db2 -> {
- db2.drop();
- return Mono.empty();
- });
- });
- });
- }).as(StepVerifier::create).verifyComplete();
-
- verify(session).startTransaction();
- verify(session2).startTransaction();
-
- verify(databaseFactory, times(1)).withSession(eq(session));
- verify(databaseFactory).withSession(eq(session2));
-
- verify(db).drop();
- verify(db2).drop();
-
- verify(session).close();
- verify(session2).close();
- }
-
- @Test // DATAMONGO-2265
- void readonlyShouldInitiateASessionStartAndCommitTransaction() {
-
- ReactiveMongoTransactionManager txManager = new ReactiveMongoTransactionManager(databaseFactory);
- ReactiveMongoTemplate template = new ReactiveMongoTemplate(databaseFactory);
- when(session.commitTransaction()).thenReturn(Mono.empty());
-
- DefaultTransactionDefinition readonlyTxDefinition = new DefaultTransactionDefinition();
- readonlyTxDefinition.setReadOnly(true);
- TransactionalOperator operator = TransactionalOperator.create(txManager, readonlyTxDefinition);
-
- template.execute(db -> {
- db.drop();
- return Mono.empty();
-
- }).as(operator::transactional) //
- .as(StepVerifier::create) //
- .verifyComplete();
-
- verify(databaseFactory).withSession(eq(session));
-
- verify(session).startTransaction();
- verify(session).commitTransaction();
- verify(session).close();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/ReactiveTransactionIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/ReactiveTransactionIntegrationTests.java
deleted file mode 100644
index 9fedeb5498..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/ReactiveTransactionIntegrationTests.java
+++ /dev/null
@@ -1,355 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb;
-
-import lombok.AllArgsConstructor;
-import lombok.Data;
-import lombok.RequiredArgsConstructor;
-import reactor.core.publisher.Flux;
-import reactor.core.publisher.Mono;
-import reactor.test.StepVerifier;
-
-import java.time.Duration;
-import java.util.Collections;
-import java.util.Set;
-
-import org.bson.types.ObjectId;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
-import org.junit.jupiter.api.extension.ExtendWith;
-
-import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.support.GenericApplicationContext;
-import org.springframework.data.mongodb.config.AbstractReactiveMongoConfiguration;
-import org.springframework.data.mongodb.core.ReactiveMongoOperations;
-import org.springframework.data.mongodb.core.mapping.Document;
-import org.springframework.data.mongodb.core.query.Query;
-import org.springframework.data.mongodb.test.util.Client;
-import org.springframework.data.mongodb.test.util.EnableIfMongoServerVersion;
-import org.springframework.data.mongodb.test.util.EnableIfReplicaSetAvailable;
-import org.springframework.data.mongodb.test.util.MongoClientExtension;
-import org.springframework.data.mongodb.test.util.MongoTestUtils;
-import org.springframework.transaction.annotation.Transactional;
-import org.springframework.transaction.reactive.TransactionalOperator;
-import org.springframework.transaction.support.DefaultTransactionDefinition;
-
-import com.mongodb.reactivestreams.client.MongoClient;
-
-/**
- * Integration tests for reactive transaction management.
- *
- * @author Mark Paluch
- * @author Christoph Strobl
- */
-@ExtendWith(MongoClientExtension.class)
-@EnableIfMongoServerVersion(isGreaterThanEqual = "4.0")
-@EnableIfReplicaSetAvailable
-@DisabledIfSystemProperty(named = "user.name", matches = "jenkins")
-public class ReactiveTransactionIntegrationTests {
-
- private static final String DATABASE = "rxtx-test";
-
- static @Client MongoClient mongoClient;
- static GenericApplicationContext context;
-
- PersonService personService;
- ReactiveMongoOperations operations;
-
- @BeforeAll
- public static void init() {
- context = new AnnotationConfigApplicationContext(TestMongoConfig.class, PersonService.class);
- }
-
- @AfterAll
- public static void after() {
- context.close();
- }
-
- @BeforeEach
- public void setUp() {
-
- personService = context.getBean(PersonService.class);
- operations = context.getBean(ReactiveMongoOperations.class);
-
- try (MongoClient client = MongoTestUtils.reactiveClient()) {
-
- Flux.merge( //
- MongoTestUtils.createOrReplaceCollection(DATABASE, operations.getCollectionName(Person.class), client),
- MongoTestUtils.createOrReplaceCollection(DATABASE, operations.getCollectionName(EventLog.class), client) //
- ).then().as(StepVerifier::create).verifyComplete();
- }
- }
-
- @Test // DATAMONGO-2265
- public void shouldRollbackAfterException() {
-
- personService.savePersonErrors(new Person(null, "Walter", "White")) //
- .as(StepVerifier::create) //
- .verifyError(RuntimeException.class);
-
- operations.count(new Query(), Person.class) //
- .as(StepVerifier::create) //
- .expectNext(0L) //
- .verifyComplete();
- }
-
- @Test // DATAMONGO-2265
- public void shouldRollbackAfterExceptionOfTxAnnotatedMethod() {
-
- personService.declarativeSavePersonErrors(new Person(null, "Walter", "White")) //
- .as(StepVerifier::create) //
- .verifyError(RuntimeException.class);
-
- operations.count(new Query(), Person.class) //
- .as(StepVerifier::create) //
- .expectNext(0L) //
- .verifyComplete();
- }
-
- @Test // DATAMONGO-2265
- public void commitShouldPersistTxEntries() {
-
- personService.savePerson(new Person(null, "Walter", "White")) //
- .as(StepVerifier::create) //
- .expectNextCount(1) //
- .verifyComplete();
-
- operations.count(new Query(), Person.class) //
- .as(StepVerifier::create) //
- .expectNext(1L) //
- .verifyComplete();
- }
-
- @Test // DATAMONGO-2265
- public void commitShouldPersistTxEntriesOfTxAnnotatedMethod() {
-
- personService.declarativeSavePerson(new Person(null, "Walter", "White")) //
- .as(StepVerifier::create) //
- .expectNextCount(1) //
- .verifyComplete();
-
- operations.count(new Query(), Person.class) //
- .as(StepVerifier::create) //
- .expectNext(1L) //
- .verifyComplete();
- }
-
- @Test // DATAMONGO-2265
- public void commitShouldPersistTxEntriesAcrossCollections() {
-
- personService.saveWithLogs(new Person(null, "Walter", "White")) //
- .then() //
- .as(StepVerifier::create) //
- .verifyComplete();
-
- operations.count(new Query(), Person.class) //
- .as(StepVerifier::create) //
- .expectNext(1L) //
- .verifyComplete();
-
- operations.count(new Query(), EventLog.class) //
- .as(StepVerifier::create) //
- .expectNext(4L) //
- .verifyComplete();
- }
-
- @Test // DATAMONGO-2265
- public void rollbackShouldAbortAcrossCollections() {
-
- personService.saveWithErrorLogs(new Person(null, "Walter", "White")) //
- .then() //
- .as(StepVerifier::create) //
- .verifyError();
-
- operations.count(new Query(), Person.class) //
- .as(StepVerifier::create) //
- .expectNext(0L) //
- .verifyComplete();
-
- operations.count(new Query(), EventLog.class) //
- .as(StepVerifier::create) //
- .expectNext(0L) //
- .verifyComplete();
- }
-
- @Test // DATAMONGO-2265
- public void countShouldWorkInsideTransaction() {
-
- personService.countDuringTx(new Person(null, "Walter", "White")) //
- .as(StepVerifier::create) //
- .expectNext(1L) //
- .verifyComplete();
- }
-
- @Test // DATAMONGO-2265
- public void emitMultipleElementsDuringTransaction() {
-
- personService.saveWithLogs(new Person(null, "Walter", "White")) //
- .as(StepVerifier::create) //
- .expectNextCount(4L) //
- .verifyComplete();
- }
-
- @Test // DATAMONGO-2265
- public void errorAfterTxShouldNotAffectPreviousStep() {
-
- personService.savePerson(new Person(null, "Walter", "White")) //
- .delayElement(Duration.ofMillis(10)) //
- .then(Mono.error(new RuntimeException("my big bad evil error"))).as(StepVerifier::create) //
- .expectError() //
- .verify();
-
- operations.count(new Query(), Person.class) //
- .as(StepVerifier::create) //
- .expectNext(1L) //
- .verifyComplete();
- }
-
- @Configuration
- static class TestMongoConfig extends AbstractReactiveMongoConfiguration {
-
- @Override
- public MongoClient reactiveMongoClient() {
- return mongoClient;
- }
-
- @Override
- protected String getDatabaseName() {
- return DATABASE;
- }
-
- @Bean
- public ReactiveMongoTransactionManager transactionManager(ReactiveMongoDatabaseFactory factory) {
- return new ReactiveMongoTransactionManager(factory);
- }
-
- @Override
- protected Set> getInitialEntitySet() {
- return Collections.singleton(Person.class);
- }
- }
-
- @RequiredArgsConstructor
- static class PersonService {
-
- final ReactiveMongoOperations operations;
- final ReactiveMongoTransactionManager manager;
-
- public Mono savePersonErrors(Person person) {
-
- TransactionalOperator transactionalOperator = TransactionalOperator.create(manager,
- new DefaultTransactionDefinition());
-
- return operations.save(person) //
- . flatMap(it -> Mono.error(new RuntimeException("poof!"))) //
- .as(transactionalOperator::transactional);
- }
-
- public Mono savePerson(Person person) {
-
- TransactionalOperator transactionalOperator = TransactionalOperator.create(manager,
- new DefaultTransactionDefinition());
-
- return operations.save(person) //
- .flatMap(Mono::just) //
- .as(transactionalOperator::transactional);
- }
-
- public Mono countDuringTx(Person person) {
-
- TransactionalOperator transactionalOperator = TransactionalOperator.create(manager,
- new DefaultTransactionDefinition());
-
- return operations.save(person) //
- .then(operations.count(new Query(), Person.class)) //
- .as(transactionalOperator::transactional);
- }
-
- public Flux saveWithLogs(Person person) {
-
- TransactionalOperator transactionalOperator = TransactionalOperator.create(manager,
- new DefaultTransactionDefinition());
-
- return Flux.merge(operations.save(new EventLog(new ObjectId(), "beforeConvert")), //
- operations.save(new EventLog(new ObjectId(), "afterConvert")), //
- operations.save(new EventLog(new ObjectId(), "beforeInsert")), //
- operations.save(person), //
- operations.save(new EventLog(new ObjectId(), "afterInsert"))) //
- .thenMany(operations.query(EventLog.class).all()) //
- .as(transactionalOperator::transactional);
- }
-
- public Flux saveWithErrorLogs(Person person) {
-
- TransactionalOperator transactionalOperator = TransactionalOperator.create(manager,
- new DefaultTransactionDefinition());
-
- return Flux.merge(operations.save(new EventLog(new ObjectId(), "beforeConvert")), //
- operations.save(new EventLog(new ObjectId(), "afterConvert")), //
- operations.save(new EventLog(new ObjectId(), "beforeInsert")), //
- operations.save(person), //
- operations.save(new EventLog(new ObjectId(), "afterInsert"))) //
- . flatMap(it -> Mono.error(new RuntimeException("poof!"))) //
- .as(transactionalOperator::transactional);
- }
-
- @Transactional
- public Flux declarativeSavePerson(Person person) {
-
- TransactionalOperator transactionalOperator = TransactionalOperator.create(manager,
- new DefaultTransactionDefinition());
-
- return transactionalOperator.execute(reactiveTransaction -> {
- return operations.save(person);
- });
- }
-
- @Transactional
- public Flux declarativeSavePersonErrors(Person person) {
-
- TransactionalOperator transactionalOperator = TransactionalOperator.create(manager,
- new DefaultTransactionDefinition());
-
- return transactionalOperator.execute(reactiveTransaction -> {
-
- return operations.save(person) //
- . flatMap(it -> Mono.error(new RuntimeException("poof!")));
- });
- }
- }
-
- @Data
- @AllArgsConstructor
- @Document("person-rx")
- static class Person {
-
- ObjectId id;
- String firstname, lastname;
- }
-
- @Data
- @AllArgsConstructor
- static class EventLog {
-
- ObjectId id;
- String action;
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/SessionAwareMethodInterceptorUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/SessionAwareMethodInterceptorUnitTests.java
deleted file mode 100644
index c6e12e2f5d..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/SessionAwareMethodInterceptorUnitTests.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright 2018-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.ArgumentMatchers.*;
-import static org.mockito.Mockito.*;
-import static org.mockito.Mockito.any;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.aop.framework.ProxyFactory;
-import org.springframework.data.mongodb.SessionAwareMethodInterceptor.MethodCache;
-import org.springframework.test.util.ReflectionTestUtils;
-import org.springframework.util.ClassUtils;
-
-import com.mongodb.MongoClientSettings;
-import com.mongodb.client.ClientSession;
-import com.mongodb.client.MongoCollection;
-import com.mongodb.client.MongoDatabase;
-
-/**
- * Unit tests for {@link SessionAwareMethodInterceptor}.
- *
- * @author Christoph Strobl
- */
-@ExtendWith(MockitoExtension.class)
-public class SessionAwareMethodInterceptorUnitTests {
-
- @Mock ClientSession session;
- @Mock MongoCollection targetCollection;
- @Mock MongoDatabase targetDatabase;
-
- MongoCollection collection;
- MongoDatabase database;
-
- @BeforeEach
- public void setUp() {
-
- collection = createProxyInstance(session, targetCollection, MongoCollection.class);
- database = createProxyInstance(session, targetDatabase, MongoDatabase.class);
- }
-
- @Test // DATAMONGO-1880
- public void proxyFactoryOnCollectionDelegatesToMethodWithSession() {
-
- collection.find();
-
- verify(targetCollection).find(eq(session));
- }
-
- @Test // DATAMONGO-1880
- public void proxyFactoryOnCollectionWithSessionInArgumentListProceedsWithExecution() {
-
- ClientSession yetAnotherSession = mock(ClientSession.class);
- collection.find(yetAnotherSession);
-
- verify(targetCollection).find(eq(yetAnotherSession));
- }
-
- @Test // DATAMONGO-1880
- public void proxyFactoryOnDatabaseDelegatesToMethodWithSession() {
-
- database.drop();
-
- verify(targetDatabase).drop(eq(session));
- }
-
- @Test // DATAMONGO-1880
- public void proxyFactoryOnDatabaseWithSessionInArgumentListProceedsWithExecution() {
-
- ClientSession yetAnotherSession = mock(ClientSession.class);
- database.drop(yetAnotherSession);
-
- verify(targetDatabase).drop(eq(yetAnotherSession));
- }
-
- @Test // DATAMONGO-1880
- public void justMoveOnIfNoOverloadWithSessionAvailable() {
-
- collection.getReadPreference();
-
- verify(targetCollection).getReadPreference();
- }
-
- @Test // DATAMONGO-1880
- public void usesCacheForMethodLookup() {
-
- MethodCache cache = (MethodCache) ReflectionTestUtils.getField(SessionAwareMethodInterceptor.class, "METHOD_CACHE");
- Method countMethod = ClassUtils.getMethod(MongoCollection.class, "countDocuments");
-
- assertThat(cache.contains(countMethod, MongoCollection.class)).isFalse();
-
- collection.countDocuments();
-
- assertThat(cache.contains(countMethod, MongoCollection.class)).isTrue();
- }
-
- @Test // DATAMONGO-1880
- public void cachesNullForMethodsThatDoNotHaveASessionOverload() {
-
- MethodCache cache = (MethodCache) ReflectionTestUtils.getField(SessionAwareMethodInterceptor.class, "METHOD_CACHE");
- Method readConcernMethod = ClassUtils.getMethod(MongoCollection.class, "getReadConcern");
-
- assertThat(cache.contains(readConcernMethod, MongoCollection.class)).isFalse();
-
- collection.getReadConcern();
-
- collection.getReadConcern();
-
- assertThat(cache.contains(readConcernMethod, MongoCollection.class)).isTrue();
- assertThat(cache.lookup(readConcernMethod, MongoCollection.class, ClientSession.class)).isEmpty();
- }
-
- @Test // DATAMONGO-1880
- public void proxiesNewDbInstanceReturnedByMethod() {
-
- MongoDatabase otherDb = mock(MongoDatabase.class);
- when(targetDatabase.withCodecRegistry(any())).thenReturn(otherDb);
-
- MongoDatabase target = database.withCodecRegistry(MongoClientSettings.getDefaultCodecRegistry());
- assertThat(target).isInstanceOf(Proxy.class).isNotSameAs(database).isNotSameAs(targetDatabase);
-
- target.drop();
-
- verify(otherDb).drop(eq(session));
- }
-
- @Test // DATAMONGO-1880
- public void proxiesNewCollectionInstanceReturnedByMethod() {
-
- MongoCollection otherCollection = mock(MongoCollection.class);
- when(targetCollection.withCodecRegistry(any())).thenReturn(otherCollection);
-
- MongoCollection target = collection.withCodecRegistry(MongoClientSettings.getDefaultCodecRegistry());
- assertThat(target).isInstanceOf(Proxy.class).isNotSameAs(collection).isNotSameAs(targetCollection);
-
- target.drop();
-
- verify(otherCollection).drop(eq(session));
- }
-
- private MongoDatabase proxyDatabase(com.mongodb.session.ClientSession session, MongoDatabase database) {
- return createProxyInstance(session, database, MongoDatabase.class);
- }
-
- private MongoCollection proxyCollection(com.mongodb.session.ClientSession session, MongoCollection collection) {
- return createProxyInstance(session, collection, MongoCollection.class);
- }
-
- private T createProxyInstance(com.mongodb.session.ClientSession session, T target, Class targetType) {
-
- ProxyFactory factory = new ProxyFactory();
- factory.setTarget(target);
- factory.setInterfaces(targetType);
- factory.setOpaque(true);
-
- factory.addAdvice(new SessionAwareMethodInterceptor<>(session, target, ClientSession.class, MongoDatabase.class,
- this::proxyDatabase, MongoCollection.class, this::proxyCollection));
-
- return targetType.cast(factory.getProxy());
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/SpringDataMongoDBTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/SpringDataMongoDBTests.java
deleted file mode 100644
index 56cfff43b1..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/SpringDataMongoDBTests.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 2020-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * @author Christoph Strobl
- */
-class SpringDataMongoDBTests {
-
- @Test // DATAMONGO-2427
- void driverInformationHoldsSpringDataHint() {
- assertThat(SpringDataMongoDB.driverInformation().getDriverNames()).contains("spring-data");
- }
-
- @Test // DATAMONGO-2427
- void versionIsDetectedFromPackage() {
- assertThat(SpringDataMongoDB.version()).isNotNull();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractIntegrationTests.java
deleted file mode 100644
index 701e2eb986..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractIntegrationTests.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright 2013-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.springframework.data.mongodb.test.util.Assertions.*;
-
-import java.util.Collections;
-import java.util.Set;
-
-import org.bson.Document;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.dao.DataAccessException;
-import org.springframework.data.mongodb.core.CollectionCallback;
-import org.springframework.data.mongodb.core.MongoOperations;
-import org.springframework.data.mongodb.test.util.MongoTestUtils;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import com.mongodb.MongoException;
-import com.mongodb.client.MongoClient;
-import com.mongodb.client.MongoCollection;
-
-/**
- * @author Oliver Gierke
- */
-@RunWith(SpringRunner.class)
-@ContextConfiguration
-public abstract class AbstractIntegrationTests {
-
- @Configuration
- static class TestConfig extends AbstractMongoClientConfiguration {
-
- @Override
- protected String getDatabaseName() {
- return "database";
- }
-
- @Override
- public MongoClient mongoClient() {
- return MongoTestUtils.client();
- }
-
- @Override
- protected Set> getInitialEntitySet() throws ClassNotFoundException {
- return Collections.emptySet();
- }
-
- @Override
- protected boolean autoIndexCreation() {
- return true;
- }
- }
-
- @Autowired MongoOperations operations;
-
- @Before
- @After
- public void cleanUp() {
-
- for (String collectionName : operations.getCollectionNames()) {
- if (!collectionName.startsWith("system")) {
- operations.execute(collectionName, new CollectionCallback() {
- @Override
- public Void doInCollection(MongoCollection collection) throws MongoException, DataAccessException {
- collection.deleteMany(new Document());
- assertThat(collection.find().iterator().hasNext()).isFalse();
- return null;
- }
- });
- }
- }
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractMongoConfigurationUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractMongoConfigurationUnitTests.java
deleted file mode 100644
index 1ec266bacf..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractMongoConfigurationUnitTests.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright 2012-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import example.first.First;
-import example.second.Second;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Set;
-
-import org.junit.jupiter.api.Test;
-
-import org.springframework.beans.factory.NoSuchBeanDefinitionException;
-import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.support.AbstractApplicationContext;
-import org.springframework.data.mongodb.MongoDatabaseFactory;
-import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
-import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
-import org.springframework.data.mongodb.core.convert.MongoTypeMapper;
-import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity;
-import org.springframework.data.mongodb.core.mapping.Document;
-import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
-import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
-import org.springframework.data.spel.EvaluationContextProvider;
-import org.springframework.data.spel.ExtensionAwareEvaluationContextProvider;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import com.mongodb.client.MongoClient;
-import com.mongodb.client.MongoClients;
-
-/**
- * Unit tests for {@link AbstractMongoClientConfiguration}.
- *
- * @author Oliver Gierke
- * @author Thomas Darimont
- * @author Mark Paluch
- */
-public class AbstractMongoConfigurationUnitTests {
-
- @Test // DATAMONGO-496
- public void usesConfigClassPackageAsBaseMappingPackage() throws ClassNotFoundException {
-
- AbstractMongoClientConfiguration configuration = new SampleMongoConfiguration();
- assertThat(configuration.getMappingBasePackage()).isEqualTo(SampleMongoConfiguration.class.getPackage().getName());
- assertThat(configuration.getInitialEntitySet()).hasSize(2);
- assertThat(configuration.getInitialEntitySet()).contains(Entity.class);
- }
-
- @Test // DATAMONGO-496
- public void doesNotScanPackageIfMappingPackageIsNull() throws ClassNotFoundException {
- assertScanningDisabled(null);
- }
-
- @Test // DATAMONGO-496
- public void doesNotScanPackageIfMappingPackageIsEmpty() throws ClassNotFoundException {
-
- assertScanningDisabled("");
- assertScanningDisabled(" ");
- }
-
- @Test // DATAMONGO-569
- public void containsMongoDbFactoryButNoMongoBean() {
-
- AbstractApplicationContext context = new AnnotationConfigApplicationContext(SampleMongoConfiguration.class);
-
- assertThat(context.getBean(MongoDatabaseFactory.class)).isNotNull();
- assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> context.getBean(MongoClient.class));
-
- context.close();
- }
-
- @Test
- public void returnsUninitializedMappingContext() throws Exception {
-
- SampleMongoConfiguration configuration = new SampleMongoConfiguration();
- MongoMappingContext context = configuration.mongoMappingContext(configuration.customConversions());
-
- assertThat(context.getPersistentEntities()).isEmpty();
- context.initialize();
- assertThat(context.getPersistentEntities()).isNotEmpty();
- }
-
- @Test // DATAMONGO-717
- public void lifecycleCallbacksAreInvokedInAppropriateOrder() {
-
- AbstractApplicationContext context = new AnnotationConfigApplicationContext(SampleMongoConfiguration.class);
- MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class);
- MongoPersistentEntity> entity = mappingContext.getRequiredPersistentEntity(Entity.class);
- EvaluationContextProvider provider = (EvaluationContextProvider) ReflectionTestUtils.getField(entity,
- "evaluationContextProvider");
-
- assertThat(provider).isInstanceOf(ExtensionAwareEvaluationContextProvider.class);
- context.close();
- }
-
- @Test // DATAMONGO-725
- public void shouldBeAbleToConfigureCustomTypeMapperViaJavaConfig() {
-
- AbstractApplicationContext context = new AnnotationConfigApplicationContext(SampleMongoConfiguration.class);
- MongoTypeMapper typeMapper = context.getBean(CustomMongoTypeMapper.class);
- MappingMongoConverter mmc = context.getBean(MappingMongoConverter.class);
-
- assertThat(mmc).isNotNull();
- assertThat(mmc.getTypeMapper()).isEqualTo(typeMapper);
- context.close();
- }
-
- @Test // DATAMONGO-1470
- @SuppressWarnings("unchecked")
- public void allowsMultipleEntityBasePackages() throws ClassNotFoundException {
-
- ConfigurationWithMultipleBasePackages config = new ConfigurationWithMultipleBasePackages();
- Set> entities = config.getInitialEntitySet();
-
- assertThat(entities).hasSize(2);
- assertThat(entities).contains(First.class, Second.class);
- }
-
- private static void assertScanningDisabled(final String value) throws ClassNotFoundException {
-
- AbstractMongoClientConfiguration configuration = new SampleMongoConfiguration() {
- @Override
- protected Collection getMappingBasePackages() {
- return Collections.singleton(value);
- }
- };
-
- assertThat(configuration.getMappingBasePackages()).contains(value);
- assertThat(configuration.getInitialEntitySet()).hasSize(0);
- }
-
- @Configuration
- static class SampleMongoConfiguration extends AbstractMongoClientConfiguration {
-
- @Override
- protected String getDatabaseName() {
- return "database";
- }
-
- @Override
- public MongoClient mongoClient() {
- return MongoClients.create();
- }
-
- @Override
- public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory databaseFactory,
- MongoCustomConversions customConversions, MongoMappingContext mappingContext) {
- MappingMongoConverter converter = super.mappingMongoConverter(databaseFactory, customConversions, mappingContext);
- converter.setTypeMapper(typeMapper());
-
- return converter;
- }
-
- @Bean
- public MongoTypeMapper typeMapper() {
- return new CustomMongoTypeMapper();
- }
-
- }
-
- static class ConfigurationWithMultipleBasePackages extends AbstractMongoClientConfiguration {
-
- @Override
- protected String getDatabaseName() {
- return "test";
- }
-
- @Override
- public MongoClient mongoClient() {
- return MongoClients.create();
- }
-
- @Override
- protected Collection getMappingBasePackages() {
- return Arrays.asList("example.first", "example.second");
- }
- }
-
- @Document
- static class Entity {}
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractReactiveMongoConfigurationIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractReactiveMongoConfigurationIntegrationTests.java
deleted file mode 100644
index 701d0280d8..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractReactiveMongoConfigurationIntegrationTests.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2016-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.AssertionsForInterfaceTypes.*;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mockito;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.data.mongodb.core.ReactiveMongoOperations;
-import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
-import org.springframework.data.mongodb.core.SimpleReactiveMongoDatabaseFactory;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import com.mongodb.reactivestreams.client.MongoClient;
-
-/**
- * Integration tests for {@link AbstractReactiveMongoConfiguration}.
- *
- * @author Mark Paluch
- * @author Christoph Strobl
- */
-@RunWith(SpringRunner.class)
-@ContextConfiguration
-public class AbstractReactiveMongoConfigurationIntegrationTests {
-
- @Autowired ApplicationContext context;
-
- @Test // DATAMONGO-1444
- public void contextShouldContainTemplate() {
-
- assertThat(context.getBean(SimpleReactiveMongoDatabaseFactory.class)).isNotNull();
- assertThat(context.getBean(ReactiveMongoOperations.class)).isNotNull();
- assertThat(context.getBean(ReactiveMongoTemplate.class)).isNotNull();
- }
-
- @Configuration
- static class ReactiveConfiguration extends AbstractReactiveMongoConfiguration {
-
- @Override
- public MongoClient reactiveMongoClient() {
- return Mockito.mock(MongoClient.class);
- }
-
- @Override
- protected String getDatabaseName() {
- return "database";
- }
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractReactiveMongoConfigurationUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractReactiveMongoConfigurationUnitTests.java
deleted file mode 100644
index abbb7e0287..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractReactiveMongoConfigurationUnitTests.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright 2016-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import example.first.First;
-import example.second.Second;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Set;
-
-import org.junit.jupiter.api.Test;
-import org.mockito.Mockito;
-import org.springframework.beans.factory.NoSuchBeanDefinitionException;
-import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.support.AbstractApplicationContext;
-import org.springframework.data.mongodb.ReactiveMongoDatabaseFactory;
-import org.springframework.data.mongodb.core.SimpleReactiveMongoDatabaseFactory;
-import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
-import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
-import org.springframework.data.mongodb.core.convert.MongoTypeMapper;
-import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity;
-import org.springframework.data.mongodb.core.mapping.Document;
-import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
-import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
-import org.springframework.data.mongodb.test.util.MongoTestUtils;
-import org.springframework.data.spel.EvaluationContextProvider;
-import org.springframework.data.spel.ExtensionAwareEvaluationContextProvider;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import com.mongodb.reactivestreams.client.MongoClient;
-
-/**
- * Unit tests for {@link AbstractReactiveMongoConfiguration}.
- *
- * @author Mark Paluch
- */
-public class AbstractReactiveMongoConfigurationUnitTests {
-
- @Test // DATAMONGO-1444
- public void usesConfigClassPackageAsBaseMappingPackage() throws ClassNotFoundException {
-
- AbstractReactiveMongoConfiguration configuration = new SampleMongoConfiguration();
- assertThat(configuration.getMappingBasePackages()).contains(SampleMongoConfiguration.class.getPackage().getName());
- assertThat(configuration.getInitialEntitySet()).hasSize(2);
- assertThat(configuration.getInitialEntitySet()).contains(Entity.class);
- }
-
- @Test // DATAMONGO-1444
- public void doesNotScanPackageIfMappingPackageIsNull() throws ClassNotFoundException {
- assertScanningDisabled(null);
- }
-
- @Test // DATAMONGO-1444
- public void doesNotScanPackageIfMappingPackageIsEmpty() throws ClassNotFoundException {
-
- assertScanningDisabled("");
- assertScanningDisabled(" ");
- }
-
- @Test // DATAMONGO-1444
- public void containsMongoDbFactoryButNoMongoBean() {
-
- AbstractApplicationContext context = new AnnotationConfigApplicationContext(SampleMongoConfiguration.class);
-
- assertThat(context.getBean(SimpleReactiveMongoDatabaseFactory.class)).isNotNull();
- assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
- .isThrownBy(() -> context.getBean(com.mongodb.client.MongoClient.class));
-
- context.close();
- }
-
- @Test // DATAMONGO-1444
- public void returnsUninitializedMappingContext() throws Exception {
-
- SampleMongoConfiguration configuration = new SampleMongoConfiguration();
- MongoMappingContext context = configuration.mongoMappingContext(configuration.customConversions());
-
- assertThat(context.getPersistentEntities()).isEmpty();
- context.initialize();
- assertThat(context.getPersistentEntities()).isNotEmpty();
- }
-
- @Test // DATAMONGO-1444
- public void lifecycleCallbacksAreInvokedInAppropriateOrder() {
-
- AbstractApplicationContext context = new AnnotationConfigApplicationContext(SampleMongoConfiguration.class);
- MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class);
- MongoPersistentEntity> entity = mappingContext.getRequiredPersistentEntity(Entity.class);
- EvaluationContextProvider provider = (EvaluationContextProvider) ReflectionTestUtils.getField(entity,
- "evaluationContextProvider");
-
- assertThat(provider).isInstanceOf(ExtensionAwareEvaluationContextProvider.class);
- context.close();
- }
-
- @Test // DATAMONGO-1444
- public void shouldBeAbleToConfigureCustomTypeMapperViaJavaConfig() {
-
- AbstractApplicationContext context = new AnnotationConfigApplicationContext(SampleMongoConfiguration.class);
- MongoTypeMapper typeMapper = context.getBean(CustomMongoTypeMapper.class);
- MappingMongoConverter mmc = context.getBean(MappingMongoConverter.class);
-
- assertThat(mmc).isNotNull();
- assertThat(mmc.getTypeMapper()).isEqualTo(typeMapper);
- context.close();
- }
-
- @Test // DATAMONGO-1444
- @SuppressWarnings("unchecked")
- public void allowsMultipleEntityBasePackages() throws ClassNotFoundException {
-
- ConfigurationWithMultipleBasePackages config = new ConfigurationWithMultipleBasePackages();
- Set> entities = config.getInitialEntitySet();
-
- assertThat(entities).hasSize(2);
- assertThat(entities).contains(First.class, Second.class);
- }
-
- private static void assertScanningDisabled(final String value) throws ClassNotFoundException {
-
- AbstractReactiveMongoConfiguration configuration = new SampleMongoConfiguration() {
- @Override
- protected Collection getMappingBasePackages() {
- return Collections.singleton(value);
- }
- };
-
- assertThat(configuration.getMappingBasePackages()).contains(value);
- assertThat(configuration.getInitialEntitySet()).hasSize(0);
- }
-
- @Configuration
- static class SampleMongoConfiguration extends AbstractReactiveMongoConfiguration {
-
- @Override
- protected String getDatabaseName() {
- return "database";
- }
-
- @Override
- public MongoClient reactiveMongoClient() {
- return MongoTestUtils.reactiveClient();
- }
-
- @Override
- public MappingMongoConverter mappingMongoConverter(ReactiveMongoDatabaseFactory databaseFactory,
- MongoCustomConversions customConversions, MongoMappingContext mappingContext) {
-
- MappingMongoConverter converter = super.mappingMongoConverter(databaseFactory, customConversions, mappingContext);
- converter.setTypeMapper(typeMapper());
-
- return converter;
- }
-
- @Bean
- public MongoTypeMapper typeMapper() {
- return new CustomMongoTypeMapper();
- }
- }
-
- static class ConfigurationWithMultipleBasePackages extends AbstractReactiveMongoConfiguration {
-
- @Override
- protected String getDatabaseName() {
- return "test";
- }
-
- @Override
- public MongoClient reactiveMongoClient() {
- return Mockito.mock(MongoClient.class);
- }
-
- @Override
- protected Collection getMappingBasePackages() {
- return Arrays.asList("example.first", "example.second");
- }
- }
-
- @Document
- static class Entity {}
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AuditingIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AuditingIntegrationTests.java
deleted file mode 100644
index 92b295a707..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AuditingIntegrationTests.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright 2012-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.joda.time.DateTime;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.context.support.AbstractApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-import org.springframework.data.annotation.CreatedDate;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.annotation.LastModifiedDate;
-import org.springframework.data.mapping.callback.EntityCallbacks;
-import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
-import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback;
-
-/**
- * Integration test for the auditing support.
- *
- * @author Oliver Gierke
- * @author Mark Paluch
- */
-public class AuditingIntegrationTests {
-
- @Test // DATAMONGO-577, DATAMONGO-800, DATAMONGO-883, DATAMONGO-2261
- public void enablesAuditingAndSetsPropertiesAccordingly() throws Exception {
-
- AbstractApplicationContext context = new ClassPathXmlApplicationContext("auditing.xml", getClass());
-
- MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class);
- mappingContext.getPersistentEntity(Entity.class);
-
- EntityCallbacks callbacks = EntityCallbacks.create(context);
-
- Entity entity = new Entity();
- entity = callbacks.callback(BeforeConvertCallback.class, entity, "collection-1");
-
- assertThat(entity.created).isNotNull();
- assertThat(entity.modified).isEqualTo(entity.created);
-
- Thread.sleep(10);
- entity.id = 1L;
-
- entity = callbacks.callback(BeforeConvertCallback.class, entity, "collection-1");
-
- assertThat(entity.created).isNotNull();
- assertThat(entity.modified).isNotEqualTo(entity.created);
- context.close();
- }
-
- class Entity {
-
- @Id Long id;
- @CreatedDate DateTime created;
- DateTime modified;
-
- @LastModifiedDate
- public DateTime getModified() {
- return modified;
- }
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AuditingViaJavaConfigRepositoriesTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AuditingViaJavaConfigRepositoriesTests.java
deleted file mode 100644
index 3f7d15018e..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AuditingViaJavaConfigRepositoriesTests.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * Copyright 2013-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Function;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan.Filter;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.FilterType;
-import org.springframework.core.ResolvableType;
-import org.springframework.data.annotation.Version;
-import org.springframework.data.domain.AuditorAware;
-import org.springframework.data.mapping.callback.EntityCallback;
-import org.springframework.data.mongodb.core.AuditablePerson;
-import org.springframework.data.mongodb.core.MongoOperations;
-import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
-import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
-import org.springframework.data.mongodb.core.mapping.event.AuditingEntityCallback;
-import org.springframework.data.mongodb.core.mapping.event.ReactiveAuditingEntityCallback;
-import org.springframework.data.mongodb.repository.MongoRepository;
-import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
-import org.springframework.data.mongodb.test.util.Client;
-import org.springframework.data.mongodb.test.util.MongoClientExtension;
-import org.springframework.data.mongodb.test.util.MongoTestUtils;
-import org.springframework.stereotype.Repository;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import com.mongodb.client.MongoClient;
-
-/**
- * Integration tests for auditing via Java config.
- *
- * @author Thomas Darimont
- * @author Oliver Gierke
- * @author Mark Paluch
- */
-@ExtendWith({ MongoClientExtension.class, SpringExtension.class })
-@ContextConfiguration
-class AuditingViaJavaConfigRepositoriesTests {
-
- static @Client MongoClient mongoClient;
-
- @Autowired AuditablePersonRepository auditablePersonRepository;
- @Autowired AuditorAware auditorAware;
- @Autowired MongoMappingContext context;
- @Autowired MongoOperations operations;
-
- AuditablePerson auditor;
-
- @Configuration
- @EnableMongoAuditing(auditorAwareRef = "auditorProvider")
- @EnableMongoRepositories(basePackageClasses = AuditablePersonRepository.class, considerNestedRepositories = true,
- includeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = AuditablePersonRepository.class))
- static class Config extends AbstractMongoClientConfiguration {
-
- @Override
- protected String getDatabaseName() {
-
- return "database";
- }
-
- @Override
- public MongoClient mongoClient() {
- return mongoClient;
- }
-
- @Bean
- @SuppressWarnings("unchecked")
- public AuditorAware auditorProvider() {
- return mock(AuditorAware.class);
- }
-
- @Override
- protected Set> getInitialEntitySet() throws ClassNotFoundException {
- return new HashSet<>(
- Arrays.asList(AuditablePerson.class, VersionedAuditablePerson.class, SimpleVersionedAuditablePerson.class));
- }
- }
-
- @BeforeEach
- void setup() {
- auditablePersonRepository.deleteAll();
- this.auditor = auditablePersonRepository.save(new AuditablePerson("auditor"));
- }
-
- @Test // DATAMONGO-792, DATAMONGO-883
- void basicAuditing() {
-
- doReturn(Optional.of(this.auditor)).when(this.auditorAware).getCurrentAuditor();
-
- AuditablePerson savedUser = auditablePersonRepository.save(new AuditablePerson("user"));
-
- AuditablePerson createdBy = savedUser.getCreatedBy();
-
- assertThat(createdBy).isNotNull();
- assertThat(createdBy.getFirstname()).isEqualTo(this.auditor.getFirstname());
- assertThat(savedUser.getCreatedAt()).isNotNull();
- }
-
- @Test // DATAMONGO-843
- @SuppressWarnings("resource")
- void auditingUsesFallbackMappingContextIfNoneConfiguredWithRepositories() {
- new AnnotationConfigApplicationContext(SimpleConfigWithRepositories.class);
- }
-
- @Test // DATAMONGO-843
- @SuppressWarnings("resource")
- void auditingUsesFallbackMappingContextIfNoneConfigured() {
- new AnnotationConfigApplicationContext(SimpleConfig.class);
- }
-
- @Test // DATAMONGO-2139
- void auditingWorksForVersionedEntityWithWrapperVersion() {
-
- verifyAuditingViaVersionProperty(new VersionedAuditablePerson(), //
- it -> it.version, //
- AuditablePerson::getCreatedAt, //
- auditablePersonRepository::save, //
- null, 0L, 1L);
- }
-
- @Test // DATAMONGO-2179
- void auditingWorksForVersionedEntityBatchWithWrapperVersion() {
-
- verifyAuditingViaVersionProperty(new VersionedAuditablePerson(), //
- it -> it.version, //
- AuditablePerson::getCreatedAt, //
- s -> auditablePersonRepository.saveAll(Collections.singletonList(s)).get(0), //
- null, 0L, 1L);
- }
-
- @Test // DATAMONGO-2139
- void auditingWorksForVersionedEntityWithSimpleVersion() {
-
- verifyAuditingViaVersionProperty(new SimpleVersionedAuditablePerson(), //
- it -> it.version, //
- AuditablePerson::getCreatedAt, //
- auditablePersonRepository::save, //
- 0L, 1L, 2L);
- }
-
- @Test // DATAMONGO-2139
- void auditingWorksForVersionedEntityWithWrapperVersionOnTemplate() {
-
- verifyAuditingViaVersionProperty(new VersionedAuditablePerson(), //
- it -> it.version, //
- AuditablePerson::getCreatedAt, //
- operations::save, //
- null, 0L, 1L);
- }
-
- @Test // DATAMONGO-2139
- void auditingWorksForVersionedEntityWithSimpleVersionOnTemplate() {
-
- verifyAuditingViaVersionProperty(new SimpleVersionedAuditablePerson(), //
- it -> it.version, //
- AuditablePerson::getCreatedAt, //
- operations::save, //
- 0L, 1L, 2L);
- }
-
- @Test // DATAMONGO-2586
- void auditingShouldOnlyRegisterImperativeAuditingCallback() {
-
- Object callbacks = ReflectionTestUtils.getField(operations, "entityCallbacks");
- Object callbackDiscoverer = ReflectionTestUtils.getField(callbacks, "callbackDiscoverer");
- List> actualCallbacks = ReflectionTestUtils.invokeMethod(callbackDiscoverer, "getEntityCallbacks",
- AuditablePerson.class, ResolvableType.forClass(EntityCallback.class));
-
- assertThat(actualCallbacks) //
- .hasAtLeastOneElementOfType(AuditingEntityCallback.class) //
- .doesNotHaveAnyElementsOfTypes(ReactiveAuditingEntityCallback.class);
- }
-
- private void verifyAuditingViaVersionProperty(T instance,
- Function versionExtractor, Function createdDateExtractor, Function persister,
- Object... expectedValues) {
-
- MongoPersistentEntity> entity = context.getRequiredPersistentEntity(instance.getClass());
-
- assertThat(versionExtractor.apply(instance)).isEqualTo(expectedValues[0]);
- assertThat(createdDateExtractor.apply(instance)).isNull();
- assertThat(entity.isNew(instance)).isTrue();
-
- instance = persister.apply(instance);
-
- assertThat(versionExtractor.apply(instance)).isEqualTo(expectedValues[1]);
- assertThat(createdDateExtractor.apply(instance)).isNotNull();
- assertThat(entity.isNew(instance)).isFalse();
-
- instance = persister.apply(instance);
-
- assertThat(versionExtractor.apply(instance)).isEqualTo(expectedValues[2]);
- assertThat(entity.isNew(instance)).isFalse();
- }
-
- @Repository
- interface AuditablePersonRepository extends MongoRepository {}
-
- @Configuration
- @EnableMongoRepositories
- static class SimpleConfigWithRepositories extends SimpleConfig {}
-
- @Configuration
- @EnableMongoAuditing
- static class SimpleConfig extends AbstractMongoClientConfiguration {
-
- @Override
- public MongoClient mongoClient() {
- return MongoTestUtils.client();
- }
-
- @Override
- protected String getDatabaseName() {
- return "database";
- }
-
- @Override
- protected Set> getInitialEntitySet() throws ClassNotFoundException {
- return Collections.emptySet();
- }
- }
-
- static class VersionedAuditablePerson extends AuditablePerson {
- @Version Long version;
- }
-
- static class SimpleVersionedAuditablePerson extends AuditablePerson {
- @Version long version;
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/CustomMongoTypeMapper.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/CustomMongoTypeMapper.java
deleted file mode 100644
index 9cf0141f00..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/CustomMongoTypeMapper.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2013-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
-
-/**
- * @author Thomas Darimont
- */
-class CustomMongoTypeMapper extends DefaultMongoTypeMapper {}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/GeoJsonConfigurationIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/GeoJsonConfigurationIntegrationTests.java
deleted file mode 100644
index b257c3ecfa..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/GeoJsonConfigurationIntegrationTests.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright 2015-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.data.mongodb.core.geo.GeoJsonModule;
-import org.springframework.data.web.config.EnableSpringDataWebSupport;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringRunner;
-
-/**
- * Integration tests for {@link GeoJsonConfiguration}.
- *
- * @author Oliver Gierke
- */
-@RunWith(SpringRunner.class)
-@ContextConfiguration
-public class GeoJsonConfigurationIntegrationTests {
-
- @Configuration
- @EnableSpringDataWebSupport
- static class Config {}
-
- @Autowired GeoJsonModule geoJsonModule;
-
- @Test // DATAMONGO-1181
- public void picksUpGeoJsonModuleConfigurationByDefault() {
- assertThat(geoJsonModule).isNotNull();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MappingMongoConverterParserIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MappingMongoConverterParserIntegrationTests.java
deleted file mode 100644
index 9d92372522..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MappingMongoConverterParserIntegrationTests.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright 2011-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.util.Collections;
-import java.util.Set;
-
-import org.bson.Document;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.config.BeanReference;
-import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
-import org.springframework.beans.factory.support.BeanDefinitionRegistry;
-import org.springframework.beans.factory.support.DefaultListableBeanFactory;
-import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
-import org.springframework.core.convert.TypeDescriptor;
-import org.springframework.core.convert.converter.Converter;
-import org.springframework.core.convert.converter.GenericConverter;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.data.convert.CustomConversions;
-import org.springframework.data.mapping.model.CamelCaseAbbreviatingFieldNamingStrategy;
-import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
-import org.springframework.data.mongodb.core.convert.MongoTypeMapper;
-import org.springframework.data.mongodb.core.mapping.Account;
-import org.springframework.data.mongodb.repository.Person;
-import org.springframework.stereotype.Component;
-
-/**
- * Integration tests for {@link MappingMongoConverterParser}.
- *
- * @author Oliver Gierke
- * @author Thomas Darimont
- * @author Christoph Strobl
- * @author Ryan Tenney
- */
-public class MappingMongoConverterParserIntegrationTests {
-
- DefaultListableBeanFactory factory;
-
- @Test // DATAMONGO-243
- public void allowsDbFactoryRefAttribute() {
-
- loadValidConfiguration();
- factory.getBeanDefinition("converter");
- factory.getBean("converter");
- }
-
- @Test // DATAMONGO-725
- public void hasCustomTypeMapper() {
-
- loadValidConfiguration();
- MappingMongoConverter converter = factory.getBean("converter", MappingMongoConverter.class);
- MongoTypeMapper customMongoTypeMapper = factory.getBean(CustomMongoTypeMapper.class);
-
- assertThat(converter.getTypeMapper()).isEqualTo(customMongoTypeMapper);
- }
-
- @Test // DATAMONGO-301
- public void scansForConverterAndSetsUpCustomConversionsAccordingly() {
-
- loadValidConfiguration();
- CustomConversions conversions = factory.getBean(CustomConversions.class);
- assertThat(conversions.hasCustomWriteTarget(Person.class)).isTrue();
- assertThat(conversions.hasCustomWriteTarget(Account.class)).isTrue();
- }
-
- @Test // DATAMONGO-607
- public void activatesAbbreviatingPropertiesCorrectly() {
-
- loadValidConfiguration();
- BeanDefinition definition = factory.getBeanDefinition("abbreviatingConverter.mongoMappingContext");
- Object value = definition.getPropertyValues().getPropertyValue("fieldNamingStrategy").getValue();
-
- assertThat(value).isInstanceOf(BeanDefinition.class);
- BeanDefinition strategy = (BeanDefinition) value;
- assertThat(strategy.getBeanClassName()).isEqualTo(CamelCaseAbbreviatingFieldNamingStrategy.class.getName());
- }
-
- @Test // DATAMONGO-866
- public void rejectsInvalidFieldNamingStrategyConfiguration() {
-
- BeanDefinitionRegistry factory = new DefaultListableBeanFactory();
- XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
-
- assertThatExceptionOfType(BeanDefinitionParsingException.class)
- .isThrownBy(() -> reader.loadBeanDefinitions(new ClassPathResource("namespace/converter-invalid.xml")))
- .withMessageContaining("abbreviation").withMessageContaining("field-naming-strategy-ref");
- }
-
- @Test // DATAMONGO-892
- public void shouldThrowBeanDefinitionParsingExceptionIfConverterDefinedAsNestedBean() {
-
- assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(this::loadNestedBeanConfiguration)
- .withMessageContaining("Mongo Converter must not be defined as nested bean.");
-
- }
-
- @Test // DATAMONGO-925, DATAMONGO-928
- public void shouldSupportCustomFieldNamingStrategy() {
- assertStrategyReferenceSetFor("mappingConverterWithCustomFieldNamingStrategy");
- }
-
- @Test // DATAMONGO-925, DATAMONGO-928
- public void shouldNotFailLoadingConfigIfAbbreviationIsDisabledAndStrategySet() {
- assertStrategyReferenceSetFor("mappingConverterWithCustomFieldNamingStrategyAndAbbreviationDisabled");
- }
-
- private void loadValidConfiguration() {
- this.loadConfiguration("namespace/converter.xml");
- }
-
- private void loadNestedBeanConfiguration() {
- this.loadConfiguration("namespace/converter-nested-bean-definition.xml");
- }
-
- private void loadConfiguration(String configLocation) {
- factory = new DefaultListableBeanFactory();
- XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
- reader.loadBeanDefinitions(new ClassPathResource(configLocation));
- }
-
- private static void assertStrategyReferenceSetFor(String beanId) {
-
- BeanDefinitionRegistry factory = new DefaultListableBeanFactory();
- XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
- reader.loadBeanDefinitions(new ClassPathResource("namespace/converter-custom-fieldnamingstrategy.xml"));
-
- BeanDefinition definition = reader.getRegistry().getBeanDefinition(beanId.concat(".mongoMappingContext"));
- BeanReference value = (BeanReference) definition.getPropertyValues().getPropertyValue("fieldNamingStrategy")
- .getValue();
-
- assertThat(value.getBeanName()).isEqualTo("customFieldNamingStrategy");
- }
-
- @Component
- public static class SampleConverter implements Converter {
- public Document convert(Person source) {
- return null;
- }
- }
-
- @Component
- public static class SampleConverterFactory implements GenericConverter {
-
- public Set getConvertibleTypes() {
- return Collections.singleton(new ConvertiblePair(Account.class, Document.class));
- }
-
- public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
- return null;
- }
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MappingMongoConverterParserValidationIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MappingMongoConverterParserValidationIntegrationTests.java
deleted file mode 100644
index 84be7079f1..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MappingMongoConverterParserValidationIntegrationTests.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright 2012-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import org.springframework.beans.factory.NoSuchBeanDefinitionException;
-import org.springframework.beans.factory.support.BeanDefinitionReader;
-import org.springframework.beans.factory.support.DefaultListableBeanFactory;
-import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
-import org.springframework.core.io.ClassPathResource;
-
-/**
- * Integration test for creation of instance of
- * {@link org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener} by defining
- * {@code } in context XML.
- *
- * @author Maciej Walkowiak
- * @author Thomas Darimont
- * @author Oliver Gierke
- */
-public class MappingMongoConverterParserValidationIntegrationTests {
-
- DefaultListableBeanFactory factory;
- BeanDefinitionReader reader;
-
- @Before
- public void setUp() {
- factory = new DefaultListableBeanFactory();
- reader = new XmlBeanDefinitionReader(factory);
- }
-
- @Test // DATAMONGO-36
- public void validatingEventListenerCreatedWithDefaultConfig() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/converter-default.xml"));
- assertThat(factory.getBean(BeanNames.VALIDATING_EVENT_LISTENER_BEAN_NAME)).isNotNull();
- }
-
- @Test // DATAMONGO-36
- public void validatingEventListenerCreatedWhenValidationEnabled() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/converter-validation-enabled.xml"));
- assertThat(factory.getBean(BeanNames.VALIDATING_EVENT_LISTENER_BEAN_NAME)).isNotNull();
- }
-
- @Test(expected = NoSuchBeanDefinitionException.class) // DATAMONGO-36
- public void validatingEventListenersIsNotCreatedWhenDisabled() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/converter-validation-disabled.xml"));
- factory.getBean(BeanNames.VALIDATING_EVENT_LISTENER_BEAN_NAME);
- }
-
- @Test // DATAMONGO-36
- public void validatingEventListenerCreatedWithCustomTypeMapperConfig() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/converter-custom-typeMapper.xml"));
- assertThat(factory.getBean(BeanNames.VALIDATING_EVENT_LISTENER_BEAN_NAME)).isNotNull();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoAuditingRegistrarUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoAuditingRegistrarUnitTests.java
deleted file mode 100644
index 4a37adcd9a..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoAuditingRegistrarUnitTests.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2013-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.beans.factory.support.BeanDefinitionRegistry;
-import org.springframework.core.type.AnnotationMetadata;
-
-/**
- * Unit tests for {@link MongoAuditingRegistrar}.
- *
- * @author Oliver Gierke
- */
-@ExtendWith(MockitoExtension.class)
-class MongoAuditingRegistrarUnitTests {
-
- private MongoAuditingRegistrar registrar = new MongoAuditingRegistrar();
-
- @Mock AnnotationMetadata metadata;
- @Mock BeanDefinitionRegistry registry;
-
- @Test // DATAMONGO-792
- void rejectsNullAnnotationMetadata() {
- assertThatIllegalArgumentException().isThrownBy(() -> registrar.registerBeanDefinitions(null, registry));
- }
-
- @Test // DATAMONGO-792
- void rejectsNullBeanDefinitionRegistry() {
- assertThatIllegalArgumentException().isThrownBy(() -> registrar.registerBeanDefinitions(metadata, null));
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoClientNamespaceTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoClientNamespaceTests.java
deleted file mode 100644
index 47dd85e07a..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoClientNamespaceTests.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.test.util.ReflectionTestUtils.*;
-
-import java.util.Collections;
-import java.util.concurrent.TimeUnit;
-
-import org.bson.UuidRepresentation;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.ApplicationContext;
-import org.springframework.data.mongodb.core.MongoClientFactoryBean;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import com.mongodb.ConnectionString;
-import com.mongodb.MongoClientSettings;
-import com.mongodb.MongoCredential;
-import com.mongodb.ServerAddress;
-import com.mongodb.connection.ClusterType;
-
-/**
- * Integration tests for the MongoDB namespace.
- *
- * @author Christoph Strobl
- */
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration
-public class MongoClientNamespaceTests {
-
- @Autowired ApplicationContext ctx;
-
- @Test // DATAMONGO-2384
- public void clientWithJustHostAndPort() {
-
- assertThat(ctx.containsBean("client-with-just-host-port")).isTrue();
- MongoClientFactoryBean factoryBean = ctx.getBean("&client-with-just-host-port", MongoClientFactoryBean.class);
-
- assertThat(getField(factoryBean, "host")).isEqualTo("127.0.0.1");
- assertThat(getField(factoryBean, "port")).isEqualTo(27017);
- assertThat(getField(factoryBean, "connectionString")).isNull();
- assertThat(getField(factoryBean, "credential")).isNull();
- assertThat(getField(factoryBean, "replicaSet")).isNull();
- assertThat(getField(factoryBean, "mongoClientSettings")).isNull();
- }
-
- @Test // DATAMONGO-2384
- public void clientWithConnectionString() {
-
- assertThat(ctx.containsBean("client-with-connection-string")).isTrue();
- MongoClientFactoryBean factoryBean = ctx.getBean("&client-with-connection-string", MongoClientFactoryBean.class);
-
- assertThat(getField(factoryBean, "host")).isNull();
- assertThat(getField(factoryBean, "port")).isNull();
- assertThat(getField(factoryBean, "connectionString"))
- .isEqualTo(new ConnectionString("mongodb://127.0.0.1:27017/?replicaSet=rs0"));
- assertThat(getField(factoryBean, "credential")).isNull();
- assertThat(getField(factoryBean, "replicaSet")).isNull();
- assertThat(getField(factoryBean, "mongoClientSettings")).isNull();
- }
-
- @Test // DATAMONGO-2384
- public void clientWithReplicaSet() {
-
- assertThat(ctx.containsBean("client-with-replica-set")).isTrue();
- MongoClientFactoryBean factoryBean = ctx.getBean("&client-with-replica-set", MongoClientFactoryBean.class);
-
- assertThat(getField(factoryBean, "host")).isNull();
- assertThat(getField(factoryBean, "port")).isNull();
- assertThat(getField(factoryBean, "connectionString")).isNull();
- assertThat(getField(factoryBean, "credential")).isNull();
- assertThat(getField(factoryBean, "replicaSet")).isEqualTo("rs0");
- assertThat(getField(factoryBean, "mongoClientSettings")).isNull();
- }
-
- @Test // DATAMONGO-2384
- public void clientWithCredential() {
-
- assertThat(ctx.containsBean("client-with-auth")).isTrue();
- MongoClientFactoryBean factoryBean = ctx.getBean("&client-with-auth", MongoClientFactoryBean.class);
-
- assertThat(getField(factoryBean, "host")).isNull();
- assertThat(getField(factoryBean, "port")).isNull();
- assertThat(getField(factoryBean, "connectionString")).isNull();
- assertThat(getField(factoryBean, "credential")).isEqualTo(
- Collections.singletonList(MongoCredential.createPlainCredential("jon", "snow", "warg".toCharArray())));
- assertThat(getField(factoryBean, "replicaSet")).isNull();
- assertThat(getField(factoryBean, "mongoClientSettings")).isNull();
- }
-
- @Test // DATAMONGO-2384
- public void clientWithClusterSettings() {
-
- assertThat(ctx.containsBean("client-with-cluster-settings")).isTrue();
- MongoClientFactoryBean factoryBean = ctx.getBean("&client-with-cluster-settings", MongoClientFactoryBean.class);
-
- MongoClientSettings settings = (MongoClientSettings) getField(factoryBean, "mongoClientSettings");
-
- assertThat(settings.getClusterSettings().getRequiredClusterType()).isEqualTo(ClusterType.REPLICA_SET);
- assertThat(settings.getClusterSettings().getServerSelectionTimeout(TimeUnit.MILLISECONDS)).isEqualTo(10);
- assertThat(settings.getClusterSettings().getLocalThreshold(TimeUnit.MILLISECONDS)).isEqualTo(5);
- assertThat(settings.getClusterSettings().getHosts()).contains(new ServerAddress("localhost", 27018),
- new ServerAddress("localhost", 27019), new ServerAddress("localhost", 27020));
- }
-
- @Test // DATAMONGO-2384
- public void clientWithConnectionPoolSettings() {
-
- assertThat(ctx.containsBean("client-with-connection-pool-settings")).isTrue();
- MongoClientFactoryBean factoryBean = ctx.getBean("&client-with-connection-pool-settings",
- MongoClientFactoryBean.class);
-
- MongoClientSettings settings = (MongoClientSettings) getField(factoryBean, "mongoClientSettings");
-
- assertThat(settings.getConnectionPoolSettings().getMaxConnectionLifeTime(TimeUnit.MILLISECONDS)).isEqualTo(10);
- assertThat(settings.getConnectionPoolSettings().getMinSize()).isEqualTo(10);
- assertThat(settings.getConnectionPoolSettings().getMaxSize()).isEqualTo(20);
- assertThat(settings.getConnectionPoolSettings().getMaintenanceFrequency(TimeUnit.MILLISECONDS)).isEqualTo(10);
- assertThat(settings.getConnectionPoolSettings().getMaintenanceInitialDelay(TimeUnit.MILLISECONDS)).isEqualTo(11);
- assertThat(settings.getConnectionPoolSettings().getMaxConnectionIdleTime(TimeUnit.MILLISECONDS)).isEqualTo(30);
- assertThat(settings.getConnectionPoolSettings().getMaxWaitTime(TimeUnit.MILLISECONDS)).isEqualTo(15);
- }
-
- @Test // DATAMONGO-2427
- public void clientWithUUidSettings() {
-
- assertThat(ctx.containsBean("client-with-uuid-settings")).isTrue();
- MongoClientFactoryBean factoryBean = ctx.getBean("&client-with-uuid-settings", MongoClientFactoryBean.class);
-
- MongoClientSettings settings = (MongoClientSettings) getField(factoryBean, "mongoClientSettings");
- assertThat(settings.getUuidRepresentation()).isEqualTo(UuidRepresentation.STANDARD);
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoClientParserIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoClientParserIntegrationTests.java
deleted file mode 100644
index 8a7f1f1d97..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoClientParserIntegrationTests.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright 2015-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.util.concurrent.TimeUnit;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.springframework.beans.factory.support.BeanDefinitionReader;
-import org.springframework.beans.factory.support.DefaultListableBeanFactory;
-import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
-import org.springframework.context.support.AbstractApplicationContext;
-import org.springframework.context.support.GenericApplicationContext;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import com.mongodb.MongoClientSettings;
-import com.mongodb.MongoCredential;
-import com.mongodb.ReadPreference;
-import com.mongodb.ServerAddress;
-import com.mongodb.WriteConcern;
-import com.mongodb.client.MongoClient;
-
-/**
- * Integration tests for {@link MongoClientParser}.
- *
- * @author Christoph Strobl
- * @author Mark Paluch
- */
-public class MongoClientParserIntegrationTests {
-
- DefaultListableBeanFactory factory;
- BeanDefinitionReader reader;
-
- @BeforeEach
- public void setUp() {
-
- this.factory = new DefaultListableBeanFactory();
- this.reader = new XmlBeanDefinitionReader(factory);
- }
-
- @Test // DATAMONGO-1158
- public void createsMongoClientCorrectlyWhenGivenHostAndPort() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/mongoClient-bean.xml"));
-
- assertThat(factory.getBean("mongo-client-with-host-and-port")).isInstanceOf(MongoClient.class);
- }
-
- @Test // DATAMONGO-1158, DATAMONGO-2199
- public void createsMongoClientWithOptionsCorrectly() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/mongoClient-bean.xml"));
-
- try (AbstractApplicationContext context = new GenericApplicationContext(factory)) {
- context.refresh();
-
- MongoClientSettings settings = extractClientSettingsFromBean(context,
- "mongo-client-with-options-for-write-concern-and-read-preference");
- assertThat(settings.getReadPreference()).isEqualTo(ReadPreference.secondary());
- assertThat(settings.getWriteConcern()).isEqualTo(WriteConcern.UNACKNOWLEDGED);
- }
- }
-
- @Test // DATAMONGO-1158
- public void createsMongoClientWithDefaultsCorrectly() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/mongoClient-bean.xml"));
-
- try (AbstractApplicationContext context = new GenericApplicationContext(factory)) {
-
- context.refresh();
-
- MongoClient client = context.getBean("mongoClient", MongoClient.class);
- assertThat(client.getClusterDescription().getClusterSettings().getHosts()).containsExactly(new ServerAddress());
- }
- }
-
- @Test // DATAMONGO-1158
- public void createsMongoClientWithCredentialsCorrectly() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/mongoClient-bean.xml"));
-
- try (AbstractApplicationContext context = new GenericApplicationContext(factory)) {
-
- context.refresh();
-
- MongoClientSettings settings = extractClientSettingsFromBean(context, "mongo-client-with-credentials");
-
- assertThat(settings.getCredential())
- .isEqualTo(MongoCredential.createPlainCredential("jon", "snow", "warg".toCharArray()));
- }
- }
-
- @Test // DATAMONGO-1620
- public void createsMongoClientWithServerSelectionTimeoutCorrectly() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/mongoClient-bean.xml"));
-
- try (AbstractApplicationContext context = new GenericApplicationContext(factory)) {
- context.refresh();
-
- MongoClientSettings settings = extractClientSettingsFromBean(context,
- "mongo-client-with-server-selection-timeout");
- assertThat(settings.getClusterSettings().getServerSelectionTimeout(TimeUnit.MILLISECONDS)).isEqualTo(100);
- }
- }
-
- private MongoClientSettings extractClientSettingsFromBean(AbstractApplicationContext context, String beanName) {
- return extractClientSettings(context.getBean(beanName, MongoClient.class));
- }
-
- private MongoClientSettings extractClientSettings(MongoClient client) {
- return (MongoClientSettings) ReflectionTestUtils.getField(client, "settings");
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoCredentialPropertyEditorUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoCredentialPropertyEditorUnitTests.java
deleted file mode 100644
index d564bd830b..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoCredentialPropertyEditorUnitTests.java
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Copyright 2015-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.springframework.util.StringUtils;
-
-import com.mongodb.MongoCredential;
-
-/**
- * Unit tests for {@link MongoCredentialPropertyEditor}.
- *
- * @author Christoph Strobl
- * @author Stephen Tyler Conrad
- */
-public class MongoCredentialPropertyEditorUnitTests {
-
- static final String USER_1_NAME = "tyrion";
- static final String USER_1_PWD = "dwarf";
- static final String USER_1_DB = "lannister";
-
- static final String USER_2_NAME = "jon";
- static final String USER_2_PWD = "warg";
- static final String USER_2_DB = "snow";
-
- static final String USER_3_NAME = "CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry";
- static final String USER_3_DB = "stark";
-
- static final String USER_4_PLAIN_NAME = "m0ng0@dmin";
- static final String USER_4_ENCODED_NAME;
- static final String USER_4_PLAIN_PWD = "mo_res:bw6},Qsdxx@admin";
- static final String USER_4_ENCODED_PWD;
- static final String USER_4_DB = "targaryen";
-
- static final String USER_5_NAME = "lyanna";
- static final String USER_5_PWD = "random?password";
- static final String USER_5_DB = "mormont";
-
- static final String USER_1_AUTH_STRING = USER_1_NAME + ":" + USER_1_PWD + "@" + USER_1_DB;
- static final String USER_1_AUTH_STRING_WITH_PLAIN_AUTH_MECHANISM = USER_1_AUTH_STRING + "?uri.authMechanism=PLAIN";
-
- static final String USER_2_AUTH_STRING = USER_2_NAME + ":" + USER_2_PWD + "@" + USER_2_DB;
- static final String USER_2_AUTH_STRING_WITH_MONGODB_CR_AUTH_MECHANISM = USER_2_AUTH_STRING
- + "?uri.authMechanism=MONGODB-CR";
-
- static final String USER_3_AUTH_STRING_WITH_X509_AUTH_MECHANISM = "'" + USER_3_NAME + "@" + USER_3_DB
- + "?uri.authMechanism=MONGODB-X509'";
-
- static final String USER_4_AUTH_STRING;
-
- static final String USER_5_AUTH_STRING = USER_5_NAME + ":" + USER_5_PWD + "@" + USER_5_DB;
- static final String USER_5_AUTH_STRING_WITH_PLAIN_AUTH_MECHANISM = USER_5_AUTH_STRING + "?uri.authMechanism=PLAIN";
- static final String USER_5_AUTH_STRING_WITH_QUERY_ARGS = USER_5_AUTH_STRING + "?uri.authMechanism=PLAIN&foo=&bar";
-
- static final String SCRAM_SHA_256_AUTH_STRING = USER_1_NAME + ":" + USER_1_PWD + "@" + USER_1_DB
- + "?uri.authMechanism=SCRAM-SHA-256";
-
- static final MongoCredential USER_1_CREDENTIALS = MongoCredential.createCredential(USER_1_NAME, USER_1_DB,
- USER_1_PWD.toCharArray());
- static final MongoCredential USER_1_CREDENTIALS_PLAIN_AUTH = MongoCredential.createPlainCredential(USER_1_NAME,
- USER_1_DB, USER_1_PWD.toCharArray());
-
- static final MongoCredential USER_2_CREDENTIALS = MongoCredential.createCredential(USER_2_NAME, USER_2_DB,
- USER_2_PWD.toCharArray());
-
- static final MongoCredential USER_3_CREDENTIALS_X509_AUTH = MongoCredential.createMongoX509Credential(USER_3_NAME);
-
- static final MongoCredential USER_4_CREDENTIALS = MongoCredential.createCredential(USER_4_PLAIN_NAME, USER_4_DB,
- USER_4_PLAIN_PWD.toCharArray());
-
- static final MongoCredential USER_5_CREDENTIALS = MongoCredential.createCredential(USER_5_NAME, USER_5_DB,
- USER_5_PWD.toCharArray());
- static final MongoCredential USER_5_CREDENTIALS_PLAIN_AUTH = MongoCredential.createPlainCredential(USER_5_NAME,
- USER_5_DB, USER_5_PWD.toCharArray());
-
- static final MongoCredential SCRAM_SHA_256_CREDENTIALS = MongoCredential.createScramSha256Credential(USER_1_NAME,
- USER_1_DB, USER_1_PWD.toCharArray());
-
- MongoCredentialPropertyEditor editor;
-
- static {
-
- String encodedUserName = null;
- String encodedUserPassword = null;
- try {
- encodedUserName = URLEncoder.encode(USER_4_PLAIN_NAME, "UTF-8");
- encodedUserPassword = URLEncoder.encode(USER_4_PLAIN_PWD, "UTF-8");
- } catch (UnsupportedEncodingException e) {}
-
- USER_4_ENCODED_NAME = encodedUserName;
- USER_4_ENCODED_PWD = encodedUserPassword;
- USER_4_AUTH_STRING = USER_4_ENCODED_NAME + ":" + USER_4_ENCODED_PWD + "@" + USER_4_DB;
-
- }
-
- @Before
- public void setUp() {
- this.editor = new MongoCredentialPropertyEditor();
- }
-
- @Test // DATAMONGO-1158
- public void shouldReturnNullValueForNullText() {
-
- editor.setAsText(null);
-
- assertThat(getValue()).isNull();
- }
-
- @Test // DATAMONGO-1158
- public void shouldReturnNullValueForEmptyText() {
-
- editor.setAsText(" ");
-
- assertThat(getValue()).isNull();
- }
-
- @Test // DATAMONGO-1158
- public void shouldThrowExceptionForMalformatedCredentialsString() {
- assertThatIllegalArgumentException().isThrownBy(() -> editor.setAsText("tyrion"));
- }
-
- @Test // DATAMONGO-1158
- public void shouldThrowExceptionForMalformatedAuthMechanism() {
- assertThatIllegalArgumentException()
- .isThrownBy(() -> editor.setAsText(USER_2_AUTH_STRING + "?uri.authMechanism=Targaryen"));
- }
-
- @Test // DATAMONGO-1158
- @SuppressWarnings("unchecked")
- public void shouldReturnCredentialsValueCorrectlyWhenGivenSingleUserNamePasswordStringWithDatabaseAndNoOptions() {
-
- editor.setAsText(USER_1_AUTH_STRING);
-
- assertThat(getValue()).contains(USER_1_CREDENTIALS);
- }
-
- @Test // DATAMONGO-1158
- @SuppressWarnings("unchecked")
- public void shouldReturnCredentialsValueCorrectlyWhenGivenSingleUserNamePasswordStringWithDatabaseAndAuthOptions() {
-
- editor.setAsText(USER_1_AUTH_STRING_WITH_PLAIN_AUTH_MECHANISM);
-
- assertThat(getValue()).contains(USER_1_CREDENTIALS_PLAIN_AUTH);
- }
-
- @Test // DATAMONGO-1158
- @SuppressWarnings("unchecked")
- public void shouldReturnCredentialsValueCorrectlyWhenGivenMultipleUserNamePasswordStringWithDatabaseAndNoOptions() {
-
- editor
- .setAsText(StringUtils.collectionToCommaDelimitedString(Arrays.asList(USER_1_AUTH_STRING, USER_2_AUTH_STRING)));
-
- assertThat(getValue()).contains(USER_1_CREDENTIALS, USER_2_CREDENTIALS);
- }
-
- @Test // DATAMONGO-1158
- @SuppressWarnings("unchecked")
- public void shouldReturnCredentialsValueCorrectlyWhenGivenMultipleUserNamePasswordStringWithDatabaseAndMixedOptions() {
-
- editor.setAsText(StringUtils.collectionToCommaDelimitedString(
- Arrays.asList(USER_1_AUTH_STRING_WITH_PLAIN_AUTH_MECHANISM, USER_2_AUTH_STRING)));
-
- assertThat(getValue()).contains(USER_1_CREDENTIALS_PLAIN_AUTH, USER_2_CREDENTIALS);
- }
-
- @Test // DATAMONGO-1257
- @SuppressWarnings("unchecked")
- public void shouldReturnCredentialsValueCorrectlyWhenGivenMultipleQuotedUserNamePasswordStringWithDatabaseAndNoOptions() {
-
- editor.setAsText(StringUtils.collectionToCommaDelimitedString(
- Arrays.asList("'" + USER_1_AUTH_STRING + "'", "'" + USER_2_AUTH_STRING + "'")));
-
- assertThat(getValue()).contains(USER_1_CREDENTIALS, USER_2_CREDENTIALS);
- }
-
- @Test // DATAMONGO-1257
- @SuppressWarnings("unchecked")
- public void shouldReturnCredentialsValueCorrectlyWhenGivenSingleQuotedUserNamePasswordStringWithDatabaseAndNoOptions() {
-
- editor.setAsText("'" + USER_1_AUTH_STRING + "'");
-
- assertThat(getValue()).contains(USER_1_CREDENTIALS);
- }
-
- @Test // DATAMONGO-1257
- @SuppressWarnings("unchecked")
- public void shouldReturnX509CredentialsCorrectly() {
-
- editor.setAsText(USER_3_AUTH_STRING_WITH_X509_AUTH_MECHANISM);
-
- assertThat(getValue()).contains(USER_3_CREDENTIALS_X509_AUTH);
- }
-
- @Test // DATAMONGO-1257
- @SuppressWarnings("unchecked")
- public void shouldReturnX509CredentialsCorrectlyWhenNoDbSpecified() {
-
- editor.setAsText("tyrion?uri.authMechanism=MONGODB-X509");
-
- assertThat(getValue()).contains(MongoCredential.createMongoX509Credential("tyrion"));
- }
-
- @Test(expected = IllegalArgumentException.class) // DATAMONGO-1257
- public void shouldThrowExceptionWhenNoDbSpecifiedForMongodbCR() {
-
- editor.setAsText("tyrion?uri.authMechanism=MONGODB-CR");
-
- getValue();
- }
-
- @Test(expected = IllegalArgumentException.class) // DATAMONGO-1257
- public void shouldThrowExceptionWhenDbIsEmptyForMongodbCR() {
-
- editor.setAsText("tyrion@?uri.authMechanism=MONGODB-CR");
-
- getValue();
- }
-
- @Test // DATAMONGO-1317
- @SuppressWarnings("unchecked")
- public void encodedUserNameAndPasswordShouldBeDecoded() {
-
- editor.setAsText(USER_4_AUTH_STRING);
-
- assertThat(getValue()).contains(USER_4_CREDENTIALS);
- }
-
- @Test // DATAMONGO-2016
- @SuppressWarnings("unchecked")
- public void passwordWithQuestionMarkShouldNotBeInterpretedAsOptionString() {
-
- editor.setAsText(USER_5_AUTH_STRING);
-
- assertThat(getValue()).contains(USER_5_CREDENTIALS);
- }
-
- @Test // DATAMONGO-2016
- @SuppressWarnings("unchecked")
- public void passwordWithQuestionMarkShouldNotBreakParsingOfOptionString() {
-
- editor.setAsText(USER_5_AUTH_STRING_WITH_PLAIN_AUTH_MECHANISM);
-
- assertThat(getValue()).contains(USER_5_CREDENTIALS_PLAIN_AUTH);
- }
-
- @Test // DATAMONGO-2051
- public void shouldReturnScramSha256Credentials() {
-
- editor.setAsText(SCRAM_SHA_256_AUTH_STRING);
-
- assertThat(getValue()).contains(SCRAM_SHA_256_CREDENTIALS);
- }
-
- @Test // DATAMONGO-2016
- @SuppressWarnings("unchecked")
- public void failsGracefullyOnEmptyQueryArgument() {
- assertThatIllegalArgumentException().isThrownBy(() -> editor.setAsText(USER_5_AUTH_STRING_WITH_QUERY_ARGS));
- }
-
- @SuppressWarnings("unchecked")
- private List getValue() {
- return (List) editor.getValue();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoDbFactoryNoDatabaseRunningTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoDbFactoryNoDatabaseRunningTests.java
deleted file mode 100644
index 610473aee6..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoDbFactoryNoDatabaseRunningTests.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright 2011-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.dao.DataAccessResourceFailureException;
-import org.springframework.data.mongodb.MongoDatabaseFactory;
-import org.springframework.data.mongodb.core.MongoTemplate;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringRunner;
-
-/**
- * Integration tests for {@link MongoDatabaseFactory}.
- *
- * @author Thomas Risberg
- * @author Oliver Gierke
- */
-@RunWith(SpringRunner.class)
-@ContextConfiguration
-public class MongoDbFactoryNoDatabaseRunningTests {
-
- @Autowired MongoTemplate mongoTemplate;
-
- @Test // DATAMONGO-139
- public void startsUpWithoutADatabaseRunning() {
- assertThat(mongoTemplate.getClass().getName()).isEqualTo("org.springframework.data.mongodb.core.MongoTemplate");
- }
-
- @Test
- public void failsDataAccessWithoutADatabaseRunning() {
- assertThatExceptionOfType(DataAccessResourceFailureException.class)
- .isThrownBy(() -> mongoTemplate.getCollectionNames());
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoDbFactoryParserIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoDbFactoryParserIntegrationTests.java
deleted file mode 100644
index edd8cc9ba8..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoDbFactoryParserIntegrationTests.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Copyright 2011-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.config.ConstructorArgumentValues;
-import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder;
-import org.springframework.beans.factory.support.BeanDefinitionReader;
-import org.springframework.beans.factory.support.DefaultListableBeanFactory;
-import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
-import org.springframework.context.support.AbstractApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.data.mongodb.MongoDatabaseFactory;
-import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
-import org.springframework.data.mongodb.test.util.MongoTestUtils;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import com.mongodb.ConnectionString;
-import com.mongodb.WriteConcern;
-import com.mongodb.client.MongoClient;
-import com.mongodb.client.MongoDatabase;
-
-/**
- * Integration tests for {@link MongoDbFactoryParser}.
- *
- * @author Oliver Gierke
- * @author Christoph Strobl
- * @author Viktor Khoroshko
- */
-public class MongoDbFactoryParserIntegrationTests {
-
- DefaultListableBeanFactory factory;
- BeanDefinitionReader reader;
-
- @BeforeEach
- public void setUp() {
- factory = new DefaultListableBeanFactory();
- reader = new XmlBeanDefinitionReader(factory);
- }
-
- @Test // DATAMONGO-2199
- public void testWriteConcern() throws Exception {
-
- try (MongoClient client = MongoTestUtils.client()) {
- SimpleMongoClientDatabaseFactory dbFactory = new SimpleMongoClientDatabaseFactory(client, "database");
- dbFactory.setWriteConcern(WriteConcern.ACKNOWLEDGED);
- dbFactory.getMongoDatabase();
-
- assertThat(ReflectionTestUtils.getField(dbFactory, "writeConcern")).isEqualTo(WriteConcern.ACKNOWLEDGED);
- }
- }
-
- @Test // DATAMONGO-2199
- public void parsesWriteConcern() {
-
- ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("namespace/db-factory-bean.xml");
- assertWriteConcern(ctx, WriteConcern.ACKNOWLEDGED);
- }
-
- @Test // DATAMONGO-2199
- public void parsesCustomWriteConcern() {
-
- ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
- "namespace/db-factory-bean-custom-write-concern.xml");
- assertWriteConcern(ctx, new WriteConcern("rack1"));
- }
-
- @Test // DATAMONGO-331
- public void readsReplicasWriteConcernCorrectly() {
-
- AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(
- "namespace/db-factory-bean-custom-write-concern.xml");
- MongoDatabaseFactory factory = ctx.getBean("second", MongoDatabaseFactory.class);
- MongoDatabase db = factory.getMongoDatabase();
-
- assertThat(db.getWriteConcern()).isEqualTo(WriteConcern.W2);
- ctx.close();
- }
-
- // This test will fail since equals in WriteConcern uses == for _w and not .equals
- public void testWriteConcernEquality() {
-
- String s1 = new String("rack1");
- String s2 = new String("rack1");
- WriteConcern wc1 = new WriteConcern(s1);
- WriteConcern wc2 = new WriteConcern(s2);
- assertThat(wc1).isEqualTo(wc2);
- }
-
- @Test
- public void createsDbFactoryBean() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/db-factory-bean.xml"));
- factory.getBean("first");
- }
-
- @Test // DATAMONGO-306
- public void setsUpMongoDbFactoryUsingAMongoUriWithoutCredentials() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-uri-no-credentials.xml"));
- BeanDefinition definition = factory.getBeanDefinition("mongoDbFactory");
- ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
-
- assertThat(constructorArguments.getArgumentCount()).isOne();
- ValueHolder argument = constructorArguments.getArgumentValue(0, ConnectionString.class);
- assertThat(argument).isNotNull();
-
- MongoDatabaseFactory dbFactory = factory.getBean("mongoDbFactory", MongoDatabaseFactory.class);
- MongoDatabase db = dbFactory.getMongoDatabase();
- assertThat(db.getName()).isEqualTo("database");
- }
-
- @Test // DATAMONGO-1218
- public void setsUpMongoDbFactoryUsingAMongoClientUri() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-client-uri.xml"));
- BeanDefinition definition = factory.getBeanDefinition("mongoDbFactory");
- ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
-
- assertThat(constructorArguments.getArgumentCount()).isOne();
- ValueHolder argument = constructorArguments.getArgumentValue(0, ConnectionString.class);
- assertThat(argument).isNotNull();
- }
-
- @Test // DATAMONGO-1293
- public void setsUpClientUriWithId() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-client-uri-and-id.xml"));
- BeanDefinition definition = factory.getBeanDefinition("testMongo");
- ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
-
- assertThat(constructorArguments.getArgumentCount()).isOne();
- ValueHolder argument = constructorArguments.getArgumentValue(0, ConnectionString.class);
- assertThat(argument).isNotNull();
- }
-
- @Test // DATAMONGO-1293
- public void setsUpUriWithId() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-uri-and-id.xml"));
- BeanDefinition definition = factory.getBeanDefinition("testMongo");
- ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
-
- assertThat(constructorArguments.getArgumentCount()).isOne();
- ValueHolder argument = constructorArguments.getArgumentValue(0, ConnectionString.class);
- assertThat(argument).isNotNull();
- }
-
- @Test // DATAMONGO-2384
- public void usesConnectionStringToCreateClientClient() {
-
- ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("namespace/db-factory-bean.xml");
-
- MongoDatabaseFactory dbFactory = ctx.getBean("with-connection-string", MongoDatabaseFactory.class);
- assertThat(dbFactory).isInstanceOf(SimpleMongoClientDatabaseFactory.class);
- assertThat(ReflectionTestUtils.getField(dbFactory, "mongoClient"))
- .isInstanceOf(com.mongodb.client.MongoClient.class);
- }
-
- @Test // DATAMONGO-2384
- public void usesMongoClientClientRef() {
-
- ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("namespace/db-factory-bean.xml");
-
- MongoDatabaseFactory dbFactory = ctx.getBean("with-mongo-client-client-ref", MongoDatabaseFactory.class);
- assertThat(dbFactory).isInstanceOf(SimpleMongoClientDatabaseFactory.class);
- assertThat(ReflectionTestUtils.getField(dbFactory, "mongoClient"))
- .isInstanceOf(com.mongodb.client.MongoClient.class);
- }
-
- private static void assertWriteConcern(ClassPathXmlApplicationContext ctx, WriteConcern expectedWriteConcern) {
-
- SimpleMongoClientDatabaseFactory dbFactory = ctx.getBean("first", SimpleMongoClientDatabaseFactory.class);
- MongoDatabase db = dbFactory.getMongoDatabase();
- assertThat(db.getName()).isEqualTo("db");
-
- WriteConcern configuredConcern = (WriteConcern) ReflectionTestUtils.getField(dbFactory, "writeConcern");
-
- assertThat(configuredConcern).isEqualTo(expectedWriteConcern);
- assertThat(db.getWriteConcern()).isEqualTo(expectedWriteConcern);
- assertThat(db.getWriteConcern()).isEqualTo(expectedWriteConcern);
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceReplicaSetTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceReplicaSetTests.java
deleted file mode 100644
index f81db94d37..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceReplicaSetTests.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright 2011-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.bson.Document;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.ApplicationContext;
-import org.springframework.data.mongodb.core.MongoClientFactoryBean;
-import org.springframework.data.mongodb.core.MongoTemplate;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import com.mongodb.MongoClientSettings;
-import com.mongodb.ServerAddress;
-import com.mongodb.client.MongoClient;
-
-/**
- * @author Mark Pollack
- * @author Oliver Gierke
- * @author Thomas Darimont
- * @author Mark Paluch
- */
-@RunWith(SpringRunner.class)
-@ContextConfiguration
-public class MongoNamespaceReplicaSetTests {
-
- @Autowired private ApplicationContext ctx;
-
- @Test
- @SuppressWarnings("unchecked")
- public void testParsingMongoWithReplicaSets() throws Exception {
-
- assertThat(ctx.containsBean("replicaSetMongo")).isTrue();
- MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&replicaSetMongo");
-
- MongoClientSettings settings = (MongoClientSettings) ReflectionTestUtils.getField(mfb, "mongoClientSettings");
- List replicaSetSeeds = settings.getClusterSettings().getHosts();
-
- assertThat(replicaSetSeeds).isNotNull();
- assertThat(replicaSetSeeds).contains(new ServerAddress(InetAddress.getByName("127.0.0.1"), 10001),
- new ServerAddress(InetAddress.getByName("localhost"), 10002));
- }
-
- @Test
- @SuppressWarnings("unchecked")
- public void testParsingWithPropertyPlaceHolder() throws Exception {
-
- assertThat(ctx.containsBean("manyReplicaSetMongo")).isTrue();
- MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&manyReplicaSetMongo");
-
- MongoClientSettings settings = (MongoClientSettings) ReflectionTestUtils.getField(mfb, "mongoClientSettings");
- List replicaSetSeeds = settings.getClusterSettings().getHosts();
-
- assertThat(replicaSetSeeds).isNotNull();
- assertThat(replicaSetSeeds).hasSize(3);
-
- List ports = new ArrayList();
- for (ServerAddress replicaSetSeed : replicaSetSeeds) {
- ports.add(replicaSetSeed.getPort());
- }
-
- assertThat(ports).contains(27017, 27018, 27019);
- }
-
- @Test
- @Ignore("CI infrastructure does not yet support replica sets")
- public void testMongoWithReplicaSets() {
-
- MongoClient mongo = ctx.getBean(MongoClient.class);
- assertThat(mongo.getClusterDescription().getClusterSettings().getHosts()).isEqualTo(2);
- List servers = mongo.getClusterDescription().getClusterSettings().getHosts();
- assertThat(servers.get(0).getHost()).isEqualTo("127.0.0.1");
- assertThat(servers.get(1).getHost()).isEqualTo("localhost");
- assertThat(servers.get(0).getPort()).isEqualTo(10001);
- assertThat(servers.get(1).getPort()).isEqualTo(10002);
-
- MongoTemplate template = new MongoTemplate(mongo, "admin");
- Document result = template.executeCommand("{replSetGetStatus : 1}");
- assertThat(result.get("set").toString()).isEqualTo("blort");
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceTests.java
deleted file mode 100644
index 29cee1e488..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceTests.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Copyright 2010-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.test.util.ReflectionTestUtils.*;
-
-import javax.net.ssl.SSLSocketFactory;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.ApplicationContext;
-import org.springframework.data.mongodb.MongoDatabaseFactory;
-import org.springframework.data.mongodb.core.MongoClientFactoryBean;
-import org.springframework.data.mongodb.core.MongoOperations;
-import org.springframework.data.mongodb.core.convert.MongoConverter;
-import org.springframework.data.mongodb.gridfs.GridFsOperations;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import com.mongodb.MongoClientSettings;
-import com.mongodb.ServerAddress;
-import com.mongodb.WriteConcern;
-import com.mongodb.client.MongoClient;
-
-/**
- * Integration tests for the MongoDB namespace.
- *
- * @author Mark Pollack
- * @author Oliver Gierke
- * @author Martin Baumgartner
- * @author Thomas Darimont
- * @author Christoph Strobl
- */
-@RunWith(SpringRunner.class)
-@ContextConfiguration
-public class MongoNamespaceTests {
-
- @Autowired ApplicationContext ctx;
-
- @Test
- public void testMongoSingleton() throws Exception {
-
- assertThat(ctx.containsBean("noAttrMongo")).isTrue();
- MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&noAttrMongo");
-
- assertThat(getField(mfb, "host")).isNull();
- assertThat(getField(mfb, "port")).isNull();
- }
-
- @Test
- public void testMongoSingletonWithAttributes() throws Exception {
-
- assertThat(ctx.containsBean("defaultMongo")).isTrue();
- MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&defaultMongo");
-
- String host = (String) getField(mfb, "host");
- Integer port = (Integer) getField(mfb, "port");
-
- assertThat(host).isEqualTo("localhost");
- assertThat(port).isEqualTo(new Integer(27017));
-
- MongoClientSettings options = (MongoClientSettings) getField(mfb, "mongoClientSettings");
- assertThat(options).isNull();
- }
-
- @Test // DATAMONGO-764
- public void testMongoSingletonWithSslEnabled() throws Exception {
-
- assertThat(ctx.containsBean("mongoSsl")).isTrue();
- MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoSsl");
-
- MongoClientSettings options = (MongoClientSettings) getField(mfb, "mongoClientSettings");
- assertThat(options.getSslSettings().getContext().getSocketFactory() instanceof SSLSocketFactory)
- .as("socketFactory should be a SSLSocketFactory").isTrue();
- }
-
- @Test // DATAMONGO-1490
- public void testMongoClientSingletonWithSslEnabled() {
-
- assertThat(ctx.containsBean("mongoClientSsl")).isTrue();
- MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoClientSsl");
-
- MongoClientSettings options = (MongoClientSettings) getField(mfb, "mongoClientSettings");
- assertThat(options.getSslSettings().getContext().getSocketFactory() instanceof SSLSocketFactory)
- .as("socketFactory should be a SSLSocketFactory").isTrue();
- }
-
- @Test // DATAMONGO-764
- public void testMongoSingletonWithSslEnabledAndCustomSslSocketFactory() throws Exception {
-
- assertThat(ctx.containsBean("mongoSslWithCustomSslFactory")).isTrue();
- MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoSslWithCustomSslFactory");
-
- MongoClientSettings options = (MongoClientSettings) getField(mfb, "mongoClientSettings");
-
- assertThat(options.getSslSettings().getContext().getSocketFactory() instanceof SSLSocketFactory)
- .as("socketFactory should be a SSLSocketFactory").isTrue();
- assertThat(options.getSslSettings().getContext().getProvider().getName()).isEqualTo("SunJSSE");
- }
-
- @Test
- public void testSecondMongoDbFactory() {
-
- assertThat(ctx.containsBean("secondMongoDbFactory")).isTrue();
- MongoDatabaseFactory dbf = (MongoDatabaseFactory) ctx.getBean("secondMongoDbFactory");
-
- MongoClient mongo = (MongoClient) getField(dbf, "mongoClient");
- assertThat(mongo.getClusterDescription().getClusterSettings().getHosts()).containsExactly(new ServerAddress());
- assertThat(getField(dbf, "databaseName")).isEqualTo("database");
- }
-
- @Test // DATAMONGO-789
- public void testThirdMongoDbFactory() {
-
- assertThat(ctx.containsBean("thirdMongoDbFactory")).isTrue();
-
- MongoDatabaseFactory dbf = (MongoDatabaseFactory) ctx.getBean("thirdMongoDbFactory");
- MongoClient mongo = (MongoClient) getField(dbf, "mongoClient");
-
- assertThat(mongo.getClusterDescription().getClusterSettings().getHosts()).containsExactly(new ServerAddress());
- assertThat(getField(dbf, "databaseName")).isEqualTo("database");
- }
-
- @Test // DATAMONGO-140
- public void testMongoTemplateFactory() {
-
- assertThat(ctx.containsBean("mongoTemplate")).isTrue();
- MongoOperations operations = (MongoOperations) ctx.getBean("mongoTemplate");
-
- MongoDatabaseFactory dbf = (MongoDatabaseFactory) getField(operations, "mongoDbFactory");
- assertThat(getField(dbf, "databaseName")).isEqualTo("database");
-
- MongoConverter converter = (MongoConverter) getField(operations, "mongoConverter");
- assertThat(converter).isNotNull();
- }
-
- @Test // DATAMONGO-140
- public void testSecondMongoTemplateFactory() {
-
- assertThat(ctx.containsBean("anotherMongoTemplate")).isTrue();
- MongoOperations operations = (MongoOperations) ctx.getBean("anotherMongoTemplate");
-
- MongoDatabaseFactory dbf = (MongoDatabaseFactory) getField(operations, "mongoDbFactory");
- assertThat(getField(dbf, "databaseName")).isEqualTo("database");
-
- WriteConcern writeConcern = (WriteConcern) getField(operations, "writeConcern");
- assertThat(writeConcern).isEqualTo(WriteConcern.ACKNOWLEDGED);
- }
-
- @Test // DATAMONGO-628
- public void testGridFsTemplateFactory() {
-
- assertThat(ctx.containsBean("gridFsTemplate")).isTrue();
- GridFsOperations operations = (GridFsOperations) ctx.getBean("gridFsTemplate");
-
- MongoDatabaseFactory dbf = (MongoDatabaseFactory) getField(operations, "dbFactory");
- assertThat(getField(dbf, "databaseName")).isEqualTo("database");
-
- MongoConverter converter = (MongoConverter) getField(operations, "converter");
- assertThat(converter).isNotNull();
- }
-
- @Test // DATAMONGO-628
- public void testSecondGridFsTemplateFactory() {
-
- assertThat(ctx.containsBean("secondGridFsTemplate")).isTrue();
- GridFsOperations operations = (GridFsOperations) ctx.getBean("secondGridFsTemplate");
-
- MongoDatabaseFactory dbf = (MongoDatabaseFactory) getField(operations, "dbFactory");
- assertThat(getField(dbf, "databaseName")).isEqualTo("database");
- assertThat(getField(operations, "bucket")).isEqualTo(null);
-
- MongoConverter converter = (MongoConverter) getField(operations, "converter");
- assertThat(converter).isNotNull();
- }
-
- @Test // DATAMONGO-823
- public void testThirdGridFsTemplateFactory() {
-
- assertThat(ctx.containsBean("thirdGridFsTemplate")).isTrue();
- GridFsOperations operations = (GridFsOperations) ctx.getBean("thirdGridFsTemplate");
-
- MongoDatabaseFactory dbf = (MongoDatabaseFactory) getField(operations, "dbFactory");
- assertThat(getField(dbf, "databaseName")).isEqualTo("database");
- assertThat(getField(operations, "bucket")).isEqualTo("bucketString");
-
- MongoConverter converter = (MongoConverter) getField(operations, "converter");
- assertThat(converter).isNotNull();
- }
-
- @Test
- public void testMongoSingletonWithPropertyPlaceHolders() {
-
- assertThat(ctx.containsBean("mongoClient")).isTrue();
- MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoClient");
-
- String host = (String) getField(mfb, "host");
- Integer port = (Integer) getField(mfb, "port");
-
- assertThat(host).isEqualTo("127.0.0.1");
- assertThat(port).isEqualTo(new Integer(27017));
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoParserIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoParserIntegrationTests.java
deleted file mode 100644
index 4081b7e85c..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoParserIntegrationTests.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2011-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.util.List;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.beans.PropertyValue;
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.support.BeanDefinitionReader;
-import org.springframework.beans.factory.support.DefaultListableBeanFactory;
-import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
-import org.springframework.context.support.AbstractApplicationContext;
-import org.springframework.context.support.GenericApplicationContext;
-import org.springframework.core.io.ClassPathResource;
-
-import com.mongodb.client.MongoClient;
-
-/**
- * Integration tests for {@link MongoClientParser}.
- *
- * @author Oliver Gierke
- */
-public class MongoParserIntegrationTests {
-
- DefaultListableBeanFactory factory;
- BeanDefinitionReader reader;
-
- @BeforeEach
- public void setUp() {
-
- this.factory = new DefaultListableBeanFactory();
- this.reader = new XmlBeanDefinitionReader(factory);
- }
-
- @Test
- @Disabled
- public void readsMongoAttributesCorrectly() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-bean.xml"));
- BeanDefinition definition = factory.getBeanDefinition("mongoClient");
-
- List values = definition.getPropertyValues().getPropertyValueList();
-
- assertThat(values.get(2).getValue()).isInstanceOf(BeanDefinition.class);
- BeanDefinition x = (BeanDefinition) values.get(2).getValue();
-
- assertThat(x.getPropertyValues().getPropertyValueList()).contains(new PropertyValue("writeConcern", "SAFE"));
-
- factory.getBean("mongoClient");
- }
-
- @Test // DATAMONGO-343
- public void readsServerAddressesCorrectly() {
-
- reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-bean.xml"));
-
- AbstractApplicationContext context = new GenericApplicationContext(factory);
- context.refresh();
-
- assertThat(context.getBean("mongo2", MongoClient.class)).isNotNull();
- context.close();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/ReactiveAuditingTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/ReactiveAuditingTests.java
deleted file mode 100644
index 972d5df3f2..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/ReactiveAuditingTests.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright 2018-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.springframework.core.ResolvableType;
-import org.springframework.data.mapping.callback.EntityCallback;
-import org.springframework.data.mongodb.core.mapping.event.AuditingEntityCallback;
-import org.springframework.data.mongodb.core.mapping.event.ReactiveAuditingEntityCallback;
-import org.springframework.test.util.ReflectionTestUtils;
-import reactor.core.publisher.Mono;
-import reactor.test.StepVerifier;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.function.Function;
-
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan.Filter;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.FilterType;
-import org.springframework.data.annotation.Version;
-import org.springframework.data.domain.ReactiveAuditorAware;
-import org.springframework.data.mongodb.core.AuditablePerson;
-import org.springframework.data.mongodb.core.ReactiveMongoOperations;
-import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
-import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
-import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
-import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
-import org.springframework.data.mongodb.test.util.Client;
-import org.springframework.data.mongodb.test.util.MongoClientExtension;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
-
-import com.mongodb.reactivestreams.client.MongoClient;
-
-/**
- * Integration test for the auditing support via {@link org.springframework.data.mongodb.core.ReactiveMongoTemplate}.
- *
- * @author Mark Paluch
- */
-@ExtendWith({ MongoClientExtension.class, SpringExtension.class })
-@ContextConfiguration
-class ReactiveAuditingTests {
-
- static @Client MongoClient mongoClient;
-
- @Autowired ReactiveAuditablePersonRepository auditablePersonRepository;
- @Autowired MongoMappingContext context;
- @Autowired ReactiveMongoOperations operations;
-
- @Configuration
- @EnableReactiveMongoAuditing
- @EnableReactiveMongoRepositories(basePackageClasses = ReactiveAuditingTests.class, considerNestedRepositories = true,
- includeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = ReactiveAuditablePersonRepository.class))
- static class Config extends AbstractReactiveMongoConfiguration {
-
- @Override
- protected String getDatabaseName() {
- return "database";
- }
-
- @Override
- public MongoClient reactiveMongoClient() {
- return mongoClient;
- }
-
- @Override
- protected Set> getInitialEntitySet() {
- return new HashSet<>(
- Arrays.asList(AuditablePerson.class, VersionedAuditablePerson.class, SimpleVersionedAuditablePerson.class));
- }
-
- @Bean
- public ReactiveAuditorAware auditorProvider() {
-
- AuditablePerson person = new AuditablePerson("some-person");
- person.setId("foo");
-
- return () -> Mono.just(person);
- }
- }
-
- @Test // DATAMONGO-2139, DATAMONGO-2150, DATAMONGO-2586
- void auditingWorksForVersionedEntityWithWrapperVersion() {
-
- verifyAuditingViaVersionProperty(new VersionedAuditablePerson(), //
- it -> it.version, //
- AuditablePerson::getCreatedAt, //
- auditablePersonRepository::save, //
- null, 0L, 1L);
- }
-
- @Test // DATAMONGO-2179
- void auditingWorksForVersionedEntityBatchWithWrapperVersion() {
-
- verifyAuditingViaVersionProperty(new VersionedAuditablePerson(), //
- it -> it.version, //
- AuditablePerson::getCreatedAt, //
- s -> auditablePersonRepository.saveAll(Collections.singletonList(s)).next(), //
- null, 0L, 1L);
- }
-
- @Test // DATAMONGO-2139, DATAMONGO-2150, DATAMONGO-2586
- void auditingWorksForVersionedEntityWithSimpleVersion() {
-
- verifyAuditingViaVersionProperty(new SimpleVersionedAuditablePerson(), //
- it -> it.version, //
- AuditablePerson::getCreatedAt, //
- auditablePersonRepository::save, //
- 0L, 1L, 2L);
- }
-
- @Test // DATAMONGO-2139, DATAMONGO-2150, DATAMONGO-2586
- void auditingWorksForVersionedEntityWithWrapperVersionOnTemplate() {
-
- verifyAuditingViaVersionProperty(new VersionedAuditablePerson(), //
- it -> it.version, //
- AuditablePerson::getCreatedAt, //
- operations::save, //
- null, 0L, 1L);
- }
-
- @Test // DATAMONGO-2139, DATAMONGO-2150, DATAMONGO-2586
- void auditingWorksForVersionedEntityWithSimpleVersionOnTemplate() {
- verifyAuditingViaVersionProperty(new SimpleVersionedAuditablePerson(), //
- it -> it.version, //
- AuditablePerson::getCreatedAt, //
- operations::save, //
- 0L, 1L, 2L);
- }
-
- @Test // DATAMONGO-2586
- void auditingShouldOnlyRegisterReactiveAuditingCallback() {
-
- Object callbacks = ReflectionTestUtils.getField(operations, "entityCallbacks");
- Object callbackDiscoverer = ReflectionTestUtils.getField(callbacks, "callbackDiscoverer");
- List> actualCallbacks = ReflectionTestUtils.invokeMethod(callbackDiscoverer, "getEntityCallbacks",
- AuditablePerson.class, ResolvableType.forClass(EntityCallback.class));
-
- assertThat(actualCallbacks) //
- .hasAtLeastOneElementOfType(ReactiveAuditingEntityCallback.class) //
- .doesNotHaveAnyElementsOfTypes(AuditingEntityCallback.class);
- }
-
- private void verifyAuditingViaVersionProperty(T instance,
- Function versionExtractor, Function createdDateExtractor, Function> persister,
- Object... expectedValues) {
-
- AtomicReference instanceHolder = new AtomicReference<>(instance);
- MongoPersistentEntity> entity = context.getRequiredPersistentEntity(instance.getClass());
-
- assertThat(versionExtractor.apply(instance)).isEqualTo(expectedValues[0]);
- assertThat(createdDateExtractor.apply(instance)).isNull();
- assertThat(entity.isNew(instance)).isTrue();
-
- persister.apply(instanceHolder.get()) //
- .as(StepVerifier::create).consumeNextWith(actual -> {
-
- instanceHolder.set(actual);
-
- assertThat(versionExtractor.apply(actual)).isEqualTo(expectedValues[1]);
- assertThat(createdDateExtractor.apply(instance)).isNotNull();
- assertThat(entity.isNew(actual)).isFalse();
- }).verifyComplete();
-
- persister.apply(instanceHolder.get()) //
- .as(StepVerifier::create).consumeNextWith(actual -> {
-
- instanceHolder.set(actual);
-
- assertThat(versionExtractor.apply(actual)).isEqualTo(expectedValues[2]);
- assertThat(entity.isNew(actual)).isFalse();
- }).verifyComplete();
- }
-
- interface ReactiveAuditablePersonRepository extends ReactiveMongoRepository {}
-
- static class VersionedAuditablePerson extends AuditablePerson {
- @Version Long version;
- }
-
- static class SimpleVersionedAuditablePerson extends AuditablePerson {
- @Version long version;
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/ReadPreferencePropertyEditorUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/ReadPreferencePropertyEditorUnitTests.java
deleted file mode 100644
index c8c496fcbb..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/ReadPreferencePropertyEditorUnitTests.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright 2015-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import com.mongodb.ReadPreference;
-
-/**
- * Unit tests for {@link ReadPreferencePropertyEditor}.
- *
- * @author Christoph Strobl
- */
-public class ReadPreferencePropertyEditorUnitTests {
-
- ReadPreferencePropertyEditor editor;
-
- @BeforeEach
- public void setUp() {
- editor = new ReadPreferencePropertyEditor();
- }
-
- @Test // DATAMONGO-1158
- public void shouldThrowExceptionOnUndefinedPreferenceString() {
-
- assertThatIllegalArgumentException().isThrownBy(() -> editor.setAsText("foo")).withMessageContaining("foo")
- .withMessageContaining("ReadPreference");
- }
-
- @Test // DATAMONGO-1158
- public void shouldAllowUsageNativePreferenceStrings() {
-
- editor.setAsText("secondary");
-
- assertThat(editor.getValue()).isEqualTo((Object) ReadPreference.secondary());
- }
-
- @Test // DATAMONGO-1158
- public void shouldAllowUsageOfUppcaseEnumStringsForPreferences() {
-
- editor.setAsText("NEAREST");
-
- assertThat(editor.getValue()).isEqualTo((Object) ReadPreference.nearest());
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/ServerAddressPropertyEditorUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/ServerAddressPropertyEditorUnitTests.java
deleted file mode 100644
index 0206748044..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/ServerAddressPropertyEditorUnitTests.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright 2012-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Arrays;
-import java.util.Collection;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
-
-import com.mongodb.ServerAddress;
-
-/**
- * Unit tests for {@link ServerAddressPropertyEditor}.
- *
- * @author Oliver Gierke
- * @author Thomas Darimont
- */
-public class ServerAddressPropertyEditorUnitTests {
-
- ServerAddressPropertyEditor editor;
-
- @BeforeEach
- public void setUp() {
- editor = new ServerAddressPropertyEditor();
- }
-
- @Test // DATAMONGO-454, DATAMONGO-1062
- public void rejectsAddressConfigWithoutASingleParsableAndResolvableServerAddress() {
-
- String unknownHost1 = "gugu.nonexistant.example.org";
- String unknownHost2 = "gaga.nonexistant.example.org";
-
- assertUnresolveableHostnames(unknownHost1, unknownHost2);
-
- assertThatExceptionOfType(IllegalArgumentException.class)
- .isThrownBy(() -> editor.setAsText(unknownHost1 + "," + unknownHost2));
- }
-
- @Test // DATAMONGO-454
- @EnabledIfSystemProperty(named = "user.name", matches = "jenkins")
- public void skipsUnparsableAddressIfAtLeastOneIsParsable() throws UnknownHostException {
-
- editor.setAsText("foo, localhost");
- assertSingleAddressOfLocalhost(editor.getValue());
- }
-
- @Test // DATAMONGO-454
- public void handlesEmptyAddressAsParseError() throws UnknownHostException {
-
- editor.setAsText(", localhost");
- assertSingleAddressOfLocalhost(editor.getValue());
- }
-
- @Test // DATAMONGO-693
- public void interpretEmptyStringAsNull() {
-
- editor.setAsText("");
- assertThat(editor.getValue()).isNull();
- }
-
- @Test // DATAMONGO-808
- public void handleIPv6HostaddressLoopbackShort() throws UnknownHostException {
-
- String hostAddress = "::1";
- editor.setAsText(hostAddress);
-
- assertSingleAddressWithPort(hostAddress, null, editor.getValue());
- }
-
- @Test // DATAMONGO-808
- public void handleIPv6HostaddressLoopbackShortWithPort() throws UnknownHostException {
-
- String hostAddress = "::1";
- int port = 27017;
- editor.setAsText(hostAddress + ":" + port);
-
- assertSingleAddressWithPort(hostAddress, port, editor.getValue());
- }
-
- /**
- * Here we detect no port since the last segment of the address contains leading zeros.
- */
- @Test // DATAMONGO-808
- public void handleIPv6HostaddressLoopbackLong() throws UnknownHostException {
-
- String hostAddress = "0000:0000:0000:0000:0000:0000:0000:0001";
- editor.setAsText(hostAddress);
-
- assertSingleAddressWithPort(hostAddress, null, editor.getValue());
- }
-
- @Test // DATAMONGO-808
- public void handleIPv6HostaddressLoopbackLongWithBrackets() throws UnknownHostException {
-
- String hostAddress = "[0000:0000:0000:0000:0000:0000:0000:0001]";
- editor.setAsText(hostAddress);
-
- assertSingleAddressWithPort(hostAddress, null, editor.getValue());
- }
-
- /**
- * We can't tell whether the last part of the hostAddress represents a port or not.
- */
- @Test // DATAMONGO-808
- public void shouldFailToHandleAmbiguousIPv6HostaddressLongWithoutPortAndWithoutBrackets() {
-
- String hostAddress = "0000:0000:0000:0000:0000:0000:0000:128";
-
- assertThatIllegalArgumentException().isThrownBy(() -> editor.setAsText(hostAddress));
- }
-
- @Test // DATAMONGO-808
- public void handleIPv6HostaddressExampleAddressWithPort() throws UnknownHostException {
-
- String hostAddress = "0000:0000:0000:0000:0000:0000:0000:0001";
- int port = 27017;
- editor.setAsText(hostAddress + ":" + port);
-
- assertSingleAddressWithPort(hostAddress, port, editor.getValue());
- }
-
- @Test // DATAMONGO-808
- public void handleIPv6HostaddressExampleAddressInBracketsWithPort() throws UnknownHostException {
-
- String hostAddress = "[0000:0000:0000:0000:0000:0000:0000:0001]";
- int port = 27017;
- editor.setAsText(hostAddress + ":" + port);
-
- assertSingleAddressWithPort(hostAddress, port, editor.getValue());
- }
-
- private static void assertSingleAddressOfLocalhost(Object result) throws UnknownHostException {
- assertSingleAddressWithPort("localhost", null, result);
- }
-
- private static void assertSingleAddressWithPort(String hostAddress, Integer port, Object result)
- throws UnknownHostException {
-
- assertThat(result).isInstanceOf(ServerAddress[].class);
- Collection addresses = Arrays.asList((ServerAddress[]) result);
- assertThat(addresses).hasSize(1);
- if (port == null) {
- assertThat(addresses).contains(new ServerAddress(InetAddress.getByName(hostAddress)));
- } else {
- assertThat(addresses).contains(new ServerAddress(InetAddress.getByName(hostAddress), port));
- }
- }
-
- private void assertUnresolveableHostnames(String... hostnames) {
-
- for (String hostname : hostnames) {
- try {
- InetAddress.getByName(hostname).isReachable(1500);
- fail("Supposedly unresolveable hostname '" + hostname + "' can be resolved.");
- } catch (IOException expected) {
- // ok
- }
- }
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/StringToWriteConcernConverterUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/StringToWriteConcernConverterUnitTests.java
deleted file mode 100644
index a63bd1aa3c..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/StringToWriteConcernConverterUnitTests.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2012-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.jupiter.api.Test;
-
-import com.mongodb.WriteConcern;
-
-/**
- * Unit tests for {@link StringToWriteConcernConverter}.
- *
- * @author Oliver Gierke
- * @author Christoph Strobl
- */
-public class StringToWriteConcernConverterUnitTests {
-
- StringToWriteConcernConverter converter = new StringToWriteConcernConverter();
-
- @Test // DATAMONGO-2199
- public void createsWellKnownConstantsCorrectly() {
- assertThat(converter.convert("ACKNOWLEDGED")).isEqualTo(WriteConcern.ACKNOWLEDGED);
- }
-
- @Test
- public void createsWriteConcernForUnknownValue() {
- assertThat(converter.convert("-1")).isEqualTo(new WriteConcern("-1"));
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/WriteConcernPropertyEditorUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/WriteConcernPropertyEditorUnitTests.java
deleted file mode 100644
index ae2dcd59ab..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/WriteConcernPropertyEditorUnitTests.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright 2012-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.config;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import com.mongodb.WriteConcern;
-
-/**
- * Unit tests for {@link WriteConcernPropertyEditor}.
- *
- * @author Oliver Gierke
- * @author Christoph Strobl
- */
-public class WriteConcernPropertyEditorUnitTests {
-
- WriteConcernPropertyEditor editor;
-
- @BeforeEach
- public void setUp() {
- editor = new WriteConcernPropertyEditor();
- }
-
- @Test // DATAMONGO-2199
- public void createsWriteConcernForWellKnownConstants() {
-
- editor.setAsText("JOURNALED");
- assertThat(editor.getValue()).isEqualTo(WriteConcern.JOURNALED);
- }
-
- @Test
- public void createsWriteConcernForUnknownConstants() {
-
- editor.setAsText("-1");
- assertThat(editor.getValue()).isEqualTo(new WriteConcern("-1"));
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/AuditablePerson.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/AuditablePerson.java
deleted file mode 100644
index 07982c295d..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/AuditablePerson.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright 2013-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import java.util.Date;
-
-import org.springframework.data.annotation.CreatedBy;
-import org.springframework.data.annotation.CreatedDate;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.mongodb.core.mapping.DBRef;
-
-/**
- * Domain class for auditing functionality testing.
- *
- * @author Thomas Darimont
- */
-public class AuditablePerson {
-
- private @Id String id;
- private String firstname;
- private @DBRef @CreatedBy AuditablePerson createdBy;
- private @CreatedDate Date createdAt;
-
- public AuditablePerson() {}
-
- public AuditablePerson(String firstName) {
- this.firstname = firstName;
- }
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public String getFirstname() {
- return firstname;
- }
-
- public void setFirstname(String firstName) {
- this.firstname = firstName;
- }
-
- public AuditablePerson getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(AuditablePerson createdBy) {
- this.createdBy = createdBy;
- }
-
- public Date getCreatedAt() {
- return createdAt;
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/BaseDoc.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/BaseDoc.java
deleted file mode 100644
index 8bd671b740..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/BaseDoc.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package org.springframework.data.mongodb.core;
-
-import org.springframework.data.annotation.Id;
-
-public class BaseDoc {
- @Id String id;
- String value;
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ChangeStreamOptionsUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ChangeStreamOptionsUnitTests.java
deleted file mode 100644
index 7c09583a38..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ChangeStreamOptionsUnitTests.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.bson.BsonDocument;
-import org.junit.jupiter.api.Test;
-
-/**
- * Unit tests for {@link ChangeStreamOptions}.
- *
- * @author Mark Paluch
- */
-public class ChangeStreamOptionsUnitTests {
-
- @Test // DATAMONGO-2258
- public void shouldReportResumeAfter() {
-
- ChangeStreamOptions options = ChangeStreamOptions.builder().resumeAfter(new BsonDocument()).build();
-
- assertThat(options.isResumeAfter()).isTrue();
- assertThat(options.isStartAfter()).isFalse();
- }
-
- @Test // DATAMONGO-2258
- public void shouldReportStartAfter() {
-
- ChangeStreamOptions options = ChangeStreamOptions.builder().startAfter(new BsonDocument()).build();
-
- assertThat(options.isResumeAfter()).isFalse();
- assertThat(options.isStartAfter()).isTrue();
- }
-
- @Test // DATAMONGO-2258
- public void shouldNotReportResumeStartAfter() {
-
- ChangeStreamOptions options = ChangeStreamOptions.empty();
-
- assertThat(options.isResumeAfter()).isFalse();
- assertThat(options.isStartAfter()).isFalse();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ClientSessionTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ClientSessionTests.java
deleted file mode 100644
index 01bd934ef3..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ClientSessionTests.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright 2018-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-import static org.springframework.data.mongodb.core.query.Query.*;
-
-import lombok.AllArgsConstructor;
-import lombok.Data;
-
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
-import org.springframework.data.mongodb.core.mapping.DBRef;
-import org.springframework.data.mongodb.core.query.Query;
-import org.springframework.data.mongodb.test.util.EnableIfMongoServerVersion;
-import org.springframework.data.mongodb.test.util.EnableIfReplicaSetAvailable;
-import org.springframework.data.mongodb.test.util.MongoClientExtension;
-import org.springframework.data.mongodb.test.util.MongoTestUtils;
-import org.springframework.data.mongodb.test.util.ReplSetClient;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import com.mongodb.ClientSessionOptions;
-import com.mongodb.client.ClientSession;
-import com.mongodb.client.MongoClient;
-
-/**
- * Integration tests for {@link ClientSession} through {@link MongoTemplate#withSession(ClientSession)}.
- *
- * @author Christoph Strobl
- * @author Mark Paluch
- */
-@ExtendWith({ MongoClientExtension.class })
-@EnableIfReplicaSetAvailable
-@EnableIfMongoServerVersion(isGreaterThanEqual = "4.0")
-class ClientSessionTests {
-
- private static final String DB_NAME = "client-session-tests";
- private static final String COLLECTION_NAME = "test";
- private static final String REF_COLLECTION_NAME = "test-with-ref";
-
- private static @ReplSetClient MongoClient mongoClient;
-
- private MongoTemplate template;
-
- @BeforeEach
- void setUp() {
-
- MongoTestUtils.createOrReplaceCollection(DB_NAME, COLLECTION_NAME, mongoClient);
-
- template = new MongoTemplate(mongoClient, DB_NAME);
- template.getDb().getCollection(COLLECTION_NAME).insertOne(new Document("_id", "id-1").append("value", "spring"));
- }
-
- @Test // DATAMONGO-1880
- void shouldApplyClientSession() {
-
- ClientSession session = mongoClient.startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
-
- assertThat(session.getOperationTime()).isNull();
-
- Document doc = template.withSession(() -> session)
- .execute(action -> action.findOne(new Query(), Document.class, "test"));
-
- assertThat(doc).isNotNull();
- assertThat(session.getOperationTime()).isNotNull();
- assertThat(session.getServerSession().isClosed()).isFalse();
-
- session.close();
- }
-
- @Test // DATAMONGO-2241
- void shouldReuseConfiguredInfrastructure() {
-
- ClientSession session = mongoClient.startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
-
- MappingMongoConverter source = MappingMongoConverter.class.cast(template.getConverter());
- MappingMongoConverter sessionTemplateConverter = MappingMongoConverter.class
- .cast(template.withSession(() -> session).execute(MongoOperations::getConverter));
-
- assertThat(sessionTemplateConverter.getMappingContext()).isSameAs(source.getMappingContext());
- assertThat(ReflectionTestUtils.getField(sessionTemplateConverter, "conversions"))
- .isSameAs(ReflectionTestUtils.getField(source, "conversions"));
- assertThat(ReflectionTestUtils.getField(sessionTemplateConverter, "instantiators"))
- .isSameAs(ReflectionTestUtils.getField(source, "instantiators"));
- }
-
- @Test // DATAMONGO-1920
- void withCommittedTransaction() {
-
- ClientSession session = mongoClient.startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
-
- assertThat(session.getOperationTime()).isNull();
-
- session.startTransaction();
-
- SomeDoc saved = template.withSession(() -> session).execute(action -> {
-
- SomeDoc doc = new SomeDoc("id-2", "value2");
- action.insert(doc);
- return doc;
- });
-
- session.commitTransaction();
- session.close();
-
- assertThat(saved).isNotNull();
- assertThat(session.getOperationTime()).isNotNull();
-
- assertThat(template.exists(query(where("id").is(saved.getId())), SomeDoc.class)).isTrue();
- }
-
- @Test // DATAMONGO-1920
- void withAbortedTransaction() {
-
- ClientSession session = mongoClient.startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
-
- assertThat(session.getOperationTime()).isNull();
-
- session.startTransaction();
-
- SomeDoc saved = template.withSession(() -> session).execute(action -> {
-
- SomeDoc doc = new SomeDoc("id-2", "value2");
- action.insert(doc);
- return doc;
- });
-
- session.abortTransaction();
- session.close();
-
- assertThat(saved).isNotNull();
- assertThat(session.getOperationTime()).isNotNull();
-
- assertThat(template.exists(query(where("id").is(saved.getId())), SomeDoc.class)).isFalse();
- }
-
- @Test // DATAMONGO-2490
- void shouldBeAbleToReadDbRefDuringTransaction() {
-
- SomeDoc ref = new SomeDoc("ref-1", "da value");
- WithDbRef source = new WithDbRef("source-1", "da source", ref);
-
- ClientSession session = mongoClient.startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
-
- assertThat(session.getOperationTime()).isNull();
-
- session.startTransaction();
-
- WithDbRef saved = template.withSession(() -> session).execute(action -> {
-
- template.save(ref);
- template.save(source);
-
- return template.findOne(query(where("id").is(source.id)), WithDbRef.class);
- });
-
- assertThat(saved.getSomeDocRef()).isEqualTo(ref);
-
- session.abortTransaction();
- }
-
- @Data
- @AllArgsConstructor
- @org.springframework.data.mongodb.core.mapping.Document(COLLECTION_NAME)
- static class SomeDoc {
-
- @Id String id;
- String value;
- }
-
- @Data
- @AllArgsConstructor
- @org.springframework.data.mongodb.core.mapping.Document(REF_COLLECTION_NAME)
- static class WithDbRef {
-
- @Id String id;
- String value;
- @DBRef SomeDoc someDocRef;
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/CloseableIterableCursorAdapterUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/CloseableIterableCursorAdapterUnitTests.java
deleted file mode 100644
index 4d5f762f55..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/CloseableIterableCursorAdapterUnitTests.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright 2015-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.dao.support.PersistenceExceptionTranslator;
-import org.springframework.data.mongodb.core.MongoTemplate.CloseableIterableCursorAdapter;
-import org.springframework.data.mongodb.core.MongoTemplate.DocumentCallback;
-import org.springframework.data.util.CloseableIterator;
-
-import com.mongodb.client.MongoCursor;
-
-/**
- * Unit tests for {@link CloseableIterableCursorAdapter}.
- *
- * @author Oliver Gierke
- */
-@ExtendWith(MockitoExtension.class)
-class CloseableIterableCursorAdapterUnitTests {
-
- @Mock PersistenceExceptionTranslator exceptionTranslator;
- @Mock DocumentCallback callback;
-
- private MongoCursor cursor;
- private CloseableIterator adapter;
-
- @BeforeEach
- void setUp() {
- this.cursor = mock(MongoCursor.class);
- this.adapter = new CloseableIterableCursorAdapter<>(cursor, exceptionTranslator, callback);
- }
-
- @Test // DATAMONGO-1276
- void propagatesOriginalExceptionFromAdapterDotNext() {
-
- doThrow(IllegalArgumentException.class).when(cursor).next();
- assertThatIllegalArgumentException().isThrownBy(() -> adapter.next());
- }
-
- @Test // DATAMONGO-1276
- void propagatesOriginalExceptionFromAdapterDotHasNext() {
-
- doThrow(IllegalArgumentException.class).when(cursor).hasNext();
- assertThatIllegalArgumentException().isThrownBy(() -> adapter.hasNext());
- }
-
- @Test // DATAMONGO-1276
- void propagatesOriginalExceptionFromAdapterDotClose() {
-
- doThrow(IllegalArgumentException.class).when(cursor).close();
- assertThatIllegalArgumentException().isThrownBy(() -> adapter.close());
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/CollationUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/CollationUnitTests.java
deleted file mode 100644
index 499c17cf37..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/CollationUnitTests.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Copyright 2017-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.util.Locale;
-
-import org.bson.Document;
-import org.junit.jupiter.api.Test;
-import org.springframework.data.mongodb.core.query.Collation;
-import org.springframework.data.mongodb.core.query.Collation.Alternate;
-import org.springframework.data.mongodb.core.query.Collation.CaseFirst;
-import org.springframework.data.mongodb.core.query.Collation.CollationLocale;
-import org.springframework.data.mongodb.core.query.Collation.ComparisonLevel;
-
-/**
- * @author Christoph Strobl
- * @author Mark Paluch
- */
-public class CollationUnitTests {
-
- static final Document BINARY_COMPARISON = new Document().append("locale", "simple");
- static final Document JUST_LOCALE = new Document().append("locale", "en_US");
- static final Document LOCALE_WITH_VARIANT = new Document().append("locale", "de_AT@collation=phonebook");
- static final Document WITH_STRENGTH_PRIMARY = new Document(JUST_LOCALE).append("strength", 1);
- static final Document WITH_STRENGTH_PRIMARY_INCLUDE_CASE = new Document(WITH_STRENGTH_PRIMARY).append("caseLevel",
- true);
- static final Document WITH_NORMALIZATION = new Document(JUST_LOCALE).append("normalization", true);
- static final Document WITH_BACKWARDS = new Document(JUST_LOCALE).append("backwards", true);
- static final Document WITH_NUMERIC_ORDERING = new Document(JUST_LOCALE).append("numericOrdering", true);
- static final Document WITH_CASE_FIRST_UPPER = new Document(JUST_LOCALE).append("strength", 3).append("caseFirst",
- "upper");
- static final Document WITH_ALTERNATE_SHIFTED = new Document(JUST_LOCALE).append("alternate", "shifted");
- static final Document WITH_ALTERNATE_SHIFTED_MAX_VARIABLE_PUNCT = new Document(WITH_ALTERNATE_SHIFTED)
- .append("maxVariable", "punct");
- static final Document ALL_THE_THINGS = new Document(LOCALE_WITH_VARIANT).append("strength", 1)
- .append("caseLevel", true).append("backwards", true).append("numericOrdering", true)
- .append("alternate", "shifted").append("maxVariable", "punct").append("normalization", true);
-
- @Test // DATAMONGO-1518
- public void justLocale() {
- assertThat(Collation.of("en_US").toDocument()).isEqualTo(JUST_LOCALE);
- }
-
- @Test // DATAMONGO-1518
- public void justLocaleFromDocument() {
- assertThat(Collation.from(JUST_LOCALE).toDocument()).isEqualTo(JUST_LOCALE);
- }
-
- @Test // DATAMONGO-1518
- public void localeWithVariant() {
- assertThat(Collation.of(CollationLocale.of("de_AT").variant("phonebook")).toDocument())
- .isEqualTo(LOCALE_WITH_VARIANT);
- }
-
- @Test // DATAMONGO-1518
- public void localeWithVariantFromDocument() {
- assertThat(Collation.from(LOCALE_WITH_VARIANT).toDocument()).isEqualTo(LOCALE_WITH_VARIANT);
- }
-
- @Test // DATAMONGO-1518
- public void localeFromJavaUtilLocale() {
-
- assertThat(Collation.of(java.util.Locale.US).toDocument()).isEqualTo(new Document().append("locale", "en_US"));
- assertThat(Collation.of(Locale.ENGLISH).toDocument()).isEqualTo(new Document().append("locale", "en"));
- }
-
- @Test // DATAMONGO-1518
- public void withStrenghPrimary() {
- assertThat(Collation.of("en_US").strength(ComparisonLevel.primary()).toDocument()).isEqualTo(WITH_STRENGTH_PRIMARY);
- }
-
- @Test // DATAMONGO-1518
- public void withStrenghPrimaryFromDocument() {
- assertThat(Collation.from(WITH_STRENGTH_PRIMARY).toDocument()).isEqualTo(WITH_STRENGTH_PRIMARY);
- }
-
- @Test // DATAMONGO-1518
- public void withStrenghPrimaryAndIncludeCase() {
-
- assertThat(Collation.of("en_US").strength(ComparisonLevel.primary().includeCase()).toDocument())
- .isEqualTo(WITH_STRENGTH_PRIMARY_INCLUDE_CASE);
- }
-
- @Test // DATAMONGO-1518
- public void withStrenghPrimaryAndIncludeCaseFromDocument() {
-
- assertThat(Collation.from(WITH_STRENGTH_PRIMARY_INCLUDE_CASE).toDocument())
- .isEqualTo(WITH_STRENGTH_PRIMARY_INCLUDE_CASE);
- }
-
- @Test // DATAMONGO-1518
- public void withNormalization() {
- assertThat(Collation.of("en_US").normalization(true).toDocument()).isEqualTo(WITH_NORMALIZATION);
- }
-
- @Test // DATAMONGO-1518
- public void withNormalizationFromDocument() {
- assertThat(Collation.from(WITH_NORMALIZATION).toDocument()).isEqualTo(WITH_NORMALIZATION);
- }
-
- @Test // DATAMONGO-1518
- public void withBackwards() {
- assertThat(Collation.of("en_US").backwards(true).toDocument()).isEqualTo(WITH_BACKWARDS);
- }
-
- @Test // DATAMONGO-1518
- public void withBackwardsFromDocument() {
- assertThat(Collation.from(WITH_BACKWARDS).toDocument()).isEqualTo(WITH_BACKWARDS);
- }
-
- @Test // DATAMONGO-1518
- public void withNumericOrdering() {
- assertThat(Collation.of("en_US").numericOrdering(true).toDocument()).isEqualTo(WITH_NUMERIC_ORDERING);
- }
-
- @Test // DATAMONGO-1518
- public void withNumericOrderingFromDocument() {
- assertThat(Collation.from(WITH_NUMERIC_ORDERING).toDocument()).isEqualTo(WITH_NUMERIC_ORDERING);
- }
-
- @Test // DATAMONGO-1518
- public void withCaseFirst() {
- assertThat(Collation.of("en_US").caseFirst(CaseFirst.upper()).toDocument()).isEqualTo(WITH_CASE_FIRST_UPPER);
- }
-
- @Test // DATAMONGO-1518
- public void withCaseFirstFromDocument() {
- assertThat(Collation.from(WITH_CASE_FIRST_UPPER).toDocument()).isEqualTo(WITH_CASE_FIRST_UPPER);
- }
-
- @Test // DATAMONGO-1518
- public void withAlternate() {
- assertThat(Collation.of("en_US").alternate(Alternate.shifted()).toDocument()).isEqualTo(WITH_ALTERNATE_SHIFTED);
- }
-
- @Test // DATAMONGO-1518
- public void withAlternateFromDocument() {
- assertThat(Collation.from(WITH_ALTERNATE_SHIFTED).toDocument()).isEqualTo(WITH_ALTERNATE_SHIFTED);
- }
-
- @Test // DATAMONGO-1518
- public void withAlternateAndMaxVariable() {
-
- assertThat(Collation.of("en_US").alternate(Alternate.shifted().punct()).toDocument())
- .isEqualTo(WITH_ALTERNATE_SHIFTED_MAX_VARIABLE_PUNCT);
- }
-
- @Test // DATAMONGO-1518
- public void withAlternateAndMaxVariableFromDocument() {
-
- assertThat(Collation.from(WITH_ALTERNATE_SHIFTED_MAX_VARIABLE_PUNCT).toDocument())
- .isEqualTo(WITH_ALTERNATE_SHIFTED_MAX_VARIABLE_PUNCT);
- }
-
- @Test // DATAMONGO-1518
- public void allTheThings() {
-
- assertThat(Collation.of(CollationLocale.of("de_AT").variant("phonebook"))
- .strength(ComparisonLevel.primary().includeCase()).normalizationEnabled().backwardDiacriticSort()
- .numericOrderingEnabled().alternate(Alternate.shifted().punct()).toDocument()).isEqualTo(ALL_THE_THINGS);
- }
-
- @Test // DATAMONGO-1518
- public void allTheThingsFromDocument() {
- assertThat(Collation.from(ALL_THE_THINGS).toDocument()).isEqualTo(ALL_THE_THINGS);
- }
-
- @Test // DATAMONGO-1518
- public void justTheDefault() {
- assertThat(Collation.simple().toDocument()).isEqualTo(BINARY_COMPARISON);
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/CountQueryUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/CountQueryUnitTests.java
deleted file mode 100644
index 4b5ed6f2a8..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/CountQueryUnitTests.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.mockito.Mockito.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-import static org.springframework.data.mongodb.core.query.Query.*;
-import static org.springframework.data.mongodb.test.util.Assertions.*;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.data.geo.Point;
-import org.springframework.data.mongodb.MongoDatabaseFactory;
-import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
-import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
-import org.springframework.data.mongodb.core.convert.QueryMapper;
-import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
-import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
-import org.springframework.data.mongodb.core.query.Criteria;
-import org.springframework.data.mongodb.core.query.Query;
-
-/**
- * Unit tests for {@link CountQuery}.
- *
- * @author Mark Paluch
- * @author Christoph Strobl
- */
-public class CountQueryUnitTests {
-
- QueryMapper mapper;
- MongoMappingContext context;
- MappingMongoConverter converter;
-
- MongoDatabaseFactory factory = mock(MongoDatabaseFactory.class);
-
- @BeforeEach
- public void setUp() {
-
- this.context = new MongoMappingContext();
-
- this.converter = new MappingMongoConverter(new DefaultDbRefResolver(factory), context);
- this.converter.afterPropertiesSet();
-
- this.mapper = new QueryMapper(converter);
- }
-
- @Test // DATAMONGO-2059
- public void nearToGeoWithinWithoutDistance() {
-
- Query source = query(where("location").near(new Point(-73.99171, 40.738868)));
- org.bson.Document target = postProcessQueryForCount(source);
-
- assertThat(target).isEqualTo(org.bson.Document
- .parse("{\"location\": {\"$geoWithin\": {\"$center\": [[-73.99171, 40.738868], 1.7976931348623157E308]}}}"));
- }
-
- @Test // DATAMONGO-2059
- public void nearAndExisting$and() {
-
- Query source = query(where("location").near(new Point(-73.99171, 40.738868)).minDistance(0.01))
- .addCriteria(new Criteria().andOperator(where("foo").is("bar")));
- org.bson.Document target = postProcessQueryForCount(source);
-
- assertThat(target).isEqualTo(org.bson.Document.parse("{\"$and\":[" //
- + "{\"foo\":\"bar\"}" //
- + "{\"$nor\":[{\"location\":{\"$geoWithin\":{\"$center\":[ [ -73.99171, 40.738868 ], 0.01]}}}]},"//
- + " {\"location\":{\"$geoWithin\":{\"$center\":[ [ -73.99171, 40.738868 ], 1.7976931348623157E308]}}},"//
- + "]}"));
- }
-
- @Test // DATAMONGO-2059
- public void nearSphereToGeoWithinWithoutDistance() {
-
- Query source = query(where("location").nearSphere(new Point(-73.99171, 40.738868)));
- org.bson.Document target = postProcessQueryForCount(source);
-
- assertThat(target).isEqualTo(org.bson.Document.parse(
- "{\"location\": {\"$geoWithin\": {\"$centerSphere\": [[-73.99171, 40.738868], 1.7976931348623157E308]}}}"));
- }
-
- @Test // DATAMONGO-2059
- public void nearToGeoWithinWithMaxDistance() {
-
- Query source = query(where("location").near(new Point(-73.99171, 40.738868)).maxDistance(10));
- org.bson.Document target = postProcessQueryForCount(source);
-
- assertThat(target).isEqualTo(
- org.bson.Document.parse("{\"location\": {\"$geoWithin\": {\"$center\": [[-73.99171, 40.738868], 10.0]}}}"));
- }
-
- @Test // DATAMONGO-2059
- public void nearSphereToGeoWithinWithMaxDistance() {
-
- Query source = query(where("location").nearSphere(new Point(-73.99171, 40.738868)).maxDistance(10));
- org.bson.Document target = postProcessQueryForCount(source);
-
- assertThat(target).isEqualTo(org.bson.Document
- .parse("{\"location\": {\"$geoWithin\": {\"$centerSphere\": [[-73.99171, 40.738868], 10.0]}}}"));
- }
-
- @Test // DATAMONGO-2059
- public void nearToGeoWithinWithMinDistance() {
-
- Query source = query(where("location").near(new Point(-73.99171, 40.738868)).minDistance(0.01));
- org.bson.Document target = postProcessQueryForCount(source);
-
- assertThat(target).isEqualTo(org.bson.Document.parse(
- "{\"$and\":[{\"$nor\":[{\"location\":{\"$geoWithin\":{\"$center\":[ [ -73.99171, 40.738868 ], 0.01]}}}]},"
- + " {\"location\":{\"$geoWithin\":{\"$center\":[ [ -73.99171, 40.738868 ], 1.7976931348623157E308]}}}]}"));
- }
-
- @Test // DATAMONGO-2059
- public void nearToGeoWithinWithMaxDistanceAndCombinedWithOtherCriteria() {
-
- Query source = query(
- where("name").is("food").and("location").near(new Point(-73.99171, 40.738868)).maxDistance(10));
- org.bson.Document target = postProcessQueryForCount(source);
-
- assertThat(target).isEqualTo(org.bson.Document
- .parse("{\"name\": \"food\", \"location\": {\"$geoWithin\": {\"$center\": [[-73.99171, 40.738868], 10.0]}}}"));
- }
-
- @Test // DATAMONGO-2059
- public void nearToGeoWithinWithMinDistanceOrCombinedWithOtherCriteria() {
-
- Query source = query(new Criteria().orOperator(where("name").is("food"),
- where("location").near(new Point(-73.99171, 40.738868)).minDistance(0.01)));
- org.bson.Document target = postProcessQueryForCount(source);
-
- assertThat(target).isEqualTo(org.bson.Document.parse(
- "{\"$or\" : [ { \"name\": \"food\" }, {\"$and\":[{\"$nor\":[{\"location\":{\"$geoWithin\":{\"$center\":[ [ -73.99171, 40.738868 ], 0.01]}}}]},{\"location\":{\"$geoWithin\":{\"$center\":[ [ -73.99171, 40.738868 ], 1.7976931348623157E308]}}}]} ]}"));
- }
-
- @Test // DATAMONGO-2059
- public void nearToGeoWithinWithMaxDistanceOrCombinedWithOtherCriteria() {
-
- Query source = query(new Criteria().orOperator(where("name").is("food"),
- where("location").near(new Point(-73.99171, 40.738868)).maxDistance(10)));
- org.bson.Document target = postProcessQueryForCount(source);
-
- assertThat(target).isEqualTo(org.bson.Document.parse(
- "{\"$or\" : [ { \"name\": \"food\" }, {\"location\": {\"$geoWithin\": {\"$center\": [[-73.99171, 40.738868], 10.0]}}} ]}"));
- }
-
- private org.bson.Document postProcessQueryForCount(Query source) {
-
- org.bson.Document intermediate = mapper.getMappedObject(source.getQueryObject(), (MongoPersistentEntity>) null);
- return CountQuery.of(intermediate).toQueryDocument();
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultBulkOperationsIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultBulkOperationsIntegrationTests.java
deleted file mode 100644
index d194c12493..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultBulkOperationsIntegrationTests.java
+++ /dev/null
@@ -1,386 +0,0 @@
-/*
- * Copyright 2015-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.dao.DuplicateKeyException;
-import org.springframework.data.mongodb.BulkOperationException;
-import org.springframework.data.mongodb.core.BulkOperations.BulkMode;
-import org.springframework.data.mongodb.core.DefaultBulkOperations.BulkOperationContext;
-import org.springframework.data.mongodb.core.convert.QueryMapper;
-import org.springframework.data.mongodb.core.convert.UpdateMapper;
-import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
-import org.springframework.data.mongodb.core.query.Criteria;
-import org.springframework.data.mongodb.core.query.Query;
-import org.springframework.data.mongodb.core.query.Update;
-import org.springframework.data.mongodb.test.util.MongoTemplateExtension;
-import org.springframework.data.mongodb.test.util.MongoTestTemplate;
-import org.springframework.data.mongodb.test.util.Template;
-import org.springframework.data.util.Pair;
-
-import com.mongodb.MongoBulkWriteException;
-import com.mongodb.WriteConcern;
-import com.mongodb.client.MongoCollection;
-
-/**
- * Integration tests for {@link DefaultBulkOperations}.
- *
- * @author Tobias Trelle
- * @author Oliver Gierke
- * @author Christoph Strobl
- * @author Minsu Kim
- */
-@ExtendWith(MongoTemplateExtension.class)
-public class DefaultBulkOperationsIntegrationTests {
-
- static final String COLLECTION_NAME = "bulk_ops";
-
- @Template(initialEntitySet = BaseDoc.class) //
- static MongoTestTemplate operations;
-
- @BeforeEach
- public void setUp() {
- operations.flush(COLLECTION_NAME);
- }
-
- @Test // DATAMONGO-934
- public void rejectsNullMongoOperations() {
- assertThatIllegalArgumentException().isThrownBy(() -> new DefaultBulkOperations(null, COLLECTION_NAME,
- new BulkOperationContext(BulkMode.ORDERED, Optional.empty(), null, null, null, null)));
- }
-
- @Test // DATAMONGO-934
- public void rejectsNullCollectionName() {
- assertThatIllegalArgumentException().isThrownBy(() -> new DefaultBulkOperations(operations, null,
- new BulkOperationContext(BulkMode.ORDERED, Optional.empty(), null, null, null, null)));
- }
-
- @Test // DATAMONGO-934
- public void rejectsEmptyCollectionName() {
- assertThatIllegalArgumentException().isThrownBy(() -> new DefaultBulkOperations(operations, "",
- new BulkOperationContext(BulkMode.ORDERED, Optional.empty(), null, null, null, null)));
- }
-
- @Test // DATAMONGO-934
- public void insertOrdered() {
-
- List documents = Arrays.asList(newDoc("1"), newDoc("2"));
-
- assertThat(createBulkOps(BulkMode.ORDERED).insert(documents).execute().getInsertedCount()).isEqualTo(2);
- }
-
- @Test // DATAMONGO-934, DATAMONGO-2285
- public void insertOrderedFails() {
-
- List documents = Arrays.asList(newDoc("1"), newDoc("1"), newDoc("2"));
-
- assertThatThrownBy(() -> createBulkOps(BulkMode.ORDERED).insert(documents).execute()) //
- .isInstanceOf(BulkOperationException.class) //
- .hasCauseInstanceOf(MongoBulkWriteException.class) //
- .extracting(Throwable::getCause) //
- .satisfies(it -> {
-
- MongoBulkWriteException ex = (MongoBulkWriteException) it;
- assertThat(ex.getWriteResult().getInsertedCount()).isOne();
- assertThat(ex.getWriteErrors()).isNotNull();
- assertThat(ex.getWriteErrors().size()).isOne();
- });
- }
-
- @Test // DATAMONGO-934
- public void insertUnOrdered() {
-
- List documents = Arrays.asList(newDoc("1"), newDoc("2"));
-
- assertThat(createBulkOps(BulkMode.UNORDERED).insert(documents).execute().getInsertedCount()).isEqualTo(2);
- }
-
- @Test // DATAMONGO-934, DATAMONGO-2285
- public void insertUnOrderedContinuesOnError() {
-
- List documents = Arrays.asList(newDoc("1"), newDoc("1"), newDoc("2"));
-
- assertThatThrownBy(() -> createBulkOps(BulkMode.UNORDERED).insert(documents).execute()) //
- .isInstanceOf(BulkOperationException.class) //
- .hasCauseInstanceOf(MongoBulkWriteException.class) //
- .extracting(Throwable::getCause) //
- .satisfies(it -> {
-
- MongoBulkWriteException ex = (MongoBulkWriteException) it;
- assertThat(ex.getWriteResult().getInsertedCount()).isEqualTo(2);
- assertThat(ex.getWriteErrors()).isNotNull();
- assertThat(ex.getWriteErrors().size()).isOne();
- });
- }
-
- @Test // DATAMONGO-934
- public void upsertDoesUpdate() {
-
- insertSomeDocuments();
-
- com.mongodb.bulk.BulkWriteResult result = createBulkOps(BulkMode.ORDERED).//
- upsert(where("value", "value1"), set("value", "value2")).//
- execute();
-
- assertThat(result).isNotNull();
- assertThat(result.getMatchedCount()).isEqualTo(2);
- assertThat(result.getModifiedCount()).isEqualTo(2);
- assertThat(result.getInsertedCount()).isZero();
- assertThat(result.getUpserts()).isNotNull();
- assertThat(result.getUpserts().size()).isZero();
- }
-
- @Test // DATAMONGO-934
- public void upsertDoesInsert() {
-
- com.mongodb.bulk.BulkWriteResult result = createBulkOps(BulkMode.ORDERED).//
- upsert(where("_id", "1"), set("value", "v1")).//
- execute();
-
- assertThat(result).isNotNull();
- assertThat(result.getMatchedCount()).isZero();
- assertThat(result.getModifiedCount()).isZero();
- assertThat(result.getUpserts()).isNotNull();
- assertThat(result.getUpserts().size()).isOne();
- }
-
- @Test // DATAMONGO-934
- public void updateOneOrdered() {
- testUpdate(BulkMode.ORDERED, false, 2);
- }
-
- @Test // DATAMONGO-934
- public void updateMultiOrdered() {
- testUpdate(BulkMode.ORDERED, true, 4);
- }
-
- @Test // DATAMONGO-934
- public void updateOneUnOrdered() {
- testUpdate(BulkMode.UNORDERED, false, 2);
- }
-
- @Test // DATAMONGO-934
- public void updateMultiUnOrdered() {
- testUpdate(BulkMode.UNORDERED, true, 4);
- }
-
- @Test // DATAMONGO-934
- public void removeOrdered() {
- testRemove(BulkMode.ORDERED);
- }
-
- @Test // DATAMONGO-934
- public void removeUnordered() {
- testRemove(BulkMode.UNORDERED);
- }
-
- @Test // DATAMONGO-2218
- public void replaceOneOrdered() {
- testReplaceOne(BulkMode.ORDERED);
- }
-
- @Test // DATAMONGO-2218
- public void replaceOneUnordered() {
- testReplaceOne(BulkMode.UNORDERED);
- }
-
- @Test // DATAMONGO-2218
- public void replaceOneDoesReplace() {
-
- insertSomeDocuments();
-
- com.mongodb.bulk.BulkWriteResult result = createBulkOps(BulkMode.ORDERED).//
- replaceOne(where("_id", "1"), rawDoc("1", "value2")).//
- execute();
-
- assertThat(result).isNotNull();
- assertThat(result.getMatchedCount()).isOne();
- assertThat(result.getModifiedCount()).isOne();
- assertThat(result.getInsertedCount()).isZero();
- }
-
- @Test // DATAMONGO-2218
- public void replaceOneWithUpsert() {
-
- com.mongodb.bulk.BulkWriteResult result = createBulkOps(BulkMode.ORDERED).//
- replaceOne(where("_id", "1"), rawDoc("1", "value2"), FindAndReplaceOptions.options().upsert()).//
- execute();
-
- assertThat(result).isNotNull();
- assertThat(result.getMatchedCount()).isZero();
- assertThat(result.getInsertedCount()).isZero();
- assertThat(result.getModifiedCount()).isZero();
- assertThat(result.getUpserts().size()).isOne();
- }
-
- /**
- * If working on the same set of documents, only an ordered bulk operation will yield predictable results.
- */
- @Test // DATAMONGO-934
- public void mixedBulkOrdered() {
-
- com.mongodb.bulk.BulkWriteResult result = createBulkOps(BulkMode.ORDERED, BaseDoc.class).insert(newDoc("1", "v1")).//
- updateOne(where("_id", "1"), set("value", "v2")).//
- remove(where("value", "v2")).//
- execute();
-
- assertThat(result).isNotNull();
- assertThat(result.getInsertedCount()).isOne();
- assertThat(result.getModifiedCount()).isOne();
- assertThat(result.getDeletedCount()).isOne();
- }
-
- /**
- * If working on the same set of documents, only an ordered bulk operation will yield predictable results.
- */
- @Test
- @SuppressWarnings("unchecked")
- public void mixedBulkOrderedWithList() {
-
- List inserts = Arrays.asList(newDoc("1", "v1"), newDoc("2", "v2"), newDoc("3", "v2"));
- List> updates = Arrays.asList(Pair.of(where("value", "v2"), set("value", "v3")));
- List removes = Arrays.asList(where("_id", "1"));
-
- com.mongodb.bulk.BulkWriteResult result = createBulkOps(BulkMode.ORDERED, BaseDoc.class).insert(inserts)
- .updateMulti(updates).remove(removes).execute();
-
- assertThat(result).isNotNull();
- assertThat(result.getInsertedCount()).isEqualTo(3);
- assertThat(result.getModifiedCount()).isEqualTo(2);
- assertThat(result.getDeletedCount()).isOne();
- }
-
- @Test // DATAMONGO-1534
- public void insertShouldConsiderInheritance() {
-
- SpecialDoc specialDoc = new SpecialDoc();
- specialDoc.id = "id-special";
- specialDoc.value = "normal-value";
- specialDoc.specialValue = "special-value";
-
- createBulkOps(BulkMode.ORDERED, SpecialDoc.class).insert(Arrays.asList(specialDoc)).execute();
-
- BaseDoc doc = operations.findOne(where("_id", specialDoc.id), BaseDoc.class, COLLECTION_NAME);
-
- assertThat(doc).isNotNull();
- assertThat(doc).isInstanceOf(SpecialDoc.class);
- }
-
- private void testUpdate(BulkMode mode, boolean multi, int expectedUpdates) {
-
- BulkOperations bulkOps = createBulkOps(mode);
-
- insertSomeDocuments();
-
- List> updates = new ArrayList>();
- updates.add(Pair.of(where("value", "value1"), set("value", "value3")));
- updates.add(Pair.of(where("value", "value2"), set("value", "value4")));
-
- int modifiedCount = multi ? bulkOps.updateMulti(updates).execute().getModifiedCount()
- : bulkOps.updateOne(updates).execute().getModifiedCount();
-
- assertThat(modifiedCount).isEqualTo(expectedUpdates);
- }
-
- private void testRemove(BulkMode mode) {
-
- insertSomeDocuments();
-
- List removes = Arrays.asList(where("_id", "1"), where("value", "value2"));
-
- assertThat(createBulkOps(mode).remove(removes).execute().getDeletedCount()).isEqualTo(3);
- }
-
- private void testReplaceOne(BulkMode mode) {
-
- BulkOperations bulkOps = createBulkOps(mode);
-
- insertSomeDocuments();
-
- Query query = where("_id", "1");
- Document document = rawDoc("1", "value2");
- int modifiedCount = bulkOps.replaceOne(query, document).execute().getModifiedCount();
-
- assertThat(modifiedCount).isOne();
- }
-
- private BulkOperations createBulkOps(BulkMode mode) {
- return createBulkOps(mode, null);
- }
-
- private BulkOperations createBulkOps(BulkMode mode, Class> entityType) {
-
- Optional extends MongoPersistentEntity>> entity = entityType != null
- ? Optional.of(operations.getConverter().getMappingContext().getPersistentEntity(entityType))
- : Optional.empty();
-
- BulkOperationContext bulkOperationContext = new BulkOperationContext(mode, entity,
- new QueryMapper(operations.getConverter()), new UpdateMapper(operations.getConverter()), null, null);
-
- DefaultBulkOperations bulkOps = new DefaultBulkOperations(operations, COLLECTION_NAME, bulkOperationContext);
- bulkOps.setDefaultWriteConcern(WriteConcern.ACKNOWLEDGED);
-
- return bulkOps;
- }
-
- private void insertSomeDocuments() {
-
- final MongoCollection coll = operations.getCollection(COLLECTION_NAME);
-
- coll.insertOne(rawDoc("1", "value1"));
- coll.insertOne(rawDoc("2", "value1"));
- coll.insertOne(rawDoc("3", "value2"));
- coll.insertOne(rawDoc("4", "value2"));
- }
-
- private static BaseDoc newDoc(String id) {
-
- BaseDoc doc = new BaseDoc();
- doc.id = id;
-
- return doc;
- }
-
- private static BaseDoc newDoc(String id, String value) {
-
- BaseDoc doc = newDoc(id);
- doc.value = value;
-
- return doc;
- }
-
- private static Query where(String field, String value) {
- return new Query().addCriteria(Criteria.where(field).is(value));
- }
-
- private static Update set(String field, String value) {
- return new Update().set(field, value);
- }
-
- private static Document rawDoc(String id, String value) {
- return new Document("_id", id).append("value", value);
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultBulkOperationsUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultBulkOperationsUnitTests.java
deleted file mode 100644
index 405b595f1f..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultBulkOperationsUnitTests.java
+++ /dev/null
@@ -1,466 +0,0 @@
-/*
- * Copyright 2017-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.ArgumentMatchers.*;
-import static org.mockito.Mockito.*;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyList;
-import static org.mockito.Mockito.eq;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-import static org.springframework.data.mongodb.core.query.Query.*;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-
-import org.bson.BsonDocument;
-import org.bson.BsonString;
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Answers;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-import org.springframework.context.ApplicationEventPublisher;
-import org.springframework.dao.DataAccessException;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.support.PersistenceExceptionTranslator;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.mapping.callback.EntityCallbacks;
-import org.springframework.data.mongodb.BulkOperationException;
-import org.springframework.data.mongodb.MongoDatabaseFactory;
-import org.springframework.data.mongodb.core.BulkOperations.BulkMode;
-import org.springframework.data.mongodb.core.DefaultBulkOperations.BulkOperationContext;
-import org.springframework.data.mongodb.core.convert.DbRefResolver;
-import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
-import org.springframework.data.mongodb.core.convert.MongoConverter;
-import org.springframework.data.mongodb.core.convert.QueryMapper;
-import org.springframework.data.mongodb.core.convert.UpdateMapper;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
-import org.springframework.data.mongodb.core.mapping.event.AfterSaveCallback;
-import org.springframework.data.mongodb.core.mapping.event.AfterSaveEvent;
-import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback;
-import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
-import org.springframework.data.mongodb.core.mapping.event.BeforeSaveCallback;
-import org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent;
-import org.springframework.data.mongodb.core.query.BasicQuery;
-import org.springframework.data.mongodb.core.query.Collation;
-import org.springframework.data.mongodb.core.query.Criteria;
-import org.springframework.data.mongodb.core.query.Update;
-
-import com.mongodb.MongoBulkWriteException;
-import com.mongodb.MongoWriteException;
-import com.mongodb.ServerAddress;
-import com.mongodb.WriteConcern;
-import com.mongodb.WriteError;
-import com.mongodb.bulk.BulkWriteError;
-import com.mongodb.bulk.WriteConcernError;
-import com.mongodb.client.MongoCollection;
-import com.mongodb.client.MongoDatabase;
-import com.mongodb.client.model.BulkWriteOptions;
-import com.mongodb.client.model.DeleteManyModel;
-import com.mongodb.client.model.InsertOneModel;
-import com.mongodb.client.model.ReplaceOneModel;
-import com.mongodb.client.model.UpdateManyModel;
-import com.mongodb.client.model.UpdateOneModel;
-import com.mongodb.client.model.WriteModel;
-
-/**
- * Unit tests for {@link DefaultBulkOperations}.
- *
- * @author Christoph Strobl
- * @author Mark Paluch
- * @author Minsu Kim
- * @author Jens Schauder
- * @author Roman Puchkovskiy
- * @author Jacob Botuck
- */
-@ExtendWith(MockitoExtension.class)
-class DefaultBulkOperationsUnitTests {
-
- private MongoTemplate template;
- @Mock MongoDatabase database;
- @Mock(answer = Answers.RETURNS_DEEP_STUBS) MongoCollection collection;
- @Mock MongoDatabaseFactory factory;
- @Mock DbRefResolver dbRefResolver;
- @Captor ArgumentCaptor>> captor;
- private MongoConverter converter;
- private MongoMappingContext mappingContext;
-
- private DefaultBulkOperations ops;
-
- @BeforeEach
- void setUp() {
-
- when(factory.getMongoDatabase()).thenReturn(database);
- when(factory.getExceptionTranslator()).thenReturn(new NullExceptionTranslator());
- when(database.getCollection(anyString(), eq(Document.class))).thenReturn(collection);
-
- mappingContext = new MongoMappingContext();
- mappingContext.afterPropertiesSet();
-
- converter = new MappingMongoConverter(dbRefResolver, mappingContext);
- template = new MongoTemplate(factory, converter);
-
- ops = new DefaultBulkOperations(template, "collection-1",
- new BulkOperationContext(BulkMode.ORDERED,
- Optional.of(mappingContext.getPersistentEntity(SomeDomainType.class)), new QueryMapper(converter),
- new UpdateMapper(converter), null, null));
- }
-
- @Test // DATAMONGO-1518
- void updateOneShouldUseCollationWhenPresent() {
-
- ops.updateOne(new BasicQuery("{}").collation(Collation.of("de")), new Update().set("lastName", "targaryen"))
- .execute();
-
- verify(collection).bulkWrite(captor.capture(), any());
-
- assertThat(captor.getValue().get(0)).isInstanceOf(UpdateOneModel.class);
- assertThat(((UpdateOneModel) captor.getValue().get(0)).getOptions().getCollation())
- .isEqualTo(com.mongodb.client.model.Collation.builder().locale("de").build());
- }
-
- @Test // DATAMONGO-1518
- void updateManyShouldUseCollationWhenPresent() {
-
- ops.updateMulti(new BasicQuery("{}").collation(Collation.of("de")), new Update().set("lastName", "targaryen"))
- .execute();
-
- verify(collection).bulkWrite(captor.capture(), any());
-
- assertThat(captor.getValue().get(0)).isInstanceOf(UpdateManyModel.class);
- assertThat(((UpdateManyModel) captor.getValue().get(0)).getOptions().getCollation())
- .isEqualTo(com.mongodb.client.model.Collation.builder().locale("de").build());
- }
-
- @Test // DATAMONGO-1518
- void removeShouldUseCollationWhenPresent() {
-
- ops.remove(new BasicQuery("{}").collation(Collation.of("de"))).execute();
-
- verify(collection).bulkWrite(captor.capture(), any());
-
- assertThat(captor.getValue().get(0)).isInstanceOf(DeleteManyModel.class);
- assertThat(((DeleteManyModel) captor.getValue().get(0)).getOptions().getCollation())
- .isEqualTo(com.mongodb.client.model.Collation.builder().locale("de").build());
- }
-
- @Test // DATAMONGO-2218
- void replaceOneShouldUseCollationWhenPresent() {
-
- ops.replaceOne(new BasicQuery("{}").collation(Collation.of("de")), new SomeDomainType()).execute();
-
- verify(collection).bulkWrite(captor.capture(), any());
-
- assertThat(captor.getValue().get(0)).isInstanceOf(ReplaceOneModel.class);
- assertThat(((ReplaceOneModel) captor.getValue().get(0)).getReplaceOptions().getCollation())
- .isEqualTo(com.mongodb.client.model.Collation.builder().locale("de").build());
- }
-
- @Test // DATAMONGO-1678
- void bulkUpdateShouldMapQueryAndUpdateCorrectly() {
-
- ops.updateOne(query(where("firstName").is("danerys")), Update.update("firstName", "queen danerys")).execute();
-
- verify(collection).bulkWrite(captor.capture(), any());
-
- UpdateOneModel updateModel = (UpdateOneModel) captor.getValue().get(0);
- assertThat(updateModel.getFilter()).isEqualTo(new Document("first_name", "danerys"));
- assertThat(updateModel.getUpdate()).isEqualTo(new Document("$set", new Document("first_name", "queen danerys")));
- }
-
- @Test // DATAMONGO-1678
- void bulkRemoveShouldMapQueryCorrectly() {
-
- ops.remove(query(where("firstName").is("danerys"))).execute();
-
- verify(collection).bulkWrite(captor.capture(), any());
-
- DeleteManyModel updateModel = (DeleteManyModel) captor.getValue().get(0);
- assertThat(updateModel.getFilter()).isEqualTo(new Document("first_name", "danerys"));
- }
-
- @Test // DATAMONGO-2218
- void bulkReplaceOneShouldMapQueryCorrectly() {
-
- SomeDomainType replacement = new SomeDomainType();
- replacement.firstName = "Minsu";
- replacement.lastName = "Kim";
-
- ops.replaceOne(query(where("firstName").is("danerys")), replacement).execute();
-
- verify(collection).bulkWrite(captor.capture(), any());
-
- ReplaceOneModel updateModel = (ReplaceOneModel) captor.getValue().get(0);
- assertThat(updateModel.getFilter()).isEqualTo(new Document("first_name", "danerys"));
- assertThat(updateModel.getReplacement().getString("first_name")).isEqualTo("Minsu");
- assertThat(updateModel.getReplacement().getString("lastName")).isEqualTo("Kim");
- }
-
- @Test // DATAMONGO-2261, DATAMONGO-2479
- void bulkInsertInvokesEntityCallbacks() {
-
- BeforeConvertPersonCallback beforeConvertCallback = spy(new BeforeConvertPersonCallback());
- BeforeSavePersonCallback beforeSaveCallback = spy(new BeforeSavePersonCallback());
- AfterSavePersonCallback afterSaveCallback = spy(new AfterSavePersonCallback());
-
- ops = new DefaultBulkOperations(template, "collection-1",
- new BulkOperationContext(BulkMode.ORDERED, Optional.of(mappingContext.getPersistentEntity(Person.class)),
- new QueryMapper(converter), new UpdateMapper(converter), null,
- EntityCallbacks.create(beforeConvertCallback, beforeSaveCallback, afterSaveCallback)));
-
- Person entity = new Person("init");
- ops.insert(entity);
-
- ArgumentCaptor personArgumentCaptor = ArgumentCaptor.forClass(Person.class);
- verify(beforeConvertCallback).onBeforeConvert(personArgumentCaptor.capture(), eq("collection-1"));
- verifyZeroInteractions(beforeSaveCallback);
-
- ops.execute();
-
- verify(beforeSaveCallback).onBeforeSave(personArgumentCaptor.capture(), any(), eq("collection-1"));
- verify(afterSaveCallback).onAfterSave(personArgumentCaptor.capture(), any(), eq("collection-1"));
- assertThat(personArgumentCaptor.getAllValues()).extracting("firstName").containsExactly("init", "before-convert",
- "before-convert");
- verify(collection).bulkWrite(captor.capture(), any());
-
- InsertOneModel updateModel = (InsertOneModel) captor.getValue().get(0);
- assertThat(updateModel.getDocument()).containsEntry("firstName", "after-save");
- }
-
- @Test // DATAMONGO-2290
- void bulkReplaceOneEmitsEventsCorrectly() {
-
- ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
-
- ops = new DefaultBulkOperations(template, "collection-1",
- new BulkOperationContext(BulkMode.ORDERED, Optional.of(mappingContext.getPersistentEntity(Person.class)),
- new QueryMapper(converter), new UpdateMapper(converter), eventPublisher, null));
-
- ops.replaceOne(query(where("firstName").is("danerys")), new SomeDomainType());
-
- verify(eventPublisher).publishEvent(any(BeforeConvertEvent.class));
- verify(eventPublisher, never()).publishEvent(any(BeforeSaveEvent.class));
- verify(eventPublisher, never()).publishEvent(any(AfterSaveEvent.class));
-
- ops.execute();
-
- verify(eventPublisher).publishEvent(any(BeforeSaveEvent.class));
- verify(eventPublisher).publishEvent(any(AfterSaveEvent.class));
- }
-
- @Test // DATAMONGO-2290
- void bulkInsertEmitsEventsCorrectly() {
-
- ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
-
- ops = new DefaultBulkOperations(template, "collection-1",
- new BulkOperationContext(BulkMode.ORDERED, Optional.of(mappingContext.getPersistentEntity(Person.class)),
- new QueryMapper(converter), new UpdateMapper(converter), eventPublisher, null));
-
- ops.insert(new SomeDomainType());
-
- verify(eventPublisher).publishEvent(any(BeforeConvertEvent.class));
- verify(eventPublisher, never()).publishEvent(any(BeforeSaveEvent.class));
- verify(eventPublisher, never()).publishEvent(any(AfterSaveEvent.class));
-
- ops.execute();
-
- verify(eventPublisher).publishEvent(any(BeforeSaveEvent.class));
- verify(eventPublisher).publishEvent(any(AfterSaveEvent.class));
- }
-
- @Test // DATAMONGO-2290
- void noAfterSaveEventOnFailure() {
-
- ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
- when(collection.bulkWrite(anyList(), any(BulkWriteOptions.class))).thenThrow(new MongoWriteException(
- new WriteError(89, "NetworkTimeout", new BsonDocument("hi", new BsonString("there!"))), null));
-
- ops = new DefaultBulkOperations(template, "collection-1",
- new BulkOperationContext(BulkMode.ORDERED, Optional.of(mappingContext.getPersistentEntity(Person.class)),
- new QueryMapper(converter), new UpdateMapper(converter), eventPublisher, null));
-
- ops.insert(new SomeDomainType());
-
- verify(eventPublisher).publishEvent(any(BeforeConvertEvent.class));
-
- try {
- ops.execute();
- fail("Missing MongoWriteException");
- } catch (MongoWriteException expected) {
-
- }
-
- verify(eventPublisher).publishEvent(any(BeforeSaveEvent.class));
- }
-
- @Test // DATAMONGO-2330
- void writeConcernNotAppliedWhenNotSet() {
-
- ops.updateOne(new BasicQuery("{}").collation(Collation.of("de")), new Update().set("lastName", "targaryen"))
- .execute();
-
- verify(collection, never()).withWriteConcern(any());
- }
-
- @Test // DATAMONGO-2330
- void writeConcernAppliedCorrectlyWhenSet() {
-
- ops.setDefaultWriteConcern(WriteConcern.MAJORITY);
-
- ops.updateOne(new BasicQuery("{}").collation(Collation.of("de")), new Update().set("lastName", "targaryen"))
- .execute();
-
- verify(collection).withWriteConcern(eq(WriteConcern.MAJORITY));
- }
-
- @Test // DATAMONGO-2450
- void appliesArrayFilterWhenPresent() {
-
- ops.updateOne(new BasicQuery("{}"), new Update().filterArray(Criteria.where("element").gte(100))).execute();
-
- verify(collection).bulkWrite(captor.capture(), any());
-
- UpdateOneModel updateModel = (UpdateOneModel) captor.getValue().get(0);
- assertThat(updateModel.getOptions().getArrayFilters().get(0))
- .isEqualTo(new org.bson.Document("element", new Document("$gte", 100)));
- }
-
- @Test // DATAMONGO-2502
- void shouldRetainNestedArrayPathWithPlaceholdersForNoMatchingPaths() {
-
- ops.updateOne(new BasicQuery("{}"), new Update().set("items.$.documents.0.fileId", "new-id")).execute();
-
- verify(collection).bulkWrite(captor.capture(), any());
-
- UpdateOneModel updateModel = (UpdateOneModel) captor.getValue().get(0);
- assertThat(updateModel.getUpdate())
- .isEqualTo(new Document("$set", new Document("items.$.documents.0.fileId", "new-id")));
- }
-
- @Test // DATAMONGO-2502
- void shouldRetainNestedArrayPathWithPlaceholdersForMappedEntity() {
-
- DefaultBulkOperations ops = new DefaultBulkOperations(template, "collection-1",
- new BulkOperationContext(BulkMode.ORDERED, Optional.of(mappingContext.getPersistentEntity(OrderTest.class)),
- new QueryMapper(converter), new UpdateMapper(converter), null, null));
-
- ops.updateOne(new BasicQuery("{}"), Update.update("items.$.documents.0.fileId", "file-id")).execute();
-
- verify(collection).bulkWrite(captor.capture(), any());
-
- UpdateOneModel updateModel = (UpdateOneModel) captor.getValue().get(0);
- assertThat(updateModel.getUpdate())
- .isEqualTo(new Document("$set", new Document("items.$.documents.0.the_file_id", "file-id")));
- }
-
- @Test // DATAMONGO-2285
- public void translateMongoBulkOperationExceptionWithWriteConcernError() {
-
- when(collection.bulkWrite(anyList(), any(BulkWriteOptions.class))).thenThrow(new MongoBulkWriteException(null,
- Collections.emptyList(),
- new WriteConcernError(42, "codename", "writeconcern error happened", new BsonDocument()), new ServerAddress()));
-
- assertThatExceptionOfType(DataIntegrityViolationException.class)
- .isThrownBy(() -> ops.insert(new SomeDomainType()).execute());
-
- }
-
- @Test // DATAMONGO-2285
- public void translateMongoBulkOperationExceptionWithoutWriteConcernError() {
-
- when(collection.bulkWrite(anyList(), any(BulkWriteOptions.class))).thenThrow(new MongoBulkWriteException(null,
- Collections.singletonList(new BulkWriteError(42, "a write error happened", new BsonDocument(), 49)), null,
- new ServerAddress()));
-
- assertThatExceptionOfType(BulkOperationException.class)
- .isThrownBy(() -> ops.insert(new SomeDomainType()).execute());
- }
-
- static class OrderTest {
-
- String id;
- List items;
- }
-
- static class OrderTestItem {
-
- private String cartId;
- private List documents;
- }
-
- static class OrderTestDocument {
-
- @Field("the_file_id")
- private String fileId;
- }
-
- class SomeDomainType {
-
- @Id String id;
- Gender gender;
- @Field("first_name") String firstName;
- @Field String lastName;
- }
-
- enum Gender {
- M, F
- }
-
- static class BeforeConvertPersonCallback implements BeforeConvertCallback {
-
- @Override
- public Person onBeforeConvert(Person entity, String collection) {
- return new Person("before-convert");
- }
- }
-
- static class BeforeSavePersonCallback implements BeforeSaveCallback {
-
- @Override
- public Person onBeforeSave(Person entity, Document document, String collection) {
-
- document.put("firstName", "before-save");
- return new Person("before-save");
- }
- }
-
- static class AfterSavePersonCallback implements AfterSaveCallback {
-
- @Override
- public Person onAfterSave(Person entity, Document document, String collection) {
-
- document.put("firstName", "after-save");
- return new Person("after-save");
- }
- }
-
- static class NullExceptionTranslator implements PersistenceExceptionTranslator {
-
- @Override
- public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
- return null;
- }
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsIntegrationTests.java
deleted file mode 100644
index 4a934a960b..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsIntegrationTests.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright 2014-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.data.mongodb.core.index.PartialIndexFilter.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-
-import org.bson.BsonDocument;
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.data.domain.Sort.Direction;
-import org.springframework.data.mongodb.core.convert.QueryMapper;
-import org.springframework.data.mongodb.core.index.Index;
-import org.springframework.data.mongodb.core.index.IndexDefinition;
-import org.springframework.data.mongodb.core.index.IndexInfo;
-import org.springframework.data.mongodb.core.index.IndexOperations;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.query.Collation;
-import org.springframework.data.mongodb.core.query.Collation.CaseFirst;
-import org.springframework.data.mongodb.test.util.MongoTemplateExtension;
-import org.springframework.data.mongodb.test.util.MongoTestTemplate;
-import org.springframework.data.mongodb.test.util.Template;
-import org.springframework.util.ObjectUtils;
-
-import com.mongodb.client.MongoCollection;
-import com.mongodb.client.model.IndexOptions;
-
-/**
- * Integration tests for {@link DefaultIndexOperations}.
- *
- * @author Christoph Strobl
- * @author Oliver Gierke
- * @author Mark Paluch
- */
-@ExtendWith(MongoTemplateExtension.class)
-public class DefaultIndexOperationsIntegrationTests {
-
- static final String COLLECTION_NAME = "default-index-operations-tests";
- static final org.bson.Document GEO_SPHERE_2D = new org.bson.Document("loaction", "2dsphere");
-
- @Template //
- static MongoTestTemplate template;
-
- MongoCollection collection = template.getCollection(COLLECTION_NAME);
- IndexOperations indexOps = template.indexOps(COLLECTION_NAME);
-
- @BeforeEach
- public void setUp() {
- template.dropIndexes(COLLECTION_NAME);
- }
-
- @Test // DATAMONGO-1008
- public void getIndexInfoShouldBeAbleToRead2dsphereIndex() {
-
- template.getCollection(COLLECTION_NAME).createIndex(GEO_SPHERE_2D);
-
- IndexInfo info = findAndReturnIndexInfo(GEO_SPHERE_2D);
- assertThat(info.getIndexFields().get(0).isGeo()).isEqualTo(true);
- }
-
- @Test // DATAMONGO-1467, DATAMONGO-2198
- public void shouldApplyPartialFilterCorrectly() {
-
- IndexDefinition id = new Index().named("partial-with-criteria").on("k3y", Direction.ASC)
- .partial(of(where("q-t-y").gte(10)));
-
- indexOps.ensureIndex(id);
-
- IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-criteria");
- assertThat(Document.parse(info.getPartialFilterExpression()))
- .isEqualTo(Document.parse("{ \"q-t-y\" : { \"$gte\" : 10 } }"));
- }
-
- @Test // DATAMONGO-1467, DATAMONGO-2198
- public void shouldApplyPartialFilterWithMappedPropertyCorrectly() {
-
- IndexDefinition id = new Index().named("partial-with-mapped-criteria").on("k3y", Direction.ASC)
- .partial(of(where("quantity").gte(10)));
-
- template.indexOps(DefaultIndexOperationsIntegrationTestsSample.class).ensureIndex(id);
-
- IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-mapped-criteria");
- assertThat(Document.parse(info.getPartialFilterExpression()))
- .isEqualTo(Document.parse("{ \"qty\" : { \"$gte\" : 10 } }"));
- }
-
- @Test // DATAMONGO-1467, DATAMONGO-2198
- public void shouldApplyPartialDBOFilterCorrectly() {
-
- IndexDefinition id = new Index().named("partial-with-dbo").on("k3y", Direction.ASC)
- .partial(of(new org.bson.Document("qty", new org.bson.Document("$gte", 10))));
-
- indexOps.ensureIndex(id);
-
- IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-dbo");
- assertThat(Document.parse(info.getPartialFilterExpression()))
- .isEqualTo(Document.parse("{ \"qty\" : { \"$gte\" : 10 } }"));
- }
-
- @Test // DATAMONGO-1467, DATAMONGO-2198
- public void shouldFavorExplicitMappingHintViaClass() {
-
- IndexDefinition id = new Index().named("partial-with-inheritance").on("k3y", Direction.ASC)
- .partial(of(where("age").gte(10)));
-
- indexOps = new DefaultIndexOperations(template.getMongoDbFactory(), COLLECTION_NAME,
- new QueryMapper(template.getConverter()), MappingToSameCollection.class);
-
- indexOps.ensureIndex(id);
-
- IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-inheritance");
- assertThat(Document.parse(info.getPartialFilterExpression()))
- .isEqualTo(Document.parse("{ \"a_g_e\" : { \"$gte\" : 10 } }"));
- }
-
- @Test // DATAMONGO-2388
- public void shouldReadIndexWithPartialFilterContainingDbRefCorrectly() {
-
- BsonDocument partialFilter = BsonDocument.parse(
- "{ \"the-ref\" : { \"$ref\" : \"other-collection\", \"$id\" : { \"$oid\" : \"59ce08baf264b906810fe8c5\"} } }");
- IndexOptions indexOptions = new IndexOptions();
- indexOptions.name("partial-with-dbref");
- indexOptions.partialFilterExpression(partialFilter);
-
- collection.createIndex(BsonDocument.parse("{ \"key-1\" : 1, \"key-2\": 1}"), indexOptions);
-
- IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-dbref");
- assertThat(BsonDocument.parse(info.getPartialFilterExpression())).isEqualTo(partialFilter);
- }
-
- @Test // DATAMONGO-1518
- public void shouldCreateIndexWithCollationCorrectly() {
-
- IndexDefinition id = new Index().named("with-collation").on("xyz", Direction.ASC)
- .collation(Collation.of("de_AT").caseFirst(CaseFirst.off()));
-
- new DefaultIndexOperations(template.getMongoDbFactory(), COLLECTION_NAME, new QueryMapper(template.getConverter()),
- MappingToSameCollection.class);
-
- indexOps.ensureIndex(id);
-
- Document expected = new Document("locale", "de_AT") //
- .append("caseLevel", false) //
- .append("caseFirst", "off") //
- .append("strength", 3) //
- .append("numericOrdering", false) //
- .append("alternate", "non-ignorable") //
- .append("maxVariable", "punct") //
- .append("normalization", false) //
- .append("backwards", false);
-
- IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "with-collation");
-
- assertThat(info.getCollation()).isPresent();
-
- // version is set by MongoDB server - we remove it to avoid errors when upgrading server version.
- Document result = info.getCollation().get();
- result.remove("version");
-
- assertThat(result).isEqualTo(expected);
- }
-
- private IndexInfo findAndReturnIndexInfo(org.bson.Document keys) {
- return findAndReturnIndexInfo(indexOps.getIndexInfo(), keys);
- }
-
- private static IndexInfo findAndReturnIndexInfo(Iterable candidates, org.bson.Document keys) {
- return findAndReturnIndexInfo(candidates, genIndexName(keys));
- }
-
- private static IndexInfo findAndReturnIndexInfo(Iterable candidates, String name) {
-
- for (IndexInfo info : candidates) {
- if (ObjectUtils.nullSafeEquals(name, info.getName())) {
- return info;
- }
- }
- throw new AssertionError(String.format("Index with %s was not found", name));
- }
-
- private static String genIndexName(Document keys) {
-
- StringBuilder name = new StringBuilder();
-
- for (String s : keys.keySet()) {
-
- if (name.length() > 0) {
- name.append('_');
- }
-
- name.append(s).append('_');
- Object val = keys.get(s);
-
- if (val instanceof Number || val instanceof String) {
- name.append(val.toString().replace(' ', '_'));
- }
- }
-
- return name.toString();
- }
-
- @org.springframework.data.mongodb.core.mapping.Document(collection = "default-index-operations-tests")
- static class DefaultIndexOperationsIntegrationTestsSample {
-
- @Field("qty") Integer quantity;
- }
-
- @org.springframework.data.mongodb.core.mapping.Document(collection = "default-index-operations-tests")
- static class MappingToSameCollection extends DefaultIndexOperationsIntegrationTestsSample {
-
- @Field("a_g_e") Integer age;
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsUnitTests.java
deleted file mode 100644
index ca16ea312c..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsUnitTests.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-import lombok.Data;
-
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.data.domain.Sort.Direction;
-import org.springframework.data.mongodb.MongoDatabaseFactory;
-import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
-import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
-import org.springframework.data.mongodb.core.index.HashedIndex;
-import org.springframework.data.mongodb.core.index.Index;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
-import org.springframework.data.mongodb.core.query.Collation;
-
-import com.mongodb.client.MongoCollection;
-import com.mongodb.client.MongoDatabase;
-import com.mongodb.client.model.IndexOptions;
-
-/**
- * Unit tests for {@link DefaultIndexOperations}.
- *
- * @author Christoph Strobl
- */
-@ExtendWith(MockitoExtension.class)
-public class DefaultIndexOperationsUnitTests {
-
- private MongoTemplate template;
-
- @Mock MongoDatabaseFactory factory;
- @Mock MongoDatabase db;
- @Mock MongoCollection collection;
-
- private MongoExceptionTranslator exceptionTranslator = new MongoExceptionTranslator();
- private MappingMongoConverter converter;
- private MongoMappingContext mappingContext;
-
- @BeforeEach
- void setUp() {
-
- when(factory.getMongoDatabase()).thenReturn(db);
- when(factory.getExceptionTranslator()).thenReturn(exceptionTranslator);
- when(db.getCollection(any(), any(Class.class))).thenReturn(collection);
- when(collection.createIndex(any(), any(IndexOptions.class))).thenReturn("OK");
-
- this.mappingContext = new MongoMappingContext();
- this.converter = spy(new MappingMongoConverter(new DefaultDbRefResolver(factory), mappingContext));
- this.template = new MongoTemplate(factory, converter);
- }
-
- @Test // DATAMONGO-1183
- void indexOperationsMapFieldNameCorrectly() {
-
- indexOpsFor(Jedi.class).ensureIndex(new Index("name", Direction.DESC));
-
- verify(collection).createIndex(eq(new Document("firstname", -1)), any());
- }
-
- @Test // DATAMONGO-1854
- void ensureIndexDoesNotSetCollectionIfNoDefaultDefined() {
-
- indexOpsFor(Jedi.class).ensureIndex(new Index("firstname", Direction.DESC));
-
- ArgumentCaptor options = ArgumentCaptor.forClass(IndexOptions.class);
- verify(collection).createIndex(any(), options.capture());
-
- assertThat(options.getValue().getCollation()).isNull();
- }
-
- @Test // DATAMONGO-1854
- void ensureIndexUsesDefaultCollationIfNoneDefinedInOptions() {
-
- indexOpsFor(Sith.class).ensureIndex(new Index("firstname", Direction.DESC));
-
- ArgumentCaptor options = ArgumentCaptor.forClass(IndexOptions.class);
- verify(collection).createIndex(any(), options.capture());
-
- assertThat(options.getValue().getCollation())
- .isEqualTo(com.mongodb.client.model.Collation.builder().locale("de_AT").build());
- }
-
- @Test // DATAMONGO-1854
- void ensureIndexDoesNotUseDefaultCollationIfExplicitlySpecifiedInTheIndex() {
-
- indexOpsFor(Sith.class).ensureIndex(new Index("firstname", Direction.DESC).collation(Collation.of("en_US")));
-
- ArgumentCaptor options = ArgumentCaptor.forClass(IndexOptions.class);
- verify(collection).createIndex(any(), options.capture());
-
- assertThat(options.getValue().getCollation())
- .isEqualTo(com.mongodb.client.model.Collation.builder().locale("en_US").build());
- }
-
- @Test // DATAMONGO-1183
- void shouldCreateHashedIndexCorrectly() {
-
- indexOpsFor(Jedi.class).ensureIndex(HashedIndex.hashed("name"));
-
- verify(collection).createIndex(eq(new Document("firstname", "hashed")), any());
- }
-
- private DefaultIndexOperations indexOpsFor(Class> type) {
- return new DefaultIndexOperations(template, template.getCollectionName(type), type);
- }
-
- @Data
- static class Jedi {
- @Field("firstname") String name;
- }
-
- @org.springframework.data.mongodb.core.mapping.Document(collation = "de_AT")
- static class Sith {
- @Field("firstname") String name;
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultReactiveIndexOperationsTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultReactiveIndexOperationsTests.java
deleted file mode 100644
index c3e9fe9ac6..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultReactiveIndexOperationsTests.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright 2017-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.data.mongodb.core.index.PartialIndexFilter.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-
-import reactor.test.StepVerifier;
-
-import java.util.function.Predicate;
-
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.data.domain.Sort.Direction;
-import org.springframework.data.mongodb.core.convert.QueryMapper;
-import org.springframework.data.mongodb.core.index.Index;
-import org.springframework.data.mongodb.core.index.IndexDefinition;
-import org.springframework.data.mongodb.core.index.IndexInfo;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.query.Collation;
-import org.springframework.data.mongodb.core.query.Collation.CaseFirst;
-import org.springframework.data.mongodb.test.util.MongoTemplateExtension;
-import org.springframework.data.mongodb.test.util.ReactiveMongoTestTemplate;
-import org.springframework.data.mongodb.test.util.Template;
-
-import com.mongodb.reactivestreams.client.MongoCollection;
-
-/**
- * @author Christoph Strobl
- * @author Mark Paluch
- * @author Mathieu Ouellet
- */
-@ExtendWith(MongoTemplateExtension.class)
-public class DefaultReactiveIndexOperationsTests {
-
- @Template(initialEntitySet = DefaultIndexOperationsIntegrationTestsSample.class)
- static ReactiveMongoTestTemplate template;
-
- String collectionName = template.getCollectionName(DefaultIndexOperationsIntegrationTestsSample.class);
-
- DefaultReactiveIndexOperations indexOps = new DefaultReactiveIndexOperations(template, collectionName,
- new QueryMapper(template.getConverter()));
-
- @BeforeEach
- public void setUp() {
- template.getCollection(collectionName).flatMapMany(MongoCollection::dropIndexes) //
- .as(StepVerifier::create) //
- .verifyComplete();
- }
-
- @Test // DATAMONGO-1518
- public void shouldCreateIndexWithCollationCorrectly() {
-
- IndexDefinition id = new Index().named("with-collation").on("xyz", Direction.ASC)
- .collation(Collation.of("de_AT").caseFirst(CaseFirst.off()));
-
- indexOps.ensureIndex(id).as(StepVerifier::create).expectNextCount(1).verifyComplete();
-
- Document expected = new Document("locale", "de_AT") //
- .append("caseLevel", false) //
- .append("caseFirst", "off") //
- .append("strength", 3) //
- .append("numericOrdering", false) //
- .append("alternate", "non-ignorable") //
- .append("maxVariable", "punct") //
- .append("normalization", false) //
- .append("backwards", false);
-
- indexOps.getIndexInfo().filter(this.indexByName("with-collation")).as(StepVerifier::create) //
- .consumeNextWith(indexInfo -> {
-
- assertThat(indexInfo.getCollation()).isPresent();
-
- // version is set by MongoDB server - we remove it to avoid errors when upgrading server version.
- Document result = indexInfo.getCollation().get();
- result.remove("version");
-
- assertThat(result).isEqualTo(expected);
- }) //
- .verifyComplete();
- }
-
- @Test // DATAMONGO-1682, DATAMONGO-2198
- public void shouldApplyPartialFilterCorrectly() {
-
- IndexDefinition id = new Index().named("partial-with-criteria").on("k3y", Direction.ASC)
- .partial(of(where("q-t-y").gte(10)));
-
- indexOps.ensureIndex(id).as(StepVerifier::create).expectNextCount(1).verifyComplete();
-
- indexOps.getIndexInfo().filter(this.indexByName("partial-with-criteria")).as(StepVerifier::create) //
- .consumeNextWith(indexInfo -> {
- assertThat(Document.parse(indexInfo.getPartialFilterExpression()))
- .isEqualTo(Document.parse("{ \"q-t-y\" : { \"$gte\" : 10 } }"));
- }) //
- .verifyComplete();
- }
-
- @Test // DATAMONGO-1682, DATAMONGO-2198
- public void shouldApplyPartialFilterWithMappedPropertyCorrectly() {
-
- IndexDefinition id = new Index().named("partial-with-mapped-criteria").on("k3y", Direction.ASC)
- .partial(of(where("quantity").gte(10)));
-
- indexOps.ensureIndex(id).as(StepVerifier::create).expectNextCount(1).verifyComplete();
-
- indexOps.getIndexInfo().filter(this.indexByName("partial-with-mapped-criteria")).as(StepVerifier::create) //
- .consumeNextWith(indexInfo -> {
- assertThat(Document.parse(indexInfo.getPartialFilterExpression()))
- .isEqualTo(Document.parse("{ \"qty\" : { \"$gte\" : 10 } }"));
- }).verifyComplete();
- }
-
- @Test // DATAMONGO-1682, DATAMONGO-2198
- public void shouldApplyPartialDBOFilterCorrectly() {
-
- IndexDefinition id = new Index().named("partial-with-dbo").on("k3y", Direction.ASC)
- .partial(of(new org.bson.Document("qty", new org.bson.Document("$gte", 10))));
-
- indexOps.ensureIndex(id).as(StepVerifier::create).expectNextCount(1).verifyComplete();
-
- indexOps.getIndexInfo().filter(this.indexByName("partial-with-dbo")).as(StepVerifier::create) //
- .consumeNextWith(indexInfo -> {
- assertThat(Document.parse(indexInfo.getPartialFilterExpression()))
- .isEqualTo(Document.parse("{ \"qty\" : { \"$gte\" : 10 } }"));
- }) //
- .verifyComplete();
-
- }
-
- @Test // DATAMONGO-1682, DATAMONGO-2198
- public void shouldFavorExplicitMappingHintViaClass() {
-
- IndexDefinition id = new Index().named("partial-with-inheritance").on("k3y", Direction.ASC)
- .partial(of(where("age").gte(10)));
-
- indexOps = new DefaultReactiveIndexOperations(template,
- this.template.getCollectionName(DefaultIndexOperationsIntegrationTestsSample.class),
- new QueryMapper(template.getConverter()), MappingToSameCollection.class);
-
- indexOps.ensureIndex(id).as(StepVerifier::create).expectNextCount(1).verifyComplete();
-
- indexOps.getIndexInfo().filter(this.indexByName("partial-with-inheritance")).as(StepVerifier::create) //
- .consumeNextWith(indexInfo -> {
- assertThat(Document.parse(indexInfo.getPartialFilterExpression()))
- .isEqualTo(Document.parse("{ \"a_g_e\" : { \"$gte\" : 10 } }"));
- }) //
- .verifyComplete();
- }
-
- Predicate indexByName(String name) {
- return indexInfo -> indexInfo.getName().equals(name);
- }
-
- @org.springframework.data.mongodb.core.mapping.Document(collection = "default-index-operations-tests")
- static class DefaultIndexOperationsIntegrationTestsSample {
-
- @Field("qty") Integer quantity;
- }
-
- @org.springframework.data.mongodb.core.mapping.Document(collection = "default-index-operations-tests")
- static class MappingToSameCollection
- extends DefaultIndexOperationsIntegrationTests.DefaultIndexOperationsIntegrationTestsSample {
-
- @Field("a_g_e") Integer age;
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultReactiveIndexOperationsUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultReactiveIndexOperationsUnitTests.java
deleted file mode 100644
index d5dd1b4769..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultReactiveIndexOperationsUnitTests.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-import lombok.Data;
-import reactor.core.publisher.Mono;
-
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-import org.reactivestreams.Publisher;
-
-import org.springframework.data.domain.Sort.Direction;
-import org.springframework.data.mongodb.ReactiveMongoDatabaseFactory;
-import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
-import org.springframework.data.mongodb.core.convert.NoOpDbRefResolver;
-import org.springframework.data.mongodb.core.convert.QueryMapper;
-import org.springframework.data.mongodb.core.index.Index;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
-import org.springframework.data.mongodb.core.query.Collation;
-
-import com.mongodb.client.model.IndexOptions;
-import com.mongodb.reactivestreams.client.MongoCollection;
-import com.mongodb.reactivestreams.client.MongoDatabase;
-
-/**
- * @author Christoph Strobl
- * @author Mathieu Ouellet
- */
-@ExtendWith(MockitoExtension.class)
-public class DefaultReactiveIndexOperationsUnitTests {
-
- private ReactiveMongoTemplate template;
-
- @Mock ReactiveMongoDatabaseFactory factory;
- @Mock MongoDatabase db;
- @Mock MongoCollection collection;
- @Mock Publisher publisher;
-
- private MongoExceptionTranslator exceptionTranslator = new MongoExceptionTranslator();
- private MappingMongoConverter converter;
- private MongoMappingContext mappingContext;
-
- @BeforeEach
- void setUp() {
-
- when(factory.getMongoDatabase()).thenReturn(Mono.just(db));
- when(factory.getExceptionTranslator()).thenReturn(exceptionTranslator);
- when(db.getCollection(any(), any(Class.class))).thenReturn(collection);
- when(collection.createIndex(any(), any(IndexOptions.class))).thenReturn(publisher);
-
- this.mappingContext = new MongoMappingContext();
- this.converter = spy(new MappingMongoConverter(NoOpDbRefResolver.INSTANCE, mappingContext));
- this.template = new ReactiveMongoTemplate(factory, converter);
- }
-
- @Test // DATAMONGO-1854
- void ensureIndexDoesNotSetCollectionIfNoDefaultDefined() {
-
- indexOpsFor(Jedi.class).ensureIndex(new Index("firstname", Direction.DESC)).subscribe();
-
- ArgumentCaptor options = ArgumentCaptor.forClass(IndexOptions.class);
- verify(collection).createIndex(any(), options.capture());
-
- assertThat(options.getValue().getCollation()).isNull();
- }
-
- @Test // DATAMONGO-1854
- void ensureIndexUsesDefaultCollationIfNoneDefinedInOptions() {
-
- indexOpsFor(Sith.class).ensureIndex(new Index("firstname", Direction.DESC)).subscribe();
-
- ArgumentCaptor options = ArgumentCaptor.forClass(IndexOptions.class);
- verify(collection).createIndex(any(), options.capture());
-
- assertThat(options.getValue().getCollation())
- .isEqualTo(com.mongodb.client.model.Collation.builder().locale("de_AT").build());
- }
-
- @Test // DATAMONGO-1854
- void ensureIndexDoesNotUseDefaultCollationIfExplicitlySpecifiedInTheIndex() {
-
- indexOpsFor(Sith.class).ensureIndex(new Index("firstname", Direction.DESC).collation(Collation.of("en_US")))
- .subscribe();
-
- ArgumentCaptor options = ArgumentCaptor.forClass(IndexOptions.class);
- verify(collection).createIndex(any(), options.capture());
-
- assertThat(options.getValue().getCollation())
- .isEqualTo(com.mongodb.client.model.Collation.builder().locale("en_US").build());
- }
-
- private DefaultReactiveIndexOperations indexOpsFor(Class> type) {
- return new DefaultReactiveIndexOperations(template, template.getCollectionName(type),
- new QueryMapper(template.getConverter()), type);
- }
-
- @Data
- static class Jedi {
- @Field("firstname") String name;
- }
-
- @org.springframework.data.mongodb.core.mapping.Document(collation = "de_AT")
- static class Sith {
- @Field("firstname") String name;
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultScriptOperationsTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultScriptOperationsTests.java
deleted file mode 100644
index e07e0616f7..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultScriptOperationsTests.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright 2014-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-import static org.springframework.data.mongodb.core.query.Query.*;
-
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.dao.UncategorizedDataAccessException;
-import org.springframework.data.mongodb.core.query.Query;
-import org.springframework.data.mongodb.core.script.ExecutableMongoScript;
-import org.springframework.data.mongodb.core.script.NamedMongoScript;
-import org.springframework.data.mongodb.test.util.Client;
-import org.springframework.data.mongodb.test.util.EnableIfMongoServerVersion;
-import org.springframework.data.mongodb.test.util.MongoClientExtension;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
-
-import com.mongodb.client.MongoClient;
-
-/**
- * Integration tests for {@link DefaultScriptOperations}.
- *
- * @author Christoph Strobl
- * @author Oliver Gierke
- * @since 1.7
- */
-@ExtendWith({ MongoClientExtension.class, SpringExtension.class })
-@EnableIfMongoServerVersion(isLessThan = "4.1.0")
-@ContextConfiguration
-public class DefaultScriptOperationsTests {
-
- static @Client MongoClient mongoClient;
-
- @Configuration
- static class Config {
-
- private static final String DB_NAME = "script-tests";
-
- @Bean
- public MongoClient mongoClient() {
- return mongoClient;
- }
-
- @Bean
- public MongoTemplate template() throws Exception {
- return new MongoTemplate(mongoClient(), DB_NAME);
- }
- }
-
- static final String JAVASCRIPT_COLLECTION_NAME = "system.js";
- static final String SCRIPT_NAME = "echo";
- static final String JS_FUNCTION = "function(x) { return x; }";
- static final ExecutableMongoScript EXECUTABLE_SCRIPT = new ExecutableMongoScript(JS_FUNCTION);
- static final NamedMongoScript CALLABLE_SCRIPT = new NamedMongoScript(SCRIPT_NAME, JS_FUNCTION);
-
- @Autowired MongoTemplate template;
- DefaultScriptOperations scriptOps;
-
- @BeforeEach
- public void setUp() {
-
- template.getCollection(JAVASCRIPT_COLLECTION_NAME).deleteMany(new Document());
- this.scriptOps = new DefaultScriptOperations(template);
- }
-
- @Test // DATAMONGO-479
- public void executeShouldDirectlyRunExecutableMongoScript() {
- assertThat(scriptOps.execute(EXECUTABLE_SCRIPT, 10)).isEqualTo((Object) 10D);
- }
-
- @Test // DATAMONGO-479
- public void saveShouldStoreCallableScriptCorrectly() {
-
- Query query = query(where("_id").is(SCRIPT_NAME));
- assertThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME)).isFalse();
-
- scriptOps.register(CALLABLE_SCRIPT);
-
- assertThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME)).isTrue();
- }
-
- @Test // DATAMONGO-479
- public void saveShouldStoreExecutableScriptCorrectly() {
-
- NamedMongoScript script = scriptOps.register(EXECUTABLE_SCRIPT);
-
- Query query = query(where("_id").is(script.getName()));
- assertThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME)).isTrue();
- }
-
- @Test // DATAMONGO-479
- public void executeShouldRunCallableScriptThatHasBeenSavedBefore() {
-
- scriptOps.register(CALLABLE_SCRIPT);
-
- Query query = query(where("_id").is(SCRIPT_NAME));
- assertThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME)).isTrue();
-
- Object result = scriptOps.call(CALLABLE_SCRIPT.getName(), 10);
-
- assertThat(result).isEqualTo(10D);
- }
-
- @Test // DATAMONGO-479
- public void existsShouldReturnTrueIfScriptAvailableOnServer() {
-
- scriptOps.register(CALLABLE_SCRIPT);
-
- assertThat(scriptOps.exists(SCRIPT_NAME)).isTrue();
- }
-
- @Test // DATAMONGO-479
- public void existsShouldReturnFalseIfScriptNotAvailableOnServer() {
- assertThat(scriptOps.exists(SCRIPT_NAME)).isFalse();
- }
-
- @Test // DATAMONGO-479
- public void callShouldExecuteExistingScript() {
-
- scriptOps.register(CALLABLE_SCRIPT);
-
- Object result = scriptOps.call(SCRIPT_NAME, 10);
-
- assertThat(result).isEqualTo((Object) 10D);
- }
-
- @Test // DATAMONGO-479
- public void callShouldThrowExceptionWhenCallingScriptThatDoesNotExist() {
- assertThatExceptionOfType(UncategorizedDataAccessException.class).isThrownBy(() -> scriptOps.call(SCRIPT_NAME, 10));
- }
-
- @Test // DATAMONGO-479
- public void scriptNamesShouldContainNameOfRegisteredScript() {
-
- scriptOps.register(CALLABLE_SCRIPT);
-
- assertThat(scriptOps.getScriptNames()).contains("echo");
- }
-
- @Test // DATAMONGO-479
- public void scriptNamesShouldReturnEmptySetWhenNoScriptRegistered() {
- assertThat(scriptOps.getScriptNames()).isEmpty();
- }
-
- @Test // DATAMONGO-1465
- public void executeShouldNotQuoteStrings() {
- assertThat(scriptOps.execute(EXECUTABLE_SCRIPT, "spring-data")).isEqualTo((Object) "spring-data");
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultScriptOperationsUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultScriptOperationsUnitTests.java
deleted file mode 100644
index ac6f6e79d3..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultScriptOperationsUnitTests.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright 2014-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.data.mongodb.core.script.ExecutableMongoScript;
-import org.springframework.data.mongodb.core.script.NamedMongoScript;
-
-/**
- * Unit tests for {@link DefaultScriptOperations}.
- *
- * @author Christoph Strobl
- * @author Oliver Gierke
- * @since 1.7
- */
-@ExtendWith(MockitoExtension.class)
-class DefaultScriptOperationsUnitTests {
-
- private DefaultScriptOperations scriptOps;
- @Mock MongoOperations mongoOperations;
-
- @BeforeEach
- void setUp() {
- this.scriptOps = new DefaultScriptOperations(mongoOperations);
- }
-
- @Test // DATAMONGO-479
- void rejectsNullExecutableMongoScript() {
- assertThatIllegalArgumentException().isThrownBy(() -> scriptOps.register((ExecutableMongoScript) null));
- }
-
- @Test // DATAMONGO-479
- void rejectsNullNamedMongoScript() {
- assertThatIllegalArgumentException().isThrownBy(() -> scriptOps.register((NamedMongoScript) null));
- }
-
- @Test // DATAMONGO-479
- void saveShouldUseCorrectCollectionName() {
-
- scriptOps.register(new NamedMongoScript("foo", "function..."));
-
- verify(mongoOperations, times(1)).save(any(NamedMongoScript.class), eq("system.js"));
- }
-
- @Test // DATAMONGO-479
- void saveShouldGenerateScriptNameForExecutableMongoScripts() {
-
- scriptOps.register(new ExecutableMongoScript("function..."));
-
- ArgumentCaptor captor = ArgumentCaptor.forClass(NamedMongoScript.class);
-
- verify(mongoOperations, times(1)).save(captor.capture(), eq("system.js"));
- assertThat(captor.getValue().getName()).isNotNull();
- }
-
- @Test // DATAMONGO-479
- void executeShouldThrowExceptionWhenScriptIsNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> scriptOps.execute(null));
- }
-
- @Test // DATAMONGO-479
- void existsShouldThrowExceptionWhenScriptNameIsNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> scriptOps.exists(null));
- }
-
- @Test // DATAMONGO-479
- void existsShouldThrowExceptionWhenScriptNameIsEmpty() {
- assertThatIllegalArgumentException().isThrownBy(() -> scriptOps.exists(""));
- }
-
- @Test // DATAMONGO-479
- void callShouldThrowExceptionWhenScriptNameIsNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> scriptOps.call(null));
- }
-
- @Test // DATAMONGO-479
- void callShouldThrowExceptionWhenScriptNameIsEmpty() {
- assertThatIllegalArgumentException().isThrownBy(() -> scriptOps.call(""));
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DocumentTestUtils.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DocumentTestUtils.java
deleted file mode 100644
index bc7bddacd2..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DocumentTestUtils.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright 2012-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.util.Iterator;
-import java.util.List;
-
-import org.bson.Document;
-
-import com.mongodb.BasicDBList;
-
-/**
- * Helper classes to ease assertions on {@link Document}s.
- *
- * @author Oliver Gierke
- * @author Mark Paluch
- */
-public abstract class DocumentTestUtils {
-
- private DocumentTestUtils() {}
-
- /**
- * Expects the field with the given key to be not {@literal null} and a {@link Document} in turn and returns it.
- *
- * @param source the {@link Document} to lookup the nested one
- * @param key the key of the field to lokup the nested {@link Document}
- * @return
- */
- public static Document getAsDocument(Document source, String key) {
- return getTypedValue(source, key, Document.class);
- }
-
- /**
- * Expects the field with the given key to be not {@literal null} and a {@link BasicDBList}.
- *
- * @param source the {@link Document} to lookup the {@link List} in
- * @param key the key of the field to find the {@link List} in
- * @return
- */
- public static List getAsDBList(Document source, String key) {
- return getTypedValue(source, key, List.class);
- }
-
- /**
- * Expects the list element with the given index to be a non-{@literal null} {@link Document} and returns it.
- *
- * @param source the {@link List} to look up the {@link Document} element in
- * @param index the index of the element expected to contain a {@link Document}
- * @return
- */
- public static Document getAsDocument(List> source, int index) {
-
- assertThat(source.size()).isGreaterThanOrEqualTo(index + 1);
- Object value = source.get(index);
- assertThat(value).isInstanceOf(Document.class);
- return (Document) value;
- }
-
- @SuppressWarnings("unchecked")
- public static T getTypedValue(Document source, String key, Class type) {
-
- Object value = source.get(key);
- assertThat(value).isNotNull();
- assertThat(value).isInstanceOf(type);
-
- return (T) value;
- }
-
- public static void assertTypeHint(Document document, Class> type) {
- assertTypeHint(document, type.getName());
- }
-
- public static void assertTypeHint(Document document, String expectedTypeString) {
-
- Iterator keyIterator = document.keySet().iterator();
- while (keyIterator.hasNext()) {
- String key = keyIterator.next();
- if (key.equals("_class")) {
- assertThat(document.get(key)).isEqualTo(expectedTypeString);
- assertThat(keyIterator.hasNext()).isFalse();
- return;
- }
- }
-
- fail(String.format("Expected to find type info %s in %s.", document, expectedTypeString));
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/EntityOperationUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/EntityOperationUnitTests.java
deleted file mode 100644
index d24a8e8027..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/EntityOperationUnitTests.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.core.convert.ConversionService;
-import org.springframework.core.convert.support.DefaultConversionService;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.mongodb.core.EntityOperations.AdaptibleEntity;
-import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
-
-/**
- * @author Christoph Strobl
- */
-public class EntityOperationUnitTests {
-
- EntityOperations ops;
- MongoMappingContext mappingContext = new MongoMappingContext();
- ConversionService conversionService = new DefaultConversionService();
-
- @BeforeEach
- public void setUp() {
- ops = new EntityOperations(mappingContext);
- }
-
- @Test // DATAMONGO-2293
- public void populateIdShouldReturnTargetBeanWhenIdIsNull() {
- assertThat(initAdaptibleEntity(new DomainTypeWithIdProperty()).populateIdIfNecessary(null)).isNotNull();
- }
-
- AdaptibleEntity initAdaptibleEntity(T source) {
- return ops.forEntity(source, conversionService);
- }
-
- private static class DomainTypeWithIdProperty {
-
- @Id String id;
- String value;
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableAggregationOperationSupportUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableAggregationOperationSupportUnitTests.java
deleted file mode 100644
index 8b35793944..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableAggregationOperationSupportUnitTests.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright 2017-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.ArgumentMatchers.*;
-import static org.mockito.Mockito.*;
-import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.data.mongodb.core.aggregation.Aggregation;
-
-/**
- * Unit tests for {@link ExecutableAggregationOperationSupport}.
- *
- * @author Christoph Strobl
- */
-@ExtendWith(MockitoExtension.class)
-public class ExecutableAggregationOperationSupportUnitTests {
-
- @Mock MongoTemplate template;
- private ExecutableAggregationOperationSupport opSupport;
-
- @BeforeEach
- void setUp() {
- opSupport = new ExecutableAggregationOperationSupport(template);
- }
-
- @Test // DATAMONGO-1563
- void throwsExceptionOnNullDomainType() {
- assertThatIllegalArgumentException().isThrownBy(() -> opSupport.aggregateAndReturn(null));
- }
-
- @Test // DATAMONGO-1563
- void throwsExceptionOnNullCollectionWhenUsed() {
- assertThatIllegalArgumentException()
- .isThrownBy(() -> opSupport.aggregateAndReturn(Person.class).inCollection(null));
- }
-
- @Test // DATAMONGO-1563
- void throwsExceptionOnEmptyCollectionWhenUsed() {
- assertThatIllegalArgumentException().isThrownBy(() -> opSupport.aggregateAndReturn(Person.class).inCollection(""));
- }
-
- @Test // DATAMONGO-1563
- void throwsExceptionOnNullAggregation() {
- assertThatIllegalArgumentException().isThrownBy(() -> opSupport.aggregateAndReturn(Person.class).by(null));
- }
-
- @Test // DATAMONGO-1563
- void aggregateWithUntypedAggregationAndExplicitCollection() {
-
- opSupport.aggregateAndReturn(Person.class).inCollection("star-wars").by(newAggregation(project("foo"))).all();
-
- ArgumentCaptor captor = ArgumentCaptor.forClass(Class.class);
- verify(template).aggregate(any(Aggregation.class), eq("star-wars"), captor.capture());
- assertThat(captor.getValue()).isEqualTo(Person.class);
- }
-
- @Test // DATAMONGO-1563
- void aggregateWithUntypedAggregation() {
-
- when(template.getCollectionName(any(Class.class))).thenReturn("person");
-
- opSupport.aggregateAndReturn(Person.class).by(newAggregation(project("foo"))).all();
-
- ArgumentCaptor captor = ArgumentCaptor.forClass(Class.class);
-
- verify(template).getCollectionName(captor.capture());
- verify(template).aggregate(any(Aggregation.class), eq("person"), captor.capture());
-
- assertThat(captor.getAllValues()).containsExactly(Person.class, Person.class);
- }
-
- @Test // DATAMONGO-1563
- void aggregateWithTypeAggregation() {
-
- when(template.getCollectionName(any(Class.class))).thenReturn("person");
-
- opSupport.aggregateAndReturn(Jedi.class).by(newAggregation(Person.class, project("foo"))).all();
-
- ArgumentCaptor captor = ArgumentCaptor.forClass(Class.class);
-
- verify(template).getCollectionName(captor.capture());
- verify(template).aggregate(any(Aggregation.class), eq("person"), captor.capture());
-
- assertThat(captor.getAllValues()).containsExactly(Person.class, Jedi.class);
- }
-
- @Test // DATAMONGO-1563
- void aggregateStreamWithUntypedAggregationAndExplicitCollection() {
-
- opSupport.aggregateAndReturn(Person.class).inCollection("star-wars").by(newAggregation(project("foo"))).stream();
-
- ArgumentCaptor captor = ArgumentCaptor.forClass(Class.class);
- verify(template).aggregateStream(any(Aggregation.class), eq("star-wars"), captor.capture());
- assertThat(captor.getValue()).isEqualTo(Person.class);
- }
-
- @Test // DATAMONGO-1563
- void aggregateStreamWithUntypedAggregation() {
-
- when(template.getCollectionName(any(Class.class))).thenReturn("person");
-
- opSupport.aggregateAndReturn(Person.class).by(newAggregation(project("foo"))).stream();
-
- ArgumentCaptor captor = ArgumentCaptor.forClass(Class.class);
-
- verify(template).getCollectionName(captor.capture());
- verify(template).aggregateStream(any(Aggregation.class), eq("person"), captor.capture());
-
- assertThat(captor.getAllValues()).containsExactly(Person.class, Person.class);
- }
-
- @Test // DATAMONGO-1563
- void aggregateStreamWithTypeAggregation() {
-
- when(template.getCollectionName(any(Class.class))).thenReturn("person");
-
- opSupport.aggregateAndReturn(Jedi.class).by(newAggregation(Person.class, project("foo"))).stream();
-
- ArgumentCaptor captor = ArgumentCaptor.forClass(Class.class);
-
- verify(template).getCollectionName(captor.capture());
- verify(template).aggregateStream(any(Aggregation.class), eq("person"), captor.capture());
-
- assertThat(captor.getAllValues()).containsExactly(Person.class, Jedi.class);
- }
-
- static class Person {}
-
- static class Jedi {}
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableFindOperationSupportTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableFindOperationSupportTests.java
deleted file mode 100644
index 8ebf72e130..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableFindOperationSupportTests.java
+++ /dev/null
@@ -1,640 +0,0 @@
-/*
- * Copyright 2017-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-import static org.springframework.data.mongodb.core.query.Query.*;
-
-import lombok.AllArgsConstructor;
-import lombok.Data;
-import lombok.NoArgsConstructor;
-
-import java.util.Date;
-import java.util.stream.Stream;
-
-import org.bson.BsonString;
-import org.bson.BsonValue;
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.dao.IncorrectResultSizeDataAccessException;
-import org.springframework.dao.InvalidDataAccessApiUsageException;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.geo.GeoResults;
-import org.springframework.data.geo.Point;
-import org.springframework.data.mongodb.core.ExecutableFindOperation.TerminatingFind;
-import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
-import org.springframework.data.mongodb.core.index.GeospatialIndex;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.query.BasicQuery;
-import org.springframework.data.mongodb.core.query.NearQuery;
-import org.springframework.data.mongodb.test.util.MongoTemplateExtension;
-import org.springframework.data.mongodb.test.util.MongoTestTemplate;
-import org.springframework.data.mongodb.test.util.Template;
-
-/**
- * Integration tests for {@link ExecutableFindOperationSupport}.
- *
- * @author Christoph Strobl
- * @author Mark Paluch
- */
-@ExtendWith(MongoTemplateExtension.class)
-class ExecutableFindOperationSupportTests {
-
- private static final String STAR_WARS = "star-wars";
- private static final String STAR_WARS_PLANETS = "star-wars-universe";
-
- @Template(database = "executable-find-operation-support-tests", initialEntitySet = { Person.class, Planet.class }) //
- private static MongoTestTemplate template;
-
- private Person han;
- private Person luke;
-
- private Planet alderan;
- private Planet dantooine;
-
- @BeforeEach
- void setUp() {
-
- template.flush();
-
- template.indexOps(Planet.class).ensureIndex(
- new GeospatialIndex("coordinates").typed(GeoSpatialIndexType.GEO_2DSPHERE).named("planet-coordinate-idx"));
-
- initPersons();
- initPlanets();
- }
-
- @Test // DATAMONGO-1563
- void domainTypeIsRequired() {
- assertThatIllegalArgumentException().isThrownBy(() -> template.query(null));
- }
-
- @Test // DATAMONGO-1563
- void returnTypeIsRequiredOnSet() {
- assertThatIllegalArgumentException().isThrownBy(() -> template.query(Person.class).as(null));
- }
-
- @Test // DATAMONGO-1563
- void collectionIsRequiredOnSet() {
- assertThatIllegalArgumentException().isThrownBy(() -> template.query(Person.class).inCollection(null));
- }
-
- @Test // DATAMONGO-1563
- void findAll() {
- assertThat(template.query(Person.class).all()).containsExactlyInAnyOrder(han, luke);
- }
-
- @Test // DATAMONGO-1563
- void findAllWithCollection() {
- assertThat(template.query(Human.class).inCollection(STAR_WARS).all()).hasSize(2);
- }
-
- @Test // DATAMONGO-1563
- void findAllWithProjection() {
- assertThat(template.query(Person.class).as(Jedi.class).all()).hasOnlyElementsOfType(Jedi.class).hasSize(2);
- }
-
- @Test // DATAMONGO-2041
- void findAllWithProjectionOnEmbeddedType() {
-
- luke.father = new Person();
- luke.father.firstname = "anakin";
-
- template.save(luke);
-
- assertThat(template.query(Person.class).as(PersonDtoProjection.class).matching(query(where("id").is(luke.id)))
- .firstValue()).hasFieldOrPropertyWithValue("father", luke.father);
- }
-
- @Test // DATAMONGO-1733
- void findByReturningAllValuesAsClosedInterfaceProjection() {
-
- assertThat(template.query(Person.class).as(PersonProjection.class).all())
- .hasOnlyElementsOfTypes(PersonProjection.class);
- }
-
- @Test // DATAMONGO-1563
- void findAllBy() {
-
- assertThat(template.query(Person.class).matching(query(where("firstname").is("luke"))).all())
- .containsExactlyInAnyOrder(luke);
- }
-
- @Test // DATAMONGO-1563
- void findAllByWithCollectionUsingMappingInformation() {
-
- assertThat(template.query(Jedi.class).inCollection(STAR_WARS).matching(query(where("name").is("luke"))).all())
- .hasSize(1).hasOnlyElementsOfType(Jedi.class);
- }
-
- @Test // DATAMONGO-1563
- void findAllByWithCollection() {
- assertThat(template.query(Human.class).inCollection(STAR_WARS).matching(query(where("firstname").is("luke"))).all())
- .hasSize(1);
- }
-
- @Test // DATAMONGO-2323
- void findAllAsDocument() {
- assertThat(
- template.query(Document.class).inCollection(STAR_WARS).matching(query(where("firstname").is("luke"))).all())
- .hasSize(1);
- }
-
- @Test // DATAMONGO-1563
- void findAllByWithProjection() {
-
- assertThat(template.query(Person.class).as(Jedi.class).matching(query(where("firstname").is("luke"))).all())
- .hasOnlyElementsOfType(Jedi.class).hasSize(1);
- }
-
- @Test // DATAMONGO-1563
- void findBy() {
- assertThat(template.query(Person.class).matching(query(where("firstname").is("luke"))).one()).contains(luke);
- }
-
- @Test // DATAMONGO-2416
- void findByCriteria() {
- assertThat(template.query(Person.class).matching(where("firstname").is("luke")).one()).contains(luke);
- }
-
- @Test // DATAMONGO-1563
- void findByNoMatch() {
- assertThat(template.query(Person.class).matching(query(where("firstname").is("spock"))).one()).isEmpty();
- }
-
- @Test // DATAMONGO-1563
- void findByTooManyResults() {
- assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class)
- .isThrownBy(() -> template.query(Person.class).matching(query(where("firstname").in("han", "luke"))).one());
- }
-
- @Test // DATAMONGO-1726
- void findByReturningOneValue() {
- assertThat(template.query(Person.class).matching(query(where("firstname").is("luke"))).oneValue()).isEqualTo(luke);
- }
-
- @Test // DATAMONGO-1726
- void findByReturningOneValueButTooManyResults() {
- assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(
- () -> template.query(Person.class).matching(query(where("firstname").in("han", "luke"))).oneValue());
- }
-
- @Test // DATAMONGO-1726
- void findByReturningFirstValue() {
-
- assertThat(template.query(Person.class).matching(query(where("firstname").is("luke"))).firstValue())
- .isEqualTo(luke);
- }
-
- @Test // DATAMONGO-1726
- void findByReturningFirstValueForManyResults() {
-
- assertThat(template.query(Person.class).matching(query(where("firstname").in("han", "luke"))).firstValue())
- .isIn(han, luke);
- }
-
- @Test // DATAMONGO-1733
- void findByReturningFirstValueAsClosedInterfaceProjection() {
-
- PersonProjection result = template.query(Person.class).as(PersonProjection.class)
- .matching(query(where("firstname").is("han"))).firstValue();
-
- assertThat(result).isInstanceOf(PersonProjection.class);
- assertThat(result.getFirstname()).isEqualTo("han");
- }
-
- @Test // DATAMONGO-1733
- void findByReturningFirstValueAsOpenInterfaceProjection() {
-
- PersonSpELProjection result = template.query(Person.class).as(PersonSpELProjection.class)
- .matching(query(where("firstname").is("han"))).firstValue();
-
- assertThat(result).isInstanceOf(PersonSpELProjection.class);
- assertThat(result.getName()).isEqualTo("han");
- }
-
- @Test // DATAMONGO-1563
- void streamAll() {
-
- try (Stream stream = template.query(Person.class).stream()) {
- assertThat(stream).containsExactlyInAnyOrder(han, luke);
- }
- }
-
- @Test // DATAMONGO-1563
- void streamAllWithCollection() {
-
- try (Stream stream = template.query(Human.class).inCollection(STAR_WARS).stream()) {
- assertThat(stream).hasSize(2);
- }
- }
-
- @Test // DATAMONGO-1563
- void streamAllWithProjection() {
-
- try (Stream stream = template.query(Person.class).as(Jedi.class).stream()) {
- assertThat(stream).hasOnlyElementsOfType(Jedi.class).hasSize(2);
- }
- }
-
- @Test // DATAMONGO-1733
- void streamAllReturningResultsAsClosedInterfaceProjection() {
-
- TerminatingFind operation = template.query(Person.class).as(PersonProjection.class);
-
- assertThat(operation.stream()) //
- .hasSize(2) //
- .allSatisfy(it -> {
- assertThat(it).isInstanceOf(PersonProjection.class);
- assertThat(it.getFirstname()).isNotBlank();
- });
- }
-
- @Test // DATAMONGO-1733
- void streamAllReturningResultsAsOpenInterfaceProjection() {
-
- TerminatingFind operation = template.query(Person.class).as(PersonSpELProjection.class);
-
- assertThat(operation.stream()) //
- .hasSize(2) //
- .allSatisfy(it -> {
- assertThat(it).isInstanceOf(PersonSpELProjection.class);
- assertThat(it.getName()).isNotBlank();
- });
- }
-
- @Test // DATAMONGO-1563
- void streamAllBy() {
-
- try (Stream stream = template.query(Person.class).matching(query(where("firstname").is("luke"))).stream()) {
- assertThat(stream).containsExactlyInAnyOrder(luke);
- }
- }
-
- @Test // DATAMONGO-1563
- void findAllNearBy() {
-
- GeoResults results = template.query(Planet.class).near(NearQuery.near(-73.9667, 40.78).spherical(true))
- .all();
- assertThat(results.getContent()).hasSize(2);
- assertThat(results.getContent().get(0).getDistance()).isNotNull();
- }
-
- @Test // DATAMONGO-1563
- void findAllNearByWithCollectionAndProjection() {
-
- GeoResults results = template.query(Object.class).inCollection(STAR_WARS_PLANETS).as(Human.class)
- .near(NearQuery.near(-73.9667, 40.78).spherical(true)).all();
-
- assertThat(results.getContent()).hasSize(2);
- assertThat(results.getContent().get(0).getDistance()).isNotNull();
- assertThat(results.getContent().get(0).getContent()).isInstanceOf(Human.class);
- assertThat(results.getContent().get(0).getContent().getId()).isEqualTo("alderan");
- }
-
- @Test // DATAMONGO-1733
- void findAllNearByReturningGeoResultContentAsClosedInterfaceProjection() {
-
- GeoResults results = template.query(Planet.class).as(PlanetProjection.class)
- .near(NearQuery.near(-73.9667, 40.78).spherical(true)).all();
-
- assertThat(results.getContent()).allSatisfy(it -> {
-
- assertThat(it.getContent()).isInstanceOf(PlanetProjection.class);
- assertThat(it.getContent().getName()).isNotBlank();
- });
- }
-
- @Test // DATAMONGO-1733
- void findAllNearByReturningGeoResultContentAsOpenInterfaceProjection() {
-
- GeoResults results = template.query(Planet.class).as(PlanetSpELProjection.class)
- .near(NearQuery.near(-73.9667, 40.78).spherical(true)).all();
-
- assertThat(results.getContent()).allSatisfy(it -> {
-
- assertThat(it.getContent()).isInstanceOf(PlanetSpELProjection.class);
- assertThat(it.getContent().getId()).isNotBlank();
- });
- }
-
- @Test // DATAMONGO-1728
- void firstShouldReturnFirstEntryInCollection() {
- assertThat(template.query(Person.class).first()).isNotEmpty();
- }
-
- @Test // DATAMONGO-1734
- void countShouldReturnNrOfElementsInCollectionWhenNoQueryPresent() {
- assertThat(template.query(Person.class).count()).isEqualTo(2);
- }
-
- @Test // DATAMONGO-1734
- void countShouldReturnNrOfElementsMatchingQuery() {
-
- assertThat(template.query(Person.class).matching(query(where("firstname").is(luke.getFirstname()))).count())
- .isEqualTo(1);
- }
-
- @Test // DATAMONGO-1734
- void existsShouldReturnTrueIfAtLeastOneElementExistsInCollection() {
- assertThat(template.query(Person.class).exists()).isTrue();
- }
-
- @Test // DATAMONGO-1734
- void existsShouldReturnFalseIfNoElementExistsInCollection() {
-
- template.remove(new BasicQuery("{}"), STAR_WARS);
-
- assertThat(template.query(Person.class).exists()).isFalse();
- }
-
- @Test // DATAMONGO-1734
- void existsShouldReturnTrueIfAtLeastOneElementMatchesQuery() {
-
- assertThat(template.query(Person.class).matching(query(where("firstname").is(luke.getFirstname()))).exists())
- .isTrue();
- }
-
- @Test // DATAMONGO-1734
- void existsShouldReturnFalseWhenNoElementMatchesQuery() {
- assertThat(template.query(Person.class).matching(query(where("firstname").is("spock"))).exists()).isFalse();
- }
-
- @Test // DATAMONGO-1734
- void returnsTargetObjectDirectlyIfProjectionInterfaceIsImplemented() {
- assertThat(template.query(Person.class).as(Contact.class).all()).allMatch(it -> it instanceof Person);
- }
-
- @Test // DATAMONGO-1761
- void distinctReturnsEmptyListIfNoMatchFound() {
- assertThat(template.query(Person.class).distinct("actually-not-property-in-use").as(String.class).all()).isEmpty();
- }
-
- @Test // DATAMONGO-1761
- void distinctReturnsSimpleFieldValuesCorrectlyForCollectionHavingReturnTypeSpecifiedThatCanBeConvertedDirectlyByACodec() {
-
- Person anakin = new Person();
- anakin.firstname = "anakin";
- anakin.lastname = luke.lastname;
-
- template.save(anakin);
-
- assertThat(template.query(Person.class).distinct("lastname").as(String.class).all())
- .containsExactlyInAnyOrder("solo", "skywalker");
- }
-
- @Test // DATAMONGO-1761
- void distinctReturnsSimpleFieldValuesCorrectly() {
-
- Person anakin = new Person();
- anakin.firstname = "anakin";
- anakin.ability = "dark-lord";
-
- Person padme = new Person();
- padme.firstname = "padme";
- padme.ability = 42L;
-
- Person jaja = new Person();
- jaja.firstname = "jaja";
- jaja.ability = new Date();
-
- template.save(anakin);
- template.save(padme);
- template.save(jaja);
-
- assertThat(template.query(Person.class).distinct("ability").all()).containsExactlyInAnyOrder(anakin.ability,
- padme.ability, jaja.ability);
- }
-
- @Test // DATAMONGO-1761
- void distinctReturnsComplexValuesCorrectly() {
-
- Sith sith = new Sith();
- sith.rank = "lord";
-
- Person anakin = new Person();
- anakin.firstname = "anakin";
- anakin.ability = sith;
-
- template.save(anakin);
-
- assertThat(template.query(Person.class).distinct("ability").all()).containsExactlyInAnyOrder(anakin.ability);
- }
-
- @Test // DATAMONGO-1761
- void distinctReturnsComplexValuesCorrectlyHavingReturnTypeSpecified() {
-
- Sith sith = new Sith();
- sith.rank = "lord";
-
- Person anakin = new Person();
- anakin.firstname = "anakin";
- anakin.ability = sith;
-
- template.save(anakin);
-
- assertThat(template.query(Person.class).distinct("ability").as(Sith.class).all())
- .containsExactlyInAnyOrder((Sith) anakin.ability);
- }
-
- @Test // DATAMONGO-1761
- void distinctReturnsComplexValuesCorrectlyHavingReturnTypeDocumentSpecified() {
-
- Sith sith = new Sith();
- sith.rank = "lord";
-
- Person anakin = new Person();
- anakin.firstname = "anakin";
- anakin.ability = sith;
-
- template.save(anakin);
-
- assertThat(template.query(Person.class).distinct("ability").as(Document.class).all())
- .containsExactlyInAnyOrder(new Document("rank", "lord").append("_class", Sith.class.getName()));
- }
-
- @Test // DATAMONGO-1761
- void distinctMapsFieldNameCorrectly() {
-
- assertThat(template.query(Jedi.class).inCollection(STAR_WARS).distinct("name").as(String.class).all())
- .containsExactlyInAnyOrder("han", "luke");
- }
-
- @Test // DATAMONGO-1761
- void distinctReturnsRawValuesIfReturnTypeIsBsonValue() {
-
- assertThat(template.query(Person.class).distinct("lastname").as(BsonValue.class).all())
- .containsExactlyInAnyOrder(new BsonString("solo"), new BsonString("skywalker"));
- }
-
- @Test // DATAMONGO-1761
- void distinctReturnsValuesMappedToTheirJavaTypeEvenWhenNotExplicitlyDefinedByTheDomainType() {
-
- template.save(new Document("darth", "vader"), STAR_WARS);
-
- assertThat(template.query(Person.class).distinct("darth").all()).containsExactlyInAnyOrder("vader");
- }
-
- @Test // DATAMONGO-1761
- void distinctReturnsMappedDomainTypeForProjections() {
-
- luke.father = new Person();
- luke.father.firstname = "anakin";
-
- template.save(luke);
-
- assertThat(template.query(Person.class).distinct("father").as(Jedi.class).all())
- .containsExactlyInAnyOrder(new Jedi("anakin"));
- }
-
- @Test // DATAMONGO-1761
- void distinctAlllowsQueryUsingObjectSourceType() {
-
- luke.father = new Person();
- luke.father.firstname = "anakin";
-
- template.save(luke);
-
- assertThat(template.query(Object.class).inCollection(STAR_WARS).distinct("father").as(Jedi.class).all())
- .containsExactlyInAnyOrder(new Jedi("anakin"));
- }
-
- @Test // DATAMONGO-1761
- void distinctReturnsMappedDomainTypeExtractedFromPropertyWhenNoExplicitTypePresent() {
-
- luke.father = new Person();
- luke.father.firstname = "anakin";
-
- template.save(luke);
-
- Person expected = new Person();
- expected.firstname = luke.father.firstname;
-
- assertThat(template.query(Person.class).distinct("father").all()).containsExactlyInAnyOrder(expected);
- }
-
- @Test // DATAMONGO-1761
- void distinctThrowsExceptionWhenExplicitMappingTypeCannotBeApplied() {
- assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
- .isThrownBy(() -> template.query(Person.class).distinct("firstname").as(Long.class).all());
- }
-
- @Test // DATAMONGO-2507
- void distinctAppliesFilterQuery() {
-
- assertThat(template.query(Person.class).inCollection(STAR_WARS).distinct("firstname") //
- .matching(where("lastname").is(luke.lastname)) //
- .as(String.class) //
- .all() //
- ).containsExactlyInAnyOrder("luke");
- }
-
- interface Contact {}
-
- @Data
- @org.springframework.data.mongodb.core.mapping.Document(collection = STAR_WARS)
- static class Person implements Contact {
-
- @Id String id;
- String firstname;
- String lastname;
- Object ability;
- Person father;
- }
-
- interface PersonProjection {
- String getFirstname();
- }
-
- public interface PersonSpELProjection {
-
- @Value("#{target.firstname}")
- String getName();
- }
-
- static class PersonDtoProjection {
-
- @Field("firstname") String name;
- Person father;
- }
-
- @Data
- static class Human {
- @Id String id;
- }
-
- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- static class Jedi {
-
- @Field("firstname") String name;
- }
-
- @Data
- static class Sith {
-
- String rank;
- }
-
- @Data
- @AllArgsConstructor
- @org.springframework.data.mongodb.core.mapping.Document(collection = STAR_WARS_PLANETS)
- static class Planet {
-
- @Id String name;
- Point coordinates;
- }
-
- interface PlanetProjection {
- String getName();
- }
-
- interface PlanetSpELProjection {
-
- @Value("#{target.name}")
- String getId();
- }
-
- private void initPersons() {
-
- han = new Person();
- han.firstname = "han";
- han.lastname = "solo";
- han.id = "id-1";
-
- luke = new Person();
- luke.firstname = "luke";
- luke.lastname = "skywalker";
- luke.id = "id-2";
-
- template.save(han);
- template.save(luke);
- }
-
- private void initPlanets() {
-
- alderan = new Planet("alderan", new Point(-73.9836, 40.7538));
- dantooine = new Planet("dantooine", new Point(-73.9928, 40.7193));
-
- template.save(alderan);
- template.save(dantooine);
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableInsertOperationSupportUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableInsertOperationSupportUnitTests.java
deleted file mode 100644
index dfb4af90a4..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableInsertOperationSupportUnitTests.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright 2017-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.ArgumentMatchers.*;
-import static org.mockito.Mockito.*;
-
-import lombok.Data;
-
-import java.util.Arrays;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.data.annotation.Id;
-import org.springframework.data.mongodb.core.BulkOperations.BulkMode;
-
-/**
- * Unit tests for {@link ExecutableInsertOperationSupport}.
- *
- * @author Christoph Strobl
- * @author Mark Paluch
- */
-@ExtendWith(MockitoExtension.class)
-public class ExecutableInsertOperationSupportUnitTests {
-
- private static final String STAR_WARS = "star-wars";
-
- @Mock MongoTemplate template;
- @Mock BulkOperations bulkOperations;
-
- private ExecutableInsertOperationSupport ops;
-
- private Person luke, han;
-
- @BeforeEach
- void setUp() {
-
- ops = new ExecutableInsertOperationSupport(template);
-
- luke = new Person();
- luke.id = "id-1";
- luke.firstname = "luke";
-
- han = new Person();
- han.firstname = "han";
- han.id = "id-2";
- }
-
- @Test // DATAMONGO-1563
- void nullCollectionShouldThrowException() {
- assertThatIllegalArgumentException().isThrownBy(() -> ops.insert(Person.class).inCollection(null));
- }
-
- @Test // DATAMONGO-1563
- void nullBulkModeShouldThrowException() {
- assertThatIllegalArgumentException().isThrownBy(() -> ops.insert(Person.class).withBulkMode(null));
- }
-
- @Test // DATAMONGO-1563
- void insertShouldUseDerivedCollectionName() {
-
- when(template.getCollectionName(any(Class.class))).thenReturn(STAR_WARS);
-
- ops.insert(Person.class).one(luke);
-
- ArgumentCaptor captor = ArgumentCaptor.forClass(Class.class);
-
- verify(template).getCollectionName(captor.capture());
- verify(template).insert(eq(luke), eq(STAR_WARS));
-
- assertThat(captor.getAllValues()).containsExactly(Person.class);
- }
-
- @Test // DATAMONGO-1563
- void insertShouldUseExplicitCollectionName() {
-
- ops.insert(Person.class).inCollection(STAR_WARS).one(luke);
-
- verify(template, never()).getCollectionName(any(Class.class));
- verify(template).insert(eq(luke), eq(STAR_WARS));
- }
-
- @Test // DATAMONGO-1563
- void insertCollectionShouldDelegateCorrectly() {
-
- when(template.getCollectionName(any(Class.class))).thenReturn(STAR_WARS);
-
- ops.insert(Person.class).all(Arrays.asList(luke, han));
-
- verify(template).getCollectionName(any(Class.class));
- verify(template).insert(anyList(), eq(STAR_WARS));
- }
-
- @Test // DATAMONGO-1563
- void bulkInsertCollectionShouldDelegateCorrectly() {
-
- when(template.getCollectionName(any(Class.class))).thenReturn(STAR_WARS);
- when(template.bulkOps(any(), any(), any())).thenReturn(bulkOperations);
- when(bulkOperations.insert(anyList())).thenReturn(bulkOperations);
-
- ops.insert(Person.class).bulk(Arrays.asList(luke, han));
-
- ArgumentCaptor captor = ArgumentCaptor.forClass(Class.class);
-
- verify(template).getCollectionName(any(Class.class));
- verify(template).bulkOps(eq(BulkMode.ORDERED), captor.capture(), eq(STAR_WARS));
- verify(bulkOperations).insert(anyList());
- verify(bulkOperations).execute();
- }
-
- @Test // DATAMONGO-1563
- void bulkInsertWithBulkModeShouldDelegateCorrectly() {
-
- when(template.getCollectionName(any(Class.class))).thenReturn(STAR_WARS);
- when(template.bulkOps(any(), any(), any())).thenReturn(bulkOperations);
- when(bulkOperations.insert(anyList())).thenReturn(bulkOperations);
-
- ops.insert(Person.class).withBulkMode(BulkMode.UNORDERED).bulk(Arrays.asList(luke, han));
-
- ArgumentCaptor captor = ArgumentCaptor.forClass(Class.class);
-
- verify(template).getCollectionName(any(Class.class));
- verify(template).bulkOps(eq(BulkMode.UNORDERED), captor.capture(), eq(STAR_WARS));
- verify(bulkOperations).insert(anyList());
- verify(bulkOperations).execute();
- }
-
- @Data
- @org.springframework.data.mongodb.core.mapping.Document(collection = STAR_WARS)
- static class Person {
- @Id String id;
- String firstname;
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableMapReduceOperationSupportUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableMapReduceOperationSupportUnitTests.java
deleted file mode 100644
index d0aa83f445..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableMapReduceOperationSupportUnitTests.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright 2018-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.ArgumentMatchers.*;
-import static org.mockito.Mockito.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-
-import lombok.AllArgsConstructor;
-import lombok.Data;
-import lombok.NoArgsConstructor;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import org.springframework.data.annotation.Id;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions;
-import org.springframework.data.mongodb.core.query.BasicQuery;
-import org.springframework.data.mongodb.core.query.Query;
-
-/**
- * Unit tests for {@link ExecutableMapReduceOperationSupport}.
- *
- * @author Christoph Strobl
- * @author Mark Paluch
- * @currentRead Beyond the Shadows - Brent Weeks
- */
-@ExtendWith(MockitoExtension.class)
-class ExecutableMapReduceOperationSupportUnitTests {
-
- private static final String STAR_WARS = "star-wars";
- private static final String MAP_FUNCTION = "function() { emit(this.id, this.firstname) }";
- private static final String REDUCE_FUNCTION = "function(id, name) { return sum(id, name); }";
-
- @Mock MongoTemplate template;
-
- private ExecutableMapReduceOperationSupport mapReduceOpsSupport;
-
- @BeforeEach
- void setUp() {
- mapReduceOpsSupport = new ExecutableMapReduceOperationSupport(template);
- }
-
- @Test // DATAMONGO-1929
- void throwsExceptionOnNullTemplate() {
- assertThatIllegalArgumentException().isThrownBy(() -> new ExecutableMapReduceOperationSupport(null));
- }
-
- @Test // DATAMONGO-1929
- void throwsExceptionOnNullDomainType() {
- assertThatIllegalArgumentException().isThrownBy(() -> mapReduceOpsSupport.mapReduce(null));
- }
-
- @Test // DATAMONGO-1929
- void usesExtractedCollectionName() {
-
- when(template.getCollectionName(eq(Person.class))).thenReturn(STAR_WARS);
- mapReduceOpsSupport.mapReduce(Person.class).map(MAP_FUNCTION).reduce(REDUCE_FUNCTION).all();
-
- verify(template).mapReduce(any(Query.class), eq(Person.class), eq(STAR_WARS), eq(MAP_FUNCTION), eq(REDUCE_FUNCTION),
- isNull(), eq(Person.class));
- }
-
- @Test // DATAMONGO-1929
- void usesExplicitCollectionName() {
-
- mapReduceOpsSupport.mapReduce(Person.class).map(MAP_FUNCTION).reduce(REDUCE_FUNCTION)
- .inCollection("the-night-angel").all();
-
- verify(template).mapReduce(any(Query.class), eq(Person.class), eq("the-night-angel"), eq(MAP_FUNCTION),
- eq(REDUCE_FUNCTION), isNull(), eq(Person.class));
- }
-
- @Test // DATAMONGO-1929
- void usesMapReduceOptionsWhenPresent() {
-
- when(template.getCollectionName(eq(Person.class))).thenReturn(STAR_WARS);
- MapReduceOptions options = MapReduceOptions.options();
- mapReduceOpsSupport.mapReduce(Person.class).map(MAP_FUNCTION).reduce(REDUCE_FUNCTION).with(options).all();
-
- verify(template).mapReduce(any(Query.class), eq(Person.class), eq(STAR_WARS), eq(MAP_FUNCTION), eq(REDUCE_FUNCTION),
- eq(options), eq(Person.class));
- }
-
- @Test // DATAMONGO-1929
- void usesQueryWhenPresent() {
-
- when(template.getCollectionName(eq(Person.class))).thenReturn(STAR_WARS);
- Query query = new BasicQuery("{ 'lastname' : 'skywalker' }");
- mapReduceOpsSupport.mapReduce(Person.class).map(MAP_FUNCTION).reduce(REDUCE_FUNCTION).matching(query).all();
-
- verify(template).mapReduce(eq(query), eq(Person.class), eq(STAR_WARS), eq(MAP_FUNCTION), eq(REDUCE_FUNCTION),
- isNull(), eq(Person.class));
- }
-
- @Test // DATAMONGO-2416
- void usesCriteriaWhenPresent() {
-
- when(template.getCollectionName(eq(Person.class))).thenReturn(STAR_WARS);
- Query query = Query.query(where("lastname").is("skywalker"));
- mapReduceOpsSupport.mapReduce(Person.class).map(MAP_FUNCTION).reduce(REDUCE_FUNCTION)
- .matching(where("lastname").is("skywalker")).all();
-
- verify(template).mapReduce(eq(query), eq(Person.class), eq(STAR_WARS), eq(MAP_FUNCTION), eq(REDUCE_FUNCTION),
- isNull(), eq(Person.class));
- }
-
- @Test // DATAMONGO-1929
- void usesProjectionWhenPresent() {
-
- when(template.getCollectionName(eq(Person.class))).thenReturn(STAR_WARS);
- mapReduceOpsSupport.mapReduce(Person.class).map(MAP_FUNCTION).reduce(REDUCE_FUNCTION).as(Jedi.class).all();
-
- verify(template).mapReduce(any(Query.class), eq(Person.class), eq(STAR_WARS), eq(MAP_FUNCTION), eq(REDUCE_FUNCTION),
- isNull(), eq(Jedi.class));
- }
-
- interface Contact {}
-
- @Data
- @org.springframework.data.mongodb.core.mapping.Document(collection = STAR_WARS)
- static class Person implements Contact {
-
- @Id String id;
- String firstname;
- String lastname;
- Object ability;
- Person father;
- }
-
- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- static class Jedi {
-
- @Field("firstname") String name;
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableRemoveOperationSupportTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableRemoveOperationSupportTests.java
deleted file mode 100644
index aade6330b2..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableRemoveOperationSupportTests.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright 2017-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-import static org.springframework.data.mongodb.core.query.Query.*;
-
-import lombok.Data;
-
-import java.util.List;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.test.util.MongoTemplateExtension;
-import org.springframework.data.mongodb.test.util.MongoTestTemplate;
-import org.springframework.data.mongodb.test.util.Template;
-
-import com.mongodb.client.result.DeleteResult;
-
-/**
- * Integration tests for {@link ExecutableRemoveOperationSupport}.
- *
- * @author Christoph Strobl
- * @author Mark Paluch
- */
-@ExtendWith(MongoTemplateExtension.class)
-class ExecutableRemoveOperationSupportTests {
-
- private static final String STAR_WARS = "star-wars";
-
- @Template(initialEntitySet = Person.class) //
- private static MongoTestTemplate template;
-
- private Person han;
- private Person luke;
-
- @BeforeEach
- void setUp() {
-
- template.flush();
-
- han = new Person();
- han.firstname = "han";
- han.id = "id-1";
-
- luke = new Person();
- luke.firstname = "luke";
- luke.id = "id-2";
-
- template.save(han);
- template.save(luke);
- }
-
- @Test // DATAMONGO-1563
- void removeAll() {
-
- DeleteResult result = template.remove(Person.class).all();
-
- assertThat(result.getDeletedCount()).isEqualTo(2L);
- }
-
- @Test // DATAMONGO-1563
- void removeAllMatching() {
-
- DeleteResult result = template.remove(Person.class).matching(query(where("firstname").is("han"))).all();
-
- assertThat(result.getDeletedCount()).isEqualTo(1L);
- }
-
- @Test // DATAMONGO-2416
- void removeAllMatchingCriteria() {
-
- DeleteResult result = template.remove(Person.class).matching(where("firstname").is("han")).all();
-
- assertThat(result.getDeletedCount()).isEqualTo(1L);
- }
-
- @Test // DATAMONGO-1563
- void removeAllMatchingWithAlternateDomainTypeAndCollection() {
-
- DeleteResult result = template.remove(Jedi.class).inCollection(STAR_WARS).matching(query(where("name").is("luke")))
- .all();
-
- assertThat(result.getDeletedCount()).isEqualTo(1L);
- }
-
- @Test // DATAMONGO-1563
- void removeAndReturnAllMatching() {
-
- List result = template.remove(Person.class).matching(query(where("firstname").is("han"))).findAndRemove();
-
- assertThat(result).containsExactly(han);
- }
-
- @Data
- @org.springframework.data.mongodb.core.mapping.Document(collection = STAR_WARS)
- static class Person {
- @Id String id;
- String firstname;
- }
-
- @Data
- static class Jedi {
-
- @Field("firstname") String name;
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableUpdateOperationSupportTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableUpdateOperationSupportTests.java
deleted file mode 100644
index d103b73614..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ExecutableUpdateOperationSupportTests.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright 2017-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-import static org.springframework.data.mongodb.core.query.Query.*;
-
-import lombok.Data;
-
-import java.util.Optional;
-
-import org.bson.BsonString;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.query.Query;
-import org.springframework.data.mongodb.core.query.Update;
-import org.springframework.data.mongodb.test.util.MongoTemplateExtension;
-import org.springframework.data.mongodb.test.util.MongoTestTemplate;
-import org.springframework.data.mongodb.test.util.Template;
-
-import com.mongodb.client.result.UpdateResult;
-
-/**
- * Integration tests for {@link ExecutableUpdateOperationSupport}.
- *
- * @author Christoph Strobl
- * @author Mark Paluch
- */
-@ExtendWith(MongoTemplateExtension.class)
-class ExecutableUpdateOperationSupportTests {
-
- private static final String STAR_WARS = "star-wars";
-
- @Template(initialEntitySet = { Human.class, Jedi.class, Person.class }) //
- private static MongoTestTemplate template;
-
- private Person han;
- private Person luke;
-
- @BeforeEach
- void setUp() {
-
- template.flush();
-
- han = new Person();
- han.firstname = "han";
- han.id = "id-1";
-
- luke = new Person();
- luke.firstname = "luke";
- luke.id = "id-2";
-
- template.save(han);
- template.save(luke);
- }
-
- @Test // DATAMONGO-1563
- void domainTypeIsRequired() {
- assertThatIllegalArgumentException().isThrownBy(() -> template.update(null));
- }
-
- @Test // DATAMONGO-1563
- void updateIsRequired() {
- assertThatIllegalArgumentException().isThrownBy(() -> template.update(Person.class).apply(null));
- }
-
- @Test // DATAMONGO-1563
- void collectionIsRequiredOnSet() {
- assertThatIllegalArgumentException().isThrownBy(() -> template.update(Person.class).inCollection(null));
- }
-
- @Test // DATAMONGO-1563
- void findAndModifyOptionsAreRequiredOnSet() {
- assertThatIllegalArgumentException()
- .isThrownBy(() -> template.update(Person.class).apply(new Update()).withOptions(null));
- }
-
- @Test // DATAMONGO-1563
- void updateFirst() {
-
- UpdateResult result = template.update(Person.class).apply(new Update().set("firstname", "Han")).first();
-
- assertThat(result.getModifiedCount()).isEqualTo(1L);
- assertThat(result.getUpsertedId()).isNull();
- }
-
- @Test // DATAMONGO-1563
- void updateAll() {
-
- UpdateResult result = template.update(Person.class).apply(new Update().set("firstname", "Han")).all();
-
- assertThat(result.getModifiedCount()).isEqualTo(2L);
- assertThat(result.getUpsertedId()).isNull();
- }
-
- @Test // DATAMONGO-1563
- void updateAllMatching() {
-
- UpdateResult result = template.update(Person.class).matching(queryHan()).apply(new Update().set("firstname", "Han"))
- .all();
-
- assertThat(result.getModifiedCount()).isEqualTo(1L);
- assertThat(result.getUpsertedId()).isNull();
- }
-
- @Test // DATAMONGO-2416
- void updateAllMatchingCriteria() {
-
- UpdateResult result = template.update(Person.class).matching(where("id").is(han.getId()))
- .apply(new Update().set("firstname", "Han"))
- .all();
-
- assertThat(result.getModifiedCount()).isEqualTo(1L);
- assertThat(result.getUpsertedId()).isNull();
- }
-
- @Test // DATAMONGO-1563
- void updateWithDifferentDomainClassAndCollection() {
-
- UpdateResult result = template.update(Jedi.class).inCollection(STAR_WARS)
- .matching(query(where("_id").is(han.getId()))).apply(new Update().set("name", "Han")).all();
-
- assertThat(result.getModifiedCount()).isEqualTo(1L);
- assertThat(result.getUpsertedId()).isNull();
- assertThat(template.findOne(queryHan(), Person.class)).isNotEqualTo(han).hasFieldOrPropertyWithValue("firstname",
- "Han");
- }
-
- @Test // DATAMONGO-1719
- void findAndModifyValue() {
-
- Person result = template.update(Person.class).matching(queryHan()).apply(new Update().set("firstname", "Han"))
- .findAndModifyValue();
-
- assertThat(result).isEqualTo(han);
- assertThat(template.findOne(queryHan(), Person.class)).isNotEqualTo(han).hasFieldOrPropertyWithValue("firstname",
- "Han");
- }
-
- @Test // DATAMONGO-1563
- void findAndModify() {
-
- Optional result = template.update(Person.class).matching(queryHan())
- .apply(new Update().set("firstname", "Han")).findAndModify();
-
- assertThat(result).contains(han);
- assertThat(template.findOne(queryHan(), Person.class)).isNotEqualTo(han).hasFieldOrPropertyWithValue("firstname",
- "Han");
- }
-
- @Test // DATAMONGO-1563
- void findAndModifyWithDifferentDomainTypeAndCollection() {
-
- Optional result = template.update(Jedi.class).inCollection(STAR_WARS)
- .matching(query(where("_id").is(han.getId()))).apply(new Update().set("name", "Han")).findAndModify();
-
- assertThat(result.get()).hasFieldOrPropertyWithValue("name", "han");
- assertThat(template.findOne(queryHan(), Person.class)).isNotEqualTo(han).hasFieldOrPropertyWithValue("firstname",
- "Han");
- }
-
- @Test // DATAMONGO-1563
- void findAndModifyWithOptions() {
-
- Optional result = template.update(Person.class).matching(queryHan())
- .apply(new Update().set("firstname", "Han")).withOptions(FindAndModifyOptions.options().returnNew(true))
- .findAndModify();
-
- assertThat(result.get()).isNotEqualTo(han).hasFieldOrPropertyWithValue("firstname", "Han");
- }
-
- @Test // DATAMONGO-1563
- void upsert() {
-
- UpdateResult result = template.update(Person.class).matching(query(where("id").is("id-3")))
- .apply(new Update().set("firstname", "Chewbacca")).upsert();
-
- assertThat(result.getModifiedCount()).isEqualTo(0L);
- assertThat(result.getUpsertedId()).isEqualTo(new BsonString("id-3"));
- }
-
- @Test // DATAMONGO-1827
- void findAndReplaceValue() {
-
- Person luke = new Person();
- luke.firstname = "Luke";
-
- Person result = template.update(Person.class).matching(queryHan()).replaceWith(luke).findAndReplaceValue();
-
- assertThat(result).isEqualTo(han);
- assertThat(template.findOne(queryHan(), Person.class)).isNotEqualTo(han).hasFieldOrPropertyWithValue("firstname",
- "Luke");
- }
-
- @Test // DATAMONGO-1827
- void findAndReplace() {
-
- Person luke = new Person();
- luke.firstname = "Luke";
-
- Optional result = template.update(Person.class).matching(queryHan()).replaceWith(luke).findAndReplace();
-
- assertThat(result).contains(han);
- assertThat(template.findOne(queryHan(), Person.class)).isNotEqualTo(han).hasFieldOrPropertyWithValue("firstname",
- "Luke");
- }
-
- @Test // DATAMONGO-1827
- void findAndReplaceWithCollection() {
-
- Person luke = new Person();
- luke.firstname = "Luke";
-
- Optional result = template.update(Person.class).inCollection(STAR_WARS).matching(queryHan())
- .replaceWith(luke).findAndReplace();
-
- assertThat(result).contains(han);
- assertThat(template.findOne(queryHan(), Person.class)).isNotEqualTo(han).hasFieldOrPropertyWithValue("firstname",
- "Luke");
- }
-
- @Test // DATAMONGO-1827
- void findAndReplaceWithOptions() {
-
- Person luke = new Person();
- luke.firstname = "Luke";
-
- Person result = template.update(Person.class).matching(queryHan()).replaceWith(luke)
- .withOptions(FindAndReplaceOptions.options().returnNew()).findAndReplaceValue();
-
- assertThat(result).isNotEqualTo(han).hasFieldOrPropertyWithValue("firstname", "Luke");
- }
-
- @Test // DATAMONGO-1827
- void findAndReplaceWithProjection() {
-
- Person luke = new Person();
- luke.firstname = "Luke";
-
- Jedi result = template.update(Person.class).matching(queryHan()).replaceWith(luke).as(Jedi.class)
- .findAndReplaceValue();
-
- assertThat(result.getName()).isEqualTo(han.firstname);
- }
-
- private Query queryHan() {
- return query(where("id").is(han.getId()));
- }
-
- @Data
- @org.springframework.data.mongodb.core.mapping.Document(collection = STAR_WARS)
- static class Person {
- @Id String id;
- String firstname;
- }
-
- @Data
- static class Human {
- @Id String id;
- }
-
- @Data
- static class Jedi {
-
- @Field("firstname") String name;
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Friend.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Friend.java
deleted file mode 100644
index a1e6a56496..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Friend.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2010-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-public class Friend {
-
- private String id;
-
- private String firstName;
-
- private int age;
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public String getFirstName() {
- return firstName;
- }
-
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/GeoCommandStatisticsUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/GeoCommandStatisticsUnitTests.java
deleted file mode 100644
index 40f56a61ba..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/GeoCommandStatisticsUnitTests.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright 2016-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.bson.Document;
-import org.junit.jupiter.api.Test;
-
-/**
- * Unit tests for {@link GeoCommandStatistics}.
- *
- * @author Oliver Gierke
- * @author Mark Paluch
- * @soundtrack Fruitcake - Jeff Coffin (The Inside of the Outside)
- */
-public class GeoCommandStatisticsUnitTests {
-
- @Test // DATAMONGO-1361
- public void rejectsNullCommandResult() {
- assertThatIllegalArgumentException().isThrownBy(() -> GeoCommandStatistics.from(null));
- }
-
- @Test // DATAMONGO-1361
- public void fallsBackToNanIfNoAverageDistanceIsAvailable() {
-
- GeoCommandStatistics statistics = GeoCommandStatistics.from(new Document("stats", null));
- assertThat(statistics.getAverageDistance()).isNaN();
-
- statistics = GeoCommandStatistics.from(new Document("stats", new Document()));
- assertThat(statistics.getAverageDistance()).isNaN();
- }
-
- @Test // DATAMONGO-1361
- public void returnsAverageDistanceIfPresent() {
-
- GeoCommandStatistics statistics = GeoCommandStatistics
- .from(new Document("stats", new Document("avgDistance", 1.5)));
-
- assertThat(statistics.getAverageDistance()).isEqualTo(1.5);
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/JmxServer.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/JmxServer.java
deleted file mode 100644
index e3cafe93b2..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/JmxServer.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 2002-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-
-/**
- * Server application than can be run as an app or unit test.
- *
- * @author Mark Pollack
- * @author Oliver Gierke
- */
-public class JmxServer {
-
- public static void main(String[] args) {
- new JmxServer().run();
- }
-
- @SuppressWarnings("resource")
- public void run() {
- new ClassPathXmlApplicationContext(new String[] { "infrastructure.xml", "server-jmx.xml" });
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/JsonSchemaQueryTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/JsonSchemaQueryTests.java
deleted file mode 100644
index f59b87f191..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/JsonSchemaQueryTests.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Copyright 2018-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-import static org.springframework.data.mongodb.core.query.Query.*;
-import static org.springframework.data.mongodb.core.schema.JsonSchemaProperty.*;
-
-import lombok.Data;
-import reactor.test.StepVerifier;
-
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.schema.MongoJsonSchema;
-import org.springframework.data.mongodb.test.util.Client;
-import org.springframework.data.mongodb.test.util.MongoTemplateExtension;
-import org.springframework.data.mongodb.test.util.MongoTestTemplate;
-import org.springframework.data.mongodb.test.util.Template;
-
-/**
- * @author Christoph Strobl
- * @author Mark Paluch
- */
-@ExtendWith(MongoTemplateExtension.class)
-public class JsonSchemaQueryTests {
-
- public static final String DATABASE_NAME = "json-schema-query-tests";
-
- static @Client com.mongodb.reactivestreams.client.MongoClient reactiveClient;
-
- @Template(database = DATABASE_NAME, initialEntitySet = Person.class) //
- static MongoTestTemplate template;
-
- Person jellyBelly, roseSpringHeart, kazmardBoombub;
-
- @BeforeEach
- public void setUp() {
-
- template.flush();
-
- jellyBelly = new Person();
- jellyBelly.id = "1";
- jellyBelly.name = "Jelly Belly";
- jellyBelly.gender = Gender.PIXY;
- jellyBelly.address = new Address();
- jellyBelly.address.city = "Candy Hill";
- jellyBelly.address.street = "Apple Mint Street";
- jellyBelly.value = 42;
-
- roseSpringHeart = new Person();
- roseSpringHeart.id = "2";
- roseSpringHeart.name = "Rose SpringHeart";
- roseSpringHeart.gender = Gender.UNICORN;
- roseSpringHeart.address = new Address();
- roseSpringHeart.address.city = "Rainbow Valley";
- roseSpringHeart.address.street = "Twinkle Ave.";
- roseSpringHeart.value = 42L;
-
- kazmardBoombub = new Person();
- kazmardBoombub.id = "3";
- kazmardBoombub.name = "Kazmard Boombub";
- kazmardBoombub.gender = Gender.GOBLIN;
- kazmardBoombub.value = "green";
-
- template.save(jellyBelly);
- template.save(roseSpringHeart);
- template.save(kazmardBoombub);
- }
-
- @Test // DATAMONGO-1835
- public void findsDocumentsWithRequiredFieldsCorrectly() {
-
- MongoJsonSchema schema = MongoJsonSchema.builder().required("address").build();
-
- assertThat(template.find(query(matchingDocumentStructure(schema)), Person.class))
- .containsExactlyInAnyOrder(jellyBelly, roseSpringHeart);
- }
-
- @Test // DATAMONGO-1835
- public void findsDocumentsWithRequiredFieldsReactively() {
-
- MongoJsonSchema schema = MongoJsonSchema.builder().required("address").build();
-
- new ReactiveMongoTemplate(reactiveClient, DATABASE_NAME)
- .find(query(matchingDocumentStructure(schema)), Person.class).as(StepVerifier::create).expectNextCount(2)
- .verifyComplete();
- }
-
- @Test // DATAMONGO-1835
- public void findsDocumentsWithBsonFieldTypesCorrectly() {
-
- MongoJsonSchema schema = MongoJsonSchema.builder().property(int32("value")).build();
-
- assertThat(template.find(query(matchingDocumentStructure(schema)), Person.class))
- .containsExactlyInAnyOrder(jellyBelly);
- }
-
- @Test // DATAMONGO-1835
- public void findsDocumentsWithJsonFieldTypesCorrectly() {
-
- MongoJsonSchema schema = MongoJsonSchema.builder().property(number("value")).build();
-
- assertThat(template.find(query(matchingDocumentStructure(schema)), Person.class))
- .containsExactlyInAnyOrder(jellyBelly, roseSpringHeart);
- }
-
- @Test // DATAMONGO-1835
- public void combineSchemaWithOtherCriteria() {
-
- MongoJsonSchema schema = MongoJsonSchema.builder().property(number("value")).build();
-
- assertThat(
- template.find(query(matchingDocumentStructure(schema).and("name").is(roseSpringHeart.name)), Person.class))
- .containsExactlyInAnyOrder(roseSpringHeart);
- }
-
- @Test // DATAMONGO-1835
- public void usesMappedFieldNameForRequiredProperties() {
-
- MongoJsonSchema schema = MongoJsonSchema.builder().required("name").build();
-
- assertThat(template.find(query(matchingDocumentStructure(schema)), Person.class))
- .containsExactlyInAnyOrder(jellyBelly, roseSpringHeart, kazmardBoombub);
- }
-
- @Test // DATAMONGO-1835
- public void usesMappedFieldNameForProperties() {
-
- MongoJsonSchema schema = MongoJsonSchema.builder().property(string("name").matching("^R.*")).build();
-
- assertThat(template.find(query(matchingDocumentStructure(schema)), Person.class))
- .containsExactlyInAnyOrder(roseSpringHeart);
- }
-
- @Test // DATAMONGO-1835
- public void mapsNestedFieldName() {
-
- MongoJsonSchema schema = MongoJsonSchema.builder() //
- .required("address") //
- .property(object("address").properties(string("street").matching("^Apple.*"))).build();
-
- assertThat(template.find(query(matchingDocumentStructure(schema)), Person.class))
- .containsExactlyInAnyOrder(jellyBelly);
- }
-
- @Test // DATAMONGO-1835
- public void mapsEnumValuesCorrectly() {
-
- MongoJsonSchema schema = MongoJsonSchema.builder()
- .property(untyped("gender").possibleValues(Gender.PIXY, Gender.GOBLIN)).build();
-
- assertThat(template.find(query(matchingDocumentStructure(schema)), Person.class))
- .containsExactlyInAnyOrder(jellyBelly, kazmardBoombub);
- }
-
- @Test // DATAMONGO-1835
- public void useTypeOperatorOnFieldLevel() {
- assertThat(template.find(query(where("value").type(Type.intType())), Person.class)).containsExactly(jellyBelly);
- }
-
- @Test // DATAMONGO-1835
- public void useTypeOperatorWithMultipleTypesOnFieldLevel() {
-
- assertThat(template.find(query(where("value").type(Type.intType(), Type.stringType())), Person.class))
- .containsExactlyInAnyOrder(jellyBelly, kazmardBoombub);
- }
-
- @Test // DATAMONGO-1835
- public void findsWithSchemaReturningRawDocument() {
-
- MongoJsonSchema schema = MongoJsonSchema.builder().required("address").build();
-
- assertThat(template.find(query(matchingDocumentStructure(schema)), Document.class,
- template.getCollectionName(Person.class))).hasSize(2);
- }
-
- @Data
- static class Person {
-
- @Id String id;
-
- @Field("full_name") String name;
- Gender gender;
- Address address;
- Object value;
- }
-
- @Data
- static class Address {
-
- String city;
-
- @Field("str") String street;
- }
-
- static enum Gender {
- PIXY, UNICORN, GOBLIN
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MappingMongoJsonSchemaCreatorUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MappingMongoJsonSchemaCreatorUnitTests.java
deleted file mode 100644
index 9c52bbe628..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MappingMongoJsonSchemaCreatorUnitTests.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.springframework.data.mongodb.test.util.Assertions.*;
-
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.data.annotation.Transient;
-import org.springframework.data.convert.WritingConverter;
-import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
-import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
-import org.springframework.data.mongodb.core.convert.NoOpDbRefResolver;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.mapping.FieldType;
-import org.springframework.data.mongodb.core.mapping.MongoId;
-import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
-import org.springframework.data.mongodb.core.schema.MongoJsonSchema;
-
-/**
- * Unit tests for {@link MappingMongoJsonSchemaCreator}.
- *
- * @author Christoph Strobl
- * @author Mark Paluch
- */
-public class MappingMongoJsonSchemaCreatorUnitTests {
-
- MappingMongoConverter converter;
- MongoMappingContext mappingContext;
- MappingMongoJsonSchemaCreator schemaCreator;
-
- @BeforeEach
- public void setUp() {
-
- mappingContext = new MongoMappingContext();
- converter = new MappingMongoConverter(NoOpDbRefResolver.INSTANCE, mappingContext);
- schemaCreator = new MappingMongoJsonSchemaCreator(converter);
- }
-
- @Test // DATAMONGO-1849
- public void simpleTypes() {
-
- MongoJsonSchema schema = schemaCreator.createSchemaFor(VariousFieldTypes.class);
-
- assertThat(schema.toDocument().get("$jsonSchema", Document.class)).isEqualTo(Document.parse(VARIOUS_FIELD_TYPES));
- }
-
- @Test // DATAMONGO-1849
- public void withRemappedIdType() {
-
- MongoJsonSchema schema = schemaCreator.createSchemaFor(WithExplicitMongoIdTypeMapping.class);
- assertThat(schema.toDocument().get("$jsonSchema", Document.class)).isEqualTo(WITH_EXPLICIT_MONGO_ID_TYPE_MAPPING);
- }
-
- @Test // DATAMONGO-1849
- public void cyclic() {
-
- MongoJsonSchema schema = schemaCreator.createSchemaFor(Cyclic.class);
- assertThat(schema.toDocument().get("$jsonSchema", Document.class)).isEqualTo(CYCLIC);
- }
-
- @Test // DATAMONGO-1849
- public void converterRegistered() {
-
- MappingMongoConverter converter = new MappingMongoConverter(NoOpDbRefResolver.INSTANCE, mappingContext);
- MongoCustomConversions mcc = new MongoCustomConversions(
- Collections.singletonList(SimpleToDocumentConverter.INSTANCE));
- converter.setCustomConversions(mcc);
- converter.afterPropertiesSet();
-
- schemaCreator = new MappingMongoJsonSchemaCreator(converter);
-
- MongoJsonSchema schema = schemaCreator.createSchemaFor(WithNestedDomainType.class);
- assertThat(schema.toDocument().get("$jsonSchema", Document.class)).isEqualTo(
- "{ 'type' : 'object', 'properties' : { '_id' : { 'type' : 'object' }, 'nested' : { 'type' : 'object' } } }");
- }
-
- // --> TYPES AND JSON
-
- // --> ENUM
-
- static final String JUST_SOME_ENUM = "{ 'type' : 'string', 'enum' : ['ONE', 'TWO'] }";
-
- enum JustSomeEnum {
- ONE, TWO
- }
-
- // --> VARIOUS FIELD TYPES
-
- static final String VARIOUS_FIELD_TYPES = "" + //
- "{" + //
- " 'type' : 'object'," + //
- " 'required' : ['primitiveInt']," + //
- " 'properties' : {" + //
- " 'id' : { 'type' : 'string' }," + //
- " 're-named-property' : { 'type' : 'string' }," + //
- " 'retypedProperty' : { 'bsonType' : 'javascript' }," + //
- " 'primitiveInt' : { 'bsonType' : 'int' }," + //
- " 'booleanProperty' : { 'type' : 'boolean' }," + //
- " 'longProperty' : { 'bsonType' : 'long' }," + //
- " 'intProperty' : { 'bsonType' : 'int' }," + //
- " 'dateProperty' : { 'bsonType' : 'date' }," + //
- " 'arrayProperty' : { 'type' : 'array' }," + //
- " 'binaryDataProperty' : { 'bsonType' : 'binData' }," + //
- " 'collectionProperty' : { 'type' : 'array' }," + //
- " 'mapProperty' : { 'type' : 'object' }," + //
- " 'objectProperty' : { 'type' : 'object' }," + //
- " 'enumProperty' : " + JUST_SOME_ENUM + //
- " }" + //
- "}";
-
- static class VariousFieldTypes {
-
- @Field("id") String id;
- @Field("re-named-property") String renamedProperty;
- @Field(targetType = FieldType.SCRIPT) String retypedProperty;
- @Transient String transientProperty;
- int primitiveInt;
- Boolean booleanProperty;
- Long longProperty;
- Integer intProperty;
- Date dateProperty;
- Object[] arrayProperty;
- byte[] binaryDataProperty;
- List collectionProperty;
- Map mapProperty;
- Object objectProperty;
- JustSomeEnum enumProperty;
- }
-
- // --> NESTED DOMAIN TYPE
-
- static final String WITH_NESTED_DOMAIN_TYPE = "" + //
- "{" + //
- " 'type' : 'object'," + //
- " 'properties' : {" + //
- " '_id' : { 'type' : 'object' }," + //
- " 'nested' : " + VARIOUS_FIELD_TYPES + //
- " }" + //
- "}";
-
- static class WithNestedDomainType {
-
- String id;
- VariousFieldTypes nested;
- }
-
- // --> EXPLICIT MONGO_ID MAPPING
-
- final String WITH_EXPLICIT_MONGO_ID_TYPE_MAPPING = "" + //
- "{" + //
- " 'type' : 'object'," + //
- " 'properties' : {" + //
- " '_id' : { 'bsonType' : 'objectId' }," + //
- " 'nested' : " + VARIOUS_FIELD_TYPES + //
- " }" + //
- "}";
-
- static class WithExplicitMongoIdTypeMapping {
-
- @MongoId(targetType = FieldType.OBJECT_ID) String id;
- VariousFieldTypes nested;
- }
-
- // --> OH NO - A CYCLIC PROPERTY RELATIONSHIP 😱
-
- static final String CYCLIC_FIN = "" + //
- "{" + //
- " 'type' : 'object'," + //
- " 'properties' : {" + //
- " 'root' : { 'type' : 'string' }" + //
- " 'cyclic' : { 'type' : 'object' }" + //
- " }" + //
- "}";
-
- static final String CYCLIC_2 = "" + //
- "{" + //
- " 'type' : 'object'," + //
- " 'properties' : {" + //
- " 'nested2' : { 'type' : 'string' }," + //
- " 'cyclic' : " + CYCLIC_FIN + //
- " }" + //
- "}";
-
- class Cyclic2 {
-
- String nested2;
- Cyclic cyclic;
- }
-
- static final String CYCLIC_1 = "" + //
- "{" + //
- " 'type' : 'object'," + //
- " 'properties' : {" + //
- " 'nested1' : { 'type' : 'string' }," + //
- " 'cyclic2' : " + CYCLIC_2 + //
- " }" + //
- "}";
-
- class Cyclic1 {
-
- String nested1;
- Cyclic2 cyclic2;
- }
-
- static final String CYCLIC = "" + //
- "{" + //
- " 'type' : 'object'," + //
- " 'properties' : {" + //
- " 'root' : { 'type' : 'string' }," + //
- " 'cyclic1' : " + CYCLIC_1 + //
- " }" + //
- "}";
-
- class Cyclic {
-
- String root;
- Cyclic1 cyclic1;
- }
-
- @WritingConverter
- enum SimpleToDocumentConverter
- implements org.springframework.core.convert.converter.Converter {
- INSTANCE;
-
- @Override
- public org.bson.Document convert(VariousFieldTypes source) {
- return null;
- }
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoAdminIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoAdminIntegrationTests.java
deleted file mode 100644
index 86ae1f73f4..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoAdminIntegrationTests.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright 2002-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import com.mongodb.client.MongoClient;
-
-/**
- * This test class assumes that you are already running the MongoDB server.
- *
- * @author Mark Pollack
- */
-@RunWith(SpringRunner.class)
-@ContextConfiguration("classpath:infrastructure.xml")
-public class MongoAdminIntegrationTests {
-
- private static final Log logger = LogFactory.getLog(MongoAdminIntegrationTests.class);
-
- @Autowired MongoClient mongoClient;
-
- MongoAdmin mongoAdmin;
-
- @Before
- public void setUp() {
- mongoAdmin = new MongoAdmin(mongoClient);
- }
-
- @Test
- public void serverStats() {
- logger.info("stats = " + mongoAdmin.getServerStatus());
- }
-
- @Test
- public void databaseStats() {
- logger.info(mongoAdmin.getDatabaseStats("testAdminDb"));
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoClientFactoryBeanUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoClientFactoryBeanUnitTests.java
deleted file mode 100644
index 6391f4b0f8..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoClientFactoryBeanUnitTests.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.util.concurrent.TimeUnit;
-
-import org.junit.jupiter.api.Test;
-
-import com.mongodb.ConnectionString;
-import com.mongodb.MongoClientSettings;
-import com.mongodb.ServerAddress;
-
-/**
- * Unit tests for {@link MongoClientFactoryBean}.
- *
- * @author Christoph Strobl
- */
-class MongoClientFactoryBeanUnitTests {
-
- static final String CONNECTION_STRING_STRING = "mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000";
- static final ConnectionString CONNECTION_STRING = new ConnectionString(CONNECTION_STRING_STRING);
-
- @Test // DATAMONGO-2427
- void connectionStringParametersNotOverriddenByDefaults() {
-
- MongoClientFactoryBean factoryBean = new MongoClientFactoryBean();
- factoryBean.setConnectionString(CONNECTION_STRING);
- factoryBean.setMongoClientSettings(MongoClientSettings.builder().build());
-
- MongoClientSettings settings = factoryBean.computeClientSetting();
-
- assertThat(settings.getClusterSettings().getRequiredReplicaSetName()).isEqualTo("test");
- assertThat(settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)).isEqualTo(300000);
- assertThat(settings.getClusterSettings().getHosts()).hasSize(2);
- }
-
- @Test // DATAMONGO-2427
- void hostPortParametersNotOverriddenByDefaults() {
-
- MongoClientFactoryBean factoryBean = new MongoClientFactoryBean();
- factoryBean.setPort(2500);
- factoryBean.setHost("db2.example.net");
- factoryBean.setReplicaSet("rs0");
- factoryBean.setMongoClientSettings(MongoClientSettings.builder().build());
-
- MongoClientSettings settings = factoryBean.computeClientSetting();
-
- assertThat(settings.getClusterSettings().getRequiredReplicaSetName()).isEqualTo("rs0");
- assertThat(settings.getClusterSettings().getHosts()).containsExactly(new ServerAddress("db2.example.net", 2500));
- }
-
- @Test // DATAMONGO-2427
- void explicitSettingsOverrideConnectionStringOnes() {
-
- MongoClientFactoryBean factoryBean = new MongoClientFactoryBean();
- factoryBean.setConnectionString(CONNECTION_STRING);
- factoryBean.setMongoClientSettings(
- MongoClientSettings.builder().applyToClusterSettings(it -> it.requiredReplicaSetName("rs0"))
- .applyToSocketSettings(it -> it.connectTimeout(100, TimeUnit.MILLISECONDS)).build());
-
- MongoClientSettings settings = factoryBean.computeClientSetting();
-
- assertThat(settings.getClusterSettings().getRequiredReplicaSetName()).isEqualTo("rs0");
- assertThat(settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)).isEqualTo(100);
- assertThat(settings.getClusterSettings().getHosts()).hasSize(2);
- }
-
- @Test // DATAMONGO-2427
- void hostAndPortPlusConnectionStringError() {
-
- MongoClientFactoryBean factoryBean = new MongoClientFactoryBean();
- factoryBean.setConnectionString(CONNECTION_STRING);
- factoryBean.setHost("localhost");
- factoryBean.setPort(27017);
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(factoryBean::createInstance);
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoClientSettingsFactoryBeanIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoClientSettingsFactoryBeanIntegrationTests.java
deleted file mode 100644
index 8b7e14db44..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoClientSettingsFactoryBeanIntegrationTests.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2015-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.jupiter.api.Test;
-
-import org.springframework.beans.factory.support.DefaultListableBeanFactory;
-import org.springframework.beans.factory.support.RootBeanDefinition;
-import org.springframework.data.mongodb.config.ReadPreferencePropertyEditor;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import com.mongodb.ReadPreference;
-
-/**
- * Integration tests for {@link MongoClientSettingsFactoryBean}.
- *
- * @author Christoph Strobl
- */
-public class MongoClientSettingsFactoryBeanIntegrationTests {
-
- @Test // DATAMONGO-1158
- public void convertsReadPreferenceConcernCorrectly() {
-
- RootBeanDefinition definition = new RootBeanDefinition(MongoClientSettingsFactoryBean.class);
- definition.getPropertyValues().addPropertyValue("readPreference", "NEAREST");
-
- DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
- factory.registerCustomEditor(ReadPreference.class, ReadPreferencePropertyEditor.class);
-
- factory.registerBeanDefinition("factory", definition);
-
- MongoClientSettingsFactoryBean bean = factory.getBean("&factory", MongoClientSettingsFactoryBean.class);
- assertThat(ReflectionTestUtils.getField(bean, "readPreference")).isEqualTo((Object) ReadPreference.nearest());
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoClientSettingsFactoryBeanUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoClientSettingsFactoryBeanUnitTests.java
deleted file mode 100644
index c4a22ab10e..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoClientSettingsFactoryBeanUnitTests.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.bson.UuidRepresentation;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.beans.factory.support.DefaultListableBeanFactory;
-import org.springframework.beans.factory.support.RootBeanDefinition;
-import org.springframework.data.mongodb.config.ReadConcernPropertyEditor;
-import org.springframework.data.mongodb.config.ReadPreferencePropertyEditor;
-import org.springframework.data.mongodb.config.UUidRepresentationPropertyEditor;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import com.mongodb.ReadConcern;
-import com.mongodb.ReadPreference;
-
-/**
- * Unit tests for {@link MongoClientSettingsFactoryBean}.
- *
- * @author Christoph Strobl
- */
-public class MongoClientSettingsFactoryBeanUnitTests {
-
- @Test // DATAMONGO-2384
- public void convertsReadPreferenceConcernCorrectly() {
-
- RootBeanDefinition definition = new RootBeanDefinition(MongoClientSettingsFactoryBean.class);
- definition.getPropertyValues().addPropertyValue("readPreference", "NEAREST");
-
- DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
- factory.registerCustomEditor(ReadPreference.class, ReadPreferencePropertyEditor.class);
-
- factory.registerBeanDefinition("factory", definition);
-
- MongoClientSettingsFactoryBean bean = factory.getBean("&factory", MongoClientSettingsFactoryBean.class);
- assertThat(ReflectionTestUtils.getField(bean, "readPreference")).isEqualTo(ReadPreference.nearest());
- }
-
- @Test // DATAMONGO-2384
- public void convertsReadConcernConcernCorrectly() {
-
- RootBeanDefinition definition = new RootBeanDefinition(MongoClientSettingsFactoryBean.class);
- definition.getPropertyValues().addPropertyValue("readConcern", "MAJORITY");
-
- DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
- factory.registerCustomEditor(ReadPreference.class, ReadConcernPropertyEditor.class);
-
- factory.registerBeanDefinition("factory", definition);
-
- MongoClientSettingsFactoryBean bean = factory.getBean("&factory", MongoClientSettingsFactoryBean.class);
- assertThat(ReflectionTestUtils.getField(bean, "readConcern")).isEqualTo(ReadConcern.MAJORITY);
- }
-
- @Test // DATAMONGO-2427
- public void convertsUuidRepresentationCorrectly() {
-
- RootBeanDefinition definition = new RootBeanDefinition(MongoClientSettingsFactoryBean.class);
- definition.getPropertyValues().addPropertyValue("uUidRepresentation", "STANDARD");
-
- DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
- factory.registerCustomEditor(ReadPreference.class, UUidRepresentationPropertyEditor.class);
-
- factory.registerBeanDefinition("factory", definition);
-
- MongoClientSettingsFactoryBean bean = factory.getBean("&factory", MongoClientSettingsFactoryBean.class);
- assertThat(ReflectionTestUtils.getField(bean, "uUidRepresentation")).isEqualTo(UuidRepresentation.STANDARD);
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoEncryptionSettingsFactoryBeanTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoEncryptionSettingsFactoryBeanTests.java
deleted file mode 100644
index 0ada9b2b6c..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoEncryptionSettingsFactoryBeanTests.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2019-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.jupiter.api.Test;
-import org.springframework.beans.factory.support.DefaultListableBeanFactory;
-import org.springframework.beans.factory.support.RootBeanDefinition;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import com.mongodb.AutoEncryptionSettings;
-
-/**
- * Integration tests for {@link MongoEncryptionSettingsFactoryBean}.
- *
- * @author Christoph Strobl
- */
-public class MongoEncryptionSettingsFactoryBeanTests {
-
- @Test // DATAMONGO-2306
- public void createsAutoEncryptionSettings() {
-
- RootBeanDefinition definition = new RootBeanDefinition(MongoEncryptionSettingsFactoryBean.class);
- definition.getPropertyValues().addPropertyValue("bypassAutoEncryption", true);
- definition.getPropertyValues().addPropertyValue("keyVaultNamespace", "ns");
-
- DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
- factory.registerBeanDefinition("factory", definition);
-
- MongoEncryptionSettingsFactoryBean bean = factory.getBean("&factory", MongoEncryptionSettingsFactoryBean.class);
- assertThat(ReflectionTestUtils.getField(bean, "bypassAutoEncryption")).isEqualTo(true);
-
- AutoEncryptionSettings target = factory.getBean(AutoEncryptionSettings.class);
- assertThat(target.getKeyVaultNamespace()).isEqualTo("ns");
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoExceptionTranslatorUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoExceptionTranslatorUnitTests.java
deleted file mode 100644
index 9f7cb92b46..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoExceptionTranslatorUnitTests.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright 2013-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.bson.BsonDocument;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.core.NestedRuntimeException;
-import org.springframework.dao.DataAccessException;
-import org.springframework.dao.DataAccessResourceFailureException;
-import org.springframework.dao.DuplicateKeyException;
-import org.springframework.dao.InvalidDataAccessApiUsageException;
-import org.springframework.dao.InvalidDataAccessResourceUsageException;
-import org.springframework.data.mongodb.ClientSessionException;
-import org.springframework.data.mongodb.MongoTransactionException;
-import org.springframework.data.mongodb.UncategorizedMongoDbException;
-import org.springframework.lang.Nullable;
-
-import com.mongodb.MongoCursorNotFoundException;
-import com.mongodb.MongoException;
-import com.mongodb.MongoInternalException;
-import com.mongodb.MongoSocketException;
-import com.mongodb.MongoSocketReadTimeoutException;
-import com.mongodb.MongoSocketWriteException;
-import com.mongodb.ServerAddress;
-
-/**
- * Unit tests for {@link MongoExceptionTranslator}.
- *
- * @author Michal Vich
- * @author Oliver Gierke
- * @author Christoph Strobl
- * @author Brice Vandeputte
- */
-class MongoExceptionTranslatorUnitTests {
-
- private static final String EXCEPTION_MESSAGE = "IOException";
- private MongoExceptionTranslator translator;
-
- @BeforeEach
- void setUp() {
- translator = new MongoExceptionTranslator();
- }
-
- @Test
- void translateDuplicateKey() {
-
- expectExceptionWithCauseMessage(
- translator.translateExceptionIfPossible(
- new com.mongodb.DuplicateKeyException(new BsonDocument(), new ServerAddress(), null)),
- DuplicateKeyException.class, null);
- }
-
- @Test // GH-3568
- void translateSocketException() {
-
- expectExceptionWithCauseMessage(
- translator.translateExceptionIfPossible(new MongoSocketException(EXCEPTION_MESSAGE, new ServerAddress())),
- DataAccessResourceFailureException.class, EXCEPTION_MESSAGE);
- }
-
- @Test // GH-3568
- void translateSocketExceptionSubclasses() {
-
- expectExceptionWithCauseMessage(
- translator.translateExceptionIfPossible(
- new MongoSocketWriteException("intermediate message", new ServerAddress(), new Exception(EXCEPTION_MESSAGE))
- ),
- DataAccessResourceFailureException.class, EXCEPTION_MESSAGE);
-
- expectExceptionWithCauseMessage(
- translator.translateExceptionIfPossible(
- new MongoSocketReadTimeoutException("intermediate message", new ServerAddress(), new Exception(EXCEPTION_MESSAGE))
- ),
- DataAccessResourceFailureException.class, EXCEPTION_MESSAGE);
-
- }
-
- @Test
- void translateCursorNotFound() {
-
- expectExceptionWithCauseMessage(
- translator.translateExceptionIfPossible(new MongoCursorNotFoundException(1L, new ServerAddress())),
- DataAccessResourceFailureException.class);
- }
-
- @Test
- void translateToDuplicateKeyException() {
-
- checkTranslatedMongoException(DuplicateKeyException.class, 11000);
- checkTranslatedMongoException(DuplicateKeyException.class, 11001);
- }
-
- @Test
- void translateToDataAccessResourceFailureException() {
-
- checkTranslatedMongoException(DataAccessResourceFailureException.class, 12000);
- checkTranslatedMongoException(DataAccessResourceFailureException.class, 13440);
- }
-
- @Test
- void translateToInvalidDataAccessApiUsageException() {
-
- checkTranslatedMongoException(InvalidDataAccessApiUsageException.class, 10003);
- checkTranslatedMongoException(InvalidDataAccessApiUsageException.class, 12001);
- checkTranslatedMongoException(InvalidDataAccessApiUsageException.class, 12010);
- checkTranslatedMongoException(InvalidDataAccessApiUsageException.class, 12011);
- checkTranslatedMongoException(InvalidDataAccessApiUsageException.class, 12012);
- }
-
- @Test
- void translateToUncategorizedMongoDbException() {
-
- MongoException exception = new MongoException(0, "");
- DataAccessException translatedException = translator.translateExceptionIfPossible(exception);
-
- expectExceptionWithCauseMessage(translatedException, UncategorizedMongoDbException.class);
- }
-
- @Test
- void translateMongoInternalException() {
-
- MongoInternalException exception = new MongoInternalException("Internal exception");
- DataAccessException translatedException = translator.translateExceptionIfPossible(exception);
-
- expectExceptionWithCauseMessage(translatedException, InvalidDataAccessResourceUsageException.class);
- }
-
- @Test
- void translateUnsupportedException() {
-
- RuntimeException exception = new RuntimeException();
- assertThat(translator.translateExceptionIfPossible(exception)).isNull();
- }
-
- @Test // DATAMONGO-2045
- void translateSessionExceptions() {
-
- checkTranslatedMongoException(ClientSessionException.class, 206);
- checkTranslatedMongoException(ClientSessionException.class, 213);
- checkTranslatedMongoException(ClientSessionException.class, 228);
- checkTranslatedMongoException(ClientSessionException.class, 264);
- }
-
- @Test // DATAMONGO-2045
- void translateTransactionExceptions() {
-
- checkTranslatedMongoException(MongoTransactionException.class, 217);
- checkTranslatedMongoException(MongoTransactionException.class, 225);
- checkTranslatedMongoException(MongoTransactionException.class, 244);
- checkTranslatedMongoException(MongoTransactionException.class, 251);
- checkTranslatedMongoException(MongoTransactionException.class, 256);
- checkTranslatedMongoException(MongoTransactionException.class, 257);
- checkTranslatedMongoException(MongoTransactionException.class, 263);
- checkTranslatedMongoException(MongoTransactionException.class, 267);
- }
-
- private void checkTranslatedMongoException(Class extends Exception> clazz, int code) {
-
- DataAccessException translated = translator.translateExceptionIfPossible(new MongoException(code, ""));
-
- assertThat(translated).as("Expected exception of type " + clazz.getName() + "!").isNotNull();
-
- Throwable cause = translated.getRootCause();
- assertThat(cause).isInstanceOf(MongoException.class);
- assertThat(((MongoException) cause).getCode()).isEqualTo(code);
- }
-
- private static void expectExceptionWithCauseMessage(@Nullable NestedRuntimeException e,
- Class extends NestedRuntimeException> type) {
- expectExceptionWithCauseMessage(e, type, null);
- }
-
- private static void expectExceptionWithCauseMessage(@Nullable NestedRuntimeException e,
- Class extends NestedRuntimeException> type, @Nullable String message) {
-
- assertThat(e).isInstanceOf(type);
-
- if (message != null) {
- assertThat(e.getRootCause()).isNotNull();
- assertThat(e.getRootCause().getMessage()).contains(message);
- }
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoOperationsUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoOperationsUnitTests.java
deleted file mode 100644
index 3bbff3fcde..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoOperationsUnitTests.java
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * Copyright 2011-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.bson.Document;
-import org.bson.conversions.Bson;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-import org.springframework.dao.DataAccessException;
-import org.springframework.data.geo.Point;
-import org.springframework.data.mapping.MappingException;
-import org.springframework.data.mapping.context.MappingContext;
-import org.springframework.data.mongodb.core.convert.AbstractMongoConverter;
-import org.springframework.data.mongodb.core.convert.MongoConverter;
-import org.springframework.data.mongodb.core.convert.MongoTypeMapper;
-import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
-import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
-import org.springframework.data.mongodb.core.query.NearQuery;
-import org.springframework.data.util.TypeInformation;
-
-import com.mongodb.DBRef;
-
-/**
- * Abstract base class for unit tests to specify behaviour we expect from {@link MongoOperations}. Subclasses return
- * instances of their implementation and thus can see if it correctly implements the {@link MongoOperations} interface.
- *
- * @author Oliver Gierke
- * @author Thomas Darimont
- * @author Christoph Strobl
- */
-@ExtendWith(MockitoExtension.class)
-public abstract class MongoOperationsUnitTests {
-
- @Mock CollectionCallback collectionCallback;
- @Mock DbCallback dbCallback;
-
- MongoConverter converter;
- Person person;
- List persons;
-
- @BeforeEach
- public final void operationsSetUp() {
-
- person = new Person("Oliver");
- persons = Arrays.asList(person);
-
- converter = new AbstractMongoConverter(null) {
-
- public void write(Object t, Bson bson) {
- ((Document) bson).put("firstName", person.getFirstName());
- }
-
- @SuppressWarnings("unchecked")
- public S read(Class clazz, Bson bson) {
- return (S) person;
- }
-
- public MappingContext extends MongoPersistentEntity>, MongoPersistentProperty> getMappingContext() {
- return null;
- }
-
- public Object convertToMongoType(Object obj, TypeInformation> typeInformation) {
- return null;
- }
-
- public DBRef toDBRef(Object object, MongoPersistentProperty referingProperty) {
- return null;
- }
-
- @Override
- public MongoTypeMapper getTypeMapper() {
- return null;
- }
- };
- }
-
- @Test
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public void rejectsNullForCollectionCallback() {
- assertThatIllegalArgumentException().isThrownBy(() -> getOperations().execute("test", (CollectionCallback) null));
- }
-
- @Test
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public void rejectsNullForCollectionCallback2() {
- assertThatIllegalArgumentException()
- .isThrownBy(() -> getOperations().execute("collection", (CollectionCallback) null));
- }
-
- @Test
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public void rejectsNullForDbCallback() {
- assertThatIllegalArgumentException().isThrownBy(() -> getOperations().execute((DbCallback) null));
- }
-
- @Test
- public void convertsExceptionForCollectionExists() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.collectionExists("foo");
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForCreateCollection() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.createCollection("foo");
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForCreateCollection2() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.createCollection("foo", CollectionOptions.empty().size(1).maxDocuments(1).capped());
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForDropCollection() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.dropCollection("foo");
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForExecuteCollectionCallback() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.execute("test", collectionCallback);
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForExecuteDbCallback() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.execute(dbCallback);
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForExecuteCollectionCallbackAndCollection() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.execute("collection", collectionCallback);
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForExecuteCommand() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.executeCommand(new Document());
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForExecuteStringCommand() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.executeCommand("");
- }
- }.assertException(IllegalArgumentException.class);
- }
-
- @Test
- public void convertsExceptionForGetCollection() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.findAll(Object.class);
- }
- }.assertException(MappingException.class);
- }
-
- @Test
- public void convertsExceptionForGetCollectionWithCollectionName() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.getCollection("collection");
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForGetCollectionWithCollectionNameAndType() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.findAll(Object.class, "collection");
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForGetCollectionWithCollectionNameTypeAndReader() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.findAll(Object.class, "collection");
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForGetCollectionNames() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.getCollectionNames();
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForInsert() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.insert(person);
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForInsert2() {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.insert(person, "collection");
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForInsertList() throws Exception {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.insertAll(persons);
- }
- }.assertDataAccessException();
- }
-
- @Test
- public void convertsExceptionForGetInsertList2() throws Exception {
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.insert(persons, "collection");
- }
- }.assertDataAccessException();
- }
-
- @Test // DATAMONGO-341
- public void geoNearRejectsNullNearQuery() {
-
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.geoNear(null, Person.class);
- }
- }.assertDataAccessException();
- }
-
- @Test // DATAMONGO-341
- public void geoNearRejectsNullNearQueryifCollectionGiven() {
-
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.geoNear(null, Person.class, "collection");
- }
- }.assertDataAccessException();
- }
-
- @Test // DATAMONGO-341
- public void geoNearRejectsNullEntityClass() {
-
- final NearQuery query = NearQuery.near(new Point(10, 20));
-
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.geoNear(query, null);
- }
- }.assertDataAccessException();
- }
-
- @Test // DATAMONGO-341
- public void geoNearRejectsNullEntityClassIfCollectionGiven() {
-
- final NearQuery query = NearQuery.near(new Point(10, 20));
-
- new Execution() {
- @Override
- public void doWith(MongoOperations operations) {
- operations.geoNear(query, null, "collection");
- }
- }.assertDataAccessException();
- }
-
- private abstract class Execution {
-
- public void assertDataAccessException() {
- assertException(DataAccessException.class);
- }
-
- public void assertException(Class extends Exception> exception) {
-
- assertThatThrownBy(() -> doWith(getOperationsForExceptionHandling())).isInstanceOf(exception);
- }
-
- public abstract void doWith(MongoOperations operations);
- }
-
- /**
- * Expects an {@link MongoOperations} instance that will be used to check that invoking methods on it will only cause
- * {@link DataAccessException}s.
- *
- * @return
- */
- protected abstract MongoOperations getOperationsForExceptionHandling();
-
- /**
- * Returns a plain {@link MongoOperations}.
- *
- * @return
- */
- protected abstract MongoOperations getOperations();
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateCollationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateCollationTests.java
deleted file mode 100644
index 99afc2c82f..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateCollationTests.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Copyright 2017-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import org.bson.Document;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
-import org.springframework.data.mongodb.core.query.Collation;
-import org.springframework.data.mongodb.core.query.Collation.Alternate;
-import org.springframework.data.mongodb.core.query.Collation.ComparisonLevel;
-import org.springframework.data.mongodb.test.util.Client;
-import org.springframework.data.mongodb.test.util.MongoClientExtension;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
-
-import com.mongodb.client.MongoClient;
-
-/**
- * @author Christoph Strobl
- * @author Mark Paluch
- */
-@ExtendWith({ MongoClientExtension.class, SpringExtension.class })
-public class MongoTemplateCollationTests {
-
- public static final String COLLECTION_NAME = "collation-1";
- static @Client MongoClient mongoClient;
-
- @Configuration
- static class Config extends AbstractMongoClientConfiguration {
-
- @Override
- public MongoClient mongoClient() {
- return mongoClient;
- }
-
- @Override
- protected String getDatabaseName() {
- return "collation-tests";
- }
-
- @Override
- protected boolean autoIndexCreation() {
- return false;
- }
-
- @Override
- protected Set> getInitialEntitySet() throws ClassNotFoundException {
- return Collections.emptySet();
- }
- }
-
- @Autowired MongoTemplate template;
-
- @BeforeEach
- public void setUp() {
- template.dropCollection(COLLECTION_NAME);
- }
-
- @Test // DATAMONGO-1518
- public void createCollectionWithCollation() {
-
- template.createCollection(COLLECTION_NAME, CollectionOptions.just(Collation.of("en_US")));
-
- Document collation = getCollationInfo(COLLECTION_NAME);
- assertThat(collation.get("locale")).isEqualTo("en_US");
- }
-
- @Test // DATAMONGO-1518
- public void createCollectionWithCollationHavingLocaleVariant() {
-
- template.createCollection(COLLECTION_NAME,
- CollectionOptions.just(Collation.of(new Locale("de", "AT", "phonebook"))));
-
- Document collation = getCollationInfo(COLLECTION_NAME);
- assertThat(collation.get("locale")).isEqualTo("de_AT@collation=phonebook");
- }
-
- @Test // DATAMONGO-1518
- public void createCollectionWithCollationHavingStrength() {
-
- template.createCollection(COLLECTION_NAME,
- CollectionOptions.just(Collation.of("en_US").strength(ComparisonLevel.primary().includeCase())));
-
- Document collation = getCollationInfo(COLLECTION_NAME);
- assertThat(collation.get("strength")).isEqualTo(1);
- assertThat(collation.get("caseLevel")).isEqualTo(true);
- }
-
- @Test // DATAMONGO-1518
- public void createCollectionWithCollationHavingBackwardsAndNumericOrdering() {
-
- template.createCollection(COLLECTION_NAME,
- CollectionOptions.just(Collation.of("en_US").backwardDiacriticSort().numericOrderingEnabled()));
-
- Document collation = getCollationInfo(COLLECTION_NAME);
- assertThat(collation.get("backwards")).isEqualTo(true);
- assertThat(collation.get("numericOrdering")).isEqualTo(true);
- }
-
- @Test // DATAMONGO-1518
- public void createCollationWithCollationHavingAlternate() {
-
- template.createCollection(COLLECTION_NAME,
- CollectionOptions.just(Collation.of("en_US").alternate(Alternate.shifted().punct())));
-
- Document collation = getCollationInfo(COLLECTION_NAME);
- assertThat(collation.get("alternate")).isEqualTo("shifted");
- assertThat(collation.get("maxVariable")).isEqualTo("punct");
- }
-
- private Document getCollationInfo(String collectionName) {
- return getCollectionInfo(collectionName).get("options", Document.class).get("collation", Document.class);
- }
-
- private Document getCollectionInfo(String collectionName) {
-
- return template.execute(db -> {
-
- Document result = db.runCommand(
- new Document().append("listCollections", 1).append("filter", new Document("name", collectionName)));
- return (Document) result.get("cursor", Document.class).get("firstBatch", List.class).get(0);
- });
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateDbRefTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateDbRefTests.java
deleted file mode 100644
index 17196219d4..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateDbRefTests.java
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
- * Copyright 2017-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-import static org.springframework.data.mongodb.core.query.Query.*;
-
-import lombok.Data;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.bson.types.ObjectId;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.mongodb.core.convert.LazyLoadingProxy;
-import org.springframework.data.mongodb.core.convert.LazyLoadingTestUtils;
-import org.springframework.data.mongodb.core.mapping.DBRef;
-import org.springframework.data.mongodb.core.mapping.Document;
-import org.springframework.data.mongodb.core.mapping.MongoId;
-import org.springframework.data.mongodb.test.util.MongoTemplateExtension;
-import org.springframework.data.mongodb.test.util.MongoTestTemplate;
-import org.springframework.data.mongodb.test.util.Template;
-
-import com.mongodb.client.model.Filters;
-
-/**
- * {@link org.springframework.data.mongodb.core.mapping.DBRef} related integration tests for
- * {@link org.springframework.data.mongodb.core.MongoTemplate}.
- *
- * @author Christoph Strobl
- */
-@ExtendWith(MongoTemplateExtension.class)
-public class MongoTemplateDbRefTests {
-
- @Template(database = "mongo-template-dbref-tests",
- initialEntitySet = { RefCycleLoadingIntoDifferentTypeRoot.class,
- RefCycleLoadingIntoDifferentTypeIntermediate.class, RefCycleLoadingIntoDifferentTypeRootView.class,
- WithDBRefOnRawStringId.class, WithLazyDBRefOnRawStringId.class, WithRefToAnotherDb.class,
- WithLazyRefToAnotherDb.class, WithListRefToAnotherDb.class, WithLazyListRefToAnotherDb.class }) //
- static MongoTestTemplate template;
-
- @Template(database = "mongo-template-dbref-tests-other-db", initialEntitySet = JustSomeType.class) //
- static MongoTestTemplate otherDbTemplate;
-
- @BeforeEach
- public void setUp() {
-
- template.flush();
- otherDbTemplate.flush();
- }
-
- @Test // DATAMONGO-1703
- public void shouldLoadRefIntoDifferentTypeCorrectly() {
-
- // init root
- RefCycleLoadingIntoDifferentTypeRoot root = new RefCycleLoadingIntoDifferentTypeRoot();
- root.id = "root-1";
- root.content = "jon snow";
- template.save(root);
-
- // init one and set view id ref to root.id
- RefCycleLoadingIntoDifferentTypeIntermediate intermediate = new RefCycleLoadingIntoDifferentTypeIntermediate();
- intermediate.id = "one-1";
- intermediate.refToRootView = new RefCycleLoadingIntoDifferentTypeRootView();
- intermediate.refToRootView.id = root.id;
-
- template.save(intermediate);
-
- // add one ref to root
- root.refToIntermediate = intermediate;
- template.save(root);
-
- RefCycleLoadingIntoDifferentTypeRoot loaded = template.findOne(query(where("id").is(root.id)),
- RefCycleLoadingIntoDifferentTypeRoot.class);
-
- assertThat(loaded.content).isEqualTo("jon snow");
- assertThat(loaded.getRefToIntermediate()).isInstanceOf(RefCycleLoadingIntoDifferentTypeIntermediate.class);
- assertThat(loaded.getRefToIntermediate().getRefToRootView())
- .isInstanceOf(RefCycleLoadingIntoDifferentTypeRootView.class);
- assertThat(loaded.getRefToIntermediate().getRefToRootView().getContent()).isEqualTo("jon snow");
- }
-
- @Test // DATAMONGO-1798
- public void stringDBRefLoading() {
-
- RawStringId ref = new RawStringId();
- ref.id = new ObjectId().toHexString();
- ref.value = "new value";
-
- template.save(ref);
-
- WithDBRefOnRawStringId source = new WithDBRefOnRawStringId();
- source.id = "foo";
- source.value = ref;
-
- template.save(source);
-
- org.bson.Document result = template
- .execute(db -> (org.bson.Document) db.getCollection(template.getCollectionName(WithDBRefOnRawStringId.class))
- .find(Filters.eq("_id", source.id)).limit(1).into(new ArrayList()).iterator().next());
-
- assertThat(result).isNotNull();
- assertThat(result.get("value"))
- .isEqualTo(new com.mongodb.DBRef(template.getCollectionName(RawStringId.class), ref.getId()));
-
- WithDBRefOnRawStringId target = template.findOne(query(where("id").is(source.id)), WithDBRefOnRawStringId.class);
- assertThat(target.value).isEqualTo(ref);
- }
-
- @Test // DATAMONGO-1798
- public void stringDBRefLazyLoading() {
-
- RawStringId ref = new RawStringId();
- ref.id = new ObjectId().toHexString();
- ref.value = "new value";
-
- template.save(ref);
-
- WithLazyDBRefOnRawStringId source = new WithLazyDBRefOnRawStringId();
- source.id = "foo";
- source.value = ref;
-
- template.save(source);
-
- org.bson.Document result = template.execute(
- db -> (org.bson.Document) db.getCollection(template.getCollectionName(WithLazyDBRefOnRawStringId.class))
- .find(Filters.eq("_id", source.id)).limit(1).into(new ArrayList()).iterator().next());
-
- assertThat(result).isNotNull();
- assertThat(result.get("value"))
- .isEqualTo(new com.mongodb.DBRef(template.getCollectionName(RawStringId.class), ref.getId()));
-
- WithLazyDBRefOnRawStringId target = template.findOne(query(where("id").is(source.id)),
- WithLazyDBRefOnRawStringId.class);
-
- assertThat(target.value).isInstanceOf(LazyLoadingProxy.class);
- assertThat(target.getValue()).isEqualTo(ref);
- }
-
- @Test // DATAMONGO-2223
- public void shouldResolveSingleDBRefToAnotherDb() {
-
- JustSomeType one = new JustSomeType();
- one.value = "one";
-
- otherDbTemplate.insert(one);
-
- WithRefToAnotherDb source = new WithRefToAnotherDb();
- source.value = one;
-
- template.save(source);
-
- WithRefToAnotherDb target = template.findOne(query(where("id").is(source.id)), WithRefToAnotherDb.class);
- assertThat(target.getValue()).isEqualTo(one);
- }
-
- @Test // DATAMONGO-2223
- public void shouldResolveSingleLazyDBRefToAnotherDb() {
-
- JustSomeType one = new JustSomeType();
- one.value = "one";
-
- otherDbTemplate.insert(one);
-
- WithLazyRefToAnotherDb source = new WithLazyRefToAnotherDb();
- source.value = one;
-
- template.save(source);
-
- WithLazyRefToAnotherDb target = template.findOne(query(where("id").is(source.id)), WithLazyRefToAnotherDb.class);
- LazyLoadingTestUtils.assertProxyIsResolved(target.value, false);
- assertThat(target.getValue()).isEqualTo(one);
- }
-
- @Test // DATAMONGO-2223
- public void shouldResolveListDBRefToAnotherDb() {
-
- JustSomeType one = new JustSomeType();
- one.value = "one";
-
- JustSomeType two = new JustSomeType();
- two.value = "two";
-
- otherDbTemplate.insertAll(Arrays.asList(one, two));
-
- WithListRefToAnotherDb source = new WithListRefToAnotherDb();
- source.value = Arrays.asList(one, two);
-
- template.save(source);
-
- WithListRefToAnotherDb target = template.findOne(query(where("id").is(source.id)), WithListRefToAnotherDb.class);
- assertThat(target.getValue()).containsExactlyInAnyOrder(one, two);
- }
-
- @Test // DATAMONGO-2223
- public void shouldResolveLazyListDBRefToAnotherDb() {
-
- JustSomeType one = new JustSomeType();
- one.value = "one";
-
- JustSomeType two = new JustSomeType();
- two.value = "two";
-
- otherDbTemplate.insertAll(Arrays.asList(one, two));
-
- WithLazyListRefToAnotherDb source = new WithLazyListRefToAnotherDb();
- source.value = Arrays.asList(one, two);
-
- template.save(source);
-
- WithLazyListRefToAnotherDb target = template.findOne(query(where("id").is(source.id)),
- WithLazyListRefToAnotherDb.class);
- LazyLoadingTestUtils.assertProxyIsResolved(target.value, false);
- assertThat(target.getValue()).containsExactlyInAnyOrder(one, two);
- }
-
- @Data
- @Document("cycle-with-different-type-root")
- static class RefCycleLoadingIntoDifferentTypeRoot {
-
- @Id String id;
- String content;
- @DBRef RefCycleLoadingIntoDifferentTypeIntermediate refToIntermediate;
- }
-
- @Data
- @Document("cycle-with-different-type-intermediate")
- static class RefCycleLoadingIntoDifferentTypeIntermediate {
-
- @Id String id;
- @DBRef RefCycleLoadingIntoDifferentTypeRootView refToRootView;
- }
-
- @Data
- @Document("cycle-with-different-type-root")
- static class RefCycleLoadingIntoDifferentTypeRootView {
-
- @Id String id;
- String content;
- }
-
- @Data
- static class RawStringId {
-
- @MongoId String id;
- String value;
- }
-
- @Data
- static class WithDBRefOnRawStringId {
-
- @Id String id;
- @DBRef RawStringId value;
- }
-
- @Data
- static class WithLazyDBRefOnRawStringId {
-
- @Id String id;
- @DBRef(lazy = true) RawStringId value;
- }
-
- @Data
- static class WithRefToAnotherDb {
-
- @Id String id;
- @DBRef(db = "mongo-template-dbref-tests-other-db") JustSomeType value;
- }
-
- @Data
- static class WithLazyRefToAnotherDb {
-
- @Id String id;
- @DBRef(lazy = true, db = "mongo-template-dbref-tests-other-db") JustSomeType value;
- }
-
- @Data
- static class WithListRefToAnotherDb {
-
- @Id String id;
- @DBRef(db = "mongo-template-dbref-tests-other-db") List value;
- }
-
- @Data
- static class WithLazyListRefToAnotherDb {
-
- @Id String id;
- @DBRef(lazy = true, db = "mongo-template-dbref-tests-other-db") List value;
- }
-
- @Data
- static class JustSomeType {
-
- @Id String id;
- String value;
- }
-
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateFieldProjectionTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateFieldProjectionTests.java
deleted file mode 100644
index e39b4f4f1f..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateFieldProjectionTests.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Copyright 2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-
-import lombok.EqualsAndHashCode;
-import lombok.ToString;
-
-import java.util.function.Consumer;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.mongodb.MongoExpression;
-import org.springframework.data.mongodb.core.aggregation.AggregationSpELExpression;
-import org.springframework.data.mongodb.core.aggregation.StringOperators;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.mapping.Unwrapped;
-import org.springframework.data.mongodb.core.query.Criteria;
-import org.springframework.data.mongodb.core.query.Query;
-import org.springframework.data.mongodb.test.util.EnableIfMongoServerVersion;
-import org.springframework.data.mongodb.test.util.MongoTemplateExtension;
-import org.springframework.data.mongodb.test.util.MongoTestTemplate;
-import org.springframework.data.mongodb.test.util.Template;
-
-/**
- * Integration tests for {@link org.springframework.data.mongodb.core.query.Field}.
- *
- * @author Christoph Strobl
- * @author Mark Paluch
- */
-@ExtendWith(MongoTemplateExtension.class)
-@EnableIfMongoServerVersion(isGreaterThanEqual = "4.4")
-class MongoTemplateFieldProjectionTests {
-
- private static @Template MongoTestTemplate template;
-
- private Person luke;
-
- @BeforeEach
- void beforeEach() {
-
- luke = new Person();
- luke.id = "luke";
- luke.firstname = "luke";
- luke.lastname = "skywalker";
-
- template.save(luke);
- }
-
- @AfterEach
- void afterEach() {
- template.flush(Person.class, Wrapper.class);
- }
-
- @Test // GH-3583
- void usesMongoExpressionAsIs() {
-
- Person result = findLuke(fields -> {
- fields.include("firstname").project(MongoExpression.create("'$toUpper' : '$last_name'"))
- .as("last_name");
- });
-
- assertThat(result).isEqualTo(luke.upperCaseLastnameClone());
- }
-
- @Test // GH-3583
- void usesMongoExpressionWithPlaceholdersAsIs() {
-
- Person result = findLuke(fields -> {
- fields.include("firstname").project(MongoExpression.create("'$toUpper' : '$?0'", "last_name"))
- .as("last_name");
- });
-
- assertThat(result).isEqualTo(luke.upperCaseLastnameClone());
- }
-
- @Test // GH-3583
- void mapsAggregationExpressionToDomainType() {
-
- Person result = findLuke(fields -> {
- fields.include("firstname").project(StringOperators.valueOf("lastname").toUpper()).as("last_name");
- });
-
- assertThat(result).isEqualTo(luke.upperCaseLastnameClone());
- }
-
- @Test // GH-3583
- void mapsAggregationSpELExpressionToDomainType() {
-
- Person result = findLuke(fields -> {
- fields.include("firstname").project(AggregationSpELExpression.expressionOf("toUpper(lastname)")).as("last_name");
- });
-
- assertThat(result).isEqualTo(luke.upperCaseLastnameClone());
- }
-
- @Test // GH-3583
- void mapsNestedPathAggregationExpressionToDomainType() {
-
- Wrapper wrapper = new Wrapper();
- wrapper.id = "wrapper";
- wrapper.person = luke;
-
- template.save(wrapper);
-
- Query query = Query.query(Criteria.where("id").is(wrapper.id));
- query.fields().include("person.firstname", "person.id")
- .project(StringOperators.valueOf("person.lastname").toUpper()).as("person.last_name");
-
- Wrapper result = template.findOne(query, Wrapper.class);
- assertThat(result.person).isEqualTo(luke.upperCaseLastnameClone());
- }
-
- @Test // GH-3583
- void mapsProjectionOnUnwrapped() {
-
- luke.address = new Address();
- luke.address.planet = "tatoine";
-
- template.save(luke);
-
- Person result = findLuke(fields -> {
- fields.project(StringOperators.valueOf("address.planet").toUpper()).as("planet");
- });
-
- assertThat(result.address.planet).isEqualTo("TATOINE");
- }
-
- private Person findLuke(Consumer projection) {
-
- Query query = Query.query(Criteria.where("id").is(luke.id));
- projection.accept(query.fields());
- return template.findOne(query, Person.class);
- }
-
- @EqualsAndHashCode
- @ToString
- static class Wrapper {
- @Id String id;
- Person person;
- }
-
- @EqualsAndHashCode
- @ToString
- static class Person {
-
- @Id String id;
- String firstname;
-
- @Field("last_name") //
- String lastname;
-
- @Unwrapped.Nullable Address address;
-
- Person toUpperCaseLastnameClone(Person source) {
-
- Person target = new Person();
- target.id = source.id;
- target.firstname = source.firstname;
- target.lastname = source.lastname.toUpperCase();
- target.address = source.address;
-
- return target;
- }
-
- Person upperCaseLastnameClone() {
- return toUpperCaseLastnameClone(this);
- }
- }
-
- @EqualsAndHashCode
- @ToString
- static class Address {
- String planet;
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateMappingTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateMappingTests.java
deleted file mode 100644
index 878f89f70e..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateMappingTests.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright 2011-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-import static org.springframework.data.mongodb.core.query.Query.*;
-
-import lombok.Data;
-
-import java.util.Arrays;
-
-import org.bson.Document;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.dao.DataAccessException;
-import org.springframework.data.annotation.Id;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import com.mongodb.MongoException;
-import com.mongodb.client.MongoCollection;
-import com.mongodb.client.model.geojson.Geometry;
-import com.mongodb.client.model.geojson.MultiPolygon;
-import com.mongodb.client.model.geojson.PolygonCoordinates;
-import com.mongodb.client.model.geojson.Position;
-
-/**
- * Integration test for {@link MongoTemplate}.
- *
- * @author Oliver Gierke
- * @author Thomas Risberg
- * @author Mark Paluch
- */
-@RunWith(SpringRunner.class)
-@ContextConfiguration("classpath:template-mapping.xml")
-public class MongoTemplateMappingTests {
-
- @Autowired @Qualifier("mongoTemplate1") MongoTemplate template1;
-
- @Autowired @Qualifier("mongoTemplate2") MongoTemplate template2;
-
- @Before
- public void setUp() {
- template1.dropCollection(template1.getCollectionName(Person.class));
- }
-
- @Test
- public void insertsEntityCorrectly1() {
-
- addAndRetrievePerson(template1);
- checkPersonPersisted(template1);
- }
-
- @Test
- public void insertsEntityCorrectly2() {
-
- addAndRetrievePerson(template2);
- checkPersonPersisted(template2);
- }
-
- @Test // DATAMONGO-2357
- public void writesAndReadsEntityWithNativeMongoGeoJsonTypesCorrectly() {
-
- WithMongoGeoJson source = new WithMongoGeoJson();
- source.id = "id-2";
- source.multiPolygon = new MultiPolygon(Arrays.asList(new PolygonCoordinates(Arrays.asList(new Position(0, 0),
- new Position(0, 1), new Position(1, 1), new Position(1, 0), new Position(0, 0)))));
-
- template1.save(source);
-
- assertThat(template1.findOne(query(where("id").is(source.id)), WithMongoGeoJson.class)).isEqualTo(source);
- }
-
- @Test // DATAMONGO-2357
- public void writesAndReadsEntityWithOpenNativeMongoGeoJsonTypesCorrectly() {
-
- WithOpenMongoGeoJson source = new WithOpenMongoGeoJson();
- source.id = "id-2";
- source.geometry = new MultiPolygon(Arrays.asList(new PolygonCoordinates(Arrays.asList(new Position(0, 0),
- new Position(0, 1), new Position(1, 1), new Position(1, 0), new Position(0, 0)))));
-
- template1.save(source);
-
- assertThat(template1.findOne(query(where("id").is(source.id)), WithOpenMongoGeoJson.class)).isEqualTo(source);
- }
-
- @Data
- static class WithMongoGeoJson {
-
- @Id String id;
- MultiPolygon multiPolygon;
- }
-
- @Data
- static class WithOpenMongoGeoJson {
-
- @Id String id;
- Geometry geometry;
- }
-
- private void addAndRetrievePerson(MongoTemplate template) {
- Person person = new Person("Oliver");
- person.setAge(25);
- template.insert(person);
-
- Person result = template.findById(person.getId(), Person.class);
- assertThat(result.getFirstName()).isEqualTo("Oliver");
- assertThat(result.getAge()).isEqualTo(25);
- }
-
- private void checkPersonPersisted(MongoTemplate template) {
- template.execute(Person.class, new CollectionCallback() {
- public Object doInCollection(MongoCollection collection) throws MongoException, DataAccessException {
- Document document = collection.find(new Document()).first();
- assertThat((String) document.get("name")).isEqualTo("Oliver");
- return null;
- }
- });
- }
-}
diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java
deleted file mode 100644
index b18e1066f5..0000000000
--- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java
+++ /dev/null
@@ -1,4250 +0,0 @@
-/*
- * Copyright 2011-2021 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.springframework.data.mongodb.core.query.Criteria.*;
-import static org.springframework.data.mongodb.core.query.Query.*;
-import static org.springframework.data.mongodb.core.query.Update.*;
-
-import lombok.AllArgsConstructor;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-import lombok.NoArgsConstructor;
-import lombok.Value;
-import lombok.With;
-
-import java.lang.reflect.InvocationTargetException;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.time.Duration;
-import java.time.Instant;
-import java.time.temporal.ChronoUnit;
-import java.util.*;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
-import org.bson.types.ObjectId;
-import org.joda.time.DateTime;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.support.GenericApplicationContext;
-import org.springframework.core.convert.converter.Converter;
-import org.springframework.dao.DataAccessException;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.DuplicateKeyException;
-import org.springframework.dao.InvalidDataAccessApiUsageException;
-import org.springframework.dao.OptimisticLockingFailureException;
-import org.springframework.data.annotation.Id;
-import org.springframework.data.annotation.LastModifiedDate;
-import org.springframework.data.annotation.PersistenceConstructor;
-import org.springframework.data.annotation.Version;
-import org.springframework.data.auditing.IsNewAwareAuditingHandler;
-import org.springframework.data.domain.PageRequest;
-import org.springframework.data.domain.Sort;
-import org.springframework.data.domain.Sort.Direction;
-import org.springframework.data.mapping.MappingException;
-import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
-import org.springframework.data.mongodb.MongoDatabaseFactory;
-import org.springframework.data.mongodb.core.convert.LazyLoadingProxy;
-import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
-import org.springframework.data.mongodb.core.index.Index;
-import org.springframework.data.mongodb.core.index.IndexField;
-import org.springframework.data.mongodb.core.index.IndexInfo;
-import org.springframework.data.mongodb.core.mapping.Field;
-import org.springframework.data.mongodb.core.mapping.MongoId;
-import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
-import org.springframework.data.mongodb.core.mapping.event.AfterSaveEvent;
-import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
-import org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent;
-import org.springframework.data.mongodb.core.query.BasicQuery;
-import org.springframework.data.mongodb.core.query.Criteria;
-import org.springframework.data.mongodb.core.query.Query;
-import org.springframework.data.mongodb.core.query.Update;
-import org.springframework.data.mongodb.test.util.Client;
-import org.springframework.data.mongodb.test.util.MongoClientExtension;
-import org.springframework.data.mongodb.test.util.MongoTestTemplate;
-import org.springframework.data.mongodb.test.util.MongoVersion;
-import org.springframework.data.util.CloseableIterator;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.util.ClassUtils;
-import org.springframework.util.ObjectUtils;
-import org.springframework.util.StringUtils;
-
-import com.mongodb.BasicDBObject;
-import com.mongodb.DBObject;
-import com.mongodb.DBRef;
-import com.mongodb.MongoException;
-import com.mongodb.ReadPreference;
-import com.mongodb.WriteConcern;
-import com.mongodb.client.FindIterable;
-import com.mongodb.client.ListIndexesIterable;
-import com.mongodb.client.MongoClient;
-import com.mongodb.client.MongoCollection;
-import com.mongodb.client.MongoCursor;
-import com.mongodb.client.model.Filters;
-import com.mongodb.client.model.IndexOptions;
-import com.mongodb.client.result.DeleteResult;
-import com.mongodb.client.result.UpdateResult;
-
-/**
- * Integration test for {@link MongoTemplate}.
- *
- * @author Oliver Gierke
- * @author Thomas Risberg
- * @author Amol Nayak
- * @author Patryk Wasik
- * @author Thomas Darimont
- * @author Komi Innocent
- * @author Christoph Strobl
- * @author Mark Paluch
- * @author Laszlo Csontos
- * @author duozhilin
- */
-@ExtendWith(MongoClientExtension.class)
-public class MongoTemplateTests {
-
- public static final String DB_NAME = "mongo-template-tests";
-
- static @Client MongoClient client;
-
- ConfigurableApplicationContext context = new GenericApplicationContext();
-
- MongoTestTemplate template = new MongoTestTemplate(cfg -> {
-
- cfg.configureDatabaseFactory(it -> {
-
- it.client(client);
- it.defaultDb(DB_NAME);
- });
-
- cfg.configureMappingContext(it -> {
- it.autocreateIndex(false);
- it.intitalEntitySet(AuditablePerson.class);
-
- });
-
- cfg.configureApplicationContext(it -> {
- it.applicationContext(context);
- it.addEventListener(new PersonWithIdPropertyOfTypeUUIDListener());
- });
-
- cfg.configureAuditing(it -> {
- it.auditingHandler(IsNewAwareAuditingHandler::new);
- });
- });
-
- MongoTestTemplate mappingTemplate = new MongoTestTemplate(cfg -> {
-
- cfg.configureDatabaseFactory(it -> {
-
- it.client(client);
- it.defaultDb(DB_NAME);
- });
-
- cfg.configureConversion(it -> {
- it.customConverters(DateToDateTimeConverter.INSTANCE, DateTimeToDateConverter.INSTANCE);
- });
-
- cfg.configureMappingContext(it -> {
- it.autocreateIndex(false);
- });
-
- cfg.configureApplicationContext(it -> {
- it.applicationContext(new GenericApplicationContext());
- it.addEventListener(new PersonWithIdPropertyOfTypeUUIDListener());
- });
- });
-
- MongoDatabaseFactory factory = template.getMongoDbFactory();
-
- @AfterEach
- public void cleanUp() {
-
- template.flush();
- template.flush("collection", "personX", "findandreplace");
-
- mappingTemplate.flush();
-
- template.dropCollection(Person.class);
- }
-
- @Test
- public void insertsSimpleEntityCorrectly() throws Exception {
-
- Person person = new Person("Oliver");
- person.setAge(25);
- template.insert(person);
-
- List result = template.find(new Query(Criteria.where("_id").is(person.getId())), Person.class);
- assertThat(result.size()).isEqualTo(1);
- assertThat(result).contains(person);
- }
-
- @Test
- public void bogusUpdateDoesNotTriggerException() throws Exception {
-
- MongoTemplate mongoTemplate = new MongoTemplate(factory);
- mongoTemplate.setWriteResultChecking(WriteResultChecking.EXCEPTION);
-
- Person person = new Person("Oliver2");
- person.setAge(25);
- mongoTemplate.insert(person);
-
- Query q = new Query(Criteria.where("BOGUS").gt(22));
- Update u = new Update().set("firstName", "Sven");
- mongoTemplate.updateFirst(q, u, Person.class);
- }
-
- @Test // DATAMONGO-480
- public void throwsExceptionForDuplicateIds() {
-
- MongoTemplate template = new MongoTemplate(factory);
- template.setWriteResultChecking(WriteResultChecking.EXCEPTION);
-
- Person person = new Person(new ObjectId(), "Amol");
- person.setAge(28);
-
- template.insert(person);
-
- try {
- template.insert(person);
- fail("Expected DataIntegrityViolationException!");
- } catch (DataIntegrityViolationException e) {
- assertThat(e.getMessage()).contains("E11000 duplicate key error");
- }
- }
-
- @Test // DATAMONGO-480, DATAMONGO-799
- public void throwsExceptionForUpdateWithInvalidPushOperator() {
-
- MongoTemplate template = new MongoTemplate(factory);
- template.setWriteResultChecking(WriteResultChecking.EXCEPTION);
-
- ObjectId id = new ObjectId();
- Person person = new Person(id, "Amol");
- person.setAge(28);
-
- template.insert(person);
-
- Query query = new Query(Criteria.where("firstName").is("Amol"));
- Update upd = new Update().push("age", 29);
-
- assertThatExceptionOfType(DataIntegrityViolationException.class)
- .isThrownBy(() -> template.updateFirst(query, upd, Person.class)).withMessageContaining("array")
- .withMessageContaining("age");
- }
-
- @Test // DATAMONGO-480
- public void throwsExceptionForIndexViolationIfConfigured() {
-
- MongoTemplate template = new MongoTemplate(factory);
- template.setWriteResultChecking(WriteResultChecking.EXCEPTION);
- template.indexOps(Person.class).ensureIndex(new Index().on("firstName", Direction.DESC).unique());
-
- Person person = new Person(new ObjectId(), "Amol");
- person.setAge(28);
-
- template.save(person);
-
- person = new Person(new ObjectId(), "Amol");
- person.setAge(28);
-
- try {
- template.save(person);
- fail("Expected DataIntegrityViolationException!");
- } catch (DataIntegrityViolationException e) {
- assertThat(e.getMessage()).contains("E11000 duplicate key error");
- }
- }
-
- @Test // DATAMONGO-480
- public void rejectsDuplicateIdInInsertAll() {
-
- MongoTemplate template = new MongoTemplate(factory);
- template.setWriteResultChecking(WriteResultChecking.EXCEPTION);
-
- ObjectId id = new ObjectId();
- Person person = new Person(id, "Amol");
- person.setAge(28);
-
- List records = new ArrayList<>();
- records.add(person);
- records.add(person);
-
- assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(() -> template.insertAll(records))
- .withMessageContaining("E11000 duplicate key error");
- }
-
- @Test // DATAMONGO-1687
- public void createCappedCollection() {
-
- template.createCollection(Person.class, CollectionOptions.empty().capped().size(1000).maxDocuments(1000));
-
- org.bson.Document collectionOptions = getCollectionInfo(template.getCollectionName(Person.class)).get("options",
- org.bson.Document.class);
- assertThat(collectionOptions.get("capped")).isEqualTo(true);
- }
-
- private org.bson.Document getCollectionInfo(String collectionName) {
-
- return template.execute(db -> {
-
- org.bson.Document result = db.runCommand(new org.bson.Document().append("listCollections", 1).append("filter",
- new org.bson.Document("name", collectionName)));
- return (org.bson.Document) result.get("cursor", org.bson.Document.class).get("firstBatch", List.class).get(0);
- });
- }
-
- @Test
- public void testEnsureIndex() throws Exception {
-
- Person p1 = new Person("Oliver");
- p1.setAge(25);
- template.insert(p1);
- Person p2 = new Person("Sven");
- p2.setAge(40);
- template.insert(p2);
-
- template.indexOps(Person.class).ensureIndex(new Index().on("age", Direction.DESC).unique());
-
- MongoCollection coll = template.getCollection(template.getCollectionName(Person.class));
- List indexInfo = new ArrayList<>();
- coll.listIndexes().into(indexInfo);
-
- assertThat(indexInfo.size()).isEqualTo(2);
- Object indexKey = null;
- boolean unique = false;
- for (org.bson.Document ix : indexInfo) {
-
- if ("age_-1".equals(ix.get("name"))) {
- indexKey = ix.get("key");
- unique = (Boolean) ix.get("unique");
- assertThat(ix.get("dropDups")).isNull();
- }
- }
- assertThat(((org.bson.Document) indexKey)).containsEntry("age", -1);
- assertThat(unique).isTrue();
-
- List indexInfoList = template.indexOps(Person.class).getIndexInfo();
-
- assertThat(indexInfoList.size()).isEqualTo(2);
- IndexInfo ii = indexInfoList.get(1);
- assertThat(ii.isUnique()).isTrue();
- assertThat(ii.isSparse()).isFalse();
-
- List indexFields = ii.getIndexFields();
- IndexField field = indexFields.get(0);
-
- assertThat(field).isEqualTo(IndexField.create("age", Direction.DESC));
- }
-
- @Test // DATAMONGO-746, DATAMONGO-2264
- public void testReadIndexInfoForIndicesCreatedViaMongoShellCommands() throws Exception {
-
- template.dropCollection(Person.class);
-
- assertThat(template.indexOps(Person.class).getIndexInfo().isEmpty()).isTrue();
-
- factory.getMongoDatabase().getCollection(template.getCollectionName(Person.class))
- .createIndex(new org.bson.Document("age", -1), new IndexOptions().name("age_-1").unique(true).sparse(true));
-
- ListIndexesIterable indexInfo = template.getCollection(template.getCollectionName(Person.class))
- .listIndexes();
- org.bson.Document indexKey = null;
- boolean unique = false;
-
- MongoCursor cursor = indexInfo.iterator();
-
- while (cursor.hasNext()) {
-
- org.bson.Document ix = cursor.next();
-
- if ("age_-1".equals(ix.get("name"))) {
- indexKey = (org.bson.Document) ix.get("key");
- unique = (Boolean) ix.get("unique");
- }
- }
-
- assertThat(indexKey).containsEntry("age", -1);
- assertThat(unique).isTrue();
-
- IndexInfo info = template.indexOps(Person.class).getIndexInfo().get(1);
- assertThat(info.isUnique()).isTrue();
- assertThat(info.isSparse()).isTrue();
-
- List indexFields = info.getIndexFields();
- IndexField field = indexFields.get(0);
-
- assertThat(field).isEqualTo(IndexField.create("age", Direction.DESC));
- }
-
- @Test
- public void testProperHandlingOfDifferentIdTypesWithMappingMongoConverter() throws Exception {
- testProperHandlingOfDifferentIdTypes(this.mappingTemplate);
- }
-
- private void testProperHandlingOfDifferentIdTypes(MongoTemplate mongoTemplate) throws Exception {
-
- // String id - generated
- PersonWithIdPropertyOfTypeString p1 = new PersonWithIdPropertyOfTypeString();
- p1.setFirstName("Sven_1");
- p1.setAge(22);
- // insert
- mongoTemplate.insert(p1);
- // also try save
- mongoTemplate.save(p1);
- assertThat(p1.getId()).isNotNull();
- PersonWithIdPropertyOfTypeString p1q = mongoTemplate.findOne(new Query(where("id").is(p1.getId())),
- PersonWithIdPropertyOfTypeString.class);
- assertThat(p1q).isNotNull();
- assertThat(p1q.getId()).isEqualTo(p1.getId());
- checkCollectionContents(PersonWithIdPropertyOfTypeString.class, 1);
-
- // String id - provided
- PersonWithIdPropertyOfTypeString p2 = new PersonWithIdPropertyOfTypeString();
- p2.setFirstName("Sven_2");
- p2.setAge(22);
- p2.setId("TWO");
- // insert
- mongoTemplate.insert(p2);
- // also try save
- mongoTemplate.save(p2);
- assertThat(p2.getId()).isNotNull();
- PersonWithIdPropertyOfTypeString p2q = mongoTemplate.findOne(new Query(where("id").is(p2.getId())),
- PersonWithIdPropertyOfTypeString.class);
- assertThat(p2q).isNotNull();
- assertThat(p2q.getId()).isEqualTo(p2.getId());
- checkCollectionContents(PersonWithIdPropertyOfTypeString.class, 2);
-
- // String _id - generated
- PersonWith_idPropertyOfTypeString p3 = new PersonWith_idPropertyOfTypeString();
- p3.setFirstName("Sven_3");
- p3.setAge(22);
- // insert
- mongoTemplate.insert(p3);
- // also try save
- mongoTemplate.save(p3);
- assertThat(p3.get_id()).isNotNull();
- PersonWith_idPropertyOfTypeString p3q = mongoTemplate.findOne(new Query(where("_id").is(p3.get_id())),
- PersonWith_idPropertyOfTypeString.class);
- assertThat(p3q).isNotNull();
- assertThat(p3q.get_id()).isEqualTo(p3.get_id());
- checkCollectionContents(PersonWith_idPropertyOfTypeString.class, 1);
-
- // String _id - provided
- PersonWith_idPropertyOfTypeString p4 = new PersonWith_idPropertyOfTypeString();
- p4.setFirstName("Sven_4");
- p4.setAge(22);
- p4.set_id("FOUR");
- // insert
- mongoTemplate.insert(p4);
- // also try save
- mongoTemplate.save(p4);
- assertThat(p4.get_id()).isNotNull();
- PersonWith_idPropertyOfTypeString p4q = mongoTemplate.findOne(new Query(where("_id").is(p4.get_id())),
- PersonWith_idPropertyOfTypeString.class);
- assertThat(p4q).isNotNull();
- assertThat(p4q.get_id()).isEqualTo(p4.get_id());
- checkCollectionContents(PersonWith_idPropertyOfTypeString.class, 2);
-
- // ObjectId id - generated
- PersonWithIdPropertyOfTypeObjectId p5 = new PersonWithIdPropertyOfTypeObjectId();
- p5.setFirstName("Sven_5");
- p5.setAge(22);
- // insert
- mongoTemplate.insert(p5);
- // also try save
- mongoTemplate.save(p5);
- assertThat(p5.getId()).isNotNull();
- PersonWithIdPropertyOfTypeObjectId p5q = mongoTemplate.findOne(new Query(where("id").is(p5.getId())),
- PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(p5q).isNotNull();
- assertThat(p5q.getId()).isEqualTo(p5.getId());
- checkCollectionContents(PersonWithIdPropertyOfTypeObjectId.class, 1);
-
- // ObjectId id - provided
- PersonWithIdPropertyOfTypeObjectId p6 = new PersonWithIdPropertyOfTypeObjectId();
- p6.setFirstName("Sven_6");
- p6.setAge(22);
- p6.setId(new ObjectId());
- // insert
- mongoTemplate.insert(p6);
- // also try save
- mongoTemplate.save(p6);
- assertThat(p6.getId()).isNotNull();
- PersonWithIdPropertyOfTypeObjectId p6q = mongoTemplate.findOne(new Query(where("id").is(p6.getId())),
- PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(p6q).isNotNull();
- assertThat(p6q.getId()).isEqualTo(p6.getId());
- checkCollectionContents(PersonWithIdPropertyOfTypeObjectId.class, 2);
-
- // ObjectId _id - generated
- PersonWith_idPropertyOfTypeObjectId p7 = new PersonWith_idPropertyOfTypeObjectId();
- p7.setFirstName("Sven_7");
- p7.setAge(22);
- // insert
- mongoTemplate.insert(p7);
- // also try save
- mongoTemplate.save(p7);
- assertThat(p7.get_id()).isNotNull();
- PersonWith_idPropertyOfTypeObjectId p7q = mongoTemplate.findOne(new Query(where("_id").is(p7.get_id())),
- PersonWith_idPropertyOfTypeObjectId.class);
- assertThat(p7q).isNotNull();
- assertThat(p7q.get_id()).isEqualTo(p7.get_id());
- checkCollectionContents(PersonWith_idPropertyOfTypeObjectId.class, 1);
-
- // ObjectId _id - provided
- PersonWith_idPropertyOfTypeObjectId p8 = new PersonWith_idPropertyOfTypeObjectId();
- p8.setFirstName("Sven_8");
- p8.setAge(22);
- p8.set_id(new ObjectId());
- // insert
- mongoTemplate.insert(p8);
- // also try save
- mongoTemplate.save(p8);
- assertThat(p8.get_id()).isNotNull();
- PersonWith_idPropertyOfTypeObjectId p8q = mongoTemplate.findOne(new Query(where("_id").is(p8.get_id())),
- PersonWith_idPropertyOfTypeObjectId.class);
- assertThat(p8q).isNotNull();
- assertThat(p8q.get_id()).isEqualTo(p8.get_id());
- checkCollectionContents(PersonWith_idPropertyOfTypeObjectId.class, 2);
-
- // Integer id - provided
- PersonWithIdPropertyOfTypeInteger p9 = new PersonWithIdPropertyOfTypeInteger();
- p9.setFirstName("Sven_9");
- p9.setAge(22);
- p9.setId(Integer.valueOf(12345));
- // insert
- mongoTemplate.insert(p9);
- // also try save
- mongoTemplate.save(p9);
- assertThat(p9.getId()).isNotNull();
- PersonWithIdPropertyOfTypeInteger p9q = mongoTemplate.findOne(new Query(where("id").in(p9.getId())),
- PersonWithIdPropertyOfTypeInteger.class);
- assertThat(p9q).isNotNull();
- assertThat(p9q.getId()).isEqualTo(p9.getId());
- checkCollectionContents(PersonWithIdPropertyOfTypeInteger.class, 1);
-
- // DATAMONGO-602
- // BigInteger id - provided
- PersonWithIdPropertyOfTypeBigInteger p9bi = new PersonWithIdPropertyOfTypeBigInteger();
- p9bi.setFirstName("Sven_9bi");
- p9bi.setAge(22);
- p9bi.setId(BigInteger.valueOf(12345));
- // insert
- mongoTemplate.insert(p9bi);
- // also try save
- mongoTemplate.save(p9bi);
- assertThat(p9bi.getId()).isNotNull();
- PersonWithIdPropertyOfTypeBigInteger p9qbi = mongoTemplate.findOne(new Query(where("id").in(p9bi.getId())),
- PersonWithIdPropertyOfTypeBigInteger.class);
- assertThat(p9qbi).isNotNull();
- assertThat(p9qbi.getId()).isEqualTo(p9bi.getId());
- checkCollectionContents(PersonWithIdPropertyOfTypeBigInteger.class, 1);
-
- // int id - provided
- PersonWithIdPropertyOfPrimitiveInt p10 = new PersonWithIdPropertyOfPrimitiveInt();
- p10.setFirstName("Sven_10");
- p10.setAge(22);
- p10.setId(12345);
- // insert
- mongoTemplate.insert(p10);
- // also try save
- mongoTemplate.save(p10);
- assertThat(p10.getId()).isNotNull();
- PersonWithIdPropertyOfPrimitiveInt p10q = mongoTemplate.findOne(new Query(where("id").in(p10.getId())),
- PersonWithIdPropertyOfPrimitiveInt.class);
- assertThat(p10q).isNotNull();
- assertThat(p10q.getId()).isEqualTo(p10.getId());
- checkCollectionContents(PersonWithIdPropertyOfPrimitiveInt.class, 1);
-
- // Long id - provided
- PersonWithIdPropertyOfTypeLong p11 = new PersonWithIdPropertyOfTypeLong();
- p11.setFirstName("Sven_9");
- p11.setAge(22);
- p11.setId(Long.valueOf(12345L));
- // insert
- mongoTemplate.insert(p11);
- // also try save
- mongoTemplate.save(p11);
- assertThat(p11.getId()).isNotNull();
- PersonWithIdPropertyOfTypeLong p11q = mongoTemplate.findOne(new Query(where("id").in(p11.getId())),
- PersonWithIdPropertyOfTypeLong.class);
- assertThat(p11q).isNotNull();
- assertThat(p11q.getId()).isEqualTo(p11.getId());
- checkCollectionContents(PersonWithIdPropertyOfTypeLong.class, 1);
-
- // long id - provided
- PersonWithIdPropertyOfPrimitiveLong p12 = new PersonWithIdPropertyOfPrimitiveLong();
- p12.setFirstName("Sven_10");
- p12.setAge(22);
- p12.setId(12345L);
- // insert
- mongoTemplate.insert(p12);
- // also try save
- mongoTemplate.save(p12);
- assertThat(p12.getId()).isNotNull();
- PersonWithIdPropertyOfPrimitiveLong p12q = mongoTemplate.findOne(new Query(where("id").in(p12.getId())),
- PersonWithIdPropertyOfPrimitiveLong.class);
- assertThat(p12q).isNotNull();
- assertThat(p12q.getId()).isEqualTo(p12.getId());
- checkCollectionContents(PersonWithIdPropertyOfPrimitiveLong.class, 1);
-
- // DATAMONGO-1617
- // UUID id - provided
- PersonWithIdPropertyOfTypeUUID p13 = new PersonWithIdPropertyOfTypeUUID();
- p13.setFirstName("Sven_10");
- p13.setAge(22);
- // insert
- mongoTemplate.insert(p13);
- // also try save
- mongoTemplate.save(p13);
- assertThat(p13.getId()).isNotNull();
- PersonWithIdPropertyOfTypeUUID p13q = mongoTemplate.findOne(new Query(where("id").in(p13.getId())),
- PersonWithIdPropertyOfTypeUUID.class);
- assertThat(p13q).isNotNull();
- assertThat(p13q.getId()).isEqualTo(p13.getId());
- checkCollectionContents(PersonWithIdPropertyOfTypeUUID.class, 1);
- }
-
- private void checkCollectionContents(Class> entityClass, int count) {
- assertThat(template.findAll(entityClass).size()).isEqualTo(count);
- }
-
- @Test // DATAMONGO-234
- public void testFindAndUpdate() {
-
- template.insert(new Person("Tom", 21));
- template.insert(new Person("Dick", 22));
- template.insert(new Person("Harry", 23));
-
- Query query = new Query(Criteria.where("firstName").is("Harry"));
- Update update = new Update().inc("age", 1);
- Person p = template.findAndModify(query, update, Person.class); // return old
- assertThat(p.getFirstName()).isEqualTo("Harry");
- assertThat(p.getAge()).isEqualTo(23);
- p = template.findOne(query, Person.class);
- assertThat(p.getAge()).isEqualTo(24);
-
- p = template.findAndModify(query, update, Person.class, "person");
- assertThat(p.getAge()).isEqualTo(24);
- p = template.findOne(query, Person.class);
- assertThat(p.getAge()).isEqualTo(25);
-
- p = template.findAndModify(query, update, new FindAndModifyOptions().returnNew(true), Person.class);
- assertThat(p.getAge()).isEqualTo(26);
-
- p = template.findAndModify(query, update, new FindAndModifyOptions(), Person.class, "person");
- assertThat(p.getAge()).isEqualTo(26);
- p = template.findOne(query, Person.class);
- assertThat(p.getAge()).isEqualTo(27);
-
- Query query2 = new Query(Criteria.where("firstName").is("Mary"));
- p = template.findAndModify(query2, update, new FindAndModifyOptions().returnNew(true).upsert(true), Person.class);
- assertThat(p.getFirstName()).isEqualTo("Mary");
- assertThat(p.getAge()).isEqualTo(1);
-
- }
-
- @Test
- public void testFindAndUpdateUpsert() {
- template.insert(new Person("Tom", 21));
- template.insert(new Person("Dick", 22));
- Query query = new Query(Criteria.where("firstName").is("Harry"));
- Update update = new Update().set("age", 23);
- Person p = template.findAndModify(query, update, new FindAndModifyOptions().upsert(true).returnNew(true),
- Person.class);
- assertThat(p.getFirstName()).isEqualTo("Harry");
- assertThat(p.getAge()).isEqualTo(23);
- }
-
- @Test
- public void testFindAndRemove() throws Exception {
-
- Message m1 = new Message("Hello Spring");
- template.insert(m1);
- Message m2 = new Message("Hello Mongo");
- template.insert(m2);
-
- Query q = new Query(Criteria.where("text").regex("^Hello.*"));
- Message found1 = template.findAndRemove(q, Message.class);
- Message found2 = template.findAndRemove(q, Message.class);
-
- Message notFound = template.findAndRemove(q, Message.class);
- assertThat(found1).isNotNull();
- assertThat(found2).isNotNull();
- assertThat(notFound).isNull();
- }
-
- @Test // DATAMONGO-1761
- public void testDistinct() {
-
- Address address1 = new Address();
- address1.state = "PA";
- address1.city = "Philadelphia";
-
- Address address2 = new Address();
- address2.state = "PA";
- address2.city = " New York";
-
- MyPerson person1 = new MyPerson();
- person1.name = "Ben";
- person1.address = address1;
-
- MyPerson person2 = new MyPerson();
- person2.name = "Eric";
- person2.address = address2;
-
- template.save(person1);
- template.save(person2);
-
- assertThat(template.findDistinct("name", MyPerson.class, String.class)).containsExactlyInAnyOrder(person1.getName(),
- person2.getName());
- assertThat(template.findDistinct(new BasicQuery("{'address.state' : 'PA'}"), "name", MyPerson.class, String.class))
- .containsExactlyInAnyOrder(person1.getName(), person2.getName());
- assertThat(template.findDistinct(new BasicQuery("{'address.state' : 'PA'}"), "name",
- template.getCollectionName(MyPerson.class), MyPerson.class, String.class))
- .containsExactlyInAnyOrder(person1.getName(), person2.getName());
- }
-
- @Test // DATAMONGO-1761
- public void testDistinctCovertsResultToPropertyTargetTypeCorrectly() {
-
- template.insert(new Person("garvin"));
-
- assertThat(template.findDistinct("firstName", Person.class, Object.class)).allSatisfy(String.class::isInstance);
- }
-
- @Test // DATAMONGO-1761
- public void testDistinctResolvesDbRefsCorrectly() {
-
- SomeContent content1 = new SomeContent();
- content1.text = "content-1";
-
- SomeContent content2 = new SomeContent();
- content2.text = "content-2";
-
- template.save(content1);
- template.save(content2);
-
- SomeTemplate t1 = new SomeTemplate();
- t1.content = content1;
-
- SomeTemplate t2 = new SomeTemplate();
- t2.content = content2;
-
- SomeTemplate t3 = new SomeTemplate();
- t3.content = content2;
-
- template.insert(t1);
- template.insert(t2);
- template.insert(t3);
-
- assertThat(template.findDistinct("content", SomeTemplate.class, SomeContent.class))
- .containsExactlyInAnyOrder(content1, content2);
- }
-
- @Test
- public void testUsingAnInQueryWithObjectId() throws Exception {
-
- template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class);
-
- PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
- p1.setFirstName("Sven");
- p1.setAge(11);
- template.insert(p1);
- PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
- p2.setFirstName("Mary");
- p2.setAge(21);
- template.insert(p2);
- PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId();
- p3.setFirstName("Ann");
- p3.setAge(31);
- template.insert(p3);
- PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId();
- p4.setFirstName("John");
- p4.setAge(41);
- template.insert(p4);
-
- Query q1 = new Query(Criteria.where("age").in(11, 21, 41));
- List results1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class);
- Query q2 = new Query(Criteria.where("firstName").in("Ann", "Mary"));
- List results2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class);
- Query q3 = new Query(Criteria.where("id").in(p3.getId()));
- List results3 = template.find(q3, PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(results1.size()).isEqualTo(3);
- assertThat(results2.size()).isEqualTo(2);
- assertThat(results3.size()).isEqualTo(1);
- }
-
- @Test
- public void testUsingAnInQueryWithStringId() throws Exception {
-
- template.remove(new Query(), PersonWithIdPropertyOfTypeString.class);
-
- PersonWithIdPropertyOfTypeString p1 = new PersonWithIdPropertyOfTypeString();
- p1.setFirstName("Sven");
- p1.setAge(11);
- template.insert(p1);
- PersonWithIdPropertyOfTypeString p2 = new PersonWithIdPropertyOfTypeString();
- p2.setFirstName("Mary");
- p2.setAge(21);
- template.insert(p2);
- PersonWithIdPropertyOfTypeString p3 = new PersonWithIdPropertyOfTypeString();
- p3.setFirstName("Ann");
- p3.setAge(31);
- template.insert(p3);
- PersonWithIdPropertyOfTypeString p4 = new PersonWithIdPropertyOfTypeString();
- p4.setFirstName("John");
- p4.setAge(41);
- template.insert(p4);
-
- Query q1 = new Query(Criteria.where("age").in(11, 21, 41));
- List results1 = template.find(q1, PersonWithIdPropertyOfTypeString.class);
- Query q2 = new Query(Criteria.where("firstName").in("Ann", "Mary"));
- List results2 = template.find(q2, PersonWithIdPropertyOfTypeString.class);
- Query q3 = new Query(Criteria.where("id").in(p3.getId(), p4.getId()));
- List results3 = template.find(q3, PersonWithIdPropertyOfTypeString.class);
- assertThat(results1.size()).isEqualTo(3);
- assertThat(results2.size()).isEqualTo(2);
- assertThat(results3.size()).isEqualTo(2);
- }
-
- @Test
- public void testUsingAnInQueryWithLongId() throws Exception {
-
- template.remove(new Query(), PersonWithIdPropertyOfTypeLong.class);
-
- PersonWithIdPropertyOfTypeLong p1 = new PersonWithIdPropertyOfTypeLong();
- p1.setFirstName("Sven");
- p1.setAge(11);
- p1.setId(1001L);
- template.insert(p1);
- PersonWithIdPropertyOfTypeLong p2 = new PersonWithIdPropertyOfTypeLong();
- p2.setFirstName("Mary");
- p2.setAge(21);
- p2.setId(1002L);
- template.insert(p2);
- PersonWithIdPropertyOfTypeLong p3 = new PersonWithIdPropertyOfTypeLong();
- p3.setFirstName("Ann");
- p3.setAge(31);
- p3.setId(1003L);
- template.insert(p3);
- PersonWithIdPropertyOfTypeLong p4 = new PersonWithIdPropertyOfTypeLong();
- p4.setFirstName("John");
- p4.setAge(41);
- p4.setId(1004L);
- template.insert(p4);
-
- Query q1 = new Query(Criteria.where("age").in(11, 21, 41));
- List results1 = template.find(q1, PersonWithIdPropertyOfTypeLong.class);
- Query q2 = new Query(Criteria.where("firstName").in("Ann", "Mary"));
- List results2 = template.find(q2, PersonWithIdPropertyOfTypeLong.class);
- Query q3 = new Query(Criteria.where("id").in(1001L, 1004L));
- List results3 = template.find(q3, PersonWithIdPropertyOfTypeLong.class);
- assertThat(results1.size()).isEqualTo(3);
- assertThat(results2.size()).isEqualTo(2);
- assertThat(results3.size()).isEqualTo(2);
- }
-
- @Test // DATAMONGO-602
- public void testUsingAnInQueryWithBigIntegerId() throws Exception {
-
- template.remove(new Query(), PersonWithIdPropertyOfTypeBigInteger.class);
-
- PersonWithIdPropertyOfTypeBigInteger p1 = new PersonWithIdPropertyOfTypeBigInteger();
- p1.setFirstName("Sven");
- p1.setAge(11);
- p1.setId(new BigInteger("2666666666666666665069473312490162649510603601"));
- template.insert(p1);
- PersonWithIdPropertyOfTypeBigInteger p2 = new PersonWithIdPropertyOfTypeBigInteger();
- p2.setFirstName("Mary");
- p2.setAge(21);
- p2.setId(new BigInteger("2666666666666666665069473312490162649510603602"));
- template.insert(p2);
- PersonWithIdPropertyOfTypeBigInteger p3 = new PersonWithIdPropertyOfTypeBigInteger();
- p3.setFirstName("Ann");
- p3.setAge(31);
- p3.setId(new BigInteger("2666666666666666665069473312490162649510603603"));
- template.insert(p3);
- PersonWithIdPropertyOfTypeBigInteger p4 = new PersonWithIdPropertyOfTypeBigInteger();
- p4.setFirstName("John");
- p4.setAge(41);
- p4.setId(new BigInteger("2666666666666666665069473312490162649510603604"));
- template.insert(p4);
-
- Query q1 = new Query(Criteria.where("age").in(11, 21, 41));
- List results1 = template.find(q1, PersonWithIdPropertyOfTypeBigInteger.class);
- Query q2 = new Query(Criteria.where("firstName").in("Ann", "Mary"));
- List results2 = template.find(q2, PersonWithIdPropertyOfTypeBigInteger.class);
- Query q3 = new Query(Criteria.where("id").in(new BigInteger("2666666666666666665069473312490162649510603601"),
- new BigInteger("2666666666666666665069473312490162649510603604")));
- List results3 = template.find(q3, PersonWithIdPropertyOfTypeBigInteger.class);
- assertThat(results1.size()).isEqualTo(3);
- assertThat(results2.size()).isEqualTo(2);
- assertThat(results3.size()).isEqualTo(2);
- }
-
- @Test
- public void testUsingAnInQueryWithPrimitiveIntId() throws Exception {
-
- template.remove(new Query(), PersonWithIdPropertyOfPrimitiveInt.class);
-
- PersonWithIdPropertyOfPrimitiveInt p1 = new PersonWithIdPropertyOfPrimitiveInt();
- p1.setFirstName("Sven");
- p1.setAge(11);
- p1.setId(1001);
- template.insert(p1);
- PersonWithIdPropertyOfPrimitiveInt p2 = new PersonWithIdPropertyOfPrimitiveInt();
- p2.setFirstName("Mary");
- p2.setAge(21);
- p2.setId(1002);
- template.insert(p2);
- PersonWithIdPropertyOfPrimitiveInt p3 = new PersonWithIdPropertyOfPrimitiveInt();
- p3.setFirstName("Ann");
- p3.setAge(31);
- p3.setId(1003);
- template.insert(p3);
- PersonWithIdPropertyOfPrimitiveInt p4 = new PersonWithIdPropertyOfPrimitiveInt();
- p4.setFirstName("John");
- p4.setAge(41);
- p4.setId(1004);
- template.insert(p4);
-
- Query q1 = new Query(Criteria.where("age").in(11, 21, 41));
- List results1 = template.find(q1, PersonWithIdPropertyOfPrimitiveInt.class);
- Query q2 = new Query(Criteria.where("firstName").in("Ann", "Mary"));
- List results2 = template.find(q2, PersonWithIdPropertyOfPrimitiveInt.class);
- Query q3 = new Query(Criteria.where("id").in(1001, 1003));
- List results3 = template.find(q3, PersonWithIdPropertyOfPrimitiveInt.class);
- assertThat(results1.size()).isEqualTo(3);
- assertThat(results2.size()).isEqualTo(2);
- assertThat(results3.size()).isEqualTo(2);
- }
-
- @Test
- public void testUsingInQueryWithList() throws Exception {
-
- template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class);
-
- PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
- p1.setFirstName("Sven");
- p1.setAge(11);
- template.insert(p1);
- PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
- p2.setFirstName("Mary");
- p2.setAge(21);
- template.insert(p2);
- PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId();
- p3.setFirstName("Ann");
- p3.setAge(31);
- template.insert(p3);
- PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId();
- p4.setFirstName("John");
- p4.setAge(41);
- template.insert(p4);
-
- List l1 = new ArrayList<>();
- l1.add(11);
- l1.add(21);
- l1.add(41);
- Query q1 = new Query(Criteria.where("age").in(l1));
- List results1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class);
- Query q2 = new Query(Criteria.where("age").in(l1.toArray()));
- List results2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(results1.size()).isEqualTo(3);
- assertThat(results2.size()).isEqualTo(3);
- try {
- List l2 = new ArrayList<>();
- l2.add(31);
- Query q3 = new Query(Criteria.where("age").in(l1, l2));
- template.find(q3, PersonWithIdPropertyOfTypeObjectId.class);
- fail("Should have trown an InvalidDocumentStoreApiUsageException");
- } catch (InvalidMongoDbApiUsageException e) {}
- }
-
- @Test
- public void testUsingRegexQueryWithOptions() throws Exception {
-
- template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class);
-
- PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
- p1.setFirstName("Sven");
- p1.setAge(11);
- template.insert(p1);
- PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
- p2.setFirstName("Mary");
- p2.setAge(21);
- template.insert(p2);
- PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId();
- p3.setFirstName("Ann");
- p3.setAge(31);
- template.insert(p3);
- PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId();
- p4.setFirstName("samantha");
- p4.setAge(41);
- template.insert(p4);
-
- Query q1 = new Query(Criteria.where("firstName").regex("S.*"));
- List results1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class);
- Query q2 = new Query(Criteria.where("firstName").regex("S.*", "i"));
- List results2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(results1.size()).isEqualTo(1);
- assertThat(results2.size()).isEqualTo(2);
- }
-
- @Test
- public void testUsingAnOrQuery() throws Exception {
-
- template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class);
-
- PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
- p1.setFirstName("Sven");
- p1.setAge(11);
- template.insert(p1);
- PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
- p2.setFirstName("Mary");
- p2.setAge(21);
- template.insert(p2);
- PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId();
- p3.setFirstName("Ann");
- p3.setAge(31);
- template.insert(p3);
- PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId();
- p4.setFirstName("John");
- p4.setAge(41);
- template.insert(p4);
-
- Query orQuery = new Query(new Criteria().orOperator(where("age").in(11, 21), where("age").is(31)));
- List results = template.find(orQuery, PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(results.size()).isEqualTo(3);
- for (PersonWithIdPropertyOfTypeObjectId p : results) {
- assertThat(p.getAge()).isIn(11, 21, 31);
- }
- }
-
- @Test
- public void testUsingUpdateWithMultipleSet() throws Exception {
-
- template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class);
-
- PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
- p1.setFirstName("Sven");
- p1.setAge(11);
- template.insert(p1);
- PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
- p2.setFirstName("Mary");
- p2.setAge(21);
- template.insert(p2);
-
- Update u = new Update().set("firstName", "Bob").set("age", 10);
-
- UpdateResult wr = template.updateMulti(new Query(), u, PersonWithIdPropertyOfTypeObjectId.class);
-
- if (wr.wasAcknowledged()) {
- assertThat(wr.getModifiedCount()).isEqualTo(2L);
- }
-
- Query q1 = new Query(Criteria.where("age").in(11, 21));
- List r1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(r1.size()).isEqualTo(0);
- Query q2 = new Query(Criteria.where("age").is(10));
- List r2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(r2.size()).isEqualTo(2);
- for (PersonWithIdPropertyOfTypeObjectId p : r2) {
- assertThat(p.getAge()).isEqualTo(10);
- assertThat(p.getFirstName()).isEqualTo("Bob");
- }
- }
-
- @Test
- public void testRemovingDocument() throws Exception {
-
- PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
- p1.setFirstName("Sven_to_be_removed");
- p1.setAge(51);
- template.insert(p1);
-
- Query q1 = new Query(Criteria.where("id").is(p1.getId()));
- PersonWithIdPropertyOfTypeObjectId found1 = template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(found1).isNotNull();
- Query _q = new Query(Criteria.where("_id").is(p1.getId()));
- template.remove(_q, PersonWithIdPropertyOfTypeObjectId.class);
- PersonWithIdPropertyOfTypeObjectId notFound1 = template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(notFound1).isNull();
-
- PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
- p2.setFirstName("Bubba_to_be_removed");
- p2.setAge(51);
- template.insert(p2);
-
- Query q2 = new Query(Criteria.where("id").is(p2.getId()));
- PersonWithIdPropertyOfTypeObjectId found2 = template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(found2).isNotNull();
- template.remove(q2, PersonWithIdPropertyOfTypeObjectId.class);
- PersonWithIdPropertyOfTypeObjectId notFound2 = template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(notFound2).isNull();
- }
-
- @Test
- public void testAddingToList() {
- PersonWithAList p = new PersonWithAList();
- p.setFirstName("Sven");
- p.setAge(22);
- template.insert(p);
-
- Query q1 = new Query(Criteria.where("id").is(p.getId()));
- PersonWithAList p2 = template.findOne(q1, PersonWithAList.class);
- assertThat(p2).isNotNull();
- assertThat(p2.getWishList().size()).isEqualTo(0);
-
- p2.addToWishList("please work!");
-
- template.save(p2);
-
- PersonWithAList p3 = template.findOne(q1, PersonWithAList.class);
- assertThat(p3).isNotNull();
- assertThat(p3.getWishList().size()).isEqualTo(1);
-
- Friend f = new Friend();
- p.setFirstName("Erik");
- p.setAge(21);
-
- p3.addFriend(f);
- template.save(p3);
-
- PersonWithAList p4 = template.findOne(q1, PersonWithAList.class);
- assertThat(p4).isNotNull();
- assertThat(p4.getWishList().size()).isEqualTo(1);
- assertThat(p4.getFriends().size()).isEqualTo(1);
-
- }
-
- @Test
- public void testFindOneWithSort() {
- PersonWithAList p = new PersonWithAList();
- p.setFirstName("Sven");
- p.setAge(22);
- template.insert(p);
-
- PersonWithAList p2 = new PersonWithAList();
- p2.setFirstName("Erik");
- p2.setAge(21);
- template.insert(p2);
-
- PersonWithAList p3 = new PersonWithAList();
- p3.setFirstName("Mark");
- p3.setAge(40);
- template.insert(p3);
-
- // test query with a sort
- Query q2 = new Query(Criteria.where("age").gt(10));
- q2.with(Sort.by(Direction.DESC, "age"));
- PersonWithAList p5 = template.findOne(q2, PersonWithAList.class);
- assertThat(p5.getFirstName()).isEqualTo("Mark");
- }
-
- @Test // DATAMONGO-2572
- public void testUsingReadPreference() throws Exception {
- this.template.execute("readPref", new CollectionCallback() {
- public Object doInCollection(MongoCollection collection)
- throws MongoException, DataAccessException {
-
- // assertThat(collection.getOptions(), is(0));
- // assertThat(collection.read.getDB().getOptions(), is(0));
- return null;
- }
- });
- MongoTemplate secondaryTemplate = new MongoTemplate(factory);
- secondaryTemplate.setReadPreference(ReadPreference.secondary());
- secondaryTemplate.execute("readPref", new CollectionCallback() {
- public Object doInCollection(MongoCollection collection)
- throws MongoException, DataAccessException {
- assertThat(collection.getReadPreference()).isEqualTo(ReadPreference.secondary());
- // assertThat(collection.getDB().getOptions(), is(0));
- return null;
- }
- });
- }
-
- @Test // DATADOC-166, DATAMONGO-1762
- public void removingNullIsANoOp() {
- assertThatIllegalArgumentException().isThrownBy(() -> template.remove((Object) null));
- }
-
- @Test // DATADOC-240, DATADOC-212
- public void updatesObjectIdsCorrectly() {
-
- PersonWithIdPropertyOfTypeObjectId person = new PersonWithIdPropertyOfTypeObjectId();
- person.setId(new ObjectId());
- person.setFirstName("Dave");
-
- template.save(person);
- template.updateFirst(query(where("id").is(person.getId())), update("firstName", "Carter"),
- PersonWithIdPropertyOfTypeObjectId.class);
-
- PersonWithIdPropertyOfTypeObjectId result = template.findById(person.getId(),
- PersonWithIdPropertyOfTypeObjectId.class);
- assertThat(result).isNotNull();
- assertThat(result.getId()).isEqualTo(person.getId());
- assertThat(result.getFirstName()).isEqualTo("Carter");
- }
-
- @Test
- public void testWriteConcernResolver() {
-
- PersonWithIdPropertyOfTypeObjectId person = new PersonWithIdPropertyOfTypeObjectId();
- person.setId(new ObjectId());
- person.setFirstName("Dave");
-
- template.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
- template.save(person);
- template.updateFirst(query(where("id").is(person.getId())), update("firstName", "Carter"),
- PersonWithIdPropertyOfTypeObjectId.class);
-
- FsyncSafeWriteConcernResolver resolver = new FsyncSafeWriteConcernResolver();
- template.setWriteConcernResolver(resolver);
- Query q = query(where("_id").is(person.getId()));
- Update u = update("firstName", "Carter");
- template.updateFirst(q, u, PersonWithIdPropertyOfTypeObjectId.class);
-
- MongoAction lastMongoAction = resolver.getMongoAction();
- assertThat(lastMongoAction.getCollectionName()).isEqualTo("personWithIdPropertyOfTypeObjectId");
- assertThat(lastMongoAction.getDefaultWriteConcern()).isEqualTo(WriteConcern.UNACKNOWLEDGED);
- assertThat(lastMongoAction.getDocument()).isNotNull();
- assertThat(lastMongoAction.getEntityType().toString())
- .isEqualTo(PersonWithIdPropertyOfTypeObjectId.class.toString());
- assertThat(lastMongoAction.getMongoActionOperation()).isEqualTo(MongoActionOperation.UPDATE);
- assertThat(lastMongoAction.getQuery()).isEqualTo(q.getQueryObject());
- }
-
- private class FsyncSafeWriteConcernResolver implements WriteConcernResolver {
-
- private MongoAction mongoAction;
-
- public WriteConcern resolve(MongoAction action) {
- this.mongoAction = action;
- return WriteConcern.JOURNALED;
- }
-
- public MongoAction getMongoAction() {
- return mongoAction;
- }
- }
-
- @Test // DATADOC-246
- public void updatesDBRefsCorrectly() {
-
- DBRef first = new DBRef("foo", new ObjectId());
- DBRef second = new DBRef("bar", new ObjectId());
-
- template.updateFirst(new Query(), update("dbRefs", Arrays.asList(first, second)), ClassWithDBRefs.class);
- }
-
- class ClassWithDBRefs {
- List dbrefs;
- }
-
- @Test // DATADOC-202
- public void executeDocument() {
-
- template.insert(new Person("Tom"));
- template.insert(new Person("Dick"));
- template.insert(new Person("Harry"));
- final List names = new ArrayList<>();
- template.executeQuery(new Query(), template.getCollectionName(Person.class), new DocumentCallbackHandler() {
- public void processDocument(org.bson.Document document) {
- String name = (String) document.get("firstName");
- if (name != null) {
- names.add(name);
- }
- }
- });
- assertThat(names.size()).isEqualTo(3);
- // template.remove(new Query(), Person.class);
- }
-
- @Test // DATADOC-202
- public void executeDocumentWithCursorPreparer() {
- template.insert(new Person("Tom"));
- template.insert(new Person("Dick"));
- template.insert(new Person("Harry"));
- final List names = new ArrayList<>();
- template.executeQuery(new Query(), template.getCollectionName(Person.class), new DocumentCallbackHandler() {
- public void processDocument(org.bson.Document document) {
- String name = (String) document.get("firstName");
- if (name != null) {
- names.add(name);
- }
- }
- }, new CursorPreparer() {
-
- public FindIterable prepare(FindIterable iterable) {
- iterable.limit(1);
- return iterable;
- }
-
- });
- assertThat(names.size()).isEqualTo(1);
- template.remove(new Query(), Person.class);
- }
-
- @Test // DATADOC-183
- public void countsDocumentsCorrectly() {
-
- assertThat(template.count(new Query(), Person.class)).isEqualTo(0L);
-
- Person dave = new Person("Dave");
- Person carter = new Person("Carter");
-
- template.save(dave);
- template.save(carter);
-
- assertThat(template.count(new Query(), Person.class)).isEqualTo(2L);
- assertThat(template.count(query(where("firstName").is("Carter")), Person.class)).isEqualTo(1L);
- }
-
- @Test // DATADOC-183
- public void countRejectsNullEntityClass() {
- assertThatIllegalArgumentException().isThrownBy(() -> template.count(null, (Class>) null));
- }
-
- @Test // DATADOC-183
- public void countRejectsEmptyCollectionName() {
- assertThatIllegalArgumentException().isThrownBy(() -> template.count(null, ""));
- }
-
- @Test // DATADOC-183
- public void countRejectsNullCollectionName() {
- assertThatIllegalArgumentException().isThrownBy(() -> template.count(null, (String) null));
- }
-
- @Test
- public void returnsEntityWhenQueryingForDateTime() {
-
- DateTime dateTime = new DateTime(2011, 3, 3, 12, 0, 0, 0);
- TestClass testClass = new TestClass(dateTime);
- mappingTemplate.save(testClass);
-
- List testClassList = mappingTemplate.find(new Query(Criteria.where("myDate").is(dateTime.toDate())),
- TestClass.class);
- assertThat(testClassList.size()).isEqualTo(1);
- assertThat(testClassList.get(0).myDate).isEqualTo(testClass.myDate);
- }
-
- @Test // DATADOC-230
- public void removesEntityFromCollection() {
-
- template.remove(new Query(), "mycollection");
-
- Person person = new Person("Dave");
-
- template.save(person, "mycollection");
- assertThat(template.findAll(TestClass.class, "mycollection").size()).isEqualTo(1);
-
- template.remove(person, "mycollection");
- assertThat(template.findAll(Person.class, "mycollection").isEmpty()).isTrue();
- }
-
- @Test // DATADOC-349
- public void removesEntityWithAnnotatedIdIfIdNeedsMassaging() {
-
- String id = new ObjectId().toString();
-
- Sample sample = new Sample();
- sample.id = id;
-
- template.save(sample);
-
- assertThat(template.findOne(query(where("id").is(id)), Sample.class).id).isEqualTo(id);
-
- template.remove(sample);
- assertThat(template.findOne(query(where("id").is(id)), Sample.class)).isNull();
- }
-
- @Test // DATAMONGO-423
- public void executesQueryWithNegatedRegexCorrectly() {
-
- Sample first = new Sample();
- first.field = "Matthews";
-
- Sample second = new Sample();
- second.field = "Beauford";
-
- template.save(first);
- template.save(second);
-
- Query query = query(where("field").not().regex("Matthews"));
-
- List result = template.find(query, Sample.class);
- assertThat(result.size()).isEqualTo(1);
- assertThat(result.get(0).field).isEqualTo("Beauford");
- }
-
- @Test // DATAMONGO-447
- public void storesAndRemovesTypeWithComplexId() {
-
- MyId id = new MyId();
- id.first = "foo";
- id.second = "bar";
-
- TypeWithMyId source = new TypeWithMyId();
- source.id = id;
-
- template.save(source);
- template.remove(query(where("id").is(id)), TypeWithMyId.class);
- }
-
- @Test // DATAMONGO-506
- public void exceutesBasicQueryCorrectly() {
-
- Address address = new Address();
- address.state = "PA";
- address.city = "Philadelphia";
-
- MyPerson person = new MyPerson();
- person.name = "Oleg";
- person.address = address;
-
- template.save(person);
-
- Query query = new BasicQuery("{'name' : 'Oleg'}");
- List result = template.find(query, MyPerson.class);
-
- assertThat(result).hasSize(1);
- assertThat(result.get(0).getName()).isEqualTo("Oleg");
-
- query = new BasicQuery("{'address.state' : 'PA' }");
- result = template.find(query, MyPerson.class);
-
- assertThat(result).hasSize(1);
- assertThat(result.get(0).getName()).isEqualTo("Oleg");
- }
-
- @Test // DATAMONGO-279
- public void optimisticLockingHandling() {
-
- // Init version
- PersonWithVersionPropertyOfTypeInteger person = new PersonWithVersionPropertyOfTypeInteger();
- person.age = 29;
- person.firstName = "Patryk";
- template.save(person);
-
- List result = template
- .findAll(PersonWithVersionPropertyOfTypeInteger.class);
-
- assertThat(result).hasSize(1);
- assertThat(result.get(0).version).isEqualTo(0);
-
- // Version change
- person = result.get(0);
- person.firstName = "Patryk2";
-
- template.save(person);
-
- assertThat(person.version).isEqualTo(1);
-
- result = mappingTemplate.findAll(PersonWithVersionPropertyOfTypeInteger.class);
-
- assertThat(result).hasSize(1);
- assertThat(result.get(0).version).isEqualTo(1);
-
- // Optimistic lock exception
- person.version = 0;
- person.firstName = "Patryk3";
-
- final PersonWithVersionPropertyOfTypeInteger toBeSaved = person;
-
- assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> template.save(toBeSaved));
- }
-
- @Test // DATAMONGO-562
- public void optimisticLockingHandlingWithExistingId() {
-
- PersonWithVersionPropertyOfTypeInteger person = new PersonWithVersionPropertyOfTypeInteger();
- person.id = new ObjectId().toString();
- person.age = 29;
- person.firstName = "Patryk";
- template.save(person);
- }
-
- @Test // DATAMONGO-617
- public void doesNotFailOnVersionInitForUnversionedEntity() {
-
- org.bson.Document document = new org.bson.Document();
- document.put("firstName", "Oliver");
-
- template.insert(document, template.getCollectionName(PersonWithVersionPropertyOfTypeInteger.class));
- }
-
- @Test // DATAMONGO-1617
- public void doesNotFailOnInsertForEntityWithNonAutogeneratableId() {
-
- PersonWithIdPropertyOfTypeUUID person = new PersonWithIdPropertyOfTypeUUID();
- person.setFirstName("Laszlo");
- person.setAge(33);
-
- template.insert(person);
- assertThat(person.getId()).isNotNull();
- }
-
- @Test // DATAMONGO-539
- public void removesObjectFromExplicitCollection() {
-
- String collectionName = "explicit";
- template.remove(new Query(), collectionName);
-
- PersonWithConvertedId person = new PersonWithConvertedId();
- person.name = "Dave";
- template.save(person, collectionName);
- assertThat(template.findAll(PersonWithConvertedId.class, collectionName).isEmpty()).isFalse();
-
- template.remove(person, collectionName);
- assertThat(template.findAll(PersonWithConvertedId.class, collectionName).isEmpty()).isTrue();
- }
-
- // DATAMONGO-549
- public void savesMapCorrectly() {
-
- Map map = new HashMap<>();
- map.put("key", "value");
-
- template.save(map, "maps");
- }
-
- @Test // DATAMONGO-549, DATAMONGO-1730
- public void savesMongoPrimitiveObjectCorrectly() {
- assertThatExceptionOfType(MappingException.class).isThrownBy(() -> template.save(new Object(), "collection"));
- }
-
- @Test // DATAMONGO-549
- public void rejectsNullObjectToBeSaved() {
- assertThatIllegalArgumentException().isThrownBy(() -> template.save(null));
- }
-
- @Test // DATAMONGO-550
- public void savesPlainDocumentCorrectly() {
-
- org.bson.Document document = new org.bson.Document("foo", "bar");
- template.save(document, "collection");
-
- assertThat(document.containsKey("_id")).isTrue();
- }
-
- @Test // DATAMONGO-550, DATAMONGO-1730
- public void rejectsPlainObjectWithOutExplicitCollection() {
-
- org.bson.Document document = new org.bson.Document("foo", "bar");
- template.save(document, "collection");
-
- assertThatExceptionOfType(MappingException.class)
- .isThrownBy(() -> template.findById(document.get("_id"), org.bson.Document.class));
- }
-
- @Test // DATAMONGO-550
- public void readsPlainDocumentById() {
-
- org.bson.Document document = new org.bson.Document("foo", "bar");
- template.save(document, "collection");
-
- org.bson.Document result = template.findById(document.get("_id"), org.bson.Document.class, "collection");
- assertThat(result.get("foo")).isEqualTo(document.get("foo"));
- assertThat(result.get("_id")).isEqualTo(document.get("_id"));
- }
-
- @Test // DATAMONGO-551
- public void writesPlainString() {
- template.save("{ 'foo' : 'bar' }", "collection");
- }
-
- @Test // DATAMONGO-551
- public void rejectsNonJsonStringForSave() {
- assertThatExceptionOfType(MappingException.class).isThrownBy(() -> template.save("Foobar!", "collection"));
- }
-
- @Test // DATAMONGO-588
- public void initializesVersionOnInsert() {
-
- PersonWithVersionPropertyOfTypeInteger person = new PersonWithVersionPropertyOfTypeInteger();
- person.firstName = "Dave";
-
- template.insert(person);
-
- assertThat(person.version).isEqualTo(0);
- }
-
- @Test // DATAMONGO-2195
- public void removeVersionedEntityConsidersVersion() {
-
- PersonWithVersionPropertyOfTypeInteger person = new PersonWithVersionPropertyOfTypeInteger();
- person.firstName = "Dave";
-
- template.insert(person);
- assertThat(person.version).isEqualTo(0);
- template.update(PersonWithVersionPropertyOfTypeInteger.class).matching(query(where("id").is(person.id)))
- .apply(new Update().set("firstName", "Walter")).first();
-
- DeleteResult deleteResult = template.remove(person);
-
- assertThat(deleteResult.wasAcknowledged()).isTrue();
- assertThat(deleteResult.getDeletedCount()).isZero();
- assertThat(template.count(new Query(), PersonWithVersionPropertyOfTypeInteger.class)).isOne();
- }
-
- @Test // DATAMONGO-588
- public void initializesVersionOnBatchInsert() {
-
- PersonWithVersionPropertyOfTypeInteger person = new PersonWithVersionPropertyOfTypeInteger();
- person.firstName = "Dave";
-
- template.insertAll(Arrays.asList(person));
-
- assertThat(person.version).isEqualTo(0);
- }
-
- @Test // DATAMONGO-1992
- public void initializesIdAndVersionAndOfImmutableObject() {
-
- ImmutableVersioned versioned = new ImmutableVersioned();
-
- ImmutableVersioned saved = template.insert(versioned);
-
- assertThat(saved).isNotSameAs(versioned);
- assertThat(versioned.id).isNull();
- assertThat(versioned.version).isNull();
-
- assertThat(saved.id).isNotNull();
- assertThat(saved.version).isEqualTo(0L);
- }
-
- @Test // DATAMONGO-568, DATAMONGO-1762
- public void queryCantBeNull() {
- assertThatIllegalArgumentException()
- .isThrownBy(() -> template.find(null, PersonWithIdPropertyOfTypeObjectId.class));
- }
-
- @Test // DATAMONGO-620
- public void versionsObjectIntoDedicatedCollection() {
-
- PersonWithVersionPropertyOfTypeInteger person = new PersonWithVersionPropertyOfTypeInteger();
- person.firstName = "Dave";
-
- template.save(person, "personX");
- assertThat(person.version).isEqualTo(0);
-
- template.save(person, "personX");
- assertThat(person.version).isEqualTo(1);
- }
-
- @Test // DATAMONGO-621
- public void correctlySetsLongVersionProperty() {
-
- PersonWithVersionPropertyOfTypeLong person = new PersonWithVersionPropertyOfTypeLong();
- person.firstName = "Dave";
-
- template.save(person);
- assertThat(person.version).isEqualTo(0L);
- }
-
- @Test // DATAMONGO-622
- public void preventsDuplicateInsert() {
-
- template.setWriteConcern(WriteConcern.ACKNOWLEDGED);
-
- PersonWithVersionPropertyOfTypeInteger person = new PersonWithVersionPropertyOfTypeInteger();
- person.firstName = "Dave";
-
- template.save(person);
- assertThat(person.version).isEqualTo(0);
-
- person.version = null;
- assertThatExceptionOfType(DuplicateKeyException.class).isThrownBy(() -> template.save(person));
- }
-
- @Test // DATAMONGO-629
- public void countAndFindWithoutTypeInformation() {
-
- Person person = new Person();
- template.save(person);
-
- Query query = query(where("_id").is(person.getId()));
- String collectionName = template.getCollectionName(Person.class);
-
- assertThat(template.find(query, HashMap.class, collectionName)).hasSize(1);
- assertThat(template.count(query, collectionName)).isEqualTo(1L);
- }
-
- @Test // DATAMONGO-571
- public void nullsPropertiesForVersionObjectUpdates() {
-
- VersionedPerson person = new VersionedPerson();
- person.firstname = "Dave";
- person.lastname = "Matthews";
-
- template.save(person);
- assertThat(person.id).isNotNull();
-
- person.lastname = null;
- template.save(person);
-
- person = template.findOne(query(where("id").is(person.id)), VersionedPerson.class);
- assertThat(person.lastname).isNull();
- }
-
- @Test // DATAMONGO-571
- public void nullsValuesForUpdatesOfUnversionedEntity() {
-
- Person person = new Person("Dave");
- template.save(person);
-
- person.setFirstName(null);
- template.save(person);
-
- person = template.findOne(query(where("id").is(person.getId())), Person.class);
- assertThat(person.getFirstName()).isNull();
- }
-
- @Test // DATAMONGO-679
- public void savesJsonStringCorrectly() {
-
- org.bson.Document document = new org.bson.Document().append("first", "first").append("second", "second");
-
- template.save(document, "collection");
-
- List result = template.findAll(org.bson.Document.class, "collection");
- assertThat(result.size()).isEqualTo(1);
- assertThat(result.get(0).containsKey("first")).isTrue();
- }
-
- @Test
- public void executesExistsCorrectly() {
-
- Sample sample = new Sample();
- template.save(sample);
-
- Query query = query(where("id").is(sample.id));
-
- assertThat(template.exists(query, Sample.class)).isTrue();
- assertThat(template.exists(query(where("_id").is(sample.id)), template.getCollectionName(Sample.class))).isTrue();
- assertThat(template.exists(query, Sample.class, template.getCollectionName(Sample.class))).isTrue();
- }
-
- @Test // DATAMONGO-675
- public void updateConsidersMappingAnnotations() {
-
- TypeWithFieldAnnotation entity = new TypeWithFieldAnnotation();
- entity.emailAddress = "old";
-
- template.save(entity);
-
- Query query = query(where("_id").is(entity.id));
- Update update = Update.update("emailAddress", "new");
-
- FindAndModifyOptions options = new FindAndModifyOptions().returnNew(true);
- TypeWithFieldAnnotation result = template.findAndModify(query, update, options, TypeWithFieldAnnotation.class);
- assertThat(result.emailAddress).isEqualTo("new");
- }
-
- @Test // DATAMONGO-671
- public void findsEntityByDateReference() {
-
- TypeWithDate entity = new TypeWithDate();
- entity.date = new Date(System.currentTimeMillis() - 10);
- template.save(entity);
-
- Query query = query(where("date").lt(new Date()));
- List result = template.find(query, TypeWithDate.class);
-
- assertThat(result).hasSize(1);
- assertThat(result.get(0).date).isNotNull();
- }
-
- @Test // DATAMONGO-540
- public void findOneAfterUpsertForNonExistingObjectReturnsTheInsertedObject() {
-
- String idValue = "4711";
- Query query = new Query(Criteria.where("id").is(idValue));
-
- String fieldValue = "bubu";
- Update update = Update.update("field", fieldValue);
-
- template.upsert(query, update, Sample.class);
- Sample result = template.findOne(query, Sample.class);
-
- assertThat(result).isNotNull();
- assertThat(result.field).isEqualTo(fieldValue);
- assertThat(result.id).isEqualTo(idValue);
- }
-
- @Test // DATAMONGO-392
- public void updatesShouldRetainTypeInformation() {
-
- Document doc = new Document();
- doc.id = "4711";
- doc.model = new ModelA("foo");
- template.insert(doc);
-
- Query query = new Query(Criteria.where("id").is(doc.id));
- String newModelValue = "bar";
- Update update = Update.update("model", new ModelA(newModelValue));
- template.updateFirst(query, update, Document.class);
-
- Document result = template.findOne(query, Document.class);
-
- assertThat(result).isNotNull();
- assertThat(result.id).isEqualTo(doc.id);
- assertThat(result.model).isNotNull();
- assertThat(result.model.value()).isEqualTo(newModelValue);
- }
-
- @Test // DATAMONGO-702
- public void queryShouldSupportRealAndAliasedPropertyNamesForFieldInclusions() {
-
- ObjectWith3AliasedFields obj = new ObjectWith3AliasedFields();
- obj.id = "4711";
- obj.property1 = "P1";
- obj.property2 = "P2";
- obj.property3 = "P3";
-
- template.insert(obj);
-
- Query query = new Query(Criteria.where("id").is(obj.id));
- query.fields() //
- .include("property2") // real property name
- .include("prop3"); // aliased property name
-
- ObjectWith3AliasedFields result = template.findOne(query, ObjectWith3AliasedFields.class);
-
- assertThat(result.id).isEqualTo(obj.id);
- assertThat(result.property1).isNull();
- assertThat(result.property2).isEqualTo(obj.property2);
- assertThat(result.property3).isEqualTo(obj.property3);
- }
-
- @Test // DATAMONGO-702, DATAMONGO-2294
- public void queryShouldSupportRealAndAliasedPropertyNamesForFieldExclusions() {
-
- ObjectWith3AliasedFields obj = new ObjectWith3AliasedFields();
- obj.id = "4711";
- obj.property1 = "P1";
- obj.property2 = "P2";
- obj.property3 = "P3";
-
- template.insert(obj);
-
- Query query = new Query(Criteria.where("id").is(obj.id));
- query.fields() //
- .exclude("property2", "prop3"); // real property name, aliased property name
-
- ObjectWith3AliasedFields result = template.findOne(query, ObjectWith3AliasedFields.class);
-
- assertThat(result.id).isEqualTo(obj.id);
- assertThat(result.property1).isEqualTo(obj.property1);
- assertThat(result.property2).isNull();
- assertThat(result.property3).isNull();
- }
-
- @Test // DATAMONGO-702
- public void findMultipleWithQueryShouldSupportRealAndAliasedPropertyNamesForFieldExclusions() {
-
- ObjectWith3AliasedFields obj0 = new ObjectWith3AliasedFields();
- obj0.id = "4711";
- obj0.property1 = "P10";
- obj0.property2 = "P20";
- obj0.property3 = "P30";
- ObjectWith3AliasedFields obj1 = new ObjectWith3AliasedFields();
- obj1.id = "4712";
- obj1.property1 = "P11";
- obj1.property2 = "P21";
- obj1.property3 = "P31";
-
- template.insert(obj0);
- template.insert(obj1);
-
- Query query = new Query(Criteria.where("id").in(obj0.id, obj1.id));
- query.fields() //
- .exclude("property2") // real property name
- .exclude("prop3"); // aliased property name
-
- List results = template.find(query, ObjectWith3AliasedFields.class);
-
- assertThat(results).isNotNull();
- assertThat(results.size()).isEqualTo(2);
-
- ObjectWith3AliasedFields result0 = results.get(0);
- assertThat(result0).isNotNull();
- assertThat(result0.id).isEqualTo(obj0.id);
- assertThat(result0.property1).isEqualTo(obj0.property1);
- assertThat(result0.property2).isNull();
- assertThat(result0.property3).isNull();
-
- ObjectWith3AliasedFields result1 = results.get(1);
- assertThat(result1).isNotNull();
- assertThat(result1.id).isEqualTo(obj1.id);
- assertThat(result1.property1).isEqualTo(obj1.property1);
- assertThat(result1.property2).isNull();
- assertThat(result1.property3).isNull();
- }
-
- @Test // DATAMONGO-702
- public void queryShouldSupportNestedPropertyNamesForFieldInclusions() {
-
- ObjectWith3AliasedFieldsAndNestedAddress obj = new ObjectWith3AliasedFieldsAndNestedAddress();
- obj.id = "4711";
- obj.property1 = "P1";
- obj.property2 = "P2";
- obj.property3 = "P3";
- Address address = new Address();
- String stateValue = "WA";
- address.state = stateValue;
- address.city = "Washington";
- obj.address = address;
-
- template.insert(obj);
-
- Query query = new Query(Criteria.where("id").is(obj.id));
- query.fields() //
- .include("property2") // real property name
- .include("address.state"); // aliased property name
-
- ObjectWith3AliasedFieldsAndNestedAddress result = template.findOne(query,
- ObjectWith3AliasedFieldsAndNestedAddress.class);
-
- assertThat(result.id).isEqualTo(obj.id);
- assertThat(result.property1).isNull();
- assertThat(result.property2).isEqualTo(obj.property2);
- assertThat(result.property3).isNull();
- assertThat(result.address).isNotNull();
- assertThat(result.address.city).isNull();
- assertThat(result.address.state).isEqualTo(stateValue);
- }
-
- @Test // DATAMONGO-709
- public void aQueryRestrictedWithOneRestrictedResultTypeShouldReturnOnlyInstancesOfTheRestrictedType() {
-
- BaseDoc doc0 = new BaseDoc();
- doc0.value = "foo";
- SpecialDoc doc1 = new SpecialDoc();
- doc1.value = "foo";
- doc1.specialValue = "specialfoo";
- VerySpecialDoc doc2 = new VerySpecialDoc();
- doc2.value = "foo";
- doc2.specialValue = "specialfoo";
- doc2.verySpecialValue = 4711;
-
- String collectionName = template.getCollectionName(BaseDoc.class);
- template.insert(doc0, collectionName);
- template.insert(doc1, collectionName);
- template.insert(doc2, collectionName);
-
- Query query = Query.query(where("value").is("foo")).restrict(SpecialDoc.class);
- List result = template.find(query, BaseDoc.class);
-
- assertThat(result).isNotNull();
- assertThat(result.size()).isEqualTo(1);
- assertThat(result.get(0)).isInstanceOf(SpecialDoc.class);
- }
-
- @Test // DATAMONGO-709
- public void aQueryRestrictedWithMultipleRestrictedResultTypesShouldReturnOnlyInstancesOfTheRestrictedTypes() {
-
- BaseDoc doc0 = new BaseDoc();
- doc0.value = "foo";
- SpecialDoc doc1 = new SpecialDoc();
- doc1.value = "foo";
- doc1.specialValue = "specialfoo";
- VerySpecialDoc doc2 = new VerySpecialDoc();
- doc2.value = "foo";
- doc2.specialValue = "specialfoo";
- doc2.verySpecialValue = 4711;
-
- String collectionName = template.getCollectionName(BaseDoc.class);
- template.insert(doc0, collectionName);
- template.insert(doc1, collectionName);
- template.insert(doc2, collectionName);
-
- Query query = Query.query(where("value").is("foo")).restrict(BaseDoc.class, VerySpecialDoc.class);
- List result = template.find(query, BaseDoc.class);
-
- assertThat(result).isNotNull();
- assertThat(result.size()).isEqualTo(2);
- assertThat(result.get(0).getClass()).isEqualTo((Object) BaseDoc.class);
- assertThat(result.get(1).getClass()).isEqualTo((Object) VerySpecialDoc.class);
- }
-
- @Test // DATAMONGO-709
- public void aQueryWithNoRestrictedResultTypesShouldReturnAllInstancesWithinTheGivenCollection() {
-
- BaseDoc doc0 = new BaseDoc();
- doc0.value = "foo";
- SpecialDoc doc1 = new SpecialDoc();
- doc1.value = "foo";
- doc1.specialValue = "specialfoo";
- VerySpecialDoc doc2 = new VerySpecialDoc();
- doc2.value = "foo";
- doc2.specialValue = "specialfoo";
- doc2.verySpecialValue = 4711;
-
- String collectionName = template.getCollectionName(BaseDoc.class);
- template.insert(doc0, collectionName);
- template.insert(doc1, collectionName);
- template.insert(doc2, collectionName);
-
- Query query = Query.query(where("value").is("foo"));
- List result = template.find(query, BaseDoc.class);
-
- assertThat(result).isNotNull();
- assertThat(result.size()).isEqualTo(3);
- assertThat(result.get(0).getClass()).isEqualTo((Object) BaseDoc.class);
- assertThat(result.get(1).getClass()).isEqualTo((Object) SpecialDoc.class);
- assertThat(result.get(2).getClass()).isEqualTo((Object) VerySpecialDoc.class);
- }
-
- @Test // DATAMONGO-771
- public void allowInsertWithPlainJsonString() {
-
- String id = "4711";
- String value = "bubu";
- String json = String.format("{_id:%s, field: '%s'}", id, value);
-
- template.insert(json, "sample");
- List result = template.findAll(Sample.class);
-
- assertThat(result.size()).isEqualTo(1);
- assertThat(result.get(0).id).isEqualTo(id);
- assertThat(result.get(0).field).isEqualTo(value);
- }
-
- @Test // DATAMONGO-2028
- public void allowInsertOfDbObjectWithMappedTypes() {
-
- DBObject dbObject = new BasicDBObject("_id", "foo").append("duration", Duration.ofSeconds(100));
- template.insert(dbObject, "sample");
- List result = template.findAll(org.bson.Document.class, "sample");
-
- assertThat(result.size()).isEqualTo(1);
- assertThat(result.get(0).getString("_id")).isEqualTo("foo");
- assertThat(result.get(0).getString("duration")).isEqualTo("PT1M40S");
- }
-
- @Test // DATAMONGO-816
- public void shouldExecuteQueryShouldMapQueryBeforeQueryExecution() {
-
- ObjectWithEnumValue o = new ObjectWithEnumValue();
- o.value = EnumValue.VALUE2;
- template.save(o);
-
- Query q = Query.query(Criteria.where("value").in(EnumValue.VALUE2));
-
- template.executeQuery(q, StringUtils.uncapitalize(ObjectWithEnumValue.class.getSimpleName()),
- new DocumentCallbackHandler() {
-
- @Override
- public void processDocument(org.bson.Document document) throws MongoException, DataAccessException {
-
- assertThat(document).isNotNull();
-
- ObjectWithEnumValue result = template.getConverter().read(ObjectWithEnumValue.class, document);
-
- assertThat(result.value).isEqualTo(EnumValue.VALUE2);
- }
- });
- }
-
- @Test // DATAMONGO-811
- public void updateFirstShouldIncreaseVersionForVersionedEntity() {
-
- VersionedPerson person = new VersionedPerson();
- person.firstname = "Dave";
- person.lastname = "Matthews";
- template.save(person);
- assertThat(person.id).isNotNull();
-
- Query qry = query(where("id").is(person.id));
- VersionedPerson personAfterFirstSave = template.findOne(qry, VersionedPerson.class);
- assertThat(personAfterFirstSave.version).isEqualTo(0L);
-
- template.updateFirst(qry, Update.update("lastname", "Bubu"), VersionedPerson.class);
-
- VersionedPerson personAfterUpdateFirst = template.findOne(qry, VersionedPerson.class);
- assertThat(personAfterUpdateFirst.version).isEqualTo(1L);
- assertThat(personAfterUpdateFirst.lastname).isEqualTo("Bubu");
- }
-
- @Test // DATAMONGO-811
- public void updateFirstShouldIncreaseVersionOnlyForFirstMatchingEntity() {
-
- VersionedPerson person1 = new VersionedPerson();
- person1.firstname = "Dave";
-
- VersionedPerson person2 = new VersionedPerson();
- person2.firstname = "Dave";
-
- template.save(person1);
- template.save(person2);
- Query q = query(where("id").in(person1.id, person2.id));
-
- template.updateFirst(q, Update.update("lastname", "Metthews"), VersionedPerson.class);
-
- for (VersionedPerson p : template.find(q, VersionedPerson.class)) {
- if ("Metthews".equals(p.lastname)) {
- assertThat(p.version).isEqualTo(Long.valueOf(1));
- } else {
- assertThat(p.version).isEqualTo(Long.valueOf(0));
- }
- }
- }
-
- @Test // DATAMONGO-811
- public void updateMultiShouldIncreaseVersionOfAllUpdatedEntities() {
-
- VersionedPerson person1 = new VersionedPerson();
- person1.firstname = "Dave";
-
- VersionedPerson person2 = new VersionedPerson();
- person2.firstname = "Dave";
-
- template.save(person1);
- template.save(person2);
-
- Query q = query(where("id").in(person1.id, person2.id));
- template.updateMulti(q, Update.update("lastname", "Metthews"), VersionedPerson.class);
-
- for (VersionedPerson p : template.find(q, VersionedPerson.class)) {
- assertThat(p.version).isEqualTo(Long.valueOf(1));
- }
- }
-
- @Test // DATAMONGO-686
- public void itShouldBePossibleToReuseAnExistingQuery() {
-
- Sample sample = new Sample();
- sample.id = "42";
- sample.field = "A";
-
- template.save(sample);
-
- Query query = new Query();
- query.addCriteria(where("_id").in("42", "43"));
-
- assertThat(template.count(query, Sample.class)).isEqualTo(1L);
-
- query.with(PageRequest.of(0, 10));
- query.with(Sort.by("field"));
-
- assertThat(template.find(query, Sample.class)).isNotEmpty();
- }
-
- @Test // DATAMONGO-807
- public void findAndModifyShouldRetrainTypeInformationWithinUpdatedType() {
-
- Document document = new Document();
- document.model = new ModelA("value1");
-
- template.save(document);
-
- Query query = query(where("id").is(document.id));
- Update update = Update.update("model", new ModelA("value2"));
- template.findAndModify(query, update, Document.class);
-
- Document retrieved = template.findOne(query, Document.class);
- assertThat(retrieved.model).isInstanceOf(ModelA.class);
- assertThat(retrieved.model.value()).isEqualTo("value2");
- }
-
- @Test // DATAMONGO-1210
- public void findAndModifyShouldRetainTypeInformationWithinUpdatedTypeOnDocumentWithNestedCollectionWhenWholeCollectionIsReplaced() {
-
- DocumentWithNestedCollection doc = new DocumentWithNestedCollection();
-
- Map entry = new HashMap<>();
- entry.put("key1", new ModelA("value1"));
- doc.models.add(entry);
-
- template.save(doc);
-
- entry.put("key2", new ModelA("value2"));
-
- Query query = query(where("id").is(doc.id));
- Update update = Update.update("models", Collections.singletonList(entry));
-
- assertThat(template.findOne(query, DocumentWithNestedCollection.class)).isNotNull();
-
- template.findAndModify(query, update, DocumentWithNestedCollection.class);
-
- DocumentWithNestedCollection retrieved = template.findOne(query, DocumentWithNestedCollection.class);
-
- assertThat(retrieved).isNotNull();
- assertThat(retrieved.id).isEqualTo(doc.id);
-
- assertThat(retrieved.models.get(0).entrySet()).hasSize(2);
-
- assertThat(retrieved.models.get(0).get("key1")).isInstanceOf(ModelA.class);
- assertThat(retrieved.models.get(0).get("key1").value()).isEqualTo("value1");
-
- assertThat(retrieved.models.get(0).get("key2")).isInstanceOf(ModelA.class);
- assertThat(retrieved.models.get(0).get("key2").value()).isEqualTo("value2");
- }
-
- @Test // DATAMONGO-1210
- public void findAndModifyShouldRetainTypeInformationWithinUpdatedTypeOnDocumentWithNestedCollectionWhenFirstElementIsReplaced() {
-
- DocumentWithNestedCollection doc = new DocumentWithNestedCollection();
-
- Map entry = new HashMap<>();
- entry.put("key1", new ModelA("value1"));
- doc.models.add(entry);
-
- template.save(doc);
-
- entry.put("key2", new ModelA("value2"));
-
- Query query = query(where("id").is(doc.id));
- Update update = Update.update("models.0", entry);
-
- assertThat(template.findOne(query, DocumentWithNestedCollection.class)).isNotNull();
-
- template.findAndModify(query, update, DocumentWithNestedCollection.class);
-
- DocumentWithNestedCollection retrieved = template.findOne(query, DocumentWithNestedCollection.class);
-
- assertThat(retrieved).isNotNull();
- assertThat(retrieved.id).isEqualTo(doc.id);
-
- assertThat(retrieved.models.get(0).entrySet()).hasSize(2);
-
- assertThat(retrieved.models.get(0).get("key1")).isInstanceOf(ModelA.class);
- assertThat(retrieved.models.get(0).get("key1").value()).isEqualTo("value1");
-
- assertThat(retrieved.models.get(0).get("key2")).isInstanceOf(ModelA.class);
- assertThat(retrieved.models.get(0).get("key2").value()).isEqualTo("value2");
- }
-
- @Test // DATAMONGO-1210
- public void findAndModifyShouldAddTypeInformationOnDocumentWithNestedCollectionObjectInsertedAtSecondIndex() {
-
- DocumentWithNestedCollection doc = new DocumentWithNestedCollection();
-
- Map entry = new HashMap<>();
- entry.put("key1", new ModelA("value1"));
- doc.models.add(entry);
-
- template.save(doc);
-
- Query query = query(where("id").is(doc.id));
- Update update = Update.update("models.1", Collections.singletonMap("key2", new ModelA("value2")));
-
- assertThat(template.findOne(query, DocumentWithNestedCollection.class)).isNotNull();
-
- template.findAndModify(query, update, DocumentWithNestedCollection.class);
-
- DocumentWithNestedCollection retrieved = template.findOne(query, DocumentWithNestedCollection.class);
-
- assertThat(retrieved).isNotNull();
- assertThat(retrieved.id).isEqualTo(doc.id);
-
- assertThat(retrieved.models.get(0).entrySet()).hasSize(1);
- assertThat(retrieved.models.get(1).entrySet()).hasSize(1);
-
- assertThat(retrieved.models.get(0).get("key1")).isInstanceOf(ModelA.class);
- assertThat(retrieved.models.get(0).get("key1").value()).isEqualTo("value1");
-
- assertThat(retrieved.models.get(1).get("key2")).isInstanceOf(ModelA.class);
- assertThat(retrieved.models.get(1).get("key2").value()).isEqualTo("value2");
- }
-
- @Test // DATAMONGO-1210
- public void findAndModifyShouldRetainTypeInformationWithinUpdatedTypeOnEmbeddedDocumentWithCollectionWhenUpdatingPositionedElement()
- throws Exception {
-
- List models = new ArrayList<>();
- models.add(new ModelA("value1"));
-
- DocumentWithEmbeddedDocumentWithCollection doc = new DocumentWithEmbeddedDocumentWithCollection(
- new DocumentWithCollection(models));
-
- template.save(doc);
-
- Query query = query(where("id").is(doc.id));
- Update update = Update.update("embeddedDocument.models.0", new ModelA("value2"));
-
- assertThat(template.findOne(query, DocumentWithEmbeddedDocumentWithCollection.class)).isNotNull();
-
- template.findAndModify(query, update, DocumentWithEmbeddedDocumentWithCollection.class);
-
- DocumentWithEmbeddedDocumentWithCollection retrieved = template.findOne(query,
- DocumentWithEmbeddedDocumentWithCollection.class);
-
- assertThat(retrieved).isNotNull();
- assertThat(retrieved.embeddedDocument.models).hasSize(1);
- assertThat(retrieved.embeddedDocument.models.get(0).value()).isEqualTo("value2");
- }
-
- @Test // DATAMONGO-1210
- public void findAndModifyShouldAddTypeInformationWithinUpdatedTypeOnEmbeddedDocumentWithCollectionWhenUpdatingSecondElement()
- throws Exception {
-
- List models = new ArrayList<>();
- models.add(new ModelA("value1"));
-
- DocumentWithEmbeddedDocumentWithCollection doc = new DocumentWithEmbeddedDocumentWithCollection(
- new DocumentWithCollection(models));
-
- template.save(doc);
-
- Query query = query(where("id").is(doc.id));
- Update update = Update.update("embeddedDocument.models.1", new ModelA("value2"));
-
- assertThat(template.findOne(query, DocumentWithEmbeddedDocumentWithCollection.class)).isNotNull();
-
- template.findAndModify(query, update, DocumentWithEmbeddedDocumentWithCollection.class);
-
- DocumentWithEmbeddedDocumentWithCollection retrieved = template.findOne(query,
- DocumentWithEmbeddedDocumentWithCollection.class);
-
- assertThat(retrieved).isNotNull();
- assertThat(retrieved.embeddedDocument.models).hasSize(2);
- assertThat(retrieved.embeddedDocument.models.get(0).value()).isEqualTo("value1");
- assertThat(retrieved.embeddedDocument.models.get(1).value()).isEqualTo("value2");
- }
-
- @Test // DATAMONGO-1210
- public void findAndModifyShouldAddTypeInformationWithinUpdatedTypeOnEmbeddedDocumentWithCollectionWhenRewriting()
- throws Exception {
-
- List models = Arrays. asList(new ModelA("value1"));
-
- DocumentWithEmbeddedDocumentWithCollection doc = new DocumentWithEmbeddedDocumentWithCollection(
- new DocumentWithCollection(models));
-
- template.save(doc);
-
- Query query = query(where("id").is(doc.id));
- Update update = Update.update("embeddedDocument",
- new DocumentWithCollection(Arrays. asList(new ModelA("value2"))));
-
- assertThat(template.findOne(query, DocumentWithEmbeddedDocumentWithCollection.class)).isNotNull();
-
- template.findAndModify(query, update, DocumentWithEmbeddedDocumentWithCollection.class);
-
- DocumentWithEmbeddedDocumentWithCollection retrieved = template.findOne(query,
- DocumentWithEmbeddedDocumentWithCollection.class);
-
- assertThat(retrieved).isNotNull();
- assertThat(retrieved.embeddedDocument.models).hasSize(1);
- assertThat(retrieved.embeddedDocument.models.get(0).value()).isEqualTo("value2");
- }
-
- @Test // DATAMONGO-1210
- public void findAndModifyShouldAddTypeInformationWithinUpdatedTypeOnDocumentWithNestedLists() {
-
- DocumentWithNestedList doc = new DocumentWithNestedList();
-
- List entry = new ArrayList<>();
- entry.add(new ModelA("value1"));
- doc.models.add(entry);
-
- template.save(doc);
-
- Query query = query(where("id").is(doc.id));
-
- assertThat(template.findOne(query, DocumentWithNestedList.class)).isNotNull();
-
- Update update = Update.update("models.0.1", new ModelA("value2"));
-
- template.findAndModify(query, update, DocumentWithNestedList.class);
-
- DocumentWithNestedList retrieved = template.findOne(query, DocumentWithNestedList.class);
-
- assertThat(retrieved).isNotNull();
- assertThat(retrieved.id).isEqualTo(doc.id);
-
- assertThat(retrieved.models.get(0)).hasSize(2);
-
- assertThat(retrieved.models.get(0).get(0)).isInstanceOf(ModelA.class);
- assertThat(retrieved.models.get(0).get(0).value()).isEqualTo("value1");
-
- assertThat(retrieved.models.get(0).get(1)).isInstanceOf(ModelA.class);
- assertThat(retrieved.models.get(0).get(1).value()).isEqualTo("value2");
- }
-
- @Test // DATAMONGO-1827
- public void findAndReplaceShouldReplaceDocument() {
-
- org.bson.Document doc = new org.bson.Document("foo", "bar");
- template.save(doc, "findandreplace");
-
- org.bson.Document replacement = new org.bson.Document("foo", "baz");
- org.bson.Document previous = template.findAndReplace(query(where("foo").is("bar")), replacement,
- FindAndReplaceOptions.options(), org.bson.Document.class, "findandreplace");
-
- assertThat(previous).containsEntry("foo", "bar");
- assertThat(template.findOne(query(where("foo").is("baz")), org.bson.Document.class, "findandreplace")).isNotNull();
- }
-
- @Test // DATAMONGO-1827
- @MongoVersion(asOf = "3.6")
- public void findAndReplaceShouldErrorOnIdPresent() {
-
- template.save(new MyPerson("Walter"));
-
- MyPerson replacement = new MyPerson("Heisenberg");
- replacement.id = "invalid-id";
-
- assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
- .isThrownBy(() -> template.findAndReplace(query(where("name").is("Walter")), replacement));
- }
-
- @Test // DATAMONGO-1827
- public void findAndReplaceShouldErrorOnSkip() {
-
- assertThatIllegalArgumentException().isThrownBy(
- () -> template.findAndReplace(query(where("name").is("Walter")).skip(10), new MyPerson("Heisenberg")));
- }
-
- @Test // DATAMONGO-1827
- public void findAndReplaceShouldErrorOnLimit() {
-
- assertThatIllegalArgumentException().isThrownBy(
- () -> template.findAndReplace(query(where("name").is("Walter")).limit(10), new MyPerson("Heisenberg")));
- }
-
- @Test // DATAMONGO-1827
- public void findAndReplaceShouldConsiderSortAndUpdateFirstIfMultipleFound() {
-
- MyPerson walter1 = new MyPerson("Walter 1");
- MyPerson walter2 = new MyPerson("Walter 2");
-
- template.save(walter1);
- template.save(walter2);
-
- MyPerson replacement = new MyPerson("Heisenberg");
-
- template.findAndReplace(query(where("name").regex("Walter.*")).with(Sort.by(Direction.DESC, "name")), replacement);
-
- assertThat(template.findAll(MyPerson.class)).hasSize(2).contains(walter1).doesNotContain(walter2);
- }
-
- @Test // DATAMONGO-1827
- public void findAndReplaceShouldReplaceObject() {
-
- MyPerson person = new MyPerson("Walter");
- template.save(person);
-
- MyPerson previous = template.findAndReplace(query(where("name").is("Walter")), new MyPerson("Heisenberg"));
-
- assertThat(previous.getName()).isEqualTo("Walter");
- assertThat(template.findOne(query(where("id").is(person.id)), MyPerson.class)).hasFieldOrPropertyWithValue("name",
- "Heisenberg");
- }
-
- @Test // DATAMONGO-1827
- public void findAndReplaceShouldConsiderFields() {
-
- MyPerson person = new MyPerson("Walter");
- person.address = new Address("TX", "Austin");
- template.save(person);
-
- Query query = query(where("name").is("Walter"));
- query.fields().include("address");
-
- MyPerson previous = template.findAndReplace(query, new MyPerson("Heisenberg"));
-
- assertThat(previous.getName()).isNull();
- assertThat(previous.getAddress()).isEqualTo(person.address);
- }
-
- @Test // DATAMONGO-1827
- public void findAndReplaceNonExistingWithUpsertFalse() {
-
- MyPerson previous = template.findAndReplace(query(where("name").is("Walter")), new MyPerson("Heisenberg"));
-
- assertThat(previous).isNull();
- assertThat(template.findAll(MyPerson.class)).isEmpty();
- }
-
- @Test // DATAMONGO-1827
- public void findAndReplaceNonExistingWithUpsertTrue() {
-
- MyPerson previous = template.findAndReplace(query(where("name").is("Walter")), new MyPerson("Heisenberg"),
- FindAndReplaceOptions.options().upsert());
-
- assertThat(previous).isNull();
- assertThat(template.findAll(MyPerson.class)).hasSize(1);
- }
-
- @Test // DATAMONGO-1827
- public void findAndReplaceShouldReplaceObjectReturingNew() {
-
- MyPerson person = new MyPerson("Walter");
- template.save(person);
-
- MyPerson updated = template.findAndReplace(query(where("name").is("Walter")), new MyPerson("Heisenberg"),
- FindAndReplaceOptions.options().returnNew());
-
- assertThat(updated.getName()).isEqualTo("Heisenberg");
- }
-
- @Test // DATAMONGO-1827
- public void findAndReplaceShouldProjectReturnedObjectCorrectly() {
-
- template.save(new MyPerson("Walter"));
-
- MyPersonProjection projection = template.findAndReplace(query(where("name").is("Walter")),
- new MyPerson("Heisenberg"), FindAndReplaceOptions.empty(), MyPerson.class, MyPersonProjection.class);
-
- assertThat(projection.getName()).isEqualTo("Walter");
- }
-
- @Test // DATAMONGO-407
- public void updatesShouldRetainTypeInformationEvenForCollections() {
-
- List models = Arrays. asList(new ModelA("foo"));
-
- DocumentWithCollection doc = new DocumentWithCollection(models);
- doc.id = "4711";
- template.insert(doc);
-
- Query query = new Query(Criteria.where("id").is(doc.id));
- query.addCriteria(where("models.value").is("foo"));
- String newModelValue = "bar";
- Update update = Update.update("models.$", new ModelA(newModelValue));
- template.updateFirst(query, update, DocumentWithCollection.class);
-
- Query findQuery = new Query(Criteria.where("id").is(doc.id));
- DocumentWithCollection result = template.findOne(findQuery, DocumentWithCollection.class);
-
- assertThat(result).isNotNull();
- assertThat(result.id).isEqualTo(doc.id);
- assertThat(result.models).isNotNull();
- assertThat(result.models).hasSize(1);
- assertThat(result.models.get(0).value()).isEqualTo(newModelValue);
- }
-
- @Test // DATAMONGO-812
- @MongoVersion(asOf = "2.4")
- public void updateMultiShouldAddValuesCorrectlyWhenUsingPushEachWithComplexTypes() {
-
- DocumentWithCollection document = new DocumentWithCollection(Collections. emptyList());
- template.save(document);
- Query query = query(where("id").is(document.id));
- assertThat(template.findOne(query, DocumentWithCollection.class).models).isEmpty();
-
- Update update = new Update().push("models").each(new ModelA("model-b"), new ModelA("model-c"));
- template.updateMulti(query, update, DocumentWithCollection.class);
-
- assertThat(template.findOne(query, DocumentWithCollection.class).models).hasSize(2);
- }
-
- @Test // DATAMONGO-812
- @MongoVersion(asOf = "2.4")
- public void updateMultiShouldAddValuesCorrectlyWhenUsingPushEachWithSimpleTypes() {
-
- DocumentWithCollectionOfSimpleType document = new DocumentWithCollectionOfSimpleType();
- document.values = Arrays.asList("spring");
- template.save(document);
-
- Query query = query(where("id").is(document.id));
- assertThat(template.findOne(query, DocumentWithCollectionOfSimpleType.class).values).hasSize(1);
-
- Update update = new Update().push("values").each("data", "mongodb");
- template.updateMulti(query, update, DocumentWithCollectionOfSimpleType.class);
-
- assertThat(template.findOne(query, DocumentWithCollectionOfSimpleType.class).values).hasSize(3);
- }
-
- @Test // DATAMONOGO-828
- public void updateFirstShouldDoNothingWhenCalledForEntitiesThatDoNotExist() {
-
- Query q = query(where("id").is(Long.MIN_VALUE));
-
- template.updateFirst(q, Update.update("lastname", "supercalifragilisticexpialidocious"), VersionedPerson.class);
- assertThat(template.findOne(q, VersionedPerson.class)).isNull();
- }
-
- @Test // DATAMONGO-354, DATAMONGO-1824
- @MongoVersion(until = "3.6")
- @SuppressWarnings("deprecation")
- public void testUpdateShouldAllowMultiplePushAll() {
-
- DocumentWithMultipleCollections doc = new DocumentWithMultipleCollections();
- doc.id = "1234";
- doc.string1 = Arrays.asList("spring");
- doc.string2 = Arrays.asList("one");
-
- template.save(doc);
-
- Update update = new Update().pushAll("string1", new Object[] { "data", "mongodb" });
- update.pushAll("string2", new String[] { "two", "three" });
-
- Query findQuery = new Query(Criteria.where("id").is(doc.id));
- template.updateFirst(findQuery, update, DocumentWithMultipleCollections.class);
-
- DocumentWithMultipleCollections result = template.findOne(findQuery, DocumentWithMultipleCollections.class);
- assertThat(result.string1).contains("spring", "data", "mongodb");
- assertThat(result.string2).contains("one", "two", "three");
-
- }
-
- @Test // DATAMONGO-404
- public void updateWithPullShouldRemoveNestedItemFromDbRefAnnotatedCollection() {
-
- Sample sample1 = new Sample("1", "A");
- Sample sample2 = new Sample("2", "B");
- template.save(sample1);
- template.save(sample2);
-
- DocumentWithDBRefCollection doc = new DocumentWithDBRefCollection();
- doc.id = "1";
- doc.dbRefAnnotatedList = Arrays.asList( //
- sample1, //
- sample2 //
- );
- template.save(doc);
-
- Update update = new Update().pull("dbRefAnnotatedList", doc.dbRefAnnotatedList.get(1));
-
- Query qry = query(where("id").is("1"));
- template.updateFirst(qry, update, DocumentWithDBRefCollection.class);
-
- DocumentWithDBRefCollection result = template.findOne(qry, DocumentWithDBRefCollection.class);
-
- assertThat(result).isNotNull();
- assertThat(result.dbRefAnnotatedList).hasSize(1);
- assertThat(result.dbRefAnnotatedList.get(0)).isNotNull();
- assertThat(result.dbRefAnnotatedList.get(0).id).isEqualTo((Object) "1");
- }
-
- @Test // DATAMONGO-404
- public void updateWithPullShouldRemoveNestedItemFromDbRefAnnotatedCollectionWhenGivenAnIdValueOfComponentTypeEntity() {
-
- Sample sample1 = new Sample("1", "A");
- Sample sample2 = new Sample("2", "B");
- template.save(sample1);
- template.save(sample2);
-
- DocumentWithDBRefCollection doc = new DocumentWithDBRefCollection();
- doc.id = "1";
- doc.dbRefAnnotatedList = Arrays.asList( //
- sample1, //
- sample2 //
- );
- template.save(doc);
-
- Update update = new Update().pull("dbRefAnnotatedList.id", "2");
-
- Query qry = query(where("id").is("1"));
- template.updateFirst(qry, update, DocumentWithDBRefCollection.class);
-
- DocumentWithDBRefCollection result = template.findOne(qry, DocumentWithDBRefCollection.class);
-
- assertThat(result).isNotNull();
- assertThat(result.dbRefAnnotatedList).hasSize(1);
- assertThat(result.dbRefAnnotatedList.get(0)).isNotNull();
- assertThat(result.dbRefAnnotatedList.get(0).id).isEqualTo((Object) "1");
- }
-
- @Test // DATAMONGO-852
- public void updateShouldNotBumpVersionNumberIfVersionPropertyIncludedInUpdate() {
-
- VersionedPerson person = new VersionedPerson();
- person.firstname = "Dave";
- person.lastname = "Matthews";
- template.save(person);
- assertThat(person.id).isNotNull();
-
- Query qry = query(where("id").is(person.id));
- VersionedPerson personAfterFirstSave = template.findOne(qry, VersionedPerson.class);
- assertThat(personAfterFirstSave.version).isEqualTo(0L);
-
- template.updateFirst(qry, Update.update("lastname", "Bubu").set("version", 100L), VersionedPerson.class);
-
- VersionedPerson personAfterUpdateFirst = template.findOne(qry, VersionedPerson.class);
- assertThat(personAfterUpdateFirst.version).isEqualTo(100L);
- assertThat(personAfterUpdateFirst.lastname).isEqualTo("Bubu");
- }
-
- @Test // DATAMONGO-468
- public void shouldBeAbleToUpdateDbRefPropertyWithDomainObject() {
-
- Sample sample1 = new Sample("1", "A");
- Sample sample2 = new Sample("2", "B");
- template.save(sample1);
- template.save(sample2);
-
- DocumentWithDBRefCollection doc = new DocumentWithDBRefCollection();
- doc.id = "1";
- doc.dbRefProperty = sample1;
- template.save(doc);
-
- Update update = new Update().set("dbRefProperty", sample2);
-
- Query qry = query(where("id").is("1"));
- template.updateFirst(qry, update, DocumentWithDBRefCollection.class);
-
- DocumentWithDBRefCollection updatedDoc = template.findOne(qry, DocumentWithDBRefCollection.class);
-
- assertThat(updatedDoc).isNotNull();
- assertThat(updatedDoc.dbRefProperty).isNotNull();
- assertThat(updatedDoc.dbRefProperty.id).isEqualTo(sample2.id);
- assertThat(updatedDoc.dbRefProperty.field).isEqualTo(sample2.field);
- }
-
- @Test // DATAMONGO-862
- public void testUpdateShouldWorkForPathsOnInterfaceMethods() {
-
- DocumentWithCollection document = new DocumentWithCollection(
- Arrays. asList(new ModelA("spring"), new ModelA("data")));
-
- template.save(document);
-
- Query query = query(where("id").is(document.id).and("models.value").exists(true));
- Update update = new Update().set("models.$.value", "mongodb");
- template.findAndModify(query, update, DocumentWithCollection.class);
-
- DocumentWithCollection result = template.findOne(query(where("id").is(document.id)), DocumentWithCollection.class);
- assertThat(result.models.get(0).value()).isEqualTo("mongodb");
- }
-
- @Test // DATAMONGO-773
- public void testShouldSupportQueryWithIncludedDbRefField() {
-
- Sample sample = new Sample("47111", "foo");
- template.save(sample);
-
- DocumentWithDBRefCollection doc = new DocumentWithDBRefCollection();
- doc.id = "4711";
- doc.dbRefProperty = sample;
-
- template.save(doc);
-
- Query qry = query(where("id").is(doc.id));
- qry.fields().include("dbRefProperty");
-
- List result = template.find(qry, DocumentWithDBRefCollection.class);
-
- assertThat(result).isNotNull();
- assertThat(result).hasSize(1);
- assertThat(result.get(0)).isNotNull();
- assertThat(result.get(0).dbRefProperty).isNotNull();
- assertThat(result.get(0).dbRefProperty.field).isEqualTo(sample.field);
- }
-
- @Test // DATAMONGO-566
- public void testFindAllAndRemoveFullyReturnsAndRemovesDocuments() {
-
- Sample spring = new Sample("100", "spring");
- Sample data = new Sample("200", "data");
- Sample mongodb = new Sample("300", "mongodb");
- template.insert(Arrays.asList(spring, data, mongodb), Sample.class);
-
- Query qry = query(where("field").in("spring", "mongodb"));
- List result = template.findAllAndRemove(qry, Sample.class);
-
- assertThat(result).hasSize(2);
-
- assertThat(template.getDb().getCollection("sample").countDocuments(
- new org.bson.Document("field", new org.bson.Document("$in", Arrays.asList("spring", "mongodb")))))
- .isEqualTo(0L);
- assertThat(template.getDb().getCollection("sample").countDocuments(new org.bson.Document("field", "data")))
- .isEqualTo(1L);
- }
-
- @Test // DATAMONGO-1001
- public void shouldAllowSavingOfLazyLoadedDbRefs() {
-
- template.dropCollection(SomeTemplate.class);
- template.dropCollection(SomeMessage.class);
- template.dropCollection(SomeContent.class);
-
- SomeContent content = new SomeContent();
- content.id = "content-1";
- content.text = "spring";
- template.save(content);
-
- SomeTemplate tmpl = new SomeTemplate();
- tmpl.id = "template-1";
- tmpl.content = content; // @DBRef(lazy=true) tmpl.content
-
- template.save(tmpl);
-
- SomeTemplate savedTmpl = template.findById(tmpl.id, SomeTemplate.class);
-
- SomeContent loadedContent = savedTmpl.getContent();
- loadedContent.setText("data");
- template.save(loadedContent);
-
- assertThat(template.findById(content.id, SomeContent.class).getText()).isEqualTo("data");
-
- }
-
- @Test // DATAMONGO-880
- public void savingAndReassigningLazyLoadingProxies() {
-
- template.dropCollection(SomeTemplate.class);
- template.dropCollection(SomeMessage.class);
- template.dropCollection(SomeContent.class);
-
- SomeContent content = new SomeContent();
- content.id = "C1";
- content.text = "BUBU";
- template.save(content);
-
- SomeTemplate tmpl = new SomeTemplate();
- tmpl.id = "T1";
- tmpl.content = content; // @DBRef(lazy=true) tmpl.content
-
- template.save(tmpl);
-
- SomeTemplate savedTmpl = template.findById(tmpl.id, SomeTemplate.class);
-
- SomeMessage message = new SomeMessage();
- message.id = "M1";
- message.dbrefContent = savedTmpl.content; // @DBRef message.dbrefContent
- message.normalContent = savedTmpl.content;
-
- template.save(message);
-
- SomeMessage savedMessage = template.findById(message.id, SomeMessage.class);
-
- assertThat(savedMessage.dbrefContent.text).isEqualTo(content.text);
- assertThat(savedMessage.normalContent.text).isEqualTo(content.text);
- }
-
- @Test // DATAMONGO-884
- public void callingNonObjectMethodsOnLazyLoadingProxyShouldReturnNullIfUnderlyingDbrefWasDeletedInbetween() {
-
- template.dropCollection(SomeTemplate.class);
- template.dropCollection(SomeContent.class);
-
- SomeContent content = new SomeContent();
- content.id = "C1";
- content.text = "BUBU";
- template.save(content);
-
- SomeTemplate tmpl = new SomeTemplate();
- tmpl.id = "T1";
- tmpl.content = content; // @DBRef(lazy=true) tmpl.content
-
- template.save(tmpl);
-
- SomeTemplate savedTmpl = template.findById(tmpl.id, SomeTemplate.class);
-
- template.remove(content);
-
- assertThat(savedTmpl.getContent().toString()).isEqualTo("someContent:C1$LazyLoadingProxy");
- assertThat(savedTmpl.getContent()).isInstanceOf(LazyLoadingProxy.class);
- assertThat(savedTmpl.getContent().getText()).isNull();
- }
-
- @Test // DATAMONGO-471
- public void updateMultiShouldAddValuesCorrectlyWhenUsingAddToSetWithEach() {
-
- DocumentWithCollectionOfSimpleType document = new DocumentWithCollectionOfSimpleType();
- document.values = Arrays.asList("spring");
- template.save(document);
-
- Query query = query(where("id").is(document.id));
- assertThat(template.findOne(query, DocumentWithCollectionOfSimpleType.class).values).hasSize(1);
-
- Update update = new Update().addToSet("values").each("data", "mongodb");
- template.updateMulti(query, update, DocumentWithCollectionOfSimpleType.class);
-
- assertThat(template.findOne(query, DocumentWithCollectionOfSimpleType.class).values).hasSize(3);
- }
-
- @Test // DATAMONGO-1210
- public void findAndModifyAddToSetWithEachShouldNotAddDuplicatesNorTypeHintForSimpleDocuments() {
-
- DocumentWithCollectionOfSamples doc = new DocumentWithCollectionOfSamples();
- doc.samples = Arrays.asList(new Sample(null, "sample1"));
-
- template.save(doc);
-
- Query query = query(where("id").is(doc.id));
-
- assertThat(template.findOne(query, DocumentWithCollectionOfSamples.class)).isNotNull();
-
- Update update = new Update().addToSet("samples").each(new Sample(null, "sample2"), new Sample(null, "sample1"));
-
- template.findAndModify(query, update, DocumentWithCollectionOfSamples.class);
-
- DocumentWithCollectionOfSamples retrieved = template.findOne(query, DocumentWithCollectionOfSamples.class);
-
- assertThat(retrieved).isNotNull();
- assertThat(retrieved.samples).hasSize(2);
- assertThat(retrieved.samples.get(0).field).isEqualTo("sample1");
- assertThat(retrieved.samples.get(1).field).isEqualTo("sample2");
- }
-
- @Test // DATAMONGO-888
- public void sortOnIdFieldPropertyShouldBeMappedCorrectly() {
-
- DoucmentWithNamedIdField one = new DoucmentWithNamedIdField();
- one.someIdKey = "1";
- one.value = "a";
-
- DoucmentWithNamedIdField two = new DoucmentWithNamedIdField();
- two.someIdKey = "2";
- two.value = "b";
-
- template.save(one);
- template.save(two);
-
- Query query = query(where("_id").in("1", "2")).with(Sort.by(Direction.DESC, "someIdKey"));
- assertThat(template.find(query, DoucmentWithNamedIdField.class)).containsExactly(two, one);
- }
-
- @Test // DATAMONGO-888
- public void sortOnAnnotatedFieldPropertyShouldBeMappedCorrectly() {
-
- DoucmentWithNamedIdField one = new DoucmentWithNamedIdField();
- one.someIdKey = "1";
- one.value = "a";
-
- DoucmentWithNamedIdField two = new DoucmentWithNamedIdField();
- two.someIdKey = "2";
- two.value = "b";
-
- template.save(one);
- template.save(two);
-
- Query query = query(where("_id").in("1", "2")).with(Sort.by(Direction.DESC, "value"));
- assertThat(template.find(query, DoucmentWithNamedIdField.class)).containsExactly(two, one);
- }
-
- @Test // DATAMONGO-913
- public void shouldRetrieveInitializedValueFromDbRefAssociationAfterLoad() {
-
- SomeContent content = new SomeContent();
- content.id = "content-1";
- content.name = "Content 1";
- content.text = "Some text";
-
- template.save(content);
-
- SomeTemplate tmpl = new SomeTemplate();
- tmpl.id = "template-1";
- tmpl.content = content;
-
- template.save(tmpl);
-
- SomeTemplate result = template.findOne(query(where("content").is(tmpl.getContent())), SomeTemplate.class);
-
- assertThat(result).isNotNull();
- assertThat(result.getContent()).isNotNull();
- assertThat(result.getContent().getId()).isNotNull();
- assertThat(result.getContent().getName()).isNotNull();
- assertThat(result.getContent().getText()).isEqualTo(content.getText());
- }
-
- @Test // DATAMONGO-913
- public void shouldReuseExistingDBRefInQueryFromDbRefAssociationAfterLoad() {
-
- SomeContent content = new SomeContent();
- content.id = "content-1";
- content.name = "Content 1";
- content.text = "Some text";
-
- template.save(content);
-
- SomeTemplate tmpl = new SomeTemplate();
- tmpl.id = "template-1";
- tmpl.content = content;
-
- template.save(tmpl);
-
- SomeTemplate result = template.findOne(query(where("content").is(tmpl.getContent())), SomeTemplate.class);
-
- // Use lazy-loading-proxy in query
- result = template.findOne(query(where("content").is(result.getContent())), SomeTemplate.class);
-
- assertThat(result.getContent().getName()).isNotNull();
- assertThat(result.getContent().getName()).isEqualTo(content.getName());
- }
-
- @Test // DATAMONGO-970
- public void insertsAndRemovesBasicDocumentCorrectly() {
-
- org.bson.Document object = new org.bson.Document("key", "value");
- template.insert(object, "collection");
-
- assertThat(object.get("_id")).isNotNull();
- assertThat(template.findAll(Document.class, "collection")).hasSize(1);
-
- template.remove(object, "collection");
- assertThat(template.findAll(Document.class, "collection")).hasSize(0);
- }
-
- @Test // DATAMONGO-1207
- public void ignoresNullElementsForInsertAll() {
-
- Address newYork = new Address("NY", "New York");
- Address washington = new Address("DC", "Washington");
-
- template.insertAll(Arrays.asList(newYork, null, washington));
-
- List result = template.findAll(Address.class);
-
- assertThat(result).hasSize(2);
- assertThat(result).contains(newYork, washington);
- }
-
- @Test // DATAMONGO-1176
- public void generatesIdForInsertAll() {
-
- Person walter = new Person(null, "Walter");
- Person jesse = new Person(null, "Jesse");
-
- template.insertAll(Arrays.asList(walter, jesse));
-
- List result = template.findAll(Person.class);
-
- assertThat(result).hasSize(2);
- assertThat(walter.getId()).isNotNull();
- assertThat(jesse.getId()).isNotNull();
- }
-
- @Test // DATAMONGO-1208
- public void takesSortIntoAccountWhenStreaming() {
-
- Person youngestPerson = new Person("John", 20);
- Person oldestPerson = new Person("Jane", 42);
-
- template.insertAll(Arrays.asList(oldestPerson, youngestPerson));
-
- Query q = new Query();
- q.with(Sort.by(Direction.ASC, "age"));
- CloseableIterator stream = template.stream(q, Person.class);
-
- assertThat(stream.next().getAge()).isEqualTo(youngestPerson.getAge());
- assertThat(stream.next().getAge()).isEqualTo(oldestPerson.getAge());
- }
-
- @Test // DATAMONGO-1208
- public void takesLimitIntoAccountWhenStreaming() {
-
- Person youngestPerson = new Person("John", 20);
- Person oldestPerson = new Person("Jane", 42);
-
- template.insertAll(Arrays.asList(oldestPerson, youngestPerson));
-
- Query q = new Query();
- q.with(PageRequest.of(0, 1, Sort.by(Direction.ASC, "age")));
- CloseableIterator stream = template.stream(q, Person.class);
-
- assertThat(stream.next().getAge()).isEqualTo(youngestPerson.getAge());
- assertThat(stream.hasNext()).isFalse();
- }
-
- @Test // DATAMONGO-1204
- public void resolvesCyclicDBRefCorrectly() {
-
- SomeMessage message = new SomeMessage();
- SomeContent content = new SomeContent();
-
- template.save(message);
- template.save(content);
-
- message.dbrefContent = content;
- content.dbrefMessage = message;
-
- template.save(message);
- template.save(content);
-
- SomeMessage messageLoaded = template.findOne(query(where("id").is(message.id)), SomeMessage.class);
- SomeContent contentLoaded = template.findOne(query(where("id").is(content.id)), SomeContent.class);
-
- assertThat(messageLoaded.dbrefContent.id).isEqualTo(contentLoaded.id);
- assertThat(contentLoaded.dbrefMessage.id).isEqualTo(messageLoaded.id);
- }
-
- @Test // DATAMONGO-1287, DATAMONGO-2004
- public void shouldReuseAlreadyResolvedLazyLoadedDBRefWhenUsedAsPersistenceConstructorArgument() {
-
- Document docInCtor = new Document();
- docInCtor.id = "doc-in-ctor";
- template.save(docInCtor);
-
- DocumentWithLazyDBrefUsedInPresistenceConstructor source = new DocumentWithLazyDBrefUsedInPresistenceConstructor(
- docInCtor);
-
- template.save(source);
-
- DocumentWithLazyDBrefUsedInPresistenceConstructor loaded = template.findOne(query(where("id").is(source.id)),
- DocumentWithLazyDBrefUsedInPresistenceConstructor.class);
- assertThat(loaded.refToDocUsedInCtor).isInstanceOf(LazyLoadingProxy.class);
- assertThat(loaded.refToDocNotUsedInCtor).isNull();
- }
-
- @Test // DATAMONGO-1287
- public void shouldNotReuseLazyLoadedDBRefWhenTypeUsedInPersistenceConstrcutorButValueRefersToAnotherProperty() {
-
- Document docNotUsedInCtor = new Document();
- docNotUsedInCtor.id = "doc-but-not-used-in-ctor";
- template.save(docNotUsedInCtor);
-
- DocumentWithLazyDBrefUsedInPresistenceConstructor source = new DocumentWithLazyDBrefUsedInPresistenceConstructor(
- null);
- source.refToDocNotUsedInCtor = docNotUsedInCtor;
-
- template.save(source);
-
- DocumentWithLazyDBrefUsedInPresistenceConstructor loaded = template.findOne(query(where("id").is(source.id)),
- DocumentWithLazyDBrefUsedInPresistenceConstructor.class);
- assertThat(loaded.refToDocNotUsedInCtor).isInstanceOf(LazyLoadingProxy.class);
- assertThat(loaded.refToDocUsedInCtor).isNull();
- }
-
- @Test // DATAMONGO-1287, DATAMONGO-2004
- public void shouldRespectParameterValueWhenAttemptingToReuseLazyLoadedDBRefUsedInPersistenceConstructor() {
-
- Document docInCtor = new Document();
- docInCtor.id = "doc-in-ctor";
- template.save(docInCtor);
-
- Document docNotUsedInCtor = new Document();
- docNotUsedInCtor.id = "doc-but-not-used-in-ctor";
- template.save(docNotUsedInCtor);
-
- DocumentWithLazyDBrefUsedInPresistenceConstructor source = new DocumentWithLazyDBrefUsedInPresistenceConstructor(
- docInCtor);
- source.refToDocNotUsedInCtor = docNotUsedInCtor;
-
- template.save(source);
-
- DocumentWithLazyDBrefUsedInPresistenceConstructor loaded = template.findOne(query(where("id").is(source.id)),
- DocumentWithLazyDBrefUsedInPresistenceConstructor.class);
- assertThat(loaded.refToDocUsedInCtor).isInstanceOf(LazyLoadingProxy.class);
- assertThat(loaded.refToDocNotUsedInCtor).isInstanceOf(LazyLoadingProxy.class);
- }
-
- @Test // DATAMONGO-1401
- public void updateShouldWorkForTypesContainingGeoJsonTypes() {
-
- WithGeoJson wgj = new WithGeoJson();
- wgj.id = "1";
- wgj.description = "datamongo-1401";
- wgj.point = new GeoJsonPoint(1D, 2D);
-
- template.save(wgj);
-
- wgj.description = "datamongo-1401-update";
- template.save(wgj);
-
- assertThat(template.findOne(query(where("id").is(wgj.id)), WithGeoJson.class).point).isEqualTo(wgj.point);
- }
-
- @Test // DATAMONGO-1404
- public void updatesDateValueCorrectlyWhenUsingMinOperator() {
-
- Calendar cal = Calendar.getInstance(Locale.US);
- cal.set(2013, 10, 13, 0, 0, 0);
-
- TypeWithDate twd = new TypeWithDate();
- twd.date = new Date();
- template.save(twd);
- template.updateFirst(query(where("id").is(twd.id)), new Update().min("date", cal.getTime()), TypeWithDate.class);
-
- TypeWithDate loaded = template.find(query(where("id").is(twd.id)), TypeWithDate.class).get(0);
- assertThat(loaded.date).isEqualTo(cal.getTime());
- }
-
- @Test // DATAMONGO-1404
- public void updatesNumericValueCorrectlyWhenUsingMinOperator() {
-
- TypeWithNumbers twn = new TypeWithNumbers();
- twn.byteVal = 100;
- twn.doubleVal = 200D;
- twn.floatVal = 300F;
- twn.intVal = 400;
- twn.longVal = 500L;
-
- // Note that $min operator uses String comparison for BigDecimal/BigInteger comparison according to BSON sort rules.
- twn.bigIntegerVal = new BigInteger("600");
- twn.bigDeciamVal = new BigDecimal("700.0");
-
- template.save(twn);
-
- byte byteVal = 90;
- Update update = new Update()//
- .min("byteVal", byteVal) //
- .min("doubleVal", 190D) //
- .min("floatVal", 290F) //
- .min("intVal", 390) //
- .min("longVal", 490) //
- .min("bigIntegerVal", new BigInteger("590")) //
- .min("bigDeciamVal", new BigDecimal("690")) //
- ;
-
- template.updateFirst(query(where("id").is(twn.id)), update, TypeWithNumbers.class);
-
- TypeWithNumbers loaded = template.find(query(where("id").is(twn.id)), TypeWithNumbers.class).get(0);
- assertThat(loaded.byteVal).isEqualTo(byteVal);
- assertThat(loaded.doubleVal).isEqualTo(190D);
- assertThat(loaded.floatVal).isEqualTo(290F);
- assertThat(loaded.intVal).isEqualTo(390);
- assertThat(loaded.longVal).isEqualTo(490L);
- assertThat(loaded.bigIntegerVal).isEqualTo(new BigInteger("590"));
- assertThat(loaded.bigDeciamVal).isEqualTo(new BigDecimal("690"));
- }
-
- @Test // DATAMONGO-1404
- public void updatesDateValueCorrectlyWhenUsingMaxOperator() {
-
- Calendar cal = Calendar.getInstance(Locale.US);
- cal.set(2013, 10, 13, 0, 0, 0);
-
- TypeWithDate twd = new TypeWithDate();
- twd.date = cal.getTime();
- template.save(twd);
-
- cal.set(2019, 10, 13, 0, 0, 0);
- template.updateFirst(query(where("id").is(twd.id)), new Update().max("date", cal.getTime()), TypeWithDate.class);
-
- TypeWithDate loaded = template.find(query(where("id").is(twd.id)), TypeWithDate.class).get(0);
- assertThat(loaded.date).isEqualTo(cal.getTime());
- }
-
- @Test // DATAMONGO-1404
- public void updatesNumericValueCorrectlyWhenUsingMaxOperator() {
-
- TypeWithNumbers twn = new TypeWithNumbers();
- twn.byteVal = 100;
- twn.doubleVal = 200D;
- twn.floatVal = 300F;
- twn.intVal = 400;
- twn.longVal = 500L;
-
- // Note that $max operator uses String comparison for BigDecimal/BigInteger comparison according to BSON sort rules.
- twn.bigIntegerVal = new BigInteger("600");
- twn.bigDeciamVal = new BigDecimal("700.0");
-
- template.save(twn);
-
- byte byteVal = 101;
- Update update = new Update()//
- .max("byteVal", byteVal) //
- .max("doubleVal", 290D) //
- .max("floatVal", 390F) //
- .max("intVal", 490) //
- .max("longVal", 590) //
- .max("bigIntegerVal", new BigInteger("690")) //
- .max("bigDeciamVal", new BigDecimal("790")) //
- ;
-
- template.updateFirst(query(where("id").is(twn.id)), update, TypeWithNumbers.class);
-
- TypeWithNumbers loaded = template.find(query(where("id").is(twn.id)), TypeWithNumbers.class).get(0);
- assertThat(loaded.byteVal).isEqualTo(byteVal);
- assertThat(loaded.doubleVal).isEqualTo(290D);
- assertThat(loaded.floatVal).isEqualTo(390F);
- assertThat(loaded.intVal).isEqualTo(490);
- assertThat(loaded.longVal).isEqualTo(590L);
- assertThat(loaded.bigIntegerVal).isEqualTo(new BigInteger("690"));
- assertThat(loaded.bigDeciamVal).isEqualTo(new BigDecimal("790"));
- }
-
- @Test // DATAMONGO-1404
- public void updatesBigNumberValueUsingStringComparisonWhenUsingMaxOperator() {
-
- TypeWithNumbers twn = new TypeWithNumbers();
-
- // Note that $max operator uses String comparison for BigDecimal/BigInteger comparison according to BSON sort rules.
- // Therefore "80" is considered greater than "700"
- twn.bigIntegerVal = new BigInteger("600");
- twn.bigDeciamVal = new BigDecimal("700.0");
-
- template.save(twn);
-
- Update update = new Update()//
- .max("bigIntegerVal", new BigInteger("70")) //
- .max("bigDeciamVal", new BigDecimal("80")) //
- ;
-
- template.updateFirst(query(where("id").is(twn.id)), update, TypeWithNumbers.class);
-
- TypeWithNumbers loaded = template.find(query(where("id").is(twn.id)), TypeWithNumbers.class).get(0);
- assertThat(loaded.bigIntegerVal).isEqualTo(new BigInteger("70"));
- assertThat(loaded.bigDeciamVal).isEqualTo(new BigDecimal("80"));
- }
-
- @Test // DATAMONGO-1404
- public void updatesBigNumberValueUsingStringComparisonWhenUsingMinOperator() {
-
- TypeWithNumbers twn = new TypeWithNumbers();
-
- // Note that $max operator uses String comparison for BigDecimal/BigInteger comparison according to BSON sort rules.
- // Therefore "80" is considered greater than "700"
- twn.bigIntegerVal = new BigInteger("80");
- twn.bigDeciamVal = new BigDecimal("90.0");
-
- template.save(twn);
-
- Update update = new Update()//
- .min("bigIntegerVal", new BigInteger("700")) //
- .min("bigDeciamVal", new BigDecimal("800")) //
- ;
-
- template.updateFirst(query(where("id").is(twn.id)), update, TypeWithNumbers.class);
-
- TypeWithNumbers loaded = template.find(query(where("id").is(twn.id)), TypeWithNumbers.class).get(0);
- assertThat(loaded.bigIntegerVal).isEqualTo(new BigInteger("700"));
- assertThat(loaded.bigDeciamVal).isEqualTo(new BigDecimal("800"));
- }
-
- @Test // DATAMONGO-1431, DATAMONGO-2323
- public void streamExecutionUsesExplicitCollectionName() {
-
- template.remove(new Query(), "some_special_collection");
- template.remove(new Query(), Document.class);
-
- Document document = new Document();
-
- template.insert(document, "some_special_collection");
-
- CloseableIterator stream = template.stream(new Query(), Document.class);
- assertThat(stream.hasNext()).isFalse();
-
- CloseableIterator stream2 = template.stream(new Query(where("_id").is(document.id)),
- org.bson.Document.class, "some_special_collection");
-
- assertThat(stream2.hasNext()).isTrue();
- assertThat(stream2.next().get("_id")).isEqualTo(new ObjectId(document.id));
- assertThat(stream2.hasNext()).isFalse();
- }
-
- @Test // DATAMONGO-1194
- public void shouldFetchListOfReferencesCorrectly() {
-
- Sample one = new Sample("1", "jon snow");
- Sample two = new Sample("2", "tyrion lannister");
-
- template.save(one);
- template.save(two);
-
- DocumentWithDBRefCollection source = new DocumentWithDBRefCollection();
- source.dbRefAnnotatedList = Arrays.asList(two, one);
-
- template.save(source);
-
- assertThat(template.findOne(query(where("id").is(source.id)), DocumentWithDBRefCollection.class)).isEqualTo(source);
- }
-
- @Test // DATAMONGO-1194
- public void shouldFetchListOfLazyReferencesCorrectly() {
-
- Sample one = new Sample("1", "jon snow");
- Sample two = new Sample("2", "tyrion lannister");
-
- template.save(one);
- template.save(two);
-
- DocumentWithDBRefCollection source = new DocumentWithDBRefCollection();
- source.lazyDbRefAnnotatedList = Arrays.asList(two, one);
-
- template.save(source);
-
- DocumentWithDBRefCollection target = template.findOne(query(where("id").is(source.id)),
- DocumentWithDBRefCollection.class);
-
- assertThat(target.lazyDbRefAnnotatedList).isInstanceOf(LazyLoadingProxy.class);
- assertThat(target.getLazyDbRefAnnotatedList()).containsExactly(two, one);
- }
-
- @Test // DATAMONGO-1194
- public void shouldFetchMapOfLazyReferencesCorrectly() {
-
- Sample one = new Sample("1", "jon snow");
- Sample two = new Sample("2", "tyrion lannister");
-
- template.save(one);
- template.save(two);
-
- DocumentWithDBRefCollection source = new DocumentWithDBRefCollection();
- source.lazyDbRefAnnotatedMap = new LinkedHashMap<>();
- source.lazyDbRefAnnotatedMap.put("tyrion", two);
- source.lazyDbRefAnnotatedMap.put("jon", one);
- template.save(source);
-
- DocumentWithDBRefCollection target = template.findOne(query(where("id").is(source.id)),
- DocumentWithDBRefCollection.class);
-
- assertThat(target.lazyDbRefAnnotatedMap).isInstanceOf(LazyLoadingProxy.class);
- assertThat(target.lazyDbRefAnnotatedMap.values()).containsExactly(two, one);
- }
-
- @Test // DATAMONGO-2004
- public void shouldFetchLazyReferenceWithConstructorCreationCorrectly() {
-
- Sample one = new Sample("1", "jon snow");
-
- template.save(one);
-
- DocumentWithLazyDBRefsAndConstructorCreation source = new DocumentWithLazyDBRefsAndConstructorCreation(null, one,
- null, null);
-
- template.save(source);
-
- DocumentWithLazyDBRefsAndConstructorCreation target = template.findOne(query(where("id").is(source.id)),
- DocumentWithLazyDBRefsAndConstructorCreation.class);
-
- assertThat(target.lazyDbRefProperty).isInstanceOf(LazyLoadingProxy.class);
- assertThat(target.lazyDbRefProperty).isEqualTo(one);
- }
-
- @Test // DATAMONGO-2004
- public void shouldFetchMapOfLazyReferencesWithConstructorCreationCorrectly() {
-
- Sample one = new Sample("1", "jon snow");
- Sample two = new Sample("2", "tyrion lannister");
-
- template.save(one);
- template.save(two);
-
- Map map = new LinkedHashMap<>();
- map.put("tyrion", two);
- map.put("jon", one);
-
- DocumentWithLazyDBRefsAndConstructorCreation source = new DocumentWithLazyDBRefsAndConstructorCreation(null, null,
- null, map);
-
- template.save(source);
-
- DocumentWithLazyDBRefsAndConstructorCreation target = template.findOne(query(where("id").is(source.id)),
- DocumentWithLazyDBRefsAndConstructorCreation.class);
-
- assertThat(target.lazyDbRefAnnotatedMap).isInstanceOf(LazyLoadingProxy.class);
- assertThat(target.lazyDbRefAnnotatedMap.values()).containsExactly(two, one);
- }
-
- @Test // DATAMONGO-2004
- public void shouldFetchListOfLazyReferencesWithConstructorCreationCorrectly() {
-
- Sample one = new Sample("1", "jon snow");
- Sample two = new Sample("2", "tyrion lannister");
-
- template.save(one);
- template.save(two);
-
- List list = Arrays.asList(two, one);
-
- DocumentWithLazyDBRefsAndConstructorCreation source = new DocumentWithLazyDBRefsAndConstructorCreation(null, null,
- list, null);
-
- template.save(source);
-
- DocumentWithLazyDBRefsAndConstructorCreation target = template.findOne(query(where("id").is(source.id)),
- DocumentWithLazyDBRefsAndConstructorCreation.class);
-
- assertThat(target.lazyDbRefAnnotatedList).isInstanceOf(LazyLoadingProxy.class);
- assertThat(target.getLazyDbRefAnnotatedList()).containsExactly(two, one);
- }
-
- @Test // DATAMONGO-1513
- @DirtiesContext
- public void populatesIdsAddedByEventListener() {
-
- context.addApplicationListener(new AbstractMongoEventListener() {
-
- @Override
- public void onBeforeSave(BeforeSaveEvent event) {
- event.getDocument().put("_id", UUID.randomUUID().toString());
- }
- });
-
- Document document = new Document();
-
- template.insertAll(Collections.singletonList(document));
-
- assertThat(document.id).isNotNull();
- }
-
- @Test // DATAMONGO-2189
- @DirtiesContext
- public void afterSaveEventContainsSavedObjectUsingInsertAll() {
-
- AtomicReference saved = createAfterSaveReference();
- ImmutableVersioned source = new ImmutableVersioned();
-
- template.insertAll(Collections.singletonList(source));
-
- assertThat(saved.get()).isNotNull();
- assertThat(saved.get()).isNotSameAs(source);
- assertThat(saved.get().id).isNotNull();
-
- }
-
- @Test // DATAMONGO-2189
- @DirtiesContext
- public void afterSaveEventContainsSavedObjectUsingInsert() {
-
- AtomicReference saved = createAfterSaveReference();
- ImmutableVersioned source = new ImmutableVersioned();
-
- template.insert(source);
-
- assertThat(saved.get()).isNotNull();
- assertThat(saved.get()).isNotSameAs(source);
- assertThat(saved.get().id).isNotNull();
- }
-
- @Test // DATAMONGO-1509
- public void findsByGenericNestedListElements() {
-
- List modelList = Collections.singletonList(new ModelA("value"));
- DocumentWithCollection dwc = new DocumentWithCollection(modelList);
-
- template.insert(dwc);
-
- Query query = query(where("models").is(modelList));
- assertThat(template.findOne(query, DocumentWithCollection.class)).isEqualTo(dwc);
- }
-
- @Test // DATAMONGO-1517
- @MongoVersion(asOf = "3.4")
- public void decimal128TypeShouldBeSavedAndLoadedCorrectly()
- throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
-
- Class> decimal128Type = ClassUtils.resolveClassName("org.bson.types.Decimal128", null);
-
- WithObjectTypeProperty source = new WithObjectTypeProperty();
- source.id = "decimal128-property-value";
- source.value = decimal128Type.getConstructor(BigDecimal.class).newInstance(new BigDecimal(100));
-
- template.save(source);
-
- WithObjectTypeProperty loaded = template.findOne(query(where("id").is(source.id)), WithObjectTypeProperty.class);
- assertThat(loaded.getValue()).isInstanceOf(decimal128Type);
- }
-
- @Test // DATAMONGO-1718
- public void findAndRemoveAllWithoutExplicitDomainTypeShouldRemoveAndReturnEntitiesCorrectly() {
-
- Sample jon = new Sample("1", "jon snow");
- Sample bran = new Sample("2", "bran stark");
- Sample rickon = new Sample("3", "rickon stark");
-
- template.save(jon);
- template.save(bran);
- template.save(rickon);
-
- List result = template.findAllAndRemove(query(where("field").regex(".*stark$")),
- template.getCollectionName(Sample.class));
-
- assertThat(result).hasSize(2);
- assertThat(result).contains(bran, rickon);
- assertThat(template.count(new BasicQuery("{}"), template.getCollectionName(Sample.class))).isEqualTo(1L);
- }
-
- @Test // DATAMONGO-1779
- public void appliesQueryLimitToEmptyQuery() {
-
- Sample first = new Sample("1", "Dave Matthews");
- Sample second = new Sample("2", "Carter Beauford");
-
- template.insertAll(Arrays.asList(first, second));
-
- assertThat(template.find(new Query().limit(1), Sample.class)).hasSize(1);
- }
-
- @Test // DATAMONGO-1870
- public void removeShouldConsiderLimit() {
-
- List samples = IntStream.range(0, 100) //
- .mapToObj(i -> new Sample("id-" + i, i % 2 == 0 ? "stark" : "lannister")) //
- .collect(Collectors.toList());
-
- template.insertAll(samples);
-
- DeleteResult wr = template.remove(query(where("field").is("lannister")).limit(25), Sample.class);
-
- assertThat(wr.getDeletedCount()).isEqualTo(25L);
- assertThat(template.count(new Query(), Sample.class)).isEqualTo(75L);
- }
-
- @Test // DATAMONGO-1870
- public void removeShouldConsiderSkipAndSort() {
-
- List samples = IntStream.range(0, 100) //
- .mapToObj(i -> new Sample("id-" + i, i % 2 == 0 ? "stark" : "lannister")) //
- .collect(Collectors.toList());
-
- template.insertAll(samples);
-
- DeleteResult wr = template.remove(new Query().skip(25).with(Sort.by("field")), Sample.class);
-
- assertThat(wr.getDeletedCount()).isEqualTo(75L);
- assertThat(template.count(new Query(), Sample.class)).isEqualTo(25L);
- assertThat(template.count(query(where("field").is("lannister")), Sample.class)).isEqualTo(25L);
- assertThat(template.count(query(where("field").is("stark")), Sample.class)).isEqualTo(0L);
- }
-
- @Test // DATAMONGO-1988
- public void findByNestedDocumentWithStringIdMappingToObjectIdMatchesDocumentsCorrectly() {
-
- DocumentWithNestedTypeHavingStringIdProperty source = new DocumentWithNestedTypeHavingStringIdProperty();
- source.id = "id-1";
- source.sample = new Sample();
- source.sample.id = new ObjectId().toHexString();
-
- template.save(source);
-
- DocumentWithNestedTypeHavingStringIdProperty target = template
- .query(DocumentWithNestedTypeHavingStringIdProperty.class)
- .matching(query(where("sample.id").is(source.sample.id))).firstValue();
-
- assertThat(target).isEqualTo(source);
- }
-
- @Test // DATAMONGO-1992
- public void writesAuditingMetadataForImmutableTypes() {
-
- ImmutableAudited source = new ImmutableAudited(null, null);
- ImmutableAudited result = template.save(source);
-
- assertThat(result).isNotSameAs(source).describedAs("Expected a different instances to be returned!");
- assertThat(result.modified).isNotNull().describedAs("Auditing field must not be null!");
-
- ImmutableAudited read = template.findOne(query(where("id").is(result.getId())), ImmutableAudited.class);
-
- assertThat(read.modified).isEqualTo(result.modified.truncatedTo(ChronoUnit.MILLIS))
- .describedAs("Expected auditing information to be read!");
- }
-
- @Test // DATAMONGO-1798
- public void saveAndLoadStringThatIsAnObjectIdAsString() {
-
- RawStringId source = new RawStringId();
- source.id = new ObjectId().toHexString();
- source.value = "new value";
-
- template.save(source);
-
- org.bson.Document result = template
- .execute(db -> (org.bson.Document) db.getCollection(template.getCollectionName(RawStringId.class))
- .find(Filters.eq("_id", source.id)).limit(1).into(new ArrayList()).iterator().next());
-
- assertThat(result).isNotNull();
- assertThat(result.get("_id")).isEqualTo(source.id);
-
- RawStringId target = template.findOne(query(where("id").is(source.id)), RawStringId.class);
- assertThat(target).isEqualTo(source);
- }
-
- @Test // DATAMONGO-2193
- public void shouldNotConvertStringToObjectIdForNonIdField() {
-
- ObjectId outerId = new ObjectId();
- String innerId = new ObjectId().toHexString();
-
- org.bson.Document source = new org.bson.Document() //
- .append("_id", outerId) //
- .append("inner", new org.bson.Document("id", innerId).append("value", "boooh"));
-
- template.getDb().getCollection(template.getCollectionName(Outer.class)).insertOne(source);
-
- Outer target = template.findOne(query(where("inner.id").is(innerId)), Outer.class);
- assertThat(target).isNotNull();
- assertThat(target.id).isEqualTo(outerId);
- assertThat(target.inner.id).isEqualTo(innerId);
- }
-
- @Test // DATAMONGO-2294
- public void shouldProjectWithCollections() {
-
- MyPerson person = new MyPerson("Walter");
- person.address = new Address("TX", "Austin");
- template.save(person);
-
- Query queryByChainedInclude = query(where("name").is("Walter"));
- queryByChainedInclude.fields().include("id").include("name");
-
- Query queryByCollectionInclude = query(where("name").is("Walter"));
- queryByCollectionInclude.fields().include("id", "name");
-
- MyPerson first = template.findAndReplace(queryByChainedInclude, new MyPerson("Walter"));
- MyPerson second = template.findAndReplace(queryByCollectionInclude, new MyPerson("Walter"));
-
- assertThat(first).isEqualTo(second);
- assertThat(first.address).isNull();
- assertThat(second.address).isNull();
- }
-
- @Test // DATAMONGO-2451
- public void sortOnIdFieldWithExplicitTypeShouldWork() {
-
- template.dropCollection(WithIdAndFieldAnnotation.class);
-
- WithIdAndFieldAnnotation f = new WithIdAndFieldAnnotation();
- f.id = new ObjectId().toHexString();
- f.value = "value";
-
- template.save(f);
-
- assertThat(template.find(new BasicQuery("{}").with(Sort.by("id")), WithIdAndFieldAnnotation.class)).isNotEmpty();
- }
-
- private AtomicReference createAfterSaveReference() {
-
- AtomicReference saved = new AtomicReference<>();
- context.addApplicationListener(new AbstractMongoEventListener() {
-
- @Override
- public void onAfterSave(AfterSaveEvent event) {
- saved.set(event.getSource());
- }
- });
-
- return saved;
- }
-
- static class TypeWithNumbers {
-
- @Id String id;
- Integer intVal;
- Float floatVal;
- Long longVal;
- Double doubleVal;
- BigDecimal bigDeciamVal;
- BigInteger bigIntegerVal;
- Byte byteVal;
- }
-
- static class DoucmentWithNamedIdField {
-
- @Id String someIdKey;
-
- @Field(value = "val") //
- String value;
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (someIdKey == null ? 0 : someIdKey.hashCode());
- result = prime * result + (value == null ? 0 : value.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (!(obj instanceof DoucmentWithNamedIdField)) {
- return false;
- }
- DoucmentWithNamedIdField other = (DoucmentWithNamedIdField) obj;
- if (someIdKey == null) {
- if (other.someIdKey != null) {
- return false;
- }
- } else if (!someIdKey.equals(other.someIdKey)) {
- return false;
- }
- if (value == null) {
- if (other.value != null) {
- return false;
- }
- } else if (!value.equals(other.value)) {
- return false;
- }
- return true;
- }
-
- }
-
- @Data
- static class DocumentWithDBRefCollection {
-
- @Id public String id;
-
- @Field("db_ref_list") // DATAMONGO-1058
- @org.springframework.data.mongodb.core.mapping.DBRef //
- public List dbRefAnnotatedList;
-
- @org.springframework.data.mongodb.core.mapping.DBRef //
- public Sample dbRefProperty;
-
- @Field("lazy_db_ref_list") // DATAMONGO-1194
- @org.springframework.data.mongodb.core.mapping.DBRef(lazy = true) //
- public List