diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9579df7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.gradle +build +out +.idea +*.iml +.gradle/gradle.properties \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3bcc2ae --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2021 Wholegrain Software, Jimi Steidl + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..79a29f4 --- /dev/null +++ b/README.md @@ -0,0 +1,154 @@ +# Spring MongoDB Test + +Spring MongoDB Test is a TestExecutionListener that simplifies seeding the database in spring-data-mongodb integration +tests. + +## Dependency + +### Gradle + +```groovy +testImplementation 'com.wholegrainsoftware:spring-mongodb-test:{latest}' +``` + +### Maven + +```xml + + + com.wholegrainsoftware + spring-mongodb-test + {latest} + test + +``` + +## Setup + +The following lines of code add the `MongoDBTestExecutionListener` to the SpringBootTest lifecycle. + +```java +import com.wholegrainsoftware.springmongotest.MongoDBTestExecutionListener; + +@SpringBootTest +@TestExecutionListeners( + value = {MongoDBTestExecutionListener.class}, + mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS +) +public class MyIntegrationTest { + // ... +} +``` + +The database will be determined through one of the following properties: + +```yaml +spring.data.monogdb.database: my_mongo_database +# or +spring.data.mongodb.uri: mongodb://localhost:27017/my_mongo_database +``` + +In this case everything will be executed against `my_mongo_database`. + +## Tests with Documents + +The `@Doc` annotation allows inserting documents into the given database. + +A typical test will look like this: + +```java +import com.wholegrainsoftware.springmongotest.Doc; +import com.wholegrainsoftware.springmongotest.MongoDBTest; +import org.junit.jupiter.api.Test; + +@Doc(collection = "person", files = {"/documents/john-doe.bson"}) +public class MyTest extends MyIntegrationTest { + @Test + @MongoDBTest + public void myTest() { + // ... + } +} +``` + +A bson file, located in `/src/test/resources/documents/john-doe.bson` could look like this: + +```bson +{ + _id: ObjectId('6032473edd63e50bd3565171'), + firstName: 'John', + lastName: 'Doe', + _class: 'person' +} +``` + +For the following entity: + +```java + +@Document("person") +@TypeAlias("person") +public class Person { + @Id + private ObjectId id; + private String firstName; + private String lastName; + + //... +} +``` + +You can even aggregate multiple `@Doc` annotations into custom annotations like: + +```java +import com.wholegrainsoftware.springmongotest.Doc; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +@Doc(collection = "person", files = {"/documents/john-doe.bson"}) +@Doc(collection = "department", files = {"/documents/sales.bson"}) +public @interface InsertSalesDepartment { +} +``` + +## Tests with Files + +The `@GridFsFile` annotation allows inserting files into GridFs of the given database. + +A test will look like this: + +```java +import com.wholegrainsoftware.springmongotest.GridFsFile; +import com.wholegrainsoftware.springmongotest.MongoDBTest; +import org.junit.jupiter.api.Test; + +@GridFsFile(id = "60327c7f9189342c201e0e11", filePath = "/files/test.pdf") +public class MyGridFsTest extends MyIntegrationTest { + @Test + @MongoDBTest + public void myTest() { + // ... + } +} +``` + +## Example + +For a more thorough example, please check out the [example](example/spring-example). It contains a functional Spring Boot application +and several tests that showcase this library. + +## License + +Copyright (C) [Wholegrain Software](https://wholegrain-software.com) 2021 + +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 + +[http://www.apache.org/licenses/LICENSE-2.0](http://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. \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..b2d6384 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,29 @@ +plugins { + java + id("org.cadixdev.licenser") version "0.5.0" +} + +allprojects { + apply(plugin = "java") + apply(plugin = "org.cadixdev.licenser") + + group = "com.wholegrain-software" + + java.sourceCompatibility = JavaVersion.VERSION_1_8 + java.targetCompatibility = JavaVersion.VERSION_1_8 + + repositories { + mavenCentral() + } + + tasks.withType { + useJUnitPlatform() + } + + license { + header = rootProject.file("LICENSE") + } +} + + + diff --git a/example/spring-example/build.gradle.kts b/example/spring-example/build.gradle.kts new file mode 100644 index 0000000..fba3ab0 --- /dev/null +++ b/example/spring-example/build.gradle.kts @@ -0,0 +1,24 @@ +plugins { + id("org.springframework.boot") version "2.4.3" + id("io.spring.dependency-management") version "1.0.11.RELEASE" +} + +repositories { + mavenCentral() + maven { + url = uri("https://oss.sonatype.org/content/repositories/snapshots/") + } +} + +dependencies { + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("org.springframework.boot:spring-boot-starter-data-mongodb") + + testImplementation("com.wholegrain-software:spring-mongodb-test:0.0.1-SNAPSHOT") + testImplementation("org.testcontainers:mongodb:1.15.2") + testImplementation("org.testcontainers:junit-jupiter:1.15.2") + testImplementation("org.springframework.boot:spring-boot-starter-test") { + exclude(group = "org.junit.vintage") + exclude(group = "org.junit", module = "junit") + } +} \ No newline at end of file diff --git a/example/spring-example/src/main/java/com/wholegrainsoftware/example/MongoDbApplication.java b/example/spring-example/src/main/java/com/wholegrainsoftware/example/MongoDbApplication.java new file mode 100644 index 0000000..486d803 --- /dev/null +++ b/example/spring-example/src/main/java/com/wholegrainsoftware/example/MongoDbApplication.java @@ -0,0 +1,36 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.example; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MongoDbApplication { + + public static void main(String[] args) { + SpringApplication.run(MongoDbApplication.class, args); + } +} diff --git a/example/spring-example/src/main/java/com/wholegrainsoftware/example/department/Department.java b/example/spring-example/src/main/java/com/wholegrainsoftware/example/department/Department.java new file mode 100644 index 0000000..1d9e094 --- /dev/null +++ b/example/spring-example/src/main/java/com/wholegrainsoftware/example/department/Department.java @@ -0,0 +1,83 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.example.department; + +import com.wholegrainsoftware.example.mongodb.Person; +import org.bson.types.ObjectId; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.TypeAlias; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + + +@Document("department") +@TypeAlias("department") +public class Department { + @Id + private ObjectId id; + @DBRef + private List people = new ArrayList<>(); + + public Department() { + } + + public Department(ObjectId id, List people) { + this.id = id; + this.people = people; + } + + public ObjectId getId() { + return id; + } + + public void setId(ObjectId id) { + this.id = id; + } + + public List getPeople() { + return people; + } + + public void setPeople(List people) { + this.people = people; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Department that = (Department) o; + return Objects.equals(id, that.id) && Objects.equals(people, that.people); + } + + @Override + public int hashCode() { + return Objects.hash(id, people); + } +} diff --git a/example/spring-example/src/main/java/com/wholegrainsoftware/example/department/DepartmentRepository.java b/example/spring-example/src/main/java/com/wholegrainsoftware/example/department/DepartmentRepository.java new file mode 100644 index 0000000..b41b286 --- /dev/null +++ b/example/spring-example/src/main/java/com/wholegrainsoftware/example/department/DepartmentRepository.java @@ -0,0 +1,33 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.example.department; + +import org.bson.types.ObjectId; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface DepartmentRepository extends MongoRepository { +} diff --git a/example/spring-example/src/main/java/com/wholegrainsoftware/example/mongodb/Person.java b/example/spring-example/src/main/java/com/wholegrainsoftware/example/mongodb/Person.java new file mode 100644 index 0000000..b1e319e --- /dev/null +++ b/example/spring-example/src/main/java/com/wholegrainsoftware/example/mongodb/Person.java @@ -0,0 +1,89 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.example.mongodb; + +import org.bson.types.ObjectId; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.TypeAlias; +import org.springframework.data.mongodb.core.mapping.Document; + +import java.util.Objects; + +@Document("person") +@TypeAlias("person") +public class Person { + @Id + private ObjectId id; + private String firstName; + private String lastName; + + public Person() { + } + + public Person(ObjectId id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public ObjectId getId() { + return id; + } + + public void setId(ObjectId id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Person person = (Person) o; + return Objects.equals(id, person.id) && + Objects.equals(firstName, person.firstName) && + Objects.equals(lastName, person.lastName); + } + + @Override + public int hashCode() { + return Objects.hash(id, firstName, lastName); + } +} diff --git a/example/spring-example/src/main/java/com/wholegrainsoftware/example/mongodb/PersonRepository.java b/example/spring-example/src/main/java/com/wholegrainsoftware/example/mongodb/PersonRepository.java new file mode 100644 index 0000000..0d5068d --- /dev/null +++ b/example/spring-example/src/main/java/com/wholegrainsoftware/example/mongodb/PersonRepository.java @@ -0,0 +1,33 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.example.mongodb; + +import org.bson.types.ObjectId; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PersonRepository extends MongoRepository { +} diff --git a/example/spring-example/src/main/resources/application.yaml b/example/spring-example/src/main/resources/application.yaml new file mode 100644 index 0000000..b8cdb66 --- /dev/null +++ b/example/spring-example/src/main/resources/application.yaml @@ -0,0 +1,29 @@ +# +# The MIT License (MIT) +# +# Copyright (c) 2021 Wholegrain Software, Jimi Steidl +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +server.port: 8081 +spring: + data: + mongodb: + uri: ${SPRING_DATASOURCE_URI} diff --git a/example/spring-example/src/test/java/com/wholegrainsoftware/example/MongoDbTest.java b/example/spring-example/src/test/java/com/wholegrainsoftware/example/MongoDbTest.java new file mode 100644 index 0000000..b645ed9 --- /dev/null +++ b/example/spring-example/src/test/java/com/wholegrainsoftware/example/MongoDbTest.java @@ -0,0 +1,49 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.example; + +import com.wholegrainsoftware.springmongotest.MongoDBTestExecutionListener; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.testcontainers.containers.MongoDBContainer; +import org.testcontainers.junit.jupiter.Testcontainers; + +@SpringBootTest +@Testcontainers +@ExtendWith(SpringExtension.class) +@TestExecutionListeners( + value = {MongoDBTestExecutionListener.class}, + mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS +) +public class MongoDbTest { + static { + MongoDBContainer db = new MongoDBContainer("mongo"); + db.start(); + + System.setProperty("SPRING_DATASOURCE_URI", db.getReplicaSetUrl("some_db")); + } +} diff --git a/example/spring-example/src/test/java/com/wholegrainsoftware/example/gridfs/GridFsScriptsTest.java b/example/spring-example/src/test/java/com/wholegrainsoftware/example/gridfs/GridFsScriptsTest.java new file mode 100644 index 0000000..fb86ae3 --- /dev/null +++ b/example/spring-example/src/test/java/com/wholegrainsoftware/example/gridfs/GridFsScriptsTest.java @@ -0,0 +1,61 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.example.gridfs; + +import com.mongodb.client.gridfs.model.GridFSFile; +import com.wholegrainsoftware.example.MongoDbTest; +import com.wholegrainsoftware.example.util.InsertTestPdf; +import org.bson.types.ObjectId; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.gridfs.GridFsTemplate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.data.mongodb.core.query.Criteria.where; + +public class GridFsScriptsTest extends MongoDbTest { + private static final ObjectId FILE_OID = new ObjectId(InsertTestPdf.FILE_ID); + private static final String CREATED_BY_ID = "60327cc5dbc0a320d7544ae3"; + private static final ObjectId CREATED_BY_OID = new ObjectId(CREATED_BY_ID); + + @Autowired + private GridFsTemplate gridFs; + + @Test + @InsertTestPdf + public void fileIsPersistedToDatabase() { + GridFSFile file = gridFs.findOne(new Query().addCriteria( + where("_id").is(FILE_OID) + .and("metadata.createdBy").is(CREATED_BY_OID) + )); + + assertThat(file).isNotNull(); + assertThat(file.getMetadata()).isNotNull(); + assertThat(file.getMetadata().get("createdBy")).isEqualTo(CREATED_BY_OID); + assertThat(file.getFilename()).isEqualTo("test.pdf"); + assertThat(file.getLength()).isEqualTo(78279L); + } +} diff --git a/example/spring-example/src/test/java/com/wholegrainsoftware/example/mongodb/MongoDbScriptsTest.java b/example/spring-example/src/test/java/com/wholegrainsoftware/example/mongodb/MongoDbScriptsTest.java new file mode 100644 index 0000000..c04b606 --- /dev/null +++ b/example/spring-example/src/test/java/com/wholegrainsoftware/example/mongodb/MongoDbScriptsTest.java @@ -0,0 +1,75 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.example.mongodb; + +import com.wholegrainsoftware.example.MongoDbTest; +import com.wholegrainsoftware.example.department.Department; +import com.wholegrainsoftware.example.department.DepartmentRepository; +import com.wholegrainsoftware.example.util.InsertPeople; +import com.wholegrainsoftware.example.util.InsertSalesDepartment; +import com.wholegrainsoftware.springmongotest.MongoDBTest; +import org.bson.types.ObjectId; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; + +@InsertPeople +@InsertSalesDepartment +public class MongoDbScriptsTest extends MongoDbTest { + private static final ObjectId JOHN_DOE_ID = new ObjectId("6032473edd63e50bd3565171"); + private static final ObjectId JANE_DOE_ID = new ObjectId("6032473edd63e50bd3565172"); + private static final Person JOHN_DOE = new Person(JOHN_DOE_ID, "John", "Doe"); + private static final Person JANE_DOE = new Person(JANE_DOE_ID, "Jane", "Doe"); + private static final ObjectId SALES_ID = new ObjectId("60324824dbc0a320d7544ae1"); + private static final Department SALES = new Department(SALES_ID, Arrays.asList(JOHN_DOE, JANE_DOE)); + + @Autowired + private PersonRepository personRepo; + @Autowired + private DepartmentRepository departmentRepo; + + @Test + @MongoDBTest + public void personCanBeRetrievedFromDatabase() { + List ids = Arrays.asList(JOHN_DOE_ID, JANE_DOE_ID); + Iterable persons = personRepo.findAllById(ids); + + assertThat(persons).contains(JOHN_DOE, JANE_DOE); + } + + @Test + @MongoDBTest + public void departmentCanBeRetrievedFromDatabase() { + Optional department = departmentRepo.findById(SALES_ID); + + assertThat(department.isPresent()).isTrue(); + assertThat(department.get()).isEqualTo(SALES); + } +} diff --git a/example/spring-example/src/test/java/com/wholegrainsoftware/example/util/InsertPeople.java b/example/spring-example/src/test/java/com/wholegrainsoftware/example/util/InsertPeople.java new file mode 100644 index 0000000..465f419 --- /dev/null +++ b/example/spring-example/src/test/java/com/wholegrainsoftware/example/util/InsertPeople.java @@ -0,0 +1,38 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.example.util; + +import com.wholegrainsoftware.springmongotest.Doc; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +@Doc(collection = "person", files = {"/documents/john-doe.bson", "/documents/jane-doe.bson"}) +public @interface InsertPeople { +} diff --git a/example/spring-example/src/test/java/com/wholegrainsoftware/example/util/InsertSalesDepartment.java b/example/spring-example/src/test/java/com/wholegrainsoftware/example/util/InsertSalesDepartment.java new file mode 100644 index 0000000..7b56dc8 --- /dev/null +++ b/example/spring-example/src/test/java/com/wholegrainsoftware/example/util/InsertSalesDepartment.java @@ -0,0 +1,38 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.example.util; + +import com.wholegrainsoftware.springmongotest.Doc; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +@Doc(collection = "department", files = {"/documents/sales.bson"}) +public @interface InsertSalesDepartment { +} diff --git a/example/spring-example/src/test/java/com/wholegrainsoftware/example/util/InsertTestPdf.java b/example/spring-example/src/test/java/com/wholegrainsoftware/example/util/InsertTestPdf.java new file mode 100644 index 0000000..6a5b70a --- /dev/null +++ b/example/spring-example/src/test/java/com/wholegrainsoftware/example/util/InsertTestPdf.java @@ -0,0 +1,45 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.example.util; + +import com.wholegrainsoftware.springmongotest.GridFsFile; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static com.wholegrainsoftware.example.util.InsertTestPdf.FILE_ID; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +@GridFsFile( + id = FILE_ID, + filePath = "/files/test.pdf", + metadata = "{ 'createdBy': ObjectId('60327cc5dbc0a320d7544ae3') }" +) +public @interface InsertTestPdf { + String FILE_ID = "60327c7f9189342c201e0e11"; +} diff --git a/example/spring-example/src/test/resources/documents/jane-doe.bson b/example/spring-example/src/test/resources/documents/jane-doe.bson new file mode 100644 index 0000000..80c45d3 --- /dev/null +++ b/example/spring-example/src/test/resources/documents/jane-doe.bson @@ -0,0 +1,6 @@ +{ + _id: ObjectId('6032473edd63e50bd3565172'), + firstName: 'Jane', + lastName: 'Doe', + _class: 'person' +} \ No newline at end of file diff --git a/example/spring-example/src/test/resources/documents/john-doe.bson b/example/spring-example/src/test/resources/documents/john-doe.bson new file mode 100644 index 0000000..8dc5579 --- /dev/null +++ b/example/spring-example/src/test/resources/documents/john-doe.bson @@ -0,0 +1,6 @@ +{ + _id: ObjectId('6032473edd63e50bd3565171'), + firstName: 'John', + lastName: 'Doe', + _class: 'person' +} \ No newline at end of file diff --git a/example/spring-example/src/test/resources/documents/sales.bson b/example/spring-example/src/test/resources/documents/sales.bson new file mode 100644 index 0000000..c69f3ac --- /dev/null +++ b/example/spring-example/src/test/resources/documents/sales.bson @@ -0,0 +1,14 @@ +{ + _id: ObjectId('60324824dbc0a320d7544ae1'), + people: [ + { + $ref: 'person' + $id: ObjectId('6032473edd63e50bd3565171'), + }, + { + $ref: 'person' + $id: ObjectId('6032473edd63e50bd3565172'), + }, + ] + _class: 'department' +} \ No newline at end of file diff --git a/example/spring-example/src/test/resources/files/test.pdf b/example/spring-example/src/test/resources/files/test.pdf new file mode 100644 index 0000000..fdde5cf Binary files /dev/null and b/example/spring-example/src/test/resources/files/test.pdf differ diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..be52383 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..4f906e0 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lib/build.gradle.kts b/lib/build.gradle.kts new file mode 100644 index 0000000..d2f163f --- /dev/null +++ b/lib/build.gradle.kts @@ -0,0 +1,108 @@ +plugins { + signing + `java-library` + `maven-publish` +} + +version = "0.0.1-SNAPSHOT" + +val springVersion by extra("5.3.4") +val mongoClientVersion by extra("4.1.1") +val isReleaseVersion by extra(!version.toString().endsWith("SNAPSHOT")) + +dependencies { + compileOnly("org.springframework:spring-test:${springVersion}") + compileOnly("org.springframework:spring-context:${springVersion}") + + compileOnly("org.mongodb:bson:${mongoClientVersion}") + compileOnly("org.mongodb:mongodb-driver-core:${mongoClientVersion}") + compileOnly("org.mongodb:mongodb-driver-sync:${mongoClientVersion}") + + testImplementation("org.mockito:mockito-all:1.10.19") + testImplementation("org.junit.jupiter:junit-jupiter-api:5.3.1") + testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.3.1") +} + +configurations { + testImplementation { + extendsFrom(compileOnly.get()) + } +} + +java { + withJavadocJar() + withSourcesJar() +} + +tasks.withType { + isFailOnError = false +} + +tasks.withType { + manifest { + attributes( + "Implementation-Title" to project.name, + "Implementation-Version" to project.version + ) + } +} + +publishing { + publications { + create("library") { + groupId = rootProject.group.toString() + artifactId = rootProject.name + version = version + + pom { + name.set("Spring MongoDB Test") + description.set("A TestExecutionListener for simplifying the database seeding in integration tests for Spring and MongoDB") + url.set("https://github.com/Wholegrain-Software/spring-mongodb-test") + licenses { + license { + name.set("The MIT License (MIT)") + url.set("http://opensource.org/licenses/MIT") + } + } + developers { + developer { + id.set("DevAtHeart") + name.set("Jimi Steidl") + email.set("jimi.steidl@wholegrain-software.com") + } + } + scm { + connection.set("scm:git:git://github.com/Wholegrain-Software/spring-mongodb-test.git") + developerConnection.set("scm:git:ssh://github.com/Wholegrain-Software/spring-mongodb-test.git") + url.set("https://github.com/Wholegrain-Software/spring-mongodb-test") + } + + from(components["java"]) + } + } + } + + repositories { + maven { + name = "local" + url = uri("$buildDir/repos/release") + } + + maven { + val releasesRepoUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" + val snapshotsRepoUrl = "https://oss.sonatype.org/content/repositories/snapshots/" + + name = "mavenCentral" + url = uri(if (isReleaseVersion) releasesRepoUrl else snapshotsRepoUrl) + credentials { + username = properties["mavenCentralUser"].toString() + password = properties["mavenCentralPassword"].toString() + } + } + } +} + +signing { + setRequired { isReleaseVersion } + sign(publishing.publications["library"]) +} \ No newline at end of file diff --git a/lib/src/main/java/com/wholegrainsoftware/springmongotest/AnnotationHandler.java b/lib/src/main/java/com/wholegrainsoftware/springmongotest/AnnotationHandler.java new file mode 100644 index 0000000..4d4056f --- /dev/null +++ b/lib/src/main/java/com/wholegrainsoftware/springmongotest/AnnotationHandler.java @@ -0,0 +1,36 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import org.springframework.test.context.TestContext; + +import java.lang.annotation.Annotation; + +interface AnnotationHandler { + + void runScript(TestContext context, T annotation); + + void cleanup(TestContext context); +} diff --git a/lib/src/main/java/com/wholegrainsoftware/springmongotest/AnnotationHandlerHelper.java b/lib/src/main/java/com/wholegrainsoftware/springmongotest/AnnotationHandlerHelper.java new file mode 100644 index 0000000..3a46d5f --- /dev/null +++ b/lib/src/main/java/com/wholegrainsoftware/springmongotest/AnnotationHandlerHelper.java @@ -0,0 +1,75 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import com.mongodb.ConnectionString; +import org.springframework.core.env.Environment; +import org.springframework.core.io.Resource; +import org.springframework.test.context.TestContext; +import org.springframework.util.FileCopyUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; + +import static com.wholegrainsoftware.springmongotest.MongoDBTestException.*; +import static java.nio.charset.StandardCharsets.UTF_8; + +class AnnotationHandlerHelper { + static final String MONGODB_URI = "spring.data.mongodb.uri"; + static final String MONGODB_DATABASE = "spring.data.mongodb.database"; + + public static String getDatabaseName(TestContext context) { + Environment env = context.getApplicationContext().getEnvironment(); + String database = env.getProperty(MONGODB_DATABASE); + if (database != null) return database; + String uri = env.getProperty(MONGODB_URI); + if (uri != null) return new ConnectionString(uri).getDatabase(); + throw unspecifiedDatabase(); + } + + public static String asString(Resource resource) { + try (Reader reader = new InputStreamReader(resource.getInputStream(), UTF_8)) { + return FileCopyUtils.copyToString(reader); + } catch (IOException ex) { + throw failedToReadFile(ex); + } + } + + public static InputStream getStream(Resource resource) { + try { + return resource.getInputStream(); + } catch (IOException ex) { + throw failedToReadFile(ex); + } + } + + public static String getName(Resource resource) { + String name = resource.getFilename(); + if (name == null) throw fileNameShouldNotBeNull(); + return name; + } +} diff --git a/lib/src/main/java/com/wholegrainsoftware/springmongotest/Doc.java b/lib/src/main/java/com/wholegrainsoftware/springmongotest/Doc.java new file mode 100644 index 0000000..2673070 --- /dev/null +++ b/lib/src/main/java/com/wholegrainsoftware/springmongotest/Doc.java @@ -0,0 +1,58 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import java.lang.annotation.*; + +/** + * {@code Doc} is used to annotate a test class or test method to configure + * insertion of Documents into a given mongodb instance during integration tests. + * + *

Document insertion is performed by {@link MongoDBTestExecutionListener} + * which has to be enabled manually.

+ * + * @author Jimi Steidl + * @see Docs + * @see MongoDBTestExecutionListener + * @since 0.0.1 + */ +@Inherited +@Documented +@Repeatable(Docs.class) +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface Doc { + + /** + * This specifies the collection into which the documents should be inserted. + */ + String collection(); + + /** + * The paths of the bson files, that should be inserted as a {@link org.bson.Document}. + * Each path will be interpreted as a Spring {@link org.springframework.core.io.Resource}. + */ + String[] files() default {}; +} diff --git a/lib/src/main/java/com/wholegrainsoftware/springmongotest/Docs.java b/lib/src/main/java/com/wholegrainsoftware/springmongotest/Docs.java new file mode 100644 index 0000000..ebfd8a3 --- /dev/null +++ b/lib/src/main/java/com/wholegrainsoftware/springmongotest/Docs.java @@ -0,0 +1,43 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import java.lang.annotation.*; + +/** + * {@code Docs} is a container annotation used to aggregate several {@link Doc} annotations. + * + * @author Jimi Steidl + * @see Doc + * @since 0.0.1 + */ +@Inherited +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface Docs { + + Doc[] value() default {}; +} diff --git a/lib/src/main/java/com/wholegrainsoftware/springmongotest/GridFsAnnotationHandler.java b/lib/src/main/java/com/wholegrainsoftware/springmongotest/GridFsAnnotationHandler.java new file mode 100644 index 0000000..e7b9362 --- /dev/null +++ b/lib/src/main/java/com/wholegrainsoftware/springmongotest/GridFsAnnotationHandler.java @@ -0,0 +1,82 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.gridfs.GridFSBucket; +import com.mongodb.client.gridfs.GridFSBuckets; +import com.mongodb.client.gridfs.model.GridFSUploadOptions; +import org.bson.BsonObjectId; +import org.bson.BsonValue; +import org.bson.Document; +import org.bson.types.ObjectId; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.Resource; +import org.springframework.test.context.TestContext; +import org.springframework.test.context.util.TestContextResourceUtils; + +import java.util.List; +import java.util.function.Consumer; + +import static com.wholegrainsoftware.springmongotest.AnnotationHandlerHelper.*; + +class GridFsAnnotationHandler implements AnnotationHandler { + private static final int CHUNK_SIZE = 1024; + + @Override + public void runScript(TestContext context, GridFsFile annotation) { + Class testClass = context.getTestClass(); + ApplicationContext applicationContext = context.getApplicationContext(); + + String[] fileNames = TestContextResourceUtils.convertToClasspathResourcePaths(testClass, annotation.filePath()); + List resources = TestContextResourceUtils.convertToResourceList(applicationContext, fileNames); + Resource file = resources.get(0); + + inGridFsSession(context, (bucket) -> { + bucket.uploadFromStream(id(annotation), getName(file), getStream(file), options(annotation)); + }); + } + + @Override + public void cleanup(TestContext context) { + inGridFsSession(context, GridFSBucket::drop); + } + + private void inGridFsSession(TestContext context, Consumer script) { + MongoClient client = context.getApplicationContext().getBean(MongoClient.class); + GridFSBucket bucket = GridFSBuckets.create(client.getDatabase(getDatabaseName(context))); + script.accept(bucket); + } + + private BsonValue id(GridFsFile annotation) { + return new BsonObjectId(new ObjectId(annotation.id())); + } + + private GridFSUploadOptions options(GridFsFile annotation) { + return new GridFSUploadOptions() + .chunkSizeBytes(CHUNK_SIZE) + .metadata(Document.parse(annotation.metadata())); + } +} diff --git a/lib/src/main/java/com/wholegrainsoftware/springmongotest/GridFsFile.java b/lib/src/main/java/com/wholegrainsoftware/springmongotest/GridFsFile.java new file mode 100644 index 0000000..fec9253 --- /dev/null +++ b/lib/src/main/java/com/wholegrainsoftware/springmongotest/GridFsFile.java @@ -0,0 +1,63 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import java.lang.annotation.*; + +/** + * {@code GridFsFile} is used to annotate a test class or test method to configure + * insertion of a file into GridFs in MongoDB. + * + *

File insertion is performed by {@link MongoDBTestExecutionListener} + * which has to be enabled manually.

+ * + * @author Jimi Steidl + * @see GridFsFiles + * @see MongoDBTestExecutionListener + * @since 0.0.1 + */ +@Inherited +@Documented +@Repeatable(GridFsFiles.class) +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface GridFsFile { + + /** + * The custom id value of the file in GridFs. + */ + String id(); + + /** + * The path to the file that should be inserted into GridFs. + * It will be interpreted as a Spring {@link org.springframework.core.io.Resource}. + */ + String filePath(); + + /** + * Optional metadata that can be added to the file in GridFs. + */ + String metadata() default "{}"; +} diff --git a/lib/src/main/java/com/wholegrainsoftware/springmongotest/GridFsFiles.java b/lib/src/main/java/com/wholegrainsoftware/springmongotest/GridFsFiles.java new file mode 100644 index 0000000..c7c714b --- /dev/null +++ b/lib/src/main/java/com/wholegrainsoftware/springmongotest/GridFsFiles.java @@ -0,0 +1,43 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import java.lang.annotation.*; + +/** + * {@code GridFsFiles} is a container annotation used to aggregate several {@link GridFsFile} annotations. + * + * @author Jimi Steidl + * @see GridFsFile + * @since 0.0.1 + */ +@Inherited +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface GridFsFiles { + + GridFsFile[] value() default {}; +} diff --git a/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBAnnotationHandler.java b/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBAnnotationHandler.java new file mode 100644 index 0000000..298273e --- /dev/null +++ b/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBAnnotationHandler.java @@ -0,0 +1,80 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import com.mongodb.client.ClientSession; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoDatabase; +import org.bson.Document; +import org.bson.conversions.Bson; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.Resource; +import org.springframework.test.context.TestContext; +import org.springframework.test.context.util.TestContextResourceUtils; + +import java.util.List; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import static com.wholegrainsoftware.springmongotest.AnnotationHandlerHelper.asString; +import static com.wholegrainsoftware.springmongotest.AnnotationHandlerHelper.getDatabaseName; + +class MongoDBAnnotationHandler implements AnnotationHandler { + + @Override + public void runScript(TestContext context, Doc annotation) { + Class testClass = context.getTestClass(); + ApplicationContext applicationContext = context.getApplicationContext(); + + String[] fileNames = TestContextResourceUtils.convertToClasspathResourcePaths(testClass, annotation.files()); + List resources = TestContextResourceUtils.convertToResourceList(applicationContext, fileNames); + List documents = resources.stream() + .map((res) -> Document.parse(read(res))) + .collect(Collectors.toList()); + + inDbSession(context, (db) -> db.getCollection(annotation.collection()).insertMany(documents)); + } + + @Override + public void cleanup(TestContext context) { + inDbSession(context, (db) -> db.listCollectionNames().forEach((name) -> db.getCollection(name).deleteMany(all()))); + } + + private void inDbSession(TestContext context, Consumer script) { + MongoClient client = context.getApplicationContext().getBean(MongoClient.class); + MongoDatabase database = client.getDatabase(getDatabaseName(context)); + ClientSession session = client.startSession(); + script.accept(database); + session.close(); + } + + private Bson all() { + return new Document(); + } + + private String read(Resource resource) { + return asString(resource); + } +} diff --git a/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBTest.java b/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBTest.java new file mode 100644 index 0000000..045754e --- /dev/null +++ b/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBTest.java @@ -0,0 +1,46 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * {@code MongoDBTest} is used to annotate a test method before which the + * mongodb database should be cleared. + * + *

Deletion is performed by {@link MongoDBTestExecutionListener} + * which has to be enabled manually.

+ * + * @author Jimi Steidl + * @see MongoDBTestExecutionListener + * @since 0.0.1 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD}) +public @interface MongoDBTest { +} diff --git a/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBTestException.java b/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBTestException.java new file mode 100644 index 0000000..0ddb420 --- /dev/null +++ b/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBTestException.java @@ -0,0 +1,54 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import java.io.IOException; + +import static com.wholegrainsoftware.springmongotest.AnnotationHandlerHelper.MONGODB_DATABASE; +import static com.wholegrainsoftware.springmongotest.AnnotationHandlerHelper.MONGODB_URI; + +public class MongoDBTestException extends RuntimeException { + + public MongoDBTestException(String message) { + super(message); + } + + public MongoDBTestException(String message, Exception reason) { + super(message, reason); + } + + public static MongoDBTestException unspecifiedDatabase() { + return new MongoDBTestException("Failed to determine database. You need to provide either '" + + MONGODB_DATABASE + "' or '" + MONGODB_URI + "' property in application.yaml."); + } + + public static MongoDBTestException failedToReadFile(IOException ex) { + return new MongoDBTestException("Failed to read file.", ex); + } + + public static MongoDBTestException fileNameShouldNotBeNull() { + return new MongoDBTestException("Filename should not be null."); + } +} diff --git a/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBTestExecutionListener.java b/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBTestExecutionListener.java new file mode 100644 index 0000000..2c2a749 --- /dev/null +++ b/lib/src/main/java/com/wholegrainsoftware/springmongotest/MongoDBTestExecutionListener.java @@ -0,0 +1,114 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.test.context.TestContext; +import org.springframework.test.context.support.AbstractTestExecutionListener; + +import java.lang.annotation.Annotation; +import java.util.Set; + +/** + * {@code TestExecutionListener} that provides support for inserting documents and + * files into mongodb as well as cleanup. + * + *

Database Selection

+ * The database against which these operations are performed is determined by the Spring + * datasource configuration properties in this order: + *
    + *
  1. spring.data.mongodb.database
  2. + *
  3. spring.data.mongodb.uri
  4. + *
+ * + *

Cleanup

+ * If a test method is annotated with {@link MongoDBTest}, the listener will: + *
    + *
  • delete all documents from all collections in the given database.
  • + *
  • delete all files from GridFs in the given database.
  • + *
+ * + *

Document Insertion

+ * If a test class or test method is annotated with {@link Doc}, the listener will + * retrieve the given files and insert them into the defined collection. This will happen + * for each {@link Doc} and {@link Docs} annotation found. + * + *

File Insertion

+ * If a test class or test method is annotated with {@link GridFsFile}, the listener will + * insert the given files into GridFS with the defined id as well as optional metadata. This + * will happen for each {@link GridFsFile} and {@link GridFsFiles} annotation found. + * + *

Order of Insertion

+ * Annotations at class-level are handled before annotations at method-level. + * Annotation on the same level are handling in order of declaration. + * + *

Activation

+ * Activating the TestExecutionListener can be achieved by the following statement: + *
+ * @TestExecutionListeners(
+ *         value = {MongoDBTestExecutionListener.class},
+ *         mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS
+ * )
+ * 
+ * + * Note: This {@code TestExecutionListener} has only been tested with sequential test execution. Using + * parallel test execution might introduce unintended side effects. + * + * @author Jimi Steidl + * @see Doc + * @see Docs + * @see GridFsFile + * @see GridFsFiles + * @see MongoDBTest + * @see org.springframework.test.context.TestExecutionListener + * @since 0.0.1 + */ +public class MongoDBTestExecutionListener extends AbstractTestExecutionListener { + private final MongoDBAnnotationHandler mongoDB = new MongoDBAnnotationHandler(); + private final GridFsAnnotationHandler gridFs = new GridFsAnnotationHandler(); + + @Override + public void beforeTestMethod(TestContext context) { + if (hasMongoDbTestAnnotation(context)) { + mongoDB.cleanup(context); + gridFs.cleanup(context); + } + + executePreparation(context, mongoDB, Doc.class); + executePreparation(context, gridFs, GridFsFile.class); + } + + private void executePreparation(TestContext context, AnnotationHandler preparator, Class clazz) { + Set ca = AnnotatedElementUtils.getMergedRepeatableAnnotations(context.getTestClass(), clazz); + Set ma = AnnotatedElementUtils.getMergedRepeatableAnnotations(context.getTestMethod(), clazz); + + ca.forEach(a -> preparator.runScript(context, a)); + ma.forEach(a -> preparator.runScript(context, a)); + } + + private boolean hasMongoDbTestAnnotation(TestContext context) { + return context.getTestMethod().isAnnotationPresent(MongoDBTest.class); + } +} diff --git a/lib/src/test/java/com/wholegrainsoftware/springmongotest/AnnotationHandlerHelperTest.java b/lib/src/test/java/com/wholegrainsoftware/springmongotest/AnnotationHandlerHelperTest.java new file mode 100644 index 0000000..96821d5 --- /dev/null +++ b/lib/src/test/java/com/wholegrainsoftware/springmongotest/AnnotationHandlerHelperTest.java @@ -0,0 +1,120 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Wholegrain Software, Jimi Steidl + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.wholegrainsoftware.springmongotest; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.core.env.Environment; +import org.springframework.core.io.Resource; +import org.springframework.test.context.TestContext; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import static com.wholegrainsoftware.springmongotest.AnnotationHandlerHelper.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class AnnotationHandlerHelperTest { + private final TestContext ctx = mock(TestContext.class); + private final ApplicationContext appCtx = mock(ApplicationContext.class); + private final Environment env = mock(Environment.class); + + @BeforeEach + public void setup() { + when(ctx.getApplicationContext()).thenReturn(appCtx); + when(appCtx.getEnvironment()).thenReturn(env); + } + + @Test + public void getDatabaseNameReturnsDatabaseFromDatabaseProperty() { + when(env.getProperty("spring.data.mongodb.database")).thenReturn("my_database"); + when(env.getProperty("spring.data.mongodb.uri")).thenReturn("mongodb://localhost:27017/my_other_db"); + + assertEquals(getDatabaseName(ctx), "my_database"); + } + + @Test + public void getDatabaseNameReturnsDatabaseFromUriProperty() { + when(env.getProperty("spring.data.mongodb.database")).thenReturn(null); + when(env.getProperty("spring.data.mongodb.uri")).thenReturn("mongodb://localhost:27017/my_other_db"); + + assertEquals(getDatabaseName(ctx), "my_other_db"); + } + + @Test + public void getDatabaseNameThrowsExceptionIfNeitherPropertyIsSet() { + MongoDBTestException ex = assertThrows(MongoDBTestException.class, () -> { + getDatabaseName(ctx); + }); + + assertEquals(ex.getMessage(), "Failed to determine database. You need to provide either 'spring.data.mongodb.database' or 'spring.data.mongodb.uri' property in application.yaml."); + } + + @Test + public void asStringReadsASpringResourceIntoString() throws Exception { + Resource res = mock(Resource.class); + when(res.getInputStream()).thenReturn(new ByteArrayInputStream("test".getBytes())); + + assertEquals(asString(res), "test"); + } + + @Test + public void asStringThrowsExceptionIfFileCannotBeRead() throws Exception { + IOException ioex = new IOException(); + Resource res = mock(Resource.class); + when(res.getInputStream()).thenThrow(ioex); + + MongoDBTestException ex = assertThrows(MongoDBTestException.class, () -> asString(res)); + + assertEquals(ex.getMessage(), "Failed to read file."); + assertEquals(ex.getCause(), ioex); + } + + @Test + public void getStreamThrowsExceptionIfFileCannotBeRead() throws Exception { + IOException ioex = new IOException(); + Resource res = mock(Resource.class); + when(res.getInputStream()).thenThrow(ioex); + + MongoDBTestException ex = assertThrows(MongoDBTestException.class, () -> getStream(res)); + + assertEquals(ex.getMessage(), "Failed to read file."); + assertEquals(ex.getCause(), ioex); + } + + @Test + public void getNameThrowsExceptionIfNameIsNull() { + Resource res = mock(Resource.class); + when(res.getFilename()).thenReturn(null); + + MongoDBTestException ex = assertThrows(MongoDBTestException.class, () -> getName(res)); + + assertEquals(ex.getMessage(), "Filename should not be null."); + } +} \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..2eb174d --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,4 @@ +rootProject.name = "spring-mongodb-test" +include("lib") +include("example:spring-example") +