diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 433453de8..cd0f23e23 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -54,6 +54,7 @@ jobs: with: java-version: ${{matrix.java-version}} distribution: 'adopt' + cache: maven - name: Start Database run: ./docker/start_db.sh env: @@ -61,30 +62,10 @@ jobs: STARTER_MODE: ${{matrix.topology}} DOCKER_IMAGE: ${{matrix.docker-img}} DATABASE_EXTENDED_NAMES: ${{matrix.db-ext-names}} - - name: Cache local Maven repository - uses: actions/cache@v2 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-maven- - name: Info run: mvn -version - name: Test run: mvn --no-transfer-progress test -DargLine="-Duser.language=${{matrix.user-language}}" - - name: Collect docker logs on failure - if: ${{ cancelled() || failure() }} - uses: jwalton/gh-docker-logs@v1 - with: - dest: './logs' - - name: Tar logs - if: ${{ cancelled() || failure() }} - run: tar cvzf ./logs.tgz ./logs - - name: Upload logs to GitHub - if: ${{ cancelled() || failure() }} - uses: actions/upload-artifact@master - with: - name: logs-${{github.job}}.tgz - path: ./logs.tgz # test encodeURIComponent() and normalize('NFC') comparing to Javascript behavior test-graalvm: @@ -128,6 +109,7 @@ jobs: with: java-version: ${{matrix.java-version}} distribution: 'adopt' + cache: maven - name: Start Database run: ./docker/start_db.sh env: @@ -135,12 +117,6 @@ jobs: STARTER_MODE: ${{matrix.topology}} DOCKER_IMAGE: ${{matrix.docker-img}} DATABASE_EXTENDED_NAMES: ${{matrix.db-ext-names}} - - name: Cache local Maven repository - uses: actions/cache@v2 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-maven- - name: Set JWT run: | ENDPOINT=$(./docker/find_active_endpoint.sh) @@ -152,17 +128,3 @@ jobs: run: mvn -version - name: Test run: mvn --no-transfer-progress test -DargLine="-Duser.language=${{matrix.user-language}}" - - name: Collect docker logs on failure - if: ${{ cancelled() || failure() }} - uses: jwalton/gh-docker-logs@v1 - with: - dest: './logs' - - name: Tar logs - if: ${{ cancelled() || failure() }} - run: tar cvzf ./logs.tgz ./logs - - name: Upload logs to GitHub - if: ${{ cancelled() || failure() }} - uses: actions/upload-artifact@master - with: - name: logs.tgz - path: ./logs.tgz diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml new file mode 100644 index 000000000..373d4c3de --- /dev/null +++ b/.github/workflows/native.yml @@ -0,0 +1,43 @@ +name: Native Tests + +on: + workflow_dispatch: + push: + tags: [ v** ] + +jobs: + test-native: + timeout-minutes: 20 + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + docker-img: + - docker.io/arangodb/enterprise:3.9.0 + topology: + - cluster + db-ext-names: + - false + java-version: + - 11 + + steps: + - uses: actions/checkout@v2 + - uses: graalvm/setup-graalvm@v1 + with: + version: 'latest' + java-version: ${{matrix.java-version}} + github-token: ${{ secrets.GITHUB_TOKEN }} + components: 'native-image' + - name: Start Database + run: ./docker/start_db.sh + env: + ARANGO_LICENSE_KEY: ${{ secrets.ARANGO_LICENSE_KEY }} + STARTER_MODE: ${{matrix.topology}} + DOCKER_IMAGE: ${{matrix.docker-img}} + DATABASE_EXTENDED_NAMES: ${{matrix.db-ext-names}} + - name: Info + run: mvn -version + - name: Test Native + run: mvn -Pnative --no-transfer-progress test diff --git a/.gitignore b/.gitignore index f594772c9..04451cf5c 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ /docker/jwtSecret /docker/data +/test-results-native/ diff --git a/dev-README.md b/dev-README.md index 195fe7df8..fb6f0c109 100644 --- a/dev-README.md +++ b/dev-README.md @@ -3,3 +3,16 @@ ## native image reflection configuration To generate reflection configuration run `helper.NativeImageHelper` and copy the generated json to `src/main/resources/META-INF/native-image/com.arangodb/arangodb-java-driver/reflect-config.json`. + + +## test native + +```shell +mvn -Pnative test +``` + +## test ssl + +```shell +mvn test -Dtest=com.arangodb.ArangoSslTest -DSslTest=true +``` diff --git a/pom.xml b/pom.xml index 4695daf69..61dcd4540 100644 --- a/pom.xml +++ b/pom.xml @@ -58,6 +58,40 @@ none + + native + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M5 + + + org.graalvm.buildtools + native-maven-plugin + 0.9.11 + true + + + test-native + + generateTestResourceConfig + test + + test + + + + false + + --no-fallback + + + + + + @@ -145,7 +179,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.2 + 3.0.0-M5 **/*Test.java @@ -214,13 +248,14 @@ test - org.junit.vintage - junit-vintage-engine + org.junit.jupiter + junit-jupiter-params test - org.hamcrest - hamcrest-all + org.assertj + assertj-core + 3.22.0 test @@ -232,7 +267,7 @@ org.graalvm.sdk graal-sdk - 21.2.0 + 22.0.0.2 test @@ -286,11 +321,6 @@ pom import - - org.hamcrest - hamcrest-all - 1.3 - diff --git a/src/main/java/com/arangodb/entity/EdgeDefinition.java b/src/main/java/com/arangodb/entity/EdgeDefinition.java index d48c78951..140e01567 100644 --- a/src/main/java/com/arangodb/entity/EdgeDefinition.java +++ b/src/main/java/com/arangodb/entity/EdgeDefinition.java @@ -78,7 +78,7 @@ public EdgeDefinition satellites(final String... satellites) { return this; } - private static class Options { + public static class Options { private Collection satellites; } } diff --git a/src/main/java/com/arangodb/entity/arangosearch/AnalyzerEntity.java b/src/main/java/com/arangodb/entity/arangosearch/AnalyzerEntity.java index 3d6a9a621..5b5e5c019 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/AnalyzerEntity.java +++ b/src/main/java/com/arangodb/entity/arangosearch/AnalyzerEntity.java @@ -20,6 +20,8 @@ package com.arangodb.entity.arangosearch; +import java.util.Collection; +import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -30,7 +32,7 @@ @Deprecated public class AnalyzerEntity { - private Set features; + private Collection features; private AnalyzerType type; private String name; private Map properties; @@ -39,7 +41,7 @@ public AnalyzerEntity() { } public Set getFeatures() { - return features; + return features != null ? new HashSet<>(features) : null; } public void setFeatures(Set features) { diff --git a/src/main/java/com/arangodb/entity/arangosearch/ConsolidationPolicy.java b/src/main/java/com/arangodb/entity/arangosearch/ConsolidationPolicy.java index ddb21911c..b0cb50a0a 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/ConsolidationPolicy.java +++ b/src/main/java/com/arangodb/entity/arangosearch/ConsolidationPolicy.java @@ -25,17 +25,20 @@ */ public class ConsolidationPolicy { - private final ConsolidationType type; + private ConsolidationType type; private Double threshold; private Long segmentThreshold; - private ConsolidationPolicy(final ConsolidationType type) { - super(); - this.type = type; + public ConsolidationPolicy() { } public static ConsolidationPolicy of(final ConsolidationType type) { - return new ConsolidationPolicy(type); + return new ConsolidationPolicy().type(type); + } + + public ConsolidationPolicy type(final ConsolidationType type) { + this.type = type; + return this; } /** diff --git a/src/main/java/com/arangodb/entity/arangosearch/analyzer/SearchAnalyzer.java b/src/main/java/com/arangodb/entity/arangosearch/analyzer/SearchAnalyzer.java index 3286acf4d..2155a39a8 100644 --- a/src/main/java/com/arangodb/entity/arangosearch/analyzer/SearchAnalyzer.java +++ b/src/main/java/com/arangodb/entity/arangosearch/analyzer/SearchAnalyzer.java @@ -25,6 +25,8 @@ import com.arangodb.entity.arangosearch.AnalyzerFeature; import com.arangodb.entity.arangosearch.AnalyzerType; +import java.util.Collection; +import java.util.HashSet; import java.util.Objects; import java.util.Set; @@ -34,7 +36,7 @@ public abstract class SearchAnalyzer implements Entity { private String name; private AnalyzerType type; - private Set features; + private Collection features; /** * @return The Analyzer name. @@ -62,7 +64,7 @@ public void setType(AnalyzerType type) { * @return The set of features to set on the Analyzer generated fields. */ public Set getFeatures() { - return features; + return features != null ? new HashSet<>(features) : null; } public void setFeatures(Set features) { @@ -73,10 +75,10 @@ public void setFeatures(Set features) { public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - SearchAnalyzer analyzer = (SearchAnalyzer) o; - return Objects.equals(name, analyzer.name) && - type == analyzer.type && - Objects.equals(features, analyzer.features); + SearchAnalyzer that = (SearchAnalyzer) o; + return Objects.equals(getName(), that.getName()) + && getType() == that.getType() + && Objects.equals(getFeatures(), that.getFeatures()); } @Override diff --git a/src/main/java/com/arangodb/model/AqlQueryExplainOptions.java b/src/main/java/com/arangodb/model/AqlQueryExplainOptions.java index 29b8351c6..27b962465 100644 --- a/src/main/java/com/arangodb/model/AqlQueryExplainOptions.java +++ b/src/main/java/com/arangodb/model/AqlQueryExplainOptions.java @@ -114,7 +114,7 @@ private Options getOptions() { return options; } - private static class Options { + public static class Options { private Optimizer optimizer; private Integer maxNumberOfPlans; private Boolean allPlans; @@ -127,7 +127,7 @@ protected Optimizer getOptimizer() { } } - private static class Optimizer { + public static class Optimizer { private Collection rules; } } diff --git a/src/main/java/com/arangodb/model/AqlQueryOptions.java b/src/main/java/com/arangodb/model/AqlQueryOptions.java index da9e1f1a3..52e344663 100644 --- a/src/main/java/com/arangodb/model/AqlQueryOptions.java +++ b/src/main/java/com/arangodb/model/AqlQueryOptions.java @@ -410,7 +410,7 @@ private Options getOptions() { return options; } - private static class Options implements Serializable { + public static class Options implements Serializable { private static final long serialVersionUID = 1L; @@ -446,7 +446,7 @@ protected Collection getShardIds() { } - private static class Optimizer { + public static class Optimizer { private Collection rules; } diff --git a/src/main/java/com/arangodb/model/VertexCollectionCreateOptions.java b/src/main/java/com/arangodb/model/VertexCollectionCreateOptions.java index 2806daf3a..b79b8ed41 100644 --- a/src/main/java/com/arangodb/model/VertexCollectionCreateOptions.java +++ b/src/main/java/com/arangodb/model/VertexCollectionCreateOptions.java @@ -65,7 +65,7 @@ public VertexCollectionCreateOptions satellites(final String... satellites) { return this; } - private static class Options { + public static class Options { private Collection satellites; } diff --git a/src/main/resources/META-INF/native-image/com.arangodb/arangodb-java-driver/reflect-config.json b/src/main/resources/META-INF/native-image/com.arangodb/arangodb-java-driver/reflect-config.json index d49390dc2..eac1dd6cd 100644 --- a/src/main/resources/META-INF/native-image/com.arangodb/arangodb-java-driver/reflect-config.json +++ b/src/main/resources/META-INF/native-image/com.arangodb/arangodb-java-driver/reflect-config.json @@ -10,7 +10,7 @@ ] }, { - "name": "com.arangodb.entity.CursorEntity", + "name": "com.arangodb.entity.arangosearch.analyzer.GeoPointAnalyzerProperties", "allDeclaredFields": true, "methods": [ { @@ -30,7 +30,7 @@ ] }, { - "name": "com.arangodb.entity.arangosearch.analyzer.GeoPointAnalyzerProperties", + "name": "com.arangodb.entity.CursorEntity", "allDeclaredFields": true, "methods": [ { @@ -100,7 +100,7 @@ ] }, { - "name": "com.arangodb.entity.MultiDocumentEntity", + "name": "com.arangodb.entity.CollectionEntity", "allDeclaredFields": true, "methods": [ { @@ -120,7 +120,7 @@ ] }, { - "name": "com.arangodb.entity.CollectionEntity", + "name": "com.arangodb.entity.MultiDocumentEntity", "allDeclaredFields": true, "methods": [ { @@ -150,7 +150,7 @@ ] }, { - "name": "com.arangodb.entity.CollectionPropertiesEntity", + "name": "com.arangodb.entity.arangosearch.analyzer.StopwordsAnalyzer", "allDeclaredFields": true, "methods": [ { @@ -160,7 +160,7 @@ ] }, { - "name": "com.arangodb.entity.arangosearch.analyzer.StopwordsAnalyzer", + "name": "com.arangodb.entity.CollectionPropertiesEntity", "allDeclaredFields": true, "methods": [ { @@ -240,7 +240,7 @@ ] }, { - "name": "com.arangodb.entity.EdgeEntity", + "name": "com.arangodb.entity.DatabaseEntity", "allDeclaredFields": true, "methods": [ { @@ -250,7 +250,7 @@ ] }, { - "name": "com.arangodb.entity.DatabaseEntity", + "name": "com.arangodb.entity.EdgeEntity", "allDeclaredFields": true, "methods": [ { @@ -280,7 +280,7 @@ ] }, { - "name": "com.arangodb.entity.BaseDocument", + "name": "com.arangodb.entity.AqlExecutionExplainEntity$ExecutionNode", "allDeclaredFields": true, "methods": [ { @@ -290,7 +290,7 @@ ] }, { - "name": "com.arangodb.entity.AqlExecutionExplainEntity$ExecutionNode", + "name": "com.arangodb.entity.BaseDocument", "allDeclaredFields": true, "methods": [ { @@ -350,7 +350,7 @@ ] }, { - "name": "com.arangodb.entity.CursorEntity$Warning", + "name": "com.arangodb.entity.arangosearch.analyzer.NormAnalyzer", "allDeclaredFields": true, "methods": [ { @@ -360,7 +360,7 @@ ] }, { - "name": "com.arangodb.entity.AqlExecutionExplainEntity$ExecutionStats", + "name": "com.arangodb.entity.arangosearch.analyzer.DelimiterAnalyzerProperties", "allDeclaredFields": true, "methods": [ { @@ -370,7 +370,7 @@ ] }, { - "name": "com.arangodb.entity.arangosearch.analyzer.DelimiterAnalyzerProperties", + "name": "com.arangodb.entity.CursorEntity$Warning", "allDeclaredFields": true, "methods": [ { @@ -380,7 +380,7 @@ ] }, { - "name": "com.arangodb.entity.arangosearch.analyzer.NormAnalyzer", + "name": "com.arangodb.entity.AqlExecutionExplainEntity$ExecutionStats", "allDeclaredFields": true, "methods": [ { @@ -390,7 +390,7 @@ ] }, { - "name": "com.arangodb.entity.AqlParseEntity$AstNode", + "name": "com.arangodb.entity.arangosearch.analyzer.GeoAnalyzerOptions", "allDeclaredFields": true, "methods": [ { @@ -410,7 +410,7 @@ ] }, { - "name": "com.arangodb.entity.arangosearch.analyzer.GeoAnalyzerOptions", + "name": "com.arangodb.entity.AqlParseEntity$AstNode", "allDeclaredFields": true, "methods": [ { @@ -489,6 +489,16 @@ } ] }, + { + "name": "com.arangodb.entity.EdgeDefinition$Options", + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, { "name": "com.arangodb.entity.arangosearch.AnalyzerEntity", "allDeclaredFields": true, @@ -540,7 +550,7 @@ ] }, { - "name": "com.arangodb.entity.VertexUpdateEntity", + "name": "com.arangodb.entity.arangosearch.ConsolidationPolicy", "allDeclaredFields": true, "methods": [ { @@ -550,7 +560,7 @@ ] }, { - "name": "com.arangodb.entity.KeyOptions", + "name": "com.arangodb.entity.VertexUpdateEntity", "allDeclaredFields": true, "methods": [ { @@ -569,6 +579,16 @@ } ] }, + { + "name": "com.arangodb.entity.KeyOptions", + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, { "name": "com.arangodb.entity.AqlExecutionExplainEntity$ExecutionPlan", "allDeclaredFields": true, @@ -590,7 +610,7 @@ ] }, { - "name": "com.arangodb.entity.arangosearch.analyzer.DelimiterAnalyzer", + "name": "com.arangodb.entity.ReplicationFactor", "allDeclaredFields": true, "methods": [ { @@ -600,7 +620,7 @@ ] }, { - "name": "com.arangodb.entity.ReplicationFactor", + "name": "com.arangodb.entity.arangosearch.analyzer.DelimiterAnalyzer", "allDeclaredFields": true, "methods": [ { @@ -650,7 +670,7 @@ ] }, { - "name": "com.arangodb.entity.LogEntriesEntity", + "name": "com.arangodb.entity.StreamTransactionEntity", "allDeclaredFields": true, "methods": [ { @@ -660,7 +680,7 @@ ] }, { - "name": "com.arangodb.entity.StreamTransactionEntity", + "name": "com.arangodb.entity.arangosearch.analyzer.GeoPointAnalyzer", "allDeclaredFields": true, "methods": [ { @@ -670,7 +690,7 @@ ] }, { - "name": "com.arangodb.entity.arangosearch.analyzer.GeoPointAnalyzer", + "name": "com.arangodb.entity.LogEntriesEntity", "allDeclaredFields": true, "methods": [ { @@ -750,7 +770,7 @@ ] }, { - "name": "com.arangodb.entity.CollectionRevisionEntity", + "name": "com.arangodb.entity.QueryTrackingPropertiesEntity", "allDeclaredFields": true, "methods": [ { @@ -760,7 +780,7 @@ ] }, { - "name": "com.arangodb.entity.QueryTrackingPropertiesEntity", + "name": "com.arangodb.entity.CollectionRevisionEntity", "allDeclaredFields": true, "methods": [ { @@ -800,7 +820,7 @@ ] }, { - "name": "com.arangodb.entity.arangosearch.analyzer.TextAnalyzer", + "name": "com.arangodb.entity.arangosearch.analyzer.CollationAnalyzer", "allDeclaredFields": true, "methods": [ { @@ -810,7 +830,7 @@ ] }, { - "name": "com.arangodb.entity.arangosearch.analyzer.CollationAnalyzer", + "name": "com.arangodb.entity.arangosearch.analyzer.TextAnalyzer", "allDeclaredFields": true, "methods": [ { @@ -869,6 +889,16 @@ } ] }, + { + "name": "com.arangodb.model.AqlQueryOptions$Optimizer", + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, { "name": "com.arangodb.model.DBCreateOptions", "allDeclaredFields": true, @@ -930,7 +960,7 @@ ] }, { - "name": "com.arangodb.model.StreamTransactionOptions", + "name": "com.arangodb.model.UserUpdateOptions", "allDeclaredFields": true, "methods": [ { @@ -940,7 +970,7 @@ ] }, { - "name": "com.arangodb.model.UserUpdateOptions", + "name": "com.arangodb.model.StreamTransactionOptions", "allDeclaredFields": true, "methods": [ { @@ -999,6 +1029,16 @@ } ] }, + { + "name": "com.arangodb.model.AqlQueryExplainOptions$Options", + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, { "name": "com.arangodb.model.ViewCreateOptions", "allDeclaredFields": true, @@ -1009,6 +1049,16 @@ } ] }, + { + "name": "com.arangodb.model.VertexCollectionCreateOptions$Options", + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, { "name": "com.arangodb.model.AqlQueryParseOptions", "allDeclaredFields": true, @@ -1120,7 +1170,7 @@ ] }, { - "name": "com.arangodb.model.CollectionTruncateOptions", + "name": "com.arangodb.model.TransactionOptions", "allDeclaredFields": true, "methods": [ { @@ -1130,7 +1180,7 @@ ] }, { - "name": "com.arangodb.model.TransactionOptions", + "name": "com.arangodb.model.CollectionTruncateOptions", "allDeclaredFields": true, "methods": [ { @@ -1170,7 +1220,7 @@ ] }, { - "name": "com.arangodb.model.DocumentDeleteOptions", + "name": "com.arangodb.model.CollectionSchema", "allDeclaredFields": true, "methods": [ { @@ -1190,7 +1240,17 @@ ] }, { - "name": "com.arangodb.model.CollectionSchema", + "name": "com.arangodb.model.DocumentDeleteOptions", + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.arangodb.model.AqlQueryOptions$Options", "allDeclaredFields": true, "methods": [ { @@ -1270,7 +1330,7 @@ ] }, { - "name": "com.arangodb.model.CollectionPropertiesOptions", + "name": "com.arangodb.model.UserCreateOptions", "allDeclaredFields": true, "methods": [ { @@ -1280,7 +1340,7 @@ ] }, { - "name": "com.arangodb.model.UserCreateOptions", + "name": "com.arangodb.model.CollectionPropertiesOptions", "allDeclaredFields": true, "methods": [ { @@ -1409,6 +1469,16 @@ } ] }, + { + "name": "com.arangodb.model.AqlQueryExplainOptions$Optimizer", + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, { "name": "com.arangodb.model.AqlQueryExplainOptions", "allDeclaredFields": true, diff --git a/src/test/java/com/arangodb/ArangoCollectionTest.java b/src/test/java/com/arangodb/ArangoCollectionTest.java index e704109a0..9c4ceda2d 100644 --- a/src/test/java/com/arangodb/ArangoCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoCollectionTest.java @@ -41,11 +41,11 @@ import com.arangodb.velocypack.VPackSlice; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.Arrays; @@ -57,110 +57,114 @@ import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; +import java.util.stream.Stream; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Mark Vollmary + * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class ArangoCollectionTest extends BaseTest { +class ArangoCollectionTest extends BaseJunit5 { private static final String COLLECTION_NAME = "ArangoCollectionTest_collection"; private static final String EDGE_COLLECTION_NAME = "ArangoCollectionTest_edge_collection"; - private final ArangoCollection collection; - private final ArangoCollection edgeCollection; - private final ObjectMapper mapper = new ObjectMapper(); - @BeforeClass - public static void init() { - BaseTest.initCollections(COLLECTION_NAME); - BaseTest.initEdgeCollections(EDGE_COLLECTION_NAME); + private static Stream cols() { + return dbsStream().map(db -> db.collection(COLLECTION_NAME)).map(Arguments::of); + } + + private static Stream edges() { + return dbsStream().map(db -> db.collection(EDGE_COLLECTION_NAME)).map(Arguments::of); } - public ArangoCollectionTest(final ArangoDB arangoDB) { - super(arangoDB); - collection = db.collection(COLLECTION_NAME); - edgeCollection = db.collection(EDGE_COLLECTION_NAME); + @BeforeAll + static void init() { + initCollections(COLLECTION_NAME); + initEdgeCollections(EDGE_COLLECTION_NAME); } - @Test - public void insertDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocument(ArangoCollection collection) { final DocumentCreateEntity doc = collection .insertDocument(new BaseDocument(), null); - assertThat(doc, is(notNullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); - assertThat(doc.getNew(), is(nullValue())); - assertThat(doc.getId(), is(COLLECTION_NAME + "/" + doc.getKey())); + assertThat(doc).isNotNull(); + assertThat(doc.getId()).isNotNull(); + assertThat(doc.getKey()).isNotNull(); + assertThat(doc.getRev()).isNotNull(); + assertThat(doc.getNew()).isNull(); + assertThat(doc.getId()).isEqualTo(COLLECTION_NAME + "/" + doc.getKey()); } // FIXME: v7 - @Test - @Ignore + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + @Disabled @SuppressWarnings("unchecked") - public void insertDocumentWithArrayWithNullValues() { + void insertDocumentWithArrayWithNullValues(ArangoCollection collection) { List arr = Arrays.asList("a", null); BaseDocument doc = new BaseDocument(); doc.addAttribute("arr", arr); final DocumentCreateEntity insertedDoc = collection .insertDocument(doc, new DocumentCreateOptions().returnNew(true)); - assertThat(insertedDoc, is(notNullValue())); - assertThat(insertedDoc.getId(), is(notNullValue())); - assertThat(insertedDoc.getKey(), is(notNullValue())); - assertThat(insertedDoc.getRev(), is(notNullValue())); - assertThat(insertedDoc.getId(), is(COLLECTION_NAME + "/" + insertedDoc.getKey())); + assertThat(insertedDoc).isNotNull(); + assertThat(insertedDoc.getId()).isNotNull(); + assertThat(insertedDoc.getKey()).isNotNull(); + assertThat(insertedDoc.getRev()).isNotNull(); + assertThat(insertedDoc.getId()).isEqualTo(COLLECTION_NAME + "/" + insertedDoc.getKey()); //noinspection unchecked - assertThat(((List) insertedDoc.getNew().getAttribute("arr")), contains("a", null)); + assertThat((List) insertedDoc.getNew().getAttribute("arr")).containsAll(Arrays.asList("a", null)); } // FIXME: v7 - @Test - @Ignore - public void insertDocumentWithNullValues() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + @Disabled + void insertDocumentWithNullValues(ArangoCollection collection) { BaseDocument doc = new BaseDocument(); doc.addAttribute("null", null); final DocumentCreateEntity insertedDoc = collection .insertDocument(doc, new DocumentCreateOptions().returnNew(true)); - assertThat(insertedDoc, is(notNullValue())); - assertThat(insertedDoc.getId(), is(notNullValue())); - assertThat(insertedDoc.getKey(), is(notNullValue())); - assertThat(insertedDoc.getRev(), is(notNullValue())); - assertThat(insertedDoc.getId(), is(COLLECTION_NAME + "/" + insertedDoc.getKey())); - assertThat(insertedDoc.getNew().getProperties().containsKey("null"), is(true)); + assertThat(insertedDoc).isNotNull(); + assertThat(insertedDoc.getId()).isNotNull(); + assertThat(insertedDoc.getKey()).isNotNull(); + assertThat(insertedDoc.getRev()).isNotNull(); + assertThat(insertedDoc.getId()).isEqualTo(COLLECTION_NAME + "/" + insertedDoc.getKey()); + assertThat(insertedDoc.getNew().getProperties()).containsKey("null"); } - @Test - public void insertDocumentUpdateRev() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentUpdateRev(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); final DocumentCreateEntity createResult = collection .insertDocument(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); + assertThat(doc.getRevision()).isEqualTo(createResult.getRev()); } - @Test - public void insertDocumentReturnNew() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentReturnNew(ArangoCollection collection) { final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); final DocumentCreateEntity doc = collection .insertDocument(new BaseDocument(), options); - assertThat(doc, is(notNullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); - assertThat(doc.getNew(), is(notNullValue())); + assertThat(doc).isNotNull(); + assertThat(doc.getId()).isNotNull(); + assertThat(doc.getKey()).isNotNull(); + assertThat(doc.getRev()).isNotNull(); + assertThat(doc.getNew()).isNotNull(); } - @Test - public void insertDocumentOverwriteReturnOld() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentOverwriteReturnOld(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 4)); Long initialCount = collection.count().getCount(); @@ -172,18 +176,19 @@ public void insertDocumentOverwriteReturnOld() { final DocumentCreateEntity repsert = collection .insertDocument(doc, new DocumentCreateOptions().overwrite(true).returnOld(true).returnNew(true)); - assertThat(repsert, is(notNullValue())); - assertThat(repsert.getRev(), is(not(meta.getRev()))); - assertThat(repsert.getOld().getAttribute("value").toString(), is("a")); - assertThat(repsert.getNew().getAttribute("value").toString(), is("b")); - assertThat(collection.count().getCount(), is(initialCount + 1L)); + assertThat(repsert).isNotNull(); + assertThat(repsert.getRev()).isNotEqualTo(meta.getRev()); + assertThat(repsert.getOld().getAttribute("value")).isEqualTo("a"); + assertThat(repsert.getNew().getAttribute("value")).isEqualTo("b"); + assertThat(collection.count().getCount()).isEqualTo(initialCount + 1L); } - @Test - public void insertDocumentOverwriteModeIgnore() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentOverwriteModeIgnore(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 7)); - String key = "key-" + UUID.randomUUID().toString(); + String key = "key-" + UUID.randomUUID(); final BaseDocument doc = new BaseDocument(key); doc.addAttribute("foo", "a"); final DocumentCreateEntity meta = collection.insertDocument(doc); @@ -193,34 +198,35 @@ public void insertDocumentOverwriteModeIgnore() { final DocumentCreateEntity insertIgnore = collection .insertDocument(doc2, new DocumentCreateOptions().overwriteMode(OverwriteMode.ignore)); - assertThat(insertIgnore, is(notNullValue())); - assertThat(insertIgnore.getRev(), is(meta.getRev())); + assertThat(insertIgnore).isNotNull(); + assertThat(insertIgnore.getRev()).isEqualTo(meta.getRev()); } - @Test - public void insertDocumentOverwriteModeConflict() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentOverwriteModeConflict(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 7)); - String key = "key-" + UUID.randomUUID().toString(); + String key = "key-" + UUID.randomUUID(); final BaseDocument doc = new BaseDocument(key); doc.addAttribute("foo", "a"); - final DocumentCreateEntity meta = collection.insertDocument(doc); + collection.insertDocument(doc); final BaseDocument doc2 = new BaseDocument(key); - try { - collection.insertDocument(doc2, new DocumentCreateOptions().overwriteMode(OverwriteMode.conflict)); - fail(); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(409)); - assertThat(e.getErrorNum(), is(1210)); - } + Throwable thrown = catchThrowable(() -> + collection.insertDocument(doc2, new DocumentCreateOptions().overwriteMode(OverwriteMode.conflict))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(409); + assertThat(e.getErrorNum()).isEqualTo(1210); } - @Test - public void insertDocumentOverwriteModeReplace() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentOverwriteModeReplace(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 7)); - String key = "key-" + UUID.randomUUID().toString(); + String key = "key-" + UUID.randomUUID(); final BaseDocument doc = new BaseDocument(key); doc.addAttribute("foo", "a"); final DocumentCreateEntity meta = collection.insertDocument(doc); @@ -230,14 +236,15 @@ public void insertDocumentOverwriteModeReplace() { final DocumentCreateEntity repsert = collection .insertDocument(doc2, new DocumentCreateOptions().overwriteMode(OverwriteMode.replace).returnNew(true)); - assertThat(repsert, is(notNullValue())); - assertThat(repsert.getRev(), is(not(meta.getRev()))); - assertThat(repsert.getNew().getProperties().containsKey("foo"), is(false)); - assertThat(repsert.getNew().getAttribute("bar").toString(), is("b")); + assertThat(repsert).isNotNull(); + assertThat(repsert.getRev()).isNotEqualTo(meta.getRev()); + assertThat(repsert.getNew().getProperties().containsKey("foo")).isFalse(); + assertThat(repsert.getNew().getAttribute("bar")).isEqualTo("b"); } - @Test - public void insertDocumentOverwriteModeUpdate() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentOverwriteModeUpdate(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 7)); final BaseDocument doc = new BaseDocument(); @@ -248,14 +255,15 @@ public void insertDocumentOverwriteModeUpdate() { final DocumentCreateEntity updated = collection .insertDocument(doc, new DocumentCreateOptions().overwriteMode(OverwriteMode.update).returnNew(true)); - assertThat(updated, is(notNullValue())); - assertThat(updated.getRev(), is(not(meta.getRev()))); - assertThat(updated.getNew().getAttribute("foo").toString(), is("a")); - assertThat(updated.getNew().getAttribute("bar").toString(), is("b")); + assertThat(updated).isNotNull(); + assertThat(updated.getRev()).isNotEqualTo(meta.getRev()); + assertThat(updated.getNew().getAttribute("foo")).isEqualTo("a"); + assertThat(updated.getNew().getAttribute("bar")).isEqualTo("b"); } - @Test - public void insertDocumentOverwriteModeUpdateMergeObjectsFalse() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentOverwriteModeUpdateMergeObjectsFalse(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 7)); final BaseDocument doc = new BaseDocument(); @@ -271,177 +279,199 @@ public void insertDocumentOverwriteModeUpdateMergeObjectsFalse() { .mergeObjects(false) .returnNew(true)); - assertThat(updated, is(notNullValue())); - assertThat(updated.getRev(), is(not(meta.getRev()))); - assertThat(updated.getNew().getAttribute("foo"), is(fieldB)); + assertThat(updated).isNotNull(); + assertThat(updated.getRev()).isNotEqualTo(meta.getRev()); + assertThat(updated.getNew().getAttribute("foo")).isEqualTo(fieldB); } - @Test - public void insertDocumentWaitForSync() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentWaitForSync(ArangoCollection collection) { final DocumentCreateOptions options = new DocumentCreateOptions().waitForSync(true); final DocumentCreateEntity doc = collection .insertDocument(new BaseDocument(), options); - assertThat(doc, is(notNullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); - assertThat(doc.getNew(), is(nullValue())); + assertThat(doc).isNotNull(); + assertThat(doc.getId()).isNotNull(); + assertThat(doc.getKey()).isNotNull(); + assertThat(doc.getRev()).isNotNull(); + assertThat(doc.getNew()).isNull(); } - @Test - public void insertDocumentAsJson() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentAsJson(ArangoCollection collection) { + String key = "doc-" + UUID.randomUUID(); final DocumentCreateEntity doc = collection - .insertDocument("{\"_key\":\"docRaw\",\"a\":\"test\"}", null); - assertThat(doc, is(notNullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); + .insertDocument("{\"_key\":\"" + key + "\",\"a\":\"test\"}", null); + assertThat(doc).isNotNull(); + assertThat(doc.getId()).isEqualTo(collection.name() + "/" + key); + assertThat(doc.getKey()).isEqualTo(key); + assertThat(doc.getRev()).isNotNull(); } - @Test - public void insertDocumentSilent() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentSilent(ArangoCollection collection) { assumeTrue(isSingleServer()); final DocumentCreateEntity meta = collection .insertDocument(new BaseDocument(), new DocumentCreateOptions().silent(true)); - assertThat(meta, is(notNullValue())); - assertThat(meta.getId(), is(nullValue())); - assertThat(meta.getKey(), is(nullValue())); - assertThat(meta.getRev(), is(nullValue())); + assertThat(meta).isNotNull(); + assertThat(meta.getId()).isNull(); + assertThat(meta.getKey()).isNull(); + assertThat(meta.getRev()).isNull(); } - @Test - public void insertDocumentSilentDontTouchInstance() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentSilentDontTouchInstance(ArangoCollection collection) { assumeTrue(isSingleServer()); final BaseDocument doc = new BaseDocument(); - final String key = "testkey"; + final String key = "testkey-" + UUID.randomUUID(); doc.setKey(key); final DocumentCreateEntity meta = collection .insertDocument(doc, new DocumentCreateOptions().silent(true)); - assertThat(meta, is(notNullValue())); - assertThat(meta.getKey(), is(nullValue())); - assertThat(doc.getKey(), is(key)); + assertThat(meta).isNotNull(); + assertThat(meta.getKey()).isNull(); + assertThat(doc.getKey()).isEqualTo(key); } - @Test - public void insertDocumentsSilent() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentsSilent(ArangoCollection collection) { assumeTrue(isSingleServer()); final MultiDocumentEntity> info = collection .insertDocuments(Arrays.asList(new BaseDocument(), new BaseDocument()), new DocumentCreateOptions().silent(true)); - assertThat(info, is(notNullValue())); - assertThat(info.getDocuments().isEmpty(), is(true)); - assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); - assertThat(info.getErrors().isEmpty(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getDocuments()).isEmpty(); + assertThat(info.getDocumentsAndErrors()).isEmpty(); + assertThat(info.getErrors()).isEmpty(); } - @Test - public void getDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocument(ArangoCollection collection) { final DocumentCreateEntity createResult = collection .insertDocument(new BaseDocument(), null); - assertThat(createResult.getKey(), is(notNullValue())); + assertThat(createResult.getKey()).isNotNull(); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(COLLECTION_NAME + "/" + createResult.getKey()); } - @Test - public void getDocumentIfMatch() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentIfMatch(ArangoCollection collection) { final DocumentCreateEntity createResult = collection .insertDocument(new BaseDocument(), null); - assertThat(createResult.getKey(), is(notNullValue())); + assertThat(createResult.getKey()).isNotNull(); final DocumentReadOptions options = new DocumentReadOptions().ifMatch(createResult.getRev()); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class, options); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(COLLECTION_NAME + "/" + createResult.getKey()); } - @Test - public void getDocumentIfMatchFail() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentIfMatchFail(ArangoCollection collection) { final DocumentCreateEntity createResult = collection .insertDocument(new BaseDocument(), null); - assertThat(createResult.getKey(), is(notNullValue())); + assertThat(createResult.getKey()).isNotNull(); final DocumentReadOptions options = new DocumentReadOptions().ifMatch("no"); final BaseDocument document = collection .getDocument(createResult.getKey(), BaseDocument.class, options); - assertThat(document, is(nullValue())); + assertThat(document).isNull(); } - @Test - public void getDocumentIfNoneMatch() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentIfNoneMatch(ArangoCollection collection) { final DocumentCreateEntity createResult = collection .insertDocument(new BaseDocument(), null); - assertThat(createResult.getKey(), is(notNullValue())); + assertThat(createResult.getKey()).isNotNull(); final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch("no"); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class, options); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(COLLECTION_NAME + "/" + createResult.getKey()); } - @Test - public void getDocumentIfNoneMatchFail() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentIfNoneMatchFail(ArangoCollection collection) { final DocumentCreateEntity createResult = collection .insertDocument(new BaseDocument(), null); - assertThat(createResult.getKey(), is(notNullValue())); + assertThat(createResult.getKey()).isNotNull(); final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch(createResult.getRev()); final BaseDocument document = collection .getDocument(createResult.getKey(), BaseDocument.class, options); - assertThat(document, is(nullValue())); + assertThat(document).isNull(); } - @Test - public void getDocumentAsJson() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentAsJson(ArangoCollection collection) { String key = rnd(); collection.insertDocument("{\"_key\":\"" + key + "\",\"a\":\"test\"}", null); final String readResult = collection.getDocument(key, String.class, null); - assertThat(readResult, containsString("\"_key\":\"" + key + "\"")); - assertThat(readResult, containsString("\"_id\":\"" + COLLECTION_NAME + "/" + key + "\"")); + assertThat(readResult) + .contains("\"_key\":\"" + key + "\"") + .contains("\"_id\":\"" + COLLECTION_NAME + "/" + key + "\""); } - @Test - public void getDocumentNotFound() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentNotFound(ArangoCollection collection) { final BaseDocument document = collection.getDocument("no", BaseDocument.class); - assertThat(document, is(nullValue())); + assertThat(document).isNull(); } - @Test - public void getDocumentNotFoundOptionsDefault() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentNotFoundOptionsDefault(ArangoCollection collection) { final BaseDocument document = collection .getDocument("no", BaseDocument.class, new DocumentReadOptions()); - assertThat(document, is(nullValue())); + assertThat(document).isNull(); } - @Test - public void getDocumentNotFoundOptionsNull() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentNotFoundOptionsNull(ArangoCollection collection) { final BaseDocument document = collection.getDocument("no", BaseDocument.class, null); - assertThat(document, is(nullValue())); + assertThat(document).isNull(); } - @Test(expected = ArangoDBException.class) - public void getDocumentNotFoundThrowException() { - collection - .getDocument("no", BaseDocument.class, new DocumentReadOptions().catchException(false)); + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentNotFoundThrowException(ArangoCollection collection) { + Throwable thrown = catchThrowable(() -> + collection.getDocument("no", BaseDocument.class, new DocumentReadOptions().catchException(false))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test(expected = ArangoDBException.class) - public void getDocumentWrongKey() { - collection.getDocument("no/no", BaseDocument.class); + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentWrongKey(ArangoCollection collection) { + Throwable thrown = catchThrowable(() -> collection.getDocument("no/no", BaseDocument.class)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void getDocumentDirtyRead() throws InterruptedException { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentDirtyRead(ArangoCollection collection) throws InterruptedException { final BaseDocument doc = new BaseDocument(); collection.insertDocument(doc, new DocumentCreateOptions()); Thread.sleep(2000); final VPackSlice document = collection .getDocument(doc.getKey(), VPackSlice.class, new DocumentReadOptions().allowDirtyRead(true)); - assertThat(document, is(notNullValue())); + assertThat(document).isNotNull(); } - @Test - public void getDocuments() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocuments(ArangoCollection collection) { final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); @@ -449,17 +479,17 @@ public void getDocuments() { collection.insertDocuments(values); final MultiDocumentEntity documents = collection .getDocuments(Arrays.asList("1", "2", "3"), BaseDocument.class); - assertThat(documents, is(notNullValue())); - assertThat(documents.getDocuments().size(), is(3)); + assertThat(documents).isNotNull(); + assertThat(documents.getDocuments()).hasSize(3); for (final BaseDocument document : documents.getDocuments()) { - assertThat(document.getId(), - isOneOf(COLLECTION_NAME + "/" + "1", COLLECTION_NAME + "/" + "2", COLLECTION_NAME + "/" + "3")); + assertThat(document.getId()).isIn(COLLECTION_NAME + "/" + "1", COLLECTION_NAME + "/" + "2", COLLECTION_NAME + "/" + "3"); } } - @Test - public void getDocumentsWithCustomShardingKey() { - ArangoCollection collection = db.collection("customShardingKeyCollection"); + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentsWithCustomShardingKey(ArangoCollection c) { + ArangoCollection collection = c.db().collection("customShardingKeyCollection"); if (collection.exists()) collection.drop(); @@ -479,11 +509,12 @@ public void getDocumentsWithCustomShardingKey() { final Collection documents = collection .getDocuments(insertedKeys, BaseDocument.class).getDocuments(); - assertThat(documents.size(), is(10)); + assertThat(documents).hasSize(10); } - @Test - public void getDocumentsDirtyRead() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentsDirtyRead(ArangoCollection collection) { final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); @@ -492,34 +523,36 @@ public void getDocumentsDirtyRead() { final MultiDocumentEntity documents = collection .getDocuments(Arrays.asList("1", "2", "3"), BaseDocument.class, new DocumentReadOptions().allowDirtyRead(true)); - assertThat(documents, is(notNullValue())); - assertThat(documents.getDocuments().size(), is(3)); + assertThat(documents).isNotNull(); + assertThat(documents.getDocuments()).hasSize(3); for (final BaseDocument document : documents.getDocuments()) { - assertThat(document.getId(), - isOneOf(COLLECTION_NAME + "/" + "1", COLLECTION_NAME + "/" + "2", COLLECTION_NAME + "/" + "3")); + assertThat(document.getId()).isIn(COLLECTION_NAME + "/" + "1", COLLECTION_NAME + "/" + "2", COLLECTION_NAME + "/" + "3"); } } - @Test - public void getDocumentsNotFound() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentsNotFound(ArangoCollection collection) { final MultiDocumentEntity readResult = collection .getDocuments(Collections.singleton("no"), BaseDocument.class); - assertThat(readResult, is(notNullValue())); - assertThat(readResult.getDocuments().size(), is(0)); - assertThat(readResult.getErrors().size(), is(1)); + assertThat(readResult).isNotNull(); + assertThat(readResult.getDocuments()).isEmpty(); + assertThat(readResult.getErrors()).hasSize(1); } - @Test - public void getDocumentsWrongKey() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getDocumentsWrongKey(ArangoCollection collection) { final MultiDocumentEntity readResult = collection .getDocuments(Collections.singleton("no/no"), BaseDocument.class); - assertThat(readResult, is(notNullValue())); - assertThat(readResult.getDocuments().size(), is(0)); - assertThat(readResult.getErrors().size(), is(1)); + assertThat(readResult).isNotNull(); + assertThat(readResult.getDocuments()).isEmpty(); + assertThat(readResult.getErrors()).hasSize(1); } - @Test - public void updateDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocument(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -530,54 +563,57 @@ public void updateDocument() { doc.updateAttribute("c", null); final DocumentUpdateEntity updateResult = collection .updateDocument(createResult.getKey(), doc, null); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getNew(), is(nullValue())); - assertThat(updateResult.getOld(), is(nullValue())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getNew()).isNull(); + assertThat(updateResult.getOld()).isNull(); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); - } - - @Test - public void updateDocumentWithDifferentReturnType() { - final String key = "key-" + UUID.randomUUID().toString(); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentWithDifferentReturnType(ArangoCollection collection) { + final String key = "key-" + UUID.randomUUID(); final BaseDocument doc = new BaseDocument(key); doc.addAttribute("a", "test"); collection.insertDocument(doc); final DocumentUpdateEntity updateResult = collection .updateDocument(key, Collections.singletonMap("b", "test"), new DocumentUpdateOptions().returnNew(true), BaseDocument.class); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getKey(), is(key)); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getKey()).isEqualTo(key); BaseDocument updated = updateResult.getNew(); - assertThat(updated, is(notNullValue())); - assertThat(updated.getAttribute("a"), is("test")); - assertThat(updated.getAttribute("b"), is("test")); + assertThat(updated).isNotNull(); + assertThat(updated.getAttribute("a")).isEqualTo("test"); + assertThat(updated.getAttribute("b")).isEqualTo("test"); } - @Test - public void updateDocumentUpdateRev() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentUpdateRev(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); final DocumentCreateEntity createResult = collection .insertDocument(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); + assertThat(doc.getRevision()).isEqualTo(createResult.getRev()); final DocumentUpdateEntity updateResult = collection .updateDocument(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(updateResult.getRev())); + assertThat(doc.getRevision()).isEqualTo(updateResult.getRev()); } - @Test - public void updateDocumentIfMatch() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentIfMatch(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -589,24 +625,25 @@ public void updateDocumentIfMatch() { final DocumentUpdateOptions options = new DocumentUpdateOptions().ifMatch(createResult.getRev()); final DocumentUpdateEntity updateResult = collection .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); - } - - @Test(expected = ArangoDBException.class) - public void updateDocumentIfMatchFail() { + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentIfMatchFail(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -617,11 +654,13 @@ public void updateDocumentIfMatchFail() { doc.updateAttribute("c", null); final DocumentUpdateOptions options = new DocumentUpdateOptions().ifMatch("no"); - collection.updateDocument(createResult.getKey(), doc, options); + Throwable thrown = catchThrowable(() -> collection.updateDocument(createResult.getKey(), doc, options)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void updateDocumentReturnNew() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentReturnNew(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -631,20 +670,21 @@ public void updateDocumentReturnNew() { final DocumentUpdateOptions options = new DocumentUpdateOptions().returnNew(true); final DocumentUpdateEntity updateResult = collection .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - assertThat(updateResult.getNew(), is(notNullValue())); - assertThat(updateResult.getNew().getKey(), is(createResult.getKey())); - assertThat(updateResult.getNew().getRevision(), is(not(createResult.getRev()))); - assertThat(updateResult.getNew().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(updateResult.getNew().getAttribute("a")), is("test1")); - assertThat(updateResult.getNew().getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(updateResult.getNew().getAttribute("b")), is("test")); - } - - @Test - public void updateDocumentReturnOld() { + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); + assertThat(updateResult.getNew()).isNotNull(); + assertThat(updateResult.getNew().getKey()).isEqualTo(createResult.getKey()); + assertThat(updateResult.getNew().getRevision()).isNotEqualTo(createResult.getRev()); + assertThat(updateResult.getNew().getAttribute("a")).isNotNull(); + assertThat(String.valueOf(updateResult.getNew().getAttribute("a"))).isEqualTo("test1"); + assertThat(updateResult.getNew().getAttribute("b")).isNotNull(); + assertThat(String.valueOf(updateResult.getNew().getAttribute("b"))).isEqualTo("test"); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentReturnOld(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -654,19 +694,20 @@ public void updateDocumentReturnOld() { final DocumentUpdateOptions options = new DocumentUpdateOptions().returnOld(true); final DocumentUpdateEntity updateResult = collection .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - assertThat(updateResult.getOld(), is(notNullValue())); - assertThat(updateResult.getOld().getKey(), is(createResult.getKey())); - assertThat(updateResult.getOld().getRevision(), is(createResult.getRev())); - assertThat(updateResult.getOld().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(updateResult.getOld().getAttribute("a")), is("test")); - assertThat(updateResult.getOld().getProperties().keySet(), not(hasItem("b"))); - } - - @Test - public void updateDocumentKeepNullTrue() { + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); + assertThat(updateResult.getOld()).isNotNull(); + assertThat(updateResult.getOld().getKey()).isEqualTo(createResult.getKey()); + assertThat(updateResult.getOld().getRevision()).isEqualTo(createResult.getRev()); + assertThat(updateResult.getOld().getAttribute("a")).isNotNull(); + assertThat(String.valueOf(updateResult.getOld().getAttribute("a"))).isEqualTo("test"); + assertThat(updateResult.getOld().getProperties().keySet()).doesNotContain("b"); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentKeepNullTrue(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -675,19 +716,20 @@ public void updateDocumentKeepNullTrue() { final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(true); final DocumentUpdateEntity updateResult = collection .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet(), hasItem("a")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getProperties()).containsKey("a"); } - @Test - public void updateDocumentKeepNullFalse() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentKeepNullFalse(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -696,26 +738,27 @@ public void updateDocumentKeepNullFalse() { final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(false); final DocumentUpdateEntity updateResult = collection .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getRevision(), is(notNullValue())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getRevision()).isNotNull(); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); } - private static class TestUpdateEntity { + static class TestUpdateEntity { @SuppressWarnings("unused") private String a, b; } - @Test - public void updateDocumentSerializeNullTrue() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentSerializeNullTrue(ArangoCollection collection) { final TestUpdateEntity doc = new TestUpdateEntity(); doc.a = "foo"; doc.b = "foo"; @@ -724,18 +767,19 @@ public void updateDocumentSerializeNullTrue() { patchDoc.a = "bar"; final DocumentUpdateEntity updateResult = collection .updateDocument(createResult.getKey(), patchDoc); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getKey(), is(createResult.getKey())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getKey()).isEqualTo(createResult.getKey()); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet(), hasItem("a")); - assertThat(readResult.getAttribute("a").toString(), is("bar")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getProperties()).containsKey("a"); + assertThat(readResult.getAttribute("a")).isEqualTo("bar"); } - @Test - public void updateDocumentSerializeNullFalse() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentSerializeNullFalse(ArangoCollection collection) { final TestUpdateEntity doc = new TestUpdateEntity(); doc.a = "foo"; doc.b = "foo"; @@ -744,20 +788,21 @@ public void updateDocumentSerializeNullFalse() { patchDoc.a = "bar"; final DocumentUpdateEntity updateResult = collection .updateDocument(createResult.getKey(), patchDoc, new DocumentUpdateOptions().serializeNull(false)); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getKey(), is(createResult.getKey())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getKey()).isEqualTo(createResult.getKey()); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet(), hasItems("a", "b")); - assertThat(readResult.getAttribute("a").toString(), is("bar")); - assertThat(readResult.getAttribute("b").toString(), is("foo")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getProperties()).containsKeys("a", "b"); + assertThat(readResult.getAttribute("a")).isEqualTo("bar"); + assertThat(readResult.getAttribute("b")).isEqualTo("foo"); } @SuppressWarnings("unchecked") - @Test - public void updateDocumentMergeObjectsTrue() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentMergeObjectsTrue(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); final Map a = new HashMap<>(); a.put("a", "test"); @@ -770,24 +815,24 @@ public void updateDocumentMergeObjectsTrue() { final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(true); final DocumentUpdateEntity updateResult = collection .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); final Object aResult = readResult.getAttribute("a"); - assertThat(aResult, instanceOf(Map.class)); + assertThat(aResult).isInstanceOf(Map.class); final Map aMap = (Map) aResult; - assertThat(aMap.keySet(), hasItem("a")); - assertThat(aMap.keySet(), hasItem("b")); + assertThat(aMap).containsKeys("a", "b"); } @SuppressWarnings("unchecked") - @Test - public void updateDocumentMergeObjectsFalse() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentMergeObjectsFalse(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); final Map a = new HashMap<>(); a.put("a", "test"); @@ -800,23 +845,24 @@ public void updateDocumentMergeObjectsFalse() { final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(false); final DocumentUpdateEntity updateResult = collection .updateDocument(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); final Object aResult = readResult.getAttribute("a"); - assertThat(aResult, instanceOf(Map.class)); + assertThat(aResult).isInstanceOf(Map.class); final Map aMap = (Map) aResult; - assertThat(aMap.keySet(), not(hasItem("a"))); - assertThat(aMap.keySet(), hasItem("b")); + assertThat(aMap.keySet()).doesNotContain("a"); + assertThat(aMap).containsKey("b"); } - @Test(expected = ArangoDBException.class) - public void updateDocumentIgnoreRevsFalse() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentIgnoreRevsFalse(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -825,53 +871,56 @@ public void updateDocumentIgnoreRevsFalse() { doc.setRevision("no"); final DocumentUpdateOptions options = new DocumentUpdateOptions().ignoreRevs(false); - collection.updateDocument(createResult.getKey(), doc, options); + Throwable thrown = catchThrowable(() -> collection.updateDocument(createResult.getKey(), doc, options)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void updateDocumentSilent() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentSilent(ArangoCollection collection) { assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = collection .insertDocument(new BaseDocument()); final DocumentUpdateEntity meta = collection .updateDocument(createResult.getKey(), new BaseDocument(), new DocumentUpdateOptions().silent(true)); - assertThat(meta, is(notNullValue())); - assertThat(meta.getId(), is(nullValue())); - assertThat(meta.getKey(), is(nullValue())); - assertThat(meta.getRev(), is(nullValue())); + assertThat(meta).isNotNull(); + assertThat(meta.getId()).isNull(); + assertThat(meta.getKey()).isNull(); + assertThat(meta.getRev()).isNull(); } - @Test - public void updateDocumentsSilent() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentsSilent(ArangoCollection collection) { assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = collection .insertDocument(new BaseDocument()); final MultiDocumentEntity> info = collection .updateDocuments(Collections.singletonList(new BaseDocument(createResult.getKey())), new DocumentUpdateOptions().silent(true)); - assertThat(info, is(notNullValue())); - assertThat(info.getDocuments().isEmpty(), is(true)); - assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); - assertThat(info.getErrors().isEmpty(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getDocuments()).isEmpty(); + assertThat(info.getDocumentsAndErrors()).isEmpty(); + assertThat(info.getErrors()).isEmpty(); } - @Test - public void updateNonExistingDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateNonExistingDocument(ArangoCollection collection) { final BaseDocument doc = new BaseDocument("test-" + rnd()); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); - try { - collection.updateDocument(doc.getKey(), doc, null); - fail(); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(404)); - assertThat(e.getErrorNum(), is(1202)); - } + Throwable thrown = catchThrowable(() -> collection.updateDocument(doc.getKey(), doc, null)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(404); + assertThat(e.getErrorNum()).isEqualTo(1202); } - @Test - public void updateDocumentPreconditionFailed() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentPreconditionFailed(ArangoCollection collection) { final BaseDocument doc = new BaseDocument("test-" + rnd()); doc.addAttribute("foo", "a"); final DocumentCreateEntity createResult = collection @@ -881,19 +930,19 @@ public void updateDocumentPreconditionFailed() { collection.updateDocument(doc.getKey(), doc, null); doc.updateAttribute("foo", "c"); - try { - collection.updateDocument(doc.getKey(), doc, new DocumentUpdateOptions().ifMatch(createResult.getRev())); - fail(); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1200)); - } + Throwable thrown = catchThrowable(() -> + collection.updateDocument(doc.getKey(), doc, new DocumentUpdateOptions().ifMatch(createResult.getRev()))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(412); + assertThat(e.getErrorNum()).isEqualTo(1200); BaseDocument readDocument = collection.getDocument(doc.getKey(), BaseDocument.class); - assertThat(readDocument.getAttribute("foo"), is("b")); + assertThat(readDocument.getAttribute("foo")).isEqualTo("b"); } - @Test - public void replaceDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocument(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -902,35 +951,37 @@ public void replaceDocument() { doc.addAttribute("b", "test"); final DocumentUpdateEntity replaceResult = collection .replaceDocument(createResult.getKey(), doc, null); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getNew(), is(nullValue())); - assertThat(replaceResult.getOld(), is(nullValue())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getNew()).isNull(); + assertThat(replaceResult.getOld()).isNull(); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } - @Test - public void replaceDocumentUpdateRev() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentUpdateRev(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); final DocumentCreateEntity createResult = collection .insertDocument(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); + assertThat(doc.getRevision()).isEqualTo(createResult.getRev()); final DocumentUpdateEntity replaceResult = collection .replaceDocument(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(replaceResult.getRev())); + assertThat(doc.getRevision()).isEqualTo(replaceResult.getRev()); } - @Test - public void replaceDocumentIfMatch() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentIfMatch(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -940,22 +991,23 @@ public void replaceDocumentIfMatch() { final DocumentReplaceOptions options = new DocumentReplaceOptions().ifMatch(createResult.getRev()); final DocumentUpdateEntity replaceResult = collection .replaceDocument(createResult.getKey(), doc, options); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = collection .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } - @Test(expected = ArangoDBException.class) - public void replaceDocumentIfMatchFail() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentIfMatchFail(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -964,11 +1016,14 @@ public void replaceDocumentIfMatchFail() { doc.addAttribute("b", "test"); final DocumentReplaceOptions options = new DocumentReplaceOptions().ifMatch("no"); - collection.replaceDocument(createResult.getKey(), doc, options); + Throwable thrown = catchThrowable(() -> collection.replaceDocument(createResult.getKey(), doc, options)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + } - @Test(expected = ArangoDBException.class) - public void replaceDocumentIgnoreRevsFalse() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentIgnoreRevsFalse(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -978,11 +1033,13 @@ public void replaceDocumentIgnoreRevsFalse() { doc.setRevision("no"); final DocumentReplaceOptions options = new DocumentReplaceOptions().ignoreRevs(false); - collection.replaceDocument(createResult.getKey(), doc, options); + Throwable thrown = catchThrowable(() -> collection.replaceDocument(createResult.getKey(), doc, options)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void replaceDocumentReturnNew() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentReturnNew(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -992,19 +1049,20 @@ public void replaceDocumentReturnNew() { final DocumentReplaceOptions options = new DocumentReplaceOptions().returnNew(true); final DocumentUpdateEntity replaceResult = collection .replaceDocument(createResult.getKey(), doc, options); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - assertThat(replaceResult.getNew(), is(notNullValue())); - assertThat(replaceResult.getNew().getKey(), is(createResult.getKey())); - assertThat(replaceResult.getNew().getRevision(), is(not(createResult.getRev()))); - assertThat(replaceResult.getNew().getProperties().keySet(), not(hasItem("a"))); - assertThat(replaceResult.getNew().getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(replaceResult.getNew().getAttribute("b")), is("test")); - } - - @Test - public void replaceDocumentReturnOld() { + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); + assertThat(replaceResult.getNew()).isNotNull(); + assertThat(replaceResult.getNew().getKey()).isEqualTo(createResult.getKey()); + assertThat(replaceResult.getNew().getRevision()).isNotEqualTo(createResult.getRev()); + assertThat(replaceResult.getNew().getProperties().keySet()).doesNotContain("a"); + assertThat(replaceResult.getNew().getAttribute("b")).isNotNull(); + assertThat(String.valueOf(replaceResult.getNew().getAttribute("b"))).isEqualTo("test"); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentReturnOld(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -1014,70 +1072,75 @@ public void replaceDocumentReturnOld() { final DocumentReplaceOptions options = new DocumentReplaceOptions().returnOld(true); final DocumentUpdateEntity replaceResult = collection .replaceDocument(createResult.getKey(), doc, options); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - assertThat(replaceResult.getOld(), is(notNullValue())); - assertThat(replaceResult.getOld().getKey(), is(createResult.getKey())); - assertThat(replaceResult.getOld().getRevision(), is(createResult.getRev())); - assertThat(replaceResult.getOld().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(replaceResult.getOld().getAttribute("a")), is("test")); - assertThat(replaceResult.getOld().getProperties().keySet(), not(hasItem("b"))); - } - - @Test - public void replaceDocumentSilent() { + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); + assertThat(replaceResult.getOld()).isNotNull(); + assertThat(replaceResult.getOld().getKey()).isEqualTo(createResult.getKey()); + assertThat(replaceResult.getOld().getRevision()).isEqualTo(createResult.getRev()); + assertThat(replaceResult.getOld().getAttribute("a")).isNotNull(); + assertThat(String.valueOf(replaceResult.getOld().getAttribute("a"))).isEqualTo("test"); + assertThat(replaceResult.getOld().getProperties().keySet()).doesNotContain("b"); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentSilent(ArangoCollection collection) { assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = collection .insertDocument(new BaseDocument()); final DocumentUpdateEntity meta = collection .replaceDocument(createResult.getKey(), new BaseDocument(), new DocumentReplaceOptions().silent(true)); - assertThat(meta, is(notNullValue())); - assertThat(meta.getId(), is(nullValue())); - assertThat(meta.getKey(), is(nullValue())); - assertThat(meta.getRev(), is(nullValue())); + assertThat(meta).isNotNull(); + assertThat(meta.getId()).isNull(); + assertThat(meta.getKey()).isNull(); + assertThat(meta.getRev()).isNull(); } - @Test - public void replaceDocumentSilentDontTouchInstance() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentSilentDontTouchInstance(ArangoCollection collection) { assumeTrue(isSingleServer()); final BaseDocument doc = new BaseDocument(); final DocumentCreateEntity createResult = collection.insertDocument(doc); final String revision = doc.getRevision(); - assertThat(revision, is(notNullValue())); + assertThat(revision).isNotNull(); final DocumentUpdateEntity meta = collection .replaceDocument(createResult.getKey(), doc, new DocumentReplaceOptions().silent(true)); - assertThat(meta.getRev(), is(nullValue())); - assertThat(doc.getRevision(), is(revision)); + assertThat(meta.getRev()).isNull(); + assertThat(doc.getRevision()).isEqualTo(revision); } - @Test - public void replaceDocumentsSilent() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentsSilent(ArangoCollection collection) { assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = collection .insertDocument(new BaseDocument()); final MultiDocumentEntity> info = collection .replaceDocuments(Collections.singletonList(new BaseDocument(createResult.getKey())), new DocumentReplaceOptions().silent(true)); - assertThat(info, is(notNullValue())); - assertThat(info.getDocuments().isEmpty(), is(true)); - assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); - assertThat(info.getErrors().isEmpty(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getDocuments()).isEmpty(); + assertThat(info.getDocumentsAndErrors()).isEmpty(); + assertThat(info.getErrors()).isEmpty(); } - @Test - public void deleteDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocument(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); final DocumentCreateEntity createResult = collection .insertDocument(doc, null); collection.deleteDocument(createResult.getKey(), null, null); final BaseDocument document = collection .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(document, is(nullValue())); + assertThat(document).isNull(); } - @Test - public void deleteDocumentReturnOld() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentReturnOld(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = collection @@ -1085,14 +1148,15 @@ public void deleteDocumentReturnOld() { final DocumentDeleteOptions options = new DocumentDeleteOptions().returnOld(true); final DocumentDeleteEntity deleteResult = collection .deleteDocument(createResult.getKey(), BaseDocument.class, options); - assertThat(deleteResult.getOld(), is(notNullValue())); - assertThat(deleteResult.getOld(), instanceOf(BaseDocument.class)); - assertThat(deleteResult.getOld().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(deleteResult.getOld().getAttribute("a")), is("test")); + assertThat(deleteResult.getOld()).isNotNull(); + assertThat(deleteResult.getOld()).isInstanceOf(BaseDocument.class); + assertThat(deleteResult.getOld().getAttribute("a")).isNotNull(); + assertThat(String.valueOf(deleteResult.getOld().getAttribute("a"))).isEqualTo("test"); } - @Test - public void deleteDocumentIfMatch() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentIfMatch(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); final DocumentCreateEntity createResult = collection .insertDocument(doc, null); @@ -1100,108 +1164,120 @@ public void deleteDocumentIfMatch() { collection.deleteDocument(createResult.getKey(), null, options); final BaseDocument document = collection .getDocument(createResult.getKey(), BaseDocument.class, null); - assertThat(document, is(nullValue())); + assertThat(document).isNull(); } - @Test(expected = ArangoDBException.class) - public void deleteDocumentIfMatchFail() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentIfMatchFail(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); final DocumentCreateEntity createResult = collection .insertDocument(doc, null); final DocumentDeleteOptions options = new DocumentDeleteOptions().ifMatch("no"); - collection.deleteDocument(createResult.getKey(), null, options); + Throwable thrown = catchThrowable(() -> collection.deleteDocument(createResult.getKey(), null, options)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void deleteDocumentSilent() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentSilent(ArangoCollection collection) { assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = collection .insertDocument(new BaseDocument()); final DocumentDeleteEntity meta = collection .deleteDocument(createResult.getKey(), BaseDocument.class, new DocumentDeleteOptions().silent(true)); - assertThat(meta, is(notNullValue())); - assertThat(meta.getId(), is(nullValue())); - assertThat(meta.getKey(), is(nullValue())); - assertThat(meta.getRev(), is(nullValue())); + assertThat(meta).isNotNull(); + assertThat(meta.getId()).isNull(); + assertThat(meta.getKey()).isNull(); + assertThat(meta.getRev()).isNull(); } - @Test - public void deleteDocumentsSilent() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentsSilent(ArangoCollection collection) { assumeTrue(isSingleServer()); final DocumentCreateEntity createResult = collection .insertDocument(new BaseDocument()); final MultiDocumentEntity> info = collection .deleteDocuments(Collections.singletonList(createResult.getKey()), BaseDocument.class, new DocumentDeleteOptions().silent(true)); - assertThat(info, is(notNullValue())); - assertThat(info.getDocuments().isEmpty(), is(true)); - assertThat(info.getDocumentsAndErrors().isEmpty(), is(true)); - assertThat(info.getErrors().isEmpty(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getDocuments()).isEmpty(); + assertThat(info.getDocumentsAndErrors()).isEmpty(); + assertThat(info.getErrors()).isEmpty(); } - @Test - public void getIndex() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getIndex(ArangoCollection collection) { final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = collection.ensureHashIndex(fields, null); final IndexEntity readResult = collection.getIndex(createResult.getId()); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getType(), is(createResult.getType())); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getType()).isEqualTo(createResult.getType()); } - @Test - public void getIndexByKey() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getIndexByKey(ArangoCollection collection) { final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = collection.ensureHashIndex(fields, null); final IndexEntity readResult = collection.getIndex(createResult.getId().split("/")[1]); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getType(), is(createResult.getType())); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getType()).isEqualTo(createResult.getType()); } - @Test(expected = ArangoDBException.class) - public void deleteIndex() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteIndex(ArangoCollection collection) { final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = collection.ensureHashIndex(fields, null); final String id = collection.deleteIndex(createResult.getId()); - assertThat(id, is(createResult.getId())); - db.getIndex(id); + assertThat(id).isEqualTo(createResult.getId()); + Throwable thrown = catchThrowable(() -> collection.db().getIndex(id)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test(expected = ArangoDBException.class) - public void deleteIndexByKey() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteIndexByKey(ArangoCollection collection) { final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = collection.ensureHashIndex(fields, null); final String id = collection.deleteIndex(createResult.getId().split("/")[1]); - assertThat(id, is(createResult.getId())); - db.getIndex(id); + assertThat(id).isEqualTo(createResult.getId()); + Throwable thrown = catchThrowable(() -> collection.db().getIndex(id)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void createHashIndex() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createHashIndex(ArangoCollection collection) { String f1 = "field-" + rnd(); String f2 = "field-" + rnd(); final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensureHashIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getFields(), hasItem(f2)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getFields()).contains(f2); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); if (isSingleServer()) { - assertThat(indexResult.getSelectivityEstimate(), is(greaterThan(0.0))); + assertThat(indexResult.getSelectivityEstimate()).isPositive(); } - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.hash)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult.getSparse()).isFalse(); + assertThat(indexResult.getType()).isEqualTo(IndexType.hash); + assertThat(indexResult.getUnique()).isFalse(); } - @Test - public void createHashIndexWithOptions() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createHashIndexWithOptions(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 5)); String name = "hashIndex-" + rnd(); @@ -1213,43 +1289,45 @@ public void createHashIndexWithOptions() { final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensureHashIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getFields(), hasItem(f2)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getFields()).contains(f2); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); if (isSingleServer()) { - assertThat(indexResult.getSelectivityEstimate(), is(greaterThan(0.0))); + assertThat(indexResult.getSelectivityEstimate()).isPositive(); } - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.hash)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is(name)); + assertThat(indexResult.getSparse()).isFalse(); + assertThat(indexResult.getType()).isEqualTo(IndexType.hash); + assertThat(indexResult.getUnique()).isFalse(); + assertThat(indexResult.getName()).isEqualTo(name); } - @Test - public void createGeoIndex() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createGeoIndex(ArangoCollection collection) { String f1 = "field-" + rnd(); final Collection fields = Collections.singletonList(f1); final IndexEntity indexResult = collection.ensureGeoIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isTrue(); + assertThat(indexResult.getUnique()).isFalse(); if (isAtLeastVersion(3, 4)) { - assertThat(indexResult.getType(), is(IndexType.geo)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo); } else { - assertThat(indexResult.getType(), is(IndexType.geo1)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo1); } } - @Test - public void createGeoIndexWithOptions() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createGeoIndexWithOptions(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 5)); String name = "geoIndex-" + rnd(); @@ -1259,45 +1337,47 @@ public void createGeoIndexWithOptions() { String f1 = "field-" + rnd(); final Collection fields = Collections.singletonList(f1); final IndexEntity indexResult = collection.ensureGeoIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isTrue(); + assertThat(indexResult.getUnique()).isFalse(); if (isAtLeastVersion(3, 4)) { - assertThat(indexResult.getType(), is(IndexType.geo)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo); } else { - assertThat(indexResult.getType(), is(IndexType.geo1)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo1); } - assertThat(indexResult.getName(), is(name)); + assertThat(indexResult.getName()).isEqualTo(name); } - @Test - public void createGeo2Index() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createGeo2Index(ArangoCollection collection) { String f1 = "field-" + rnd(); String f2 = "field-" + rnd(); final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensureGeoIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getFields(), hasItem(f2)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getFields()).contains(f2); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isTrue(); + assertThat(indexResult.getUnique()).isFalse(); if (isAtLeastVersion(3, 4)) { - assertThat(indexResult.getType(), is(IndexType.geo)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo); } else { - assertThat(indexResult.getType(), is(IndexType.geo2)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo2); } } - @Test - public void createGeo2IndexWithOptions() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createGeo2IndexWithOptions(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 5)); String name = "geoIndex-" + rnd(); @@ -1309,42 +1389,44 @@ public void createGeo2IndexWithOptions() { final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensureGeoIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getFields(), hasItem(f2)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getFields()).contains(f2); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isTrue(); + assertThat(indexResult.getUnique()).isFalse(); if (isAtLeastVersion(3, 4)) { - assertThat(indexResult.getType(), is(IndexType.geo)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo); } else { - assertThat(indexResult.getType(), is(IndexType.geo2)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo2); } - assertThat(indexResult.getName(), is(name)); + assertThat(indexResult.getName()).isEqualTo(name); } - @Test - public void createSkiplistIndex() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createSkiplistIndex(ArangoCollection collection) { String f1 = "field-" + rnd(); String f2 = "field-" + rnd(); final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensureSkiplistIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getFields(), hasItem(f2)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.skiplist)); - assertThat(indexResult.getUnique(), is(false)); - } - - @Test - public void createSkiplistIndexWithOptions() { + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getFields()).contains(f2); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isFalse(); + assertThat(indexResult.getType()).isEqualTo(IndexType.skiplist); + assertThat(indexResult.getUnique()).isFalse(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createSkiplistIndexWithOptions(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 5)); String name = "skiplistIndex-" + rnd(); @@ -1355,40 +1437,42 @@ public void createSkiplistIndexWithOptions() { String f2 = "field-" + rnd(); final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensureSkiplistIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getFields(), hasItem(f2)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.skiplist)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is(name)); - } - - @Test - public void createPersistentIndex() { + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getFields()).contains(f2); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isFalse(); + assertThat(indexResult.getType()).isEqualTo(IndexType.skiplist); + assertThat(indexResult.getUnique()).isFalse(); + assertThat(indexResult.getName()).isEqualTo(name); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createPersistentIndex(ArangoCollection collection) { String f1 = "field-" + rnd(); String f2 = "field-" + rnd(); final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensurePersistentIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getFields(), hasItem(f2)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.persistent)); - assertThat(indexResult.getUnique(), is(false)); - } - - @Test - public void createPersistentIndexWithOptions() { + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getFields()).contains(f2); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isFalse(); + assertThat(indexResult.getType()).isEqualTo(IndexType.persistent); + assertThat(indexResult.getUnique()).isFalse(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createPersistentIndexWithOptions(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 5)); String name = "persistentIndex-" + rnd(); @@ -1400,21 +1484,22 @@ public void createPersistentIndexWithOptions() { final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensurePersistentIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getFields(), hasItem(f2)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.persistent)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is(name)); - } - - @Test - public void createZKDIndex() { + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getFields()).contains(f2); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isFalse(); + assertThat(indexResult.getType()).isEqualTo(IndexType.persistent); + assertThat(indexResult.getUnique()).isFalse(); + assertThat(indexResult.getName()).isEqualTo(name); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createZKDIndex(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 9)); collection.truncate(); String f1 = "field-" + rnd(); @@ -1422,20 +1507,21 @@ public void createZKDIndex() { final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensureZKDIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getFields(), hasItem(f2)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getType(), is(IndexType.zkd)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getFields()).contains(f2); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getType()).isEqualTo(IndexType.zkd); + assertThat(indexResult.getUnique()).isFalse(); collection.deleteIndex(indexResult.getId()); } - @Test - public void createZKDIndexWithOptions() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createZKDIndexWithOptions(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 9)); collection.truncate(); @@ -1449,21 +1535,22 @@ public void createZKDIndexWithOptions() { final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensureZKDIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getFields(), hasItem(f2)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getType(), is(IndexType.zkd)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is(name)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getFields()).contains(f2); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getType()).isEqualTo(IndexType.zkd); + assertThat(indexResult.getUnique()).isFalse(); + assertThat(indexResult.getName()).isEqualTo(name); collection.deleteIndex(indexResult.getId()); } - @Test - public void indexEstimates() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void indexEstimates(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 8)); assumeTrue(isSingleServer()); @@ -1477,13 +1564,14 @@ public void indexEstimates() { final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensurePersistentIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getEstimates(), is(true)); - assertThat(indexResult.getSelectivityEstimate(), is(notNullValue())); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getEstimates()).isTrue(); + assertThat(indexResult.getSelectivityEstimate()).isNotNull(); } - @Test - public void indexEstimatesFalse() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void indexEstimatesFalse(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 8)); assumeTrue(isSingleServer()); @@ -1497,28 +1585,30 @@ public void indexEstimatesFalse() { final Collection fields = Arrays.asList(f1, f2); final IndexEntity indexResult = collection.ensurePersistentIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getEstimates(), is(false)); - assertThat(indexResult.getSelectivityEstimate(), is(nullValue())); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getEstimates()).isFalse(); + assertThat(indexResult.getSelectivityEstimate()).isNull(); } - @Test - public void createFulltextIndex() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createFulltextIndex(ArangoCollection collection) { String f1 = "field-" + rnd(); final Collection fields = Collections.singletonList(f1); final IndexEntity indexResult = collection.ensureFulltextIndex(fields, null); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getType(), is(IndexType.fulltext)); - assertThat(indexResult.getUnique(), is(false)); - } - - @Test - public void createFulltextIndexWithOptions() { + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getSparse()).isTrue(); + assertThat(indexResult.getType()).isEqualTo(IndexType.fulltext); + assertThat(indexResult.getUnique()).isFalse(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createFulltextIndexWithOptions(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 5)); String name = "fulltextIndex-" + rnd(); @@ -1528,34 +1618,35 @@ public void createFulltextIndexWithOptions() { String f = "field-" + rnd(); final Collection fields = Collections.singletonList(f); final IndexEntity indexResult = collection.ensureFulltextIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem(f)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getType(), is(IndexType.fulltext)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is(name)); - } - - @Test - public void createTtlIndexWithoutOptions() { + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains(f); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getSparse()).isTrue(); + assertThat(indexResult.getType()).isEqualTo(IndexType.fulltext); + assertThat(indexResult.getUnique()).isFalse(); + assertThat(indexResult.getName()).isEqualTo(name); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createTtlIndexWithoutOptions(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 5)); final Collection fields = new ArrayList<>(); fields.add("a"); - try { - collection.ensureTtlIndex(fields, null); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(400)); - assertThat(e.getErrorNum(), is(10)); - assertThat(e.getMessage(), containsString("expireAfter attribute must be a number")); - } + + Throwable thrown = catchThrowable(() -> collection.ensureTtlIndex(fields, null)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(400); + assertThat(e.getErrorNum()).isEqualTo(10); + assertThat(e.getMessage()).contains("expireAfter attribute must be a number"); } - @Test - public void createTtlIndexWithOptions() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void createTtlIndexWithOptions(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 5)); String f1 = "field-" + rnd(); @@ -1567,20 +1658,21 @@ public void createTtlIndexWithOptions() { options.expireAfter(3600); final IndexEntity indexResult = collection.ensureTtlIndex(fields, options); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem(f1)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getType(), is(IndexType.ttl)); - assertThat(indexResult.getExpireAfter(), is(3600)); - assertThat(indexResult.getName(), is(name)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getFields()).contains(f1); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getType()).isEqualTo(IndexType.ttl); + assertThat(indexResult.getExpireAfter()).isEqualTo(3600); + assertThat(indexResult.getName()).isEqualTo(name); // revert changes collection.deleteIndex(indexResult.getId()); } - @Test - public void getIndexes() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getIndexes(ArangoCollection collection) { String f1 = "field-" + rnd(); final Collection fields = Collections.singletonList(f1); collection.ensureHashIndex(fields, null); @@ -1588,101 +1680,113 @@ public void getIndexes() { .filter(i -> i.getType() == IndexType.hash) .filter(i -> i.getFields().contains(f1)) .count(); - assertThat(matchingIndexes, is(1L)); + assertThat(matchingIndexes).isEqualTo(1L); } - @Test - public void getEdgeIndex() { + @ParameterizedTest(name = "{index}") + @MethodSource("edges") + void getEdgeIndex(ArangoCollection edgeCollection) { Collection indexes = edgeCollection.getIndexes(); long primaryIndexes = indexes.stream().filter(i -> i.getType() == IndexType.primary).count(); long edgeIndexes = indexes.stream().filter(i -> i.getType() == IndexType.primary).count(); - assertThat(primaryIndexes, is(1L)); - assertThat(edgeIndexes, is(1L)); + assertThat(primaryIndexes).isEqualTo(1L); + assertThat(edgeIndexes).isEqualTo(1L); } - @Test - public void exists() { - assertThat(collection.exists(), is(true)); - assertThat(db.collection(COLLECTION_NAME + "no").exists(), is(false)); + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void exists(ArangoCollection collection) { + assertThat(collection.exists()).isTrue(); + assertThat(collection.db().collection(COLLECTION_NAME + "no").exists()).isFalse(); } - @Test - public void truncate() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void truncate(ArangoCollection collection) { final BaseDocument doc = new BaseDocument(); collection.insertDocument(doc, null); final BaseDocument readResult = collection .getDocument(doc.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(doc.getKey())); + assertThat(readResult.getKey()).isEqualTo(doc.getKey()); final CollectionEntity truncateResult = collection.truncate(); - assertThat(truncateResult, is(notNullValue())); - assertThat(truncateResult.getId(), is(notNullValue())); + assertThat(truncateResult).isNotNull(); + assertThat(truncateResult.getId()).isNotNull(); final BaseDocument document = collection .getDocument(doc.getKey(), BaseDocument.class, null); - assertThat(document, is(nullValue())); + assertThat(document).isNull(); } - @Test - public void getCount() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getCount(ArangoCollection collection) { Long initialCount = collection.count().getCount(); collection.insertDocument("{}", null); final CollectionPropertiesEntity count = collection.count(); - assertThat(count.getCount(), is(initialCount + 1L)); + assertThat(count.getCount()).isEqualTo(initialCount + 1L); } - @Test - public void documentExists() throws JsonProcessingException { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void documentExists(ArangoCollection collection) throws JsonProcessingException { final Boolean existsNot = collection.documentExists(rnd(), null); - assertThat(existsNot, is(false)); + assertThat(existsNot).isFalse(); String key = rnd(); collection.insertDocument(mapper.writeValueAsString(Collections.singletonMap("_key", key)), null); final Boolean exists = collection.documentExists(key, null); - assertThat(exists, is(true)); + assertThat(exists).isTrue(); } - @Test(expected = ArangoDBException.class) - public void documentExistsThrowExcpetion() { - collection.documentExists("no", new DocumentExistsOptions().catchException(false)); + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void documentExistsThrowExcpetion(ArangoCollection collection) { + Throwable thrown = catchThrowable(() -> collection.documentExists("no", new DocumentExistsOptions().catchException(false))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void documentExistsIfMatch() throws JsonProcessingException { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void documentExistsIfMatch(ArangoCollection collection) throws JsonProcessingException { String key = rnd(); final DocumentCreateEntity createResult = collection.insertDocument(mapper.writeValueAsString(Collections.singletonMap("_key", key)), null); final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch(createResult.getRev()); final Boolean exists = collection.documentExists(key, options); - assertThat(exists, is(true)); + assertThat(exists).isTrue(); } - @Test - public void documentExistsIfMatchFail() throws JsonProcessingException { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void documentExistsIfMatchFail(ArangoCollection collection) throws JsonProcessingException { String key = rnd(); collection.insertDocument(mapper.writeValueAsString(Collections.singletonMap("_key", key)), null); final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch("no"); final Boolean exists = collection.documentExists(key, options); - assertThat(exists, is(false)); + assertThat(exists).isFalse(); } - @Test - public void documentExistsIfNoneMatch() throws JsonProcessingException { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void documentExistsIfNoneMatch(ArangoCollection collection) throws JsonProcessingException { String key = rnd(); collection.insertDocument(mapper.writeValueAsString(Collections.singletonMap("_key", key)), null); final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch("no"); final Boolean exists = collection.documentExists(key, options); - assertThat(exists, is(true)); + assertThat(exists).isTrue(); } - @Test - public void documentExistsIfNoneMatchFail() throws JsonProcessingException { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void documentExistsIfNoneMatchFail(ArangoCollection collection) throws JsonProcessingException { String key = rnd(); final DocumentCreateEntity createResult = collection.insertDocument(mapper.writeValueAsString(Collections.singletonMap("_key", key)), null); final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch(createResult.getRev()); final Boolean exists = collection.documentExists(key, options); - assertThat(exists, is(false)); + assertThat(exists).isFalse(); } - @Test - public void insertDocuments() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocuments(ArangoCollection collection) { final Collection values = Arrays.asList( new BaseDocument(), new BaseDocument(), @@ -1691,15 +1795,16 @@ public void insertDocuments() { final MultiDocumentEntity> docs = collection .insertDocuments(values, null); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(3)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); + assertThat(docs).isNotNull(); + assertThat(docs.getDocuments()).isNotNull(); + assertThat(docs.getDocuments()).hasSize(3); + assertThat(docs.getErrors()).isNotNull(); + assertThat(docs.getErrors()).isEmpty(); } - @Test - public void insertDocumentsOverwrite() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentsOverwrite(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 4)); final BaseDocument doc1 = new BaseDocument(); @@ -1716,19 +1821,20 @@ public void insertDocumentsOverwrite() { final MultiDocumentEntity> repsert = collection .insertDocuments(Arrays.asList(doc1, doc2), new DocumentCreateOptions().overwrite(true).returnOld(true).returnNew(true)); - assertThat(repsert, is(notNullValue())); - assertThat(repsert.getDocuments().size(), is(2)); - assertThat(repsert.getErrors().size(), is(0)); + assertThat(repsert).isNotNull(); + assertThat(repsert.getDocuments()).hasSize(2); + assertThat(repsert.getErrors()).isEmpty(); for (final DocumentCreateEntity documentCreateEntity : repsert.getDocuments()) { - assertThat(documentCreateEntity.getRev(), is(not(meta1.getRev()))); - assertThat(documentCreateEntity.getRev(), is(not(meta2.getRev()))); - assertThat(documentCreateEntity.getOld().getAttribute("value").toString(), is("a")); - assertThat(documentCreateEntity.getNew().getAttribute("value").toString(), is("b")); + assertThat(documentCreateEntity.getRev()).isNotEqualTo(meta1.getRev()); + assertThat(documentCreateEntity.getRev()).isNotEqualTo(meta2.getRev()); + assertThat(documentCreateEntity.getOld().getAttribute("value")).isEqualTo("a"); + assertThat(documentCreateEntity.getNew().getAttribute("value")).isEqualTo("b"); } } - @Test - public void insertDocumentsOverwriteModeUpdate() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentsOverwriteModeUpdate(ArangoCollection collection) { assumeTrue(isAtLeastVersion(3, 7)); final BaseDocument doc1 = new BaseDocument(); @@ -1745,59 +1851,63 @@ public void insertDocumentsOverwriteModeUpdate() { final MultiDocumentEntity> repsert = collection .insertDocuments(Arrays.asList(doc1, doc2), new DocumentCreateOptions().overwriteMode(OverwriteMode.update).returnNew(true)); - assertThat(repsert, is(notNullValue())); - assertThat(repsert.getDocuments().size(), is(2)); - assertThat(repsert.getErrors().size(), is(0)); + assertThat(repsert).isNotNull(); + assertThat(repsert.getDocuments()).hasSize(2); + assertThat(repsert.getErrors()).isEmpty(); for (final DocumentCreateEntity documentCreateEntity : repsert.getDocuments()) { - assertThat(documentCreateEntity.getRev(), is(not(meta1.getRev()))); - assertThat(documentCreateEntity.getRev(), is(not(meta2.getRev()))); - assertThat(documentCreateEntity.getNew().getAttribute("foo").toString(), is("a")); - assertThat(documentCreateEntity.getNew().getAttribute("bar").toString(), is("b")); + assertThat(documentCreateEntity.getRev()).isNotEqualTo(meta1.getRev()); + assertThat(documentCreateEntity.getRev()).isNotEqualTo(meta2.getRev()); + assertThat(documentCreateEntity.getNew().getAttribute("foo")).isEqualTo("a"); + assertThat(documentCreateEntity.getNew().getAttribute("bar")).isEqualTo("b"); } } - @Test - public void insertDocumentsJson() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentsJson(ArangoCollection collection) { final Collection values = new ArrayList<>(); values.add("{}"); values.add("{}"); values.add("{}"); final MultiDocumentEntity> docs = collection .insertDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(3)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); + assertThat(docs).isNotNull(); + assertThat(docs.getDocuments()).isNotNull(); + assertThat(docs.getDocuments()).hasSize(3); + assertThat(docs.getErrors()).isNotNull(); + assertThat(docs.getErrors()).isEmpty(); } - @Test - public void insertDocumentsOne() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentsOne(ArangoCollection collection) { final Collection values = new ArrayList<>(); values.add(new BaseDocument()); final MultiDocumentEntity> docs = collection .insertDocuments(values, null); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(1)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); + assertThat(docs).isNotNull(); + assertThat(docs.getDocuments()).isNotNull(); + assertThat(docs.getDocuments()).hasSize(1); + assertThat(docs.getErrors()).isNotNull(); + assertThat(docs.getErrors()).isEmpty(); } - @Test - public void insertDocumentsEmpty() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentsEmpty(ArangoCollection collection) { final Collection values = new ArrayList<>(); final MultiDocumentEntity> docs = collection .insertDocuments(values, null); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(0)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); + assertThat(docs).isNotNull(); + assertThat(docs.getDocuments()).isNotNull(); + assertThat(docs.getDocuments()).isEmpty(); + assertThat(docs.getErrors()).isNotNull(); + assertThat(docs.getErrors()).isEmpty(); } - @Test - public void insertDocumentsReturnNew() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentsReturnNew(ArangoCollection collection) { final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); @@ -1805,21 +1915,22 @@ public void insertDocumentsReturnNew() { final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); final MultiDocumentEntity> docs = collection .insertDocuments(values, options); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(3)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); + assertThat(docs).isNotNull(); + assertThat(docs.getDocuments()).isNotNull(); + assertThat(docs.getDocuments()).hasSize(3); + assertThat(docs.getErrors()).isNotNull(); + assertThat(docs.getErrors()).isEmpty(); for (final DocumentCreateEntity doc : docs.getDocuments()) { - assertThat(doc.getNew(), is(notNullValue())); + assertThat(doc.getNew()).isNotNull(); final BaseDocument baseDocument = doc.getNew(); - assertThat(baseDocument.getKey(), is(notNullValue())); + assertThat(baseDocument.getKey()).isNotNull(); } } - @Test - public void insertDocumentsFail() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertDocumentsFail(ArangoCollection collection) { String k1 = rnd(); String k2 = rnd(); final Collection values = Arrays.asList( @@ -1830,16 +1941,17 @@ public void insertDocumentsFail() { final MultiDocumentEntity> docs = collection .insertDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(2)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(1)); - assertThat(docs.getErrors().iterator().next().getErrorNum(), is(1210)); + assertThat(docs).isNotNull(); + assertThat(docs.getDocuments()).isNotNull(); + assertThat(docs.getDocuments()).hasSize(2); + assertThat(docs.getErrors()).isNotNull(); + assertThat(docs.getErrors()).hasSize(1); + assertThat(docs.getErrors().iterator().next().getErrorNum()).isEqualTo(1210); } - @Test - public void importDocuments() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocuments(ArangoCollection collection) { final Collection values = Arrays.asList( new BaseDocument(), new BaseDocument(), @@ -1847,17 +1959,18 @@ public void importDocuments() { ); final DocumentImportEntity docs = collection.importDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(values.size())); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonList() { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(values.size()); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isZero(); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isZero(); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsJsonList(ArangoCollection collection) { final Collection values = Arrays.asList( "{}", "{}", @@ -1865,17 +1978,18 @@ public void importDocumentsJsonList() { ); final DocumentImportEntity docs = collection.importDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(values.size())); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsDuplicateDefaultError() { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(values.size()); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isZero(); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isZero(); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsDuplicateDefaultError(ArangoCollection collection) { String k1 = rnd(); String k2 = rnd(); @@ -1886,17 +2000,18 @@ public void importDocumentsDuplicateDefaultError() { ); final DocumentImportEntity docs = collection.importDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsDuplicateError() { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isZero(); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsDuplicateError(ArangoCollection collection) { String k1 = rnd(); String k2 = rnd(); @@ -1908,17 +2023,18 @@ public void importDocumentsDuplicateError() { final DocumentImportEntity docs = collection .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.error)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsDuplicateIgnore() { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isZero(); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsDuplicateIgnore(ArangoCollection collection) { String k1 = rnd(); String k2 = rnd(); @@ -1930,17 +2046,18 @@ public void importDocumentsDuplicateIgnore() { final DocumentImportEntity docs = collection .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.ignore)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(1)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsDuplicateReplace() { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isZero(); + assertThat(docs.getIgnored()).isEqualTo(1); + assertThat(docs.getUpdated()).isZero(); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsDuplicateReplace(ArangoCollection collection) { String k1 = rnd(); String k2 = rnd(); @@ -1952,17 +2069,18 @@ public void importDocumentsDuplicateReplace() { final DocumentImportEntity docs = collection .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.replace)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsDuplicateUpdate() { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isZero(); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isEqualTo(1); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsDuplicateUpdate(ArangoCollection collection) { String k1 = rnd(); String k2 = rnd(); @@ -1974,17 +2092,18 @@ public void importDocumentsDuplicateUpdate() { final DocumentImportEntity docs = collection .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.update)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsCompleteFail() { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isZero(); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isEqualTo(1); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsCompleteFail(ArangoCollection collection) { String k1 = rnd(); String k2 = rnd(); @@ -1994,16 +2113,15 @@ public void importDocumentsCompleteFail() { new BaseDocument(k2) ); - try { - collection.importDocuments(values, new DocumentImportOptions().complete(true)); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getErrorNum(), is(1210)); - } + Throwable thrown = catchThrowable(() -> collection.importDocuments(values, new DocumentImportOptions().complete(true))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getErrorNum()).isEqualTo(1210); } - @Test - public void importDocumentsDetails() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsDetails(ArangoCollection collection) { String k1 = rnd(); String k2 = rnd(); @@ -2015,18 +2133,19 @@ public void importDocumentsDetails() { final DocumentImportEntity docs = collection .importDocuments(values, new DocumentImportOptions().details(true)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails().size(), is(1)); - assertThat(docs.getDetails().iterator().next(), containsString("unique constraint violated")); - } - - @Test - public void importDocumentsOverwriteFalse() { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isZero(); + assertThat(docs.getDetails()).hasSize(1); + assertThat(docs.getDetails().iterator().next()).contains("unique constraint violated"); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsOverwriteFalse(ArangoCollection collection) { collection.insertDocument(new BaseDocument()); Long initialCount = collection.count().getCount(); @@ -2034,22 +2153,24 @@ public void importDocumentsOverwriteFalse() { values.add(new BaseDocument()); values.add(new BaseDocument()); collection.importDocuments(values, new DocumentImportOptions().overwrite(false)); - assertThat(collection.count().getCount(), is(initialCount + 2L)); + assertThat(collection.count().getCount()).isEqualTo(initialCount + 2L); } - @Test - public void importDocumentsOverwriteTrue() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsOverwriteTrue(ArangoCollection collection) { collection.insertDocument(new BaseDocument()); final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); collection.importDocuments(values, new DocumentImportOptions().overwrite(true)); - assertThat(collection.count().getCount(), is(2L)); + assertThat(collection.count().getCount()).isEqualTo(2L); } - @Test - public void importDocumentsFromToPrefix() { + @ParameterizedTest(name = "{index}") + @MethodSource("edges") + void importDocumentsFromToPrefix(ArangoCollection edgeCollection) { final Collection values = new ArrayList<>(); final String[] keys = { rnd(), @@ -2058,39 +2179,41 @@ public void importDocumentsFromToPrefix() { for (String s : keys) { values.add(new BaseEdgeDocument(s, "from", "to")); } - assertThat(values.size(), is(keys.length)); + assertThat(values).hasSize(keys.length); final DocumentImportEntity importResult = edgeCollection .importDocuments(values, new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")); - assertThat(importResult, is(notNullValue())); - assertThat(importResult.getCreated(), is(values.size())); + assertThat(importResult).isNotNull(); + assertThat(importResult.getCreated()).isEqualTo(values.size()); for (String key : keys) { final BaseEdgeDocument doc = edgeCollection.getDocument(key, BaseEdgeDocument.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getFrom(), is("foo/from")); - assertThat(doc.getTo(), is("bar/to")); + assertThat(doc).isNotNull(); + assertThat(doc.getFrom()).isEqualTo("foo/from"); + assertThat(doc.getTo()).isEqualTo("bar/to"); } } - @Test - public void importDocumentsJson() throws JsonProcessingException { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsJson(ArangoCollection collection) throws JsonProcessingException { final String values = mapper.writeValueAsString(Arrays.asList( Collections.singletonMap("_key", rnd()), Collections.singletonMap("_key", rnd()) )); final DocumentImportEntity docs = collection.importDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonDuplicateDefaultError() throws JsonProcessingException { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isZero(); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isZero(); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsJsonDuplicateDefaultError(ArangoCollection collection) throws JsonProcessingException { String k1 = rnd(); String k2 = rnd(); @@ -2101,17 +2224,18 @@ public void importDocumentsJsonDuplicateDefaultError() throws JsonProcessingExce )); final DocumentImportEntity docs = collection.importDocuments(values); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonDuplicateError() throws JsonProcessingException { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isZero(); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsJsonDuplicateError(ArangoCollection collection) throws JsonProcessingException { String k1 = rnd(); String k2 = rnd(); @@ -2123,17 +2247,18 @@ public void importDocumentsJsonDuplicateError() throws JsonProcessingException { final DocumentImportEntity docs = collection .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.error)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonDuplicateIgnore() throws JsonProcessingException { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isZero(); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsJsonDuplicateIgnore(ArangoCollection collection) throws JsonProcessingException { String k1 = rnd(); String k2 = rnd(); @@ -2144,17 +2269,18 @@ public void importDocumentsJsonDuplicateIgnore() throws JsonProcessingException )); final DocumentImportEntity docs = collection .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.ignore)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(1)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonDuplicateReplace() throws JsonProcessingException { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isZero(); + assertThat(docs.getIgnored()).isEqualTo(1); + assertThat(docs.getUpdated()).isZero(); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsJsonDuplicateReplace(ArangoCollection collection) throws JsonProcessingException { String k1 = rnd(); String k2 = rnd(); @@ -2166,17 +2292,18 @@ public void importDocumentsJsonDuplicateReplace() throws JsonProcessingException final DocumentImportEntity docs = collection .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.replace)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonDuplicateUpdate() throws JsonProcessingException { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isZero(); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isEqualTo(1); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsJsonDuplicateUpdate(ArangoCollection collection) throws JsonProcessingException { String k1 = rnd(); String k2 = rnd(); @@ -2188,28 +2315,28 @@ public void importDocumentsJsonDuplicateUpdate() throws JsonProcessingException final DocumentImportEntity docs = collection .importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.update)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); - } - - @Test - public void importDocumentsJsonCompleteFail() { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isZero(); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isEqualTo(1); + assertThat(docs.getDetails()).isEmpty(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsJsonCompleteFail(ArangoCollection collection) { final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; - try { - collection.importDocuments(values, new DocumentImportOptions().complete(true)); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getErrorNum(), is(1210)); - } + Throwable thrown = catchThrowable(() -> collection.importDocuments(values, new DocumentImportOptions().complete(true))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getErrorNum()).isEqualTo(1210); } - @Test - public void importDocumentsJsonDetails() throws JsonProcessingException { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsJsonDetails(ArangoCollection collection) throws JsonProcessingException { String k1 = rnd(); String k2 = rnd(); @@ -2221,18 +2348,19 @@ public void importDocumentsJsonDetails() throws JsonProcessingException { final DocumentImportEntity docs = collection .importDocuments(values, new DocumentImportOptions().details(true)); - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails().size(), is(1)); - assertThat(docs.getDetails().iterator().next(), containsString("unique constraint violated")); - } - - @Test - public void importDocumentsJsonOverwriteFalse() throws JsonProcessingException { + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isZero(); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isZero(); + assertThat(docs.getUpdated()).isZero(); + assertThat(docs.getDetails()).hasSize(1); + assertThat(docs.getDetails().iterator().next()).contains("unique constraint violated"); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsJsonOverwriteFalse(ArangoCollection collection) throws JsonProcessingException { collection.insertDocument(new BaseDocument()); Long initialCount = collection.count().getCount(); @@ -2241,11 +2369,12 @@ public void importDocumentsJsonOverwriteFalse() throws JsonProcessingException { Collections.singletonMap("_key", rnd()) )); collection.importDocuments(values, new DocumentImportOptions().overwrite(false)); - assertThat(collection.count().getCount(), is(initialCount + 2L)); + assertThat(collection.count().getCount()).isEqualTo(initialCount + 2L); } - @Test - public void importDocumentsJsonOverwriteTrue() throws JsonProcessingException { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void importDocumentsJsonOverwriteTrue(ArangoCollection collection) throws JsonProcessingException { collection.insertDocument(new BaseDocument()); final String values = mapper.writeValueAsString(Arrays.asList( @@ -2253,11 +2382,12 @@ public void importDocumentsJsonOverwriteTrue() throws JsonProcessingException { Collections.singletonMap("_key", rnd()) )); collection.importDocuments(values, new DocumentImportOptions().overwrite(true)); - assertThat(collection.count().getCount(), is(2L)); + assertThat(collection.count().getCount()).isEqualTo(2L); } - @Test - public void importDocumentsJsonFromToPrefix() throws JsonProcessingException { + @ParameterizedTest(name = "{index}") + @MethodSource("edges") + void importDocumentsJsonFromToPrefix(ArangoCollection edgeCollection) throws JsonProcessingException { String k1 = UUID.randomUUID().toString(); String k2 = UUID.randomUUID().toString(); @@ -2278,18 +2408,19 @@ public void importDocumentsJsonFromToPrefix() throws JsonProcessingException { final DocumentImportEntity importResult = edgeCollection .importDocuments(values, new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")); - assertThat(importResult, is(notNullValue())); - assertThat(importResult.getCreated(), is(2)); + assertThat(importResult).isNotNull(); + assertThat(importResult.getCreated()).isEqualTo(2); for (String key : keys) { final BaseEdgeDocument doc = edgeCollection.getDocument(key, BaseEdgeDocument.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getFrom(), is("foo/from")); - assertThat(doc.getTo(), is("bar/to")); + assertThat(doc).isNotNull(); + assertThat(doc.getFrom()).isEqualTo("foo/from"); + assertThat(doc.getTo()).isEqualTo("bar/to"); } } - @Test - public void deleteDocumentsByKey() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentsByKey(ArangoCollection collection) { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -2307,16 +2438,17 @@ public void deleteDocumentsByKey() { keys.add("2"); final MultiDocumentEntity> deleteResult = collection .deleteDocuments(keys, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(2)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments()).hasSize(2); for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), anyOf(is("1"), is("2"))); + assertThat(i.getKey()).isIn("1", "2"); } - assertThat(deleteResult.getErrors().size(), is(0)); + assertThat(deleteResult.getErrors()).isEmpty(); } - @Test - public void deleteDocumentsByDocuments() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentsByDocuments(ArangoCollection collection) { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -2331,16 +2463,17 @@ public void deleteDocumentsByDocuments() { collection.insertDocuments(values, null); final MultiDocumentEntity> deleteResult = collection .deleteDocuments(values, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(2)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments()).hasSize(2); for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), anyOf(is("1"), is("2"))); + assertThat(i.getKey()).isIn("1", "2"); } - assertThat(deleteResult.getErrors().size(), is(0)); + assertThat(deleteResult.getErrors()).isEmpty(); } - @Test - public void deleteDocumentsByKeyOne() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentsByKeyOne(ArangoCollection collection) { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -2352,16 +2485,17 @@ public void deleteDocumentsByKeyOne() { keys.add("1"); final MultiDocumentEntity> deleteResult = collection .deleteDocuments(keys, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(1)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments()).hasSize(1); for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), is("1")); + assertThat(i.getKey()).isEqualTo("1"); } - assertThat(deleteResult.getErrors().size(), is(0)); + assertThat(deleteResult.getErrors()).isEmpty(); } - @Test - public void deleteDocumentsByDocumentOne() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentsByDocumentOne(ArangoCollection collection) { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -2371,28 +2505,30 @@ public void deleteDocumentsByDocumentOne() { collection.insertDocuments(values, null); final MultiDocumentEntity> deleteResult = collection .deleteDocuments(values, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(1)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments()).hasSize(1); for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), is("1")); + assertThat(i.getKey()).isEqualTo("1"); } - assertThat(deleteResult.getErrors().size(), is(0)); + assertThat(deleteResult.getErrors()).isEmpty(); } - @Test - public void deleteDocumentsEmpty() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentsEmpty(ArangoCollection collection) { final Collection values = new ArrayList<>(); collection.insertDocuments(values, null); final Collection keys = new ArrayList<>(); final MultiDocumentEntity> deleteResult = collection .deleteDocuments(keys, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(0)); - assertThat(deleteResult.getErrors().size(), is(0)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments()).isEmpty(); + assertThat(deleteResult.getErrors()).isEmpty(); } - @Test - public void deleteDocumentsByKeyNotExisting() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentsByKeyNotExisting(ArangoCollection collection) { final Collection values = new ArrayList<>(); collection.insertDocuments(values, null); final Collection keys = Arrays.asList( @@ -2402,13 +2538,14 @@ public void deleteDocumentsByKeyNotExisting() { final MultiDocumentEntity> deleteResult = collection .deleteDocuments(keys, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(0)); - assertThat(deleteResult.getErrors().size(), is(2)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments()).isEmpty(); + assertThat(deleteResult.getErrors()).hasSize(2); } - @Test - public void deleteDocumentsByDocumentsNotExisting() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void deleteDocumentsByDocumentsNotExisting(ArangoCollection collection) { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -2422,13 +2559,14 @@ public void deleteDocumentsByDocumentsNotExisting() { } final MultiDocumentEntity> deleteResult = collection .deleteDocuments(values, null, null); - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(0)); - assertThat(deleteResult.getErrors().size(), is(2)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments()).isEmpty(); + assertThat(deleteResult.getErrors()).hasSize(2); } - @Test - public void updateDocuments() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocuments(ArangoCollection collection) { final Collection values = Arrays.asList( new BaseDocument(rnd()), new BaseDocument(rnd()) @@ -2438,13 +2576,14 @@ public void updateDocuments() { final MultiDocumentEntity> updateResult = collection .updateDocuments(values, null); - assertThat(updateResult.getDocuments().size(), is(2)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments()).hasSize(2); + assertThat(updateResult.getErrors()).isEmpty(); } - @Test - public void updateDocumentsWithDifferentReturnType() { - List keys = IntStream.range(0, 3).mapToObj(it -> "key-" + UUID.randomUUID().toString()).collect(Collectors.toList()); + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentsWithDifferentReturnType(ArangoCollection collection) { + List keys = IntStream.range(0, 3).mapToObj(it -> "key-" + UUID.randomUUID()).collect(Collectors.toList()); List docs = keys.stream() .map(BaseDocument::new) .peek(it -> it.addAttribute("a", "test")) @@ -2465,15 +2604,17 @@ public void updateDocumentsWithDifferentReturnType() { final MultiDocumentEntity> updateResult = collection .updateDocuments(modifiedDocs, new DocumentUpdateOptions().returnNew(true), BaseDocument.class); - assertThat(updateResult.getDocuments().size(), is(3)); - assertThat(updateResult.getErrors().size(), is(0)); - assertThat(updateResult.getDocuments().stream().map(DocumentUpdateEntity::getNew) - .allMatch(it -> it.getAttribute("a").equals("test") && it.getAttribute("b").equals("test")), - is(true)); + assertThat(updateResult.getDocuments()).hasSize(3); + assertThat(updateResult.getErrors()).isEmpty(); + assertThat(updateResult.getDocuments().stream()) + .map(DocumentUpdateEntity::getNew) + .allMatch(it -> it.getAttribute("a").equals("test")) + .allMatch(it -> it.getAttribute("b").equals("test")); } - @Test - public void updateDocumentsOne() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentsOne(ArangoCollection collection) { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -2487,21 +2628,23 @@ public void updateDocumentsOne() { updatedValues.add(first); final MultiDocumentEntity> updateResult = collection .updateDocuments(updatedValues, null); - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments()).hasSize(1); + assertThat(updateResult.getErrors()).isEmpty(); } - @Test - public void updateDocumentsEmpty() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentsEmpty(ArangoCollection collection) { final Collection values = new ArrayList<>(); final MultiDocumentEntity> updateResult = collection .updateDocuments(values, null); - assertThat(updateResult.getDocuments().size(), is(0)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments()).isEmpty(); + assertThat(updateResult.getErrors()).isEmpty(); } - @Test - public void updateDocumentsWithoutKey() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentsWithoutKey(ArangoCollection collection) { final Collection values = new ArrayList<>(); { values.add(new BaseDocument("1")); @@ -2515,12 +2658,13 @@ public void updateDocumentsWithoutKey() { updatedValues.add(new BaseDocument()); final MultiDocumentEntity> updateResult = collection .updateDocuments(updatedValues, null); - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(1)); + assertThat(updateResult.getDocuments()).hasSize(1); + assertThat(updateResult.getErrors()).hasSize(1); } - @Test - public void updateDocumentsJson() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void updateDocumentsJson(ArangoCollection collection) { final Collection values = new ArrayList<>(); values.add("{\"_key\":\"1\"}"); values.add("{\"_key\":\"2\"}"); @@ -2531,12 +2675,13 @@ public void updateDocumentsJson() { updatedValues.add("{\"_key\":\"2\", \"foo\":\"bar\"}"); final MultiDocumentEntity> updateResult = collection .updateDocuments(updatedValues); - assertThat(updateResult.getDocuments().size(), is(2)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments()).hasSize(2); + assertThat(updateResult.getErrors()).isEmpty(); } - @Test - public void replaceDocuments() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocuments(ArangoCollection collection) { final Collection values = new ArrayList<>(); { values.add(new BaseDocument("1")); @@ -2550,12 +2695,13 @@ public void replaceDocuments() { } final MultiDocumentEntity> updateResult = collection .replaceDocuments(updatedValues, null); - assertThat(updateResult.getDocuments().size(), is(2)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments()).hasSize(2); + assertThat(updateResult.getErrors()).isEmpty(); } - @Test - public void replaceDocumentsOne() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentsOne(ArangoCollection collection) { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -2569,21 +2715,23 @@ public void replaceDocumentsOne() { updatedValues.add(first); final MultiDocumentEntity> updateResult = collection .updateDocuments(updatedValues, null); - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments()).hasSize(1); + assertThat(updateResult.getErrors()).isEmpty(); } - @Test - public void replaceDocumentsEmpty() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentsEmpty(ArangoCollection collection) { final Collection values = new ArrayList<>(); final MultiDocumentEntity> updateResult = collection .updateDocuments(values, null); - assertThat(updateResult.getDocuments().size(), is(0)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments()).isEmpty(); + assertThat(updateResult.getErrors()).isEmpty(); } - @Test - public void replaceDocumentsWithoutKey() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentsWithoutKey(ArangoCollection collection) { final Collection values = new ArrayList<>(); { values.add(new BaseDocument("1")); @@ -2597,12 +2745,13 @@ public void replaceDocumentsWithoutKey() { updatedValues.add(new BaseDocument()); final MultiDocumentEntity> updateResult = collection .updateDocuments(updatedValues, null); - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(1)); + assertThat(updateResult.getDocuments()).hasSize(1); + assertThat(updateResult.getErrors()).hasSize(1); } - @Test - public void replaceDocumentsJson() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void replaceDocumentsJson(ArangoCollection collection) { final Collection values = new ArrayList<>(); values.add("{\"_key\":\"1\"}"); values.add("{\"_key\":\"2\"}"); @@ -2613,41 +2762,46 @@ public void replaceDocumentsJson() { updatedValues.add("{\"_key\":\"2\", \"foo\":\"bar\"}"); final MultiDocumentEntity> updateResult = collection .replaceDocuments(updatedValues); - assertThat(updateResult.getDocuments().size(), is(2)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments()).hasSize(2); + assertThat(updateResult.getErrors()).isEmpty(); } - @Test - public void load() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void load(ArangoCollection collection) { final CollectionEntity result = collection.load(); - assertThat(result.getName(), is(COLLECTION_NAME)); + assertThat(result.getName()).isEqualTo(COLLECTION_NAME); } - @Test - public void unload() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void unload(ArangoCollection collection) { final CollectionEntity result = collection.unload(); - assertThat(result.getName(), is(COLLECTION_NAME)); + assertThat(result.getName()).isEqualTo(COLLECTION_NAME); } - @Test - public void getInfo() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getInfo(ArangoCollection collection) { final CollectionEntity result = collection.getInfo(); - assertThat(result.getName(), is(COLLECTION_NAME)); + assertThat(result.getName()).isEqualTo(COLLECTION_NAME); } - @Test - public void getPropeties() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getPropeties(ArangoCollection collection) { final CollectionPropertiesEntity result = collection.getProperties(); - assertThat(result.getName(), is(COLLECTION_NAME)); - assertThat(result.getCount(), is(nullValue())); + assertThat(result.getName()).isEqualTo(COLLECTION_NAME); + assertThat(result.getCount()).isNull(); } - @Test - public void changeProperties() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void changeProperties(ArangoCollection collection) { final CollectionPropertiesEntity properties = collection.getProperties(); - assertThat(properties.getWaitForSync(), is(notNullValue())); + assertThat(properties.getWaitForSync()).isNotNull(); if (isAtLeastVersion(3, 7)) { - assertThat(properties.getSchema(), is(nullValue())); + assertThat(properties.getSchema()).isNull(); } String schemaRule = ("{ " + @@ -2669,13 +2823,13 @@ public void changeProperties() { ); final CollectionPropertiesEntity changedProperties = collection.changeProperties(updatedOptions); - assertThat(changedProperties.getWaitForSync(), is(notNullValue())); - assertThat(changedProperties.getWaitForSync(), is(!properties.getWaitForSync())); + assertThat(changedProperties.getWaitForSync()).isNotNull(); + assertThat(changedProperties.getWaitForSync()).isEqualTo(!properties.getWaitForSync()); if (isAtLeastVersion(3, 7)) { - assertThat(changedProperties.getSchema(), is(notNullValue())); - assertThat(changedProperties.getSchema().getLevel(), is(CollectionSchema.Level.NEW)); - assertThat(changedProperties.getSchema().getMessage(), is(schemaMessage)); - assertThat(changedProperties.getSchema().getRule(), is(schemaRule)); + assertThat(changedProperties.getSchema()).isNotNull(); + assertThat(changedProperties.getSchema().getLevel()).isEqualTo(CollectionSchema.Level.NEW); + assertThat(changedProperties.getSchema().getMessage()).isEqualTo(schemaMessage); + assertThat(changedProperties.getSchema().getRule()).isEqualTo(schemaRule); } // revert changes @@ -2684,73 +2838,80 @@ public void changeProperties() { .schema(CollectionSchema.NULL_SCHEMA) ); if (isAtLeastVersion(3, 7)) { - assertThat(revertedProperties.getSchema(), is(nullValue())); + assertThat(revertedProperties.getSchema()).isNull(); } } - @Test - public void rename() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void rename(ArangoCollection collection) { assumeTrue(isSingleServer()); + ArangoDatabase db = collection.db(); final CollectionEntity result = collection.rename(COLLECTION_NAME + "1"); - assertThat(result, is(notNullValue())); - assertThat(result.getName(), is(COLLECTION_NAME + "1")); + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo(COLLECTION_NAME + "1"); final CollectionEntity info = db.collection(COLLECTION_NAME + "1").getInfo(); - assertThat(info.getName(), is(COLLECTION_NAME + "1")); - try { - db.collection(COLLECTION_NAME).getInfo(); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(404)); - } + assertThat(info.getName()).isEqualTo(COLLECTION_NAME + "1"); + Throwable thrown = catchThrowable(() -> db.collection(COLLECTION_NAME).getInfo()); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(404); db.collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME); } - @Test - public void responsibleShard() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void responsibleShard(ArangoCollection collection) { assumeTrue(isCluster()); assumeTrue(isAtLeastVersion(3, 5)); ShardEntity shard = collection.getResponsibleShard(new BaseDocument("testKey")); - assertThat(shard, is(notNullValue())); - assertThat(shard.getShardId(), is(notNullValue())); + assertThat(shard).isNotNull(); + assertThat(shard.getShardId()).isNotNull(); } - @Test - public void renameDontBreaksCollectionHandler() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void renameDontBreaksCollectionHandler(ArangoCollection collection) { assumeTrue(isSingleServer()); collection.rename(COLLECTION_NAME + "1"); - assertThat(collection.getInfo(), is(notNullValue())); - db.collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME); + assertThat(collection.getInfo()).isNotNull(); + collection.db().collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME); } - @Test - public void getRevision() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getRevision(ArangoCollection collection) { final CollectionRevisionEntity result = collection.getRevision(); - assertThat(result, is(notNullValue())); - assertThat(result.getName(), is(COLLECTION_NAME)); - assertThat(result.getRevision(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo(COLLECTION_NAME); + assertThat(result.getRevision()).isNotNull(); } - @Test - public void keyWithSpecialCharacter() { - final String key = "myKey_-:.@()+,=;$!*'%"; + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void keyWithSpecialCharacter(ArangoCollection collection) { + final String key = "myKey_-:.@()+,=;$!*'%-" + UUID.randomUUID(); collection.insertDocument(new BaseDocument(key)); final BaseDocument doc = collection.getDocument(key, BaseDocument.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getKey(), is(key)); + assertThat(doc).isNotNull(); + assertThat(doc.getKey()).isEqualTo(key); } - @Test - public void alreadyUrlEncodedkey() { - final String key = "http%3A%2F%2Fexample.com%2F"; + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void alreadyUrlEncodedkey(ArangoCollection collection) { + final String key = "http%3A%2F%2Fexample.com%2F-" + UUID.randomUUID(); collection.insertDocument(new BaseDocument(key)); final BaseDocument doc = collection.getDocument(key, BaseDocument.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getKey(), is(key)); + assertThat(doc).isNotNull(); + assertThat(doc.getKey()).isEqualTo(key); } - @Test - public void grantAccessRW() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void grantAccessRW(ArangoCollection collection) { + ArangoDB arangoDB = collection.db().arango(); try { arangoDB.createUser("user1", "1234", null); collection.grantAccess("user1", Permissions.RW); @@ -2759,8 +2920,10 @@ public void grantAccessRW() { } } - @Test - public void grantAccessRO() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void grantAccessRO(ArangoCollection collection) { + ArangoDB arangoDB = collection.db().arango(); try { arangoDB.createUser("user1", "1234", null); collection.grantAccess("user1", Permissions.RO); @@ -2769,8 +2932,10 @@ public void grantAccessRO() { } } - @Test - public void grantAccessNONE() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void grantAccessNONE(ArangoCollection collection) { + ArangoDB arangoDB = collection.db().arango(); try { arangoDB.createUser("user1", "1234", null); collection.grantAccess("user1", Permissions.NONE); @@ -2779,13 +2944,17 @@ public void grantAccessNONE() { } } - @Test(expected = ArangoDBException.class) - public void grantAccessUserNotFound() { - collection.grantAccess("user1", Permissions.RW); + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void grantAccessUserNotFound(ArangoCollection collection) { + Throwable thrown = catchThrowable(() -> collection.grantAccess("user1", Permissions.RW)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void revokeAccess() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void revokeAccess(ArangoCollection collection) { + ArangoDB arangoDB = collection.db().arango(); try { arangoDB.createUser("user1", "1234", null); collection.grantAccess("user1", Permissions.NONE); @@ -2794,13 +2963,17 @@ public void revokeAccess() { } } - @Test(expected = ArangoDBException.class) - public void revokeAccessUserNotFound() { - collection.grantAccess("user1", Permissions.NONE); + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void revokeAccessUserNotFound(ArangoCollection collection) { + Throwable thrown = catchThrowable(() -> collection.grantAccess("user1", Permissions.NONE)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void resetAccess() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void resetAccess(ArangoCollection collection) { + ArangoDB arangoDB = collection.db().arango(); try { arangoDB.createUser("user1", "1234", null); collection.resetAccess("user1"); @@ -2809,14 +2982,17 @@ public void resetAccess() { } } - @Test(expected = ArangoDBException.class) - public void resetAccessUserNotFound() { - collection.resetAccess("user1"); + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void resetAccessUserNotFound(ArangoCollection collection) { + Throwable thrown = catchThrowable(() -> collection.resetAccess("user1")); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void getPermissions() { - assertThat(Permissions.RW, is(collection.getPermissions("root"))); + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void getPermissions(ArangoCollection collection) { + assertThat(collection.getPermissions("root")).isEqualTo(Permissions.RW); } } diff --git a/src/test/java/com/arangodb/ArangoCursorTest.java b/src/test/java/com/arangodb/ArangoCursorTest.java index ef7e4439f..2872451bf 100644 --- a/src/test/java/com/arangodb/ArangoCursorTest.java +++ b/src/test/java/com/arangodb/ArangoCursorTest.java @@ -22,255 +22,275 @@ import com.arangodb.model.AqlQueryOptions; import com.arangodb.velocypack.VPackSlice; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.*; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Vollmary + * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class ArangoCursorTest extends BaseTest { - - @BeforeClass - public static void init() { - BaseTest.initDB(); - } - - public ArangoCursorTest(final ArangoDB arangoDB) { - super(arangoDB); - } - - @Test - public void first() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final VPackSlice first = cursor.first(); - assertThat(first, is(not(nullValue()))); - assertThat(first.isInteger(), is(true)); - assertThat(first.getAsLong(), is(0L)); - } - - @Test - public void firstStream() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final Optional first = cursor.stream().findFirst(); - assertThat(first.isPresent(), is(true)); - assertThat(first.get().isInteger(), is(true)); - assertThat(first.get().getAsLong(), is(0L)); - } - - @Test - public void next() { - - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", new AqlQueryOptions().batchSize(5), VPackSlice.class); - - while (cursor.hasNext()) { - cursor.next(); - } - - } - - @Test - public void mapFilterCount() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).count(); - assertThat(count, is(50L)); - } - - @Test - public void mapFilterCountStream() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.stream().map(VPackSlice::getAsLong).filter(t -> t < 50).count(); - assertThat(count, is(50L)); - } - - @Test - public void mapMapFilterCount() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(VPackSlice::getAsLong).map(t -> t * 10).filter(t -> t < 500).count(); - assertThat(count, is(50L)); - } - - @Test - public void mapMapFilterFilterCount() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(VPackSlice::getAsLong).map(t -> t * 10).filter(t -> t < 500).filter(t -> t < 250).count(); - assertThat(count, is(25L)); - } - - @Test - public void mapFilterNext() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).iterator().next(); - assertThat(count, is(0L)); - } - - @Test - public void mapFilterFirst() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).first(); - assertThat(count, is(0L)); - } - - @Test - public void mapFilterCollectIntoList() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final List target = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).collectInto(new ArrayList<>()); - assertThat(target, is(not(nullValue()))); - assertThat(target.size(), is(50)); - } - - @Test - public void mapFilterCollectIntoSet() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final Set target = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).collectInto(new HashSet<>()); - assertThat(target, is(not(nullValue()))); - assertThat(target.size(), is(50)); - } - - @Test - public void mapFilterCollectIntoSetStream() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final Set target = cursor.stream().map(VPackSlice::getAsLong).filter(t -> t < 50).collect(Collectors.toSet()); - assertThat(target, is(not(nullValue()))); - assertThat(target.size(), is(50)); - } - - @Test - public void foreach() { - final AtomicLong i = new AtomicLong(0L); - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.foreach(t -> assertThat(t.getAsLong(), is(i.getAndIncrement()))); - } - - @Test - public void forEach() { - final AtomicLong i = new AtomicLong(0L); - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.forEach(t -> assertThat(t.getAsLong(), is(i.getAndIncrement()))); - } - - @Test - public void mapForeach() { - final AtomicLong i = new AtomicLong(0L); - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.map(VPackSlice::getAsLong).foreach(t -> assertThat(t, is(i.getAndIncrement()))); - } - - @Test - public void mapForeachStream() { - final AtomicLong i = new AtomicLong(0L); - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.stream().map(VPackSlice::getAsLong).forEach(t -> assertThat(t, is(i.getAndIncrement()))); - } - - @Test - public void mapFilterForeach() { - final AtomicLong i = new AtomicLong(0L); - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).foreach(t -> assertThat(t, is(i.getAndIncrement()))); - } - - @Test - public void mapFilterForEachStream() { - final AtomicLong i = new AtomicLong(0L); - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - cursor.stream().map(VPackSlice::getAsLong).filter(t -> t < 50).forEach(t -> assertThat(t, is(i.getAndIncrement()))); - } - - @Test - public void anyMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.anyMatch(t -> t.getAsLong() == 50L); - assertThat(match, is(true)); - } - - @Test - public void anyMatchStream() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.stream().anyMatch(t -> t.getAsLong() == 50L); - assertThat(match, is(true)); - } - - @Test - public void mapAnyMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).anyMatch(t -> t == 50L); - assertThat(match, is(true)); - } - - @Test - public void mapFilterAnyMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).anyMatch(t -> t == 25L); - assertThat(match, is(true)); - } - - @Test - public void noneMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.noneMatch(t -> t.getAsLong() == 100L); - assertThat(match, is(true)); - } - - @Test - public void noneMatchStream() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.stream().noneMatch(t -> t.getAsLong() == 100L); - assertThat(match, is(true)); - } - - @Test - public void mapNoneMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).noneMatch(t -> t == 100L); - assertThat(match, is(true)); - } - - @Test - public void mapFilterNoneMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).noneMatch(t -> t == 50L); - assertThat(match, is(true)); - } - - @Test - public void allMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.allMatch(t -> t.getAsLong() < 100L); - assertThat(match, is(true)); - } - - @Test - public void allMatchStream() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.stream().allMatch(t -> t.getAsLong() < 100L); - assertThat(match, is(true)); - } - - @Test - public void mapAllMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).allMatch(t -> t < 100); - assertThat(match, is(true)); - } - - @Test - public void mapFilterAllMatch() { - final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); - final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).allMatch(t -> t < 50); - assertThat(match, is(true)); - } +class ArangoCursorTest extends BaseJunit5 { + + @BeforeAll + static void init() { + initDB(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void first(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final VPackSlice first = cursor.first(); + assertThat(first).isNotNull(); + assertThat(first.isInteger()).isTrue(); + assertThat(first.getAsLong()).isZero(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void firstStream(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final Optional first = cursor.stream().findFirst(); + assertThat(first.isPresent()).isTrue(); + assertThat(first.get().isInteger()).isTrue(); + assertThat(first.get().getAsLong()).isZero(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void next(ArangoDatabase db) { + + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", new AqlQueryOptions().batchSize(5), VPackSlice.class); + + while (cursor.hasNext()) { + cursor.next(); + } + + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterCount(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).count(); + assertThat(count).isEqualTo(50L); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterCountStream(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final long count = cursor.stream().map(VPackSlice::getAsLong).filter(t -> t < 50).count(); + assertThat(count).isEqualTo(50L); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapMapFilterCount(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final long count = cursor.map(VPackSlice::getAsLong).map(t -> t * 10).filter(t -> t < 500).count(); + assertThat(count).isEqualTo(50L); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapMapFilterFilterCount(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final long count = cursor.map(VPackSlice::getAsLong).map(t -> t * 10).filter(t -> t < 500).filter(t -> t < 250).count(); + assertThat(count).isEqualTo(25L); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterNext(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).iterator().next(); + assertThat(count).isZero(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterFirst(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final long count = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).first(); + assertThat(count).isZero(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterCollectIntoList(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final List target = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).collectInto(new ArrayList<>()); + assertThat(target).isNotNull(); + assertThat(target).hasSize(50); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterCollectIntoSet(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final Set target = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).collectInto(new HashSet<>()); + assertThat(target).isNotNull(); + assertThat(target).hasSize(50); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterCollectIntoSetStream(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final Set target = cursor.stream().map(VPackSlice::getAsLong).filter(t -> t < 50).collect(Collectors.toSet()); + assertThat(target).isNotNull(); + assertThat(target).hasSize(50); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void foreach(ArangoDatabase db) { + final AtomicLong i = new AtomicLong(0L); + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + cursor.foreach(t -> assertThat(t.getAsLong()).isEqualTo(i.getAndIncrement())); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void forEach(ArangoDatabase db) { + final AtomicLong i = new AtomicLong(0L); + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + cursor.forEach(t -> assertThat(t.getAsLong()).isEqualTo(i.getAndIncrement())); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapForeach(ArangoDatabase db) { + final AtomicLong i = new AtomicLong(0L); + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + cursor.map(VPackSlice::getAsLong).foreach(t -> assertThat(t).isEqualTo(i.getAndIncrement())); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapForeachStream(ArangoDatabase db) { + final AtomicLong i = new AtomicLong(0L); + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + cursor.stream().map(VPackSlice::getAsLong).forEach(t -> assertThat(t).isEqualTo(i.getAndIncrement())); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterForeach(ArangoDatabase db) { + final AtomicLong i = new AtomicLong(0L); + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).foreach(t -> assertThat(t).isEqualTo(i.getAndIncrement())); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterForEachStream(ArangoDatabase db) { + final AtomicLong i = new AtomicLong(0L); + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + cursor.stream().map(VPackSlice::getAsLong).filter(t -> t < 50).forEach(t -> assertThat(t).isEqualTo(i.getAndIncrement())); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void anyMatch(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.anyMatch(t -> t.getAsLong() == 50L); + assertThat(match).isTrue(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void anyMatchStream(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.stream().anyMatch(t -> t.getAsLong() == 50L); + assertThat(match).isTrue(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapAnyMatch(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).anyMatch(t -> t == 50L); + assertThat(match).isTrue(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterAnyMatch(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).anyMatch(t -> t == 25L); + assertThat(match).isTrue(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void noneMatch(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.noneMatch(t -> t.getAsLong() == 100L); + assertThat(match).isTrue(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void noneMatchStream(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.stream().noneMatch(t -> t.getAsLong() == 100L); + assertThat(match).isTrue(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapNoneMatch(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).noneMatch(t -> t == 100L); + assertThat(match).isTrue(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterNoneMatch(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).noneMatch(t -> t == 50L); + assertThat(match).isTrue(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void allMatch(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.allMatch(t -> t.getAsLong() < 100L); + assertThat(match).isTrue(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void allMatchStream(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.stream().allMatch(t -> t.getAsLong() < 100L); + assertThat(match).isTrue(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapAllMatch(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).allMatch(t -> t < 100); + assertThat(match).isTrue(); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void mapFilterAllMatch(ArangoDatabase db) { + final ArangoCursor cursor = db.query("FOR i IN 0..99 RETURN i", VPackSlice.class); + final boolean match = cursor.map(VPackSlice::getAsLong).filter(t -> t < 50).allMatch(t -> t < 50); + assertThat(match).isTrue(); + } } diff --git a/src/test/java/com/arangodb/ArangoDBTest.java b/src/test/java/com/arangodb/ArangoDBTest.java index 8fa06bce5..3317b2d29 100644 --- a/src/test/java/com/arangodb/ArangoDBTest.java +++ b/src/test/java/com/arangodb/ArangoDBTest.java @@ -21,6 +21,7 @@ package com.arangodb; import com.arangodb.entity.*; +import com.arangodb.mapping.ArangoJack; import com.arangodb.model.*; import com.arangodb.model.LogOptions.SortOrder; import com.arangodb.util.TestUtils; @@ -28,13 +29,12 @@ import com.arangodb.velocystream.Request; import com.arangodb.velocystream.RequestType; import com.arangodb.velocystream.Response; -import org.hamcrest.Matcher; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.Collection; @@ -50,17 +50,16 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Mark Vollmary * @author ReÅŸat SABIQ + * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class ArangoDBTest { +class ArangoDBTest extends BaseJunit5 { private static final DbName DB1 = DbName.of("ArangoDBTest_db1"); private static final DbName DB2 = DbName.of("ArangoDBTest_db2"); @@ -68,58 +67,21 @@ public class ArangoDBTest { private static final String ROOT = "root"; private static final String PW = "machts der hund"; - private final ArangoDB arangoDB; - private final ArangoDatabase db1; - private final ArangoDatabase db2; - private static Boolean extendedNames; - @BeforeClass - public static void initDB() { - ArangoDB arango = BaseTest.arangos.get(0); - for (DbName db : new DbName[]{DB1, DB2}) { - ArangoDatabase database = arango.db(db); - if (!database.exists()) - database.create(); - } - } - - @AfterClass - public static void shutdown() { - ArangoDB arango = BaseTest.arangos.get(0); - for (DbName db : new DbName[]{DB1, DB2}) { - ArangoDatabase database = arango.db(db); - if (database.exists()) - database.drop(); - } - BaseTest.arangos.forEach(ArangoDB::shutdown); - } - - @Parameters - public static List builders() { - return BaseTest.arangos; - } - - public ArangoDBTest(final ArangoDB arangoDB) { - super(); - this.arangoDB = arangoDB; - db1 = arangoDB.db(DB1); - db2 = arangoDB.db(DB2); - } - - private boolean isEnterprise() { - return arangoDB.getVersion().getLicense() == License.ENTERPRISE; - } - - private boolean isCluster() { - return arangoDB.getRole() == ServerRole.COORDINATOR; + @BeforeAll + static void initDBs() { + initDB(DB1); + initDB(DB2); } - private boolean isAtLeastVersion(final int major, final int minor) { - return TestUtils.isAtLeastVersion(arangoDB.getVersion().getVersion(), major, minor, 0); + @AfterAll + static void shutdown() { + dropDB(DB1); + dropDB(DB2); } - private boolean supportsExtendedNames() { + private boolean supportsExtendedNames(ArangoDB arangoDB) { if (extendedNames == null) { try { ArangoDatabase testDb = arangoDB.db(DbName.of("test-" + TestUtils.generateRandomDbName(20, true))); @@ -133,46 +95,47 @@ private boolean supportsExtendedNames() { return extendedNames; } - @Test - public void getVersion() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getVersion(ArangoDB arangoDB) { final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); - assertThat(version.getServer(), is(notNullValue())); - assertThat(version.getVersion(), is(notNullValue())); + assertThat(version.getServer()).isNotNull(); + assertThat(version.getVersion()).isNotNull(); } - @Test - public void createAndDeleteDatabase() { - final DbName dbName = DbName.of("testDB-" + TestUtils.generateRandomDbName(20, supportsExtendedNames())); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void createAndDeleteDatabase(ArangoDB arangoDB) { + final DbName dbName = DbName.of("testDB-" + TestUtils.generateRandomDbName(20, supportsExtendedNames(arangoDB))); final Boolean resultCreate; resultCreate = arangoDB.createDatabase(dbName); - assertThat(resultCreate, is(true)); + assertThat(resultCreate).isTrue(); final Boolean resultDelete = arangoDB.db(dbName).drop(); - assertThat(resultDelete, is(true)); + assertThat(resultDelete).isTrue(); } - @Test - public void createWithNotNormalizedName() { - assumeTrue(supportsExtendedNames()); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void createWithNotNormalizedName(ArangoDB arangoDB) { + assumeTrue(supportsExtendedNames(arangoDB)); final String dbName = "testDB-\u006E\u0303\u00f1"; DbName normalized = DbName.normalize(dbName); arangoDB.createDatabase(normalized); arangoDB.db(normalized).drop(); - try { - DbName.of(dbName); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), containsString("not normalized")); - } + Throwable thrown = catchThrowable(() -> DbName.of(dbName)); + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not normalized"); } - @Test - public void createDatabaseWithOptions() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void createDatabaseWithOptions(ArangoDB arangoDB) { assumeTrue(isCluster()); assumeTrue(isAtLeastVersion(3, 6)); - final DbName dbName = DbName.of("testDB-" + TestUtils.generateRandomDbName(20, supportsExtendedNames())); + final DbName dbName = DbName.of("testDB-" + TestUtils.generateRandomDbName(20, supportsExtendedNames(arangoDB))); final Boolean resultCreate = arangoDB.createDatabase(new DBCreateOptions() .name(dbName) .options(new DatabaseOptions() @@ -181,25 +144,26 @@ public void createDatabaseWithOptions() { .sharding("") ) ); - assertThat(resultCreate, is(true)); + assertThat(resultCreate).isTrue(); DatabaseEntity info = arangoDB.db(dbName).getInfo(); - assertThat(info.getReplicationFactor(), is(2)); - assertThat(info.getWriteConcern(), is(2)); - assertThat(info.getSharding(), is("")); - assertThat(info.getSatellite(), nullValue()); + assertThat(info.getReplicationFactor()).isEqualTo(2); + assertThat(info.getWriteConcern()).isEqualTo(2); + assertThat(info.getSharding()).isEmpty(); + assertThat(info.getSatellite()).isNull(); final Boolean resultDelete = arangoDB.db(dbName).drop(); - assertThat(resultDelete, is(true)); + assertThat(resultDelete).isTrue(); } - @Test - public void createDatabaseWithOptionsSatellite() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void createDatabaseWithOptionsSatellite(ArangoDB arangoDB) { assumeTrue(isCluster()); assumeTrue(isEnterprise()); assumeTrue(isAtLeastVersion(3, 6)); - final DbName dbName = DbName.of("testDB-" + TestUtils.generateRandomDbName(20, supportsExtendedNames())); + final DbName dbName = DbName.of("testDB-" + TestUtils.generateRandomDbName(20, supportsExtendedNames(arangoDB))); final Boolean resultCreate = arangoDB.createDatabase(new DBCreateOptions() .name(dbName) .options(new DatabaseOptions() @@ -208,21 +172,22 @@ public void createDatabaseWithOptionsSatellite() { .sharding("") ) ); - assertThat(resultCreate, is(true)); + assertThat(resultCreate).isTrue(); DatabaseEntity info = arangoDB.db(dbName).getInfo(); - assertThat(info.getReplicationFactor(), nullValue()); - assertThat(info.getSatellite(), is(true)); - assertThat(info.getWriteConcern(), is(2)); - assertThat(info.getSharding(), is("")); + assertThat(info.getReplicationFactor()).isNull(); + assertThat(info.getSatellite()).isTrue(); + assertThat(info.getWriteConcern()).isEqualTo(2); + assertThat(info.getSharding()).isEmpty(); final Boolean resultDelete = arangoDB.db(dbName).drop(); - assertThat(resultDelete, is(true)); + assertThat(resultDelete).isTrue(); } - @Test - public void createDatabaseWithUsers() throws InterruptedException { - final DbName dbName = DbName.of("testDB-" + TestUtils.generateRandomDbName(20, supportsExtendedNames())); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void createDatabaseWithUsers(ArangoDB arangoDB) throws InterruptedException { + final DbName dbName = DbName.of("testDB-" + TestUtils.generateRandomDbName(20, supportsExtendedNames(arangoDB))); final Map extra = Collections.singletonMap("key", "value"); final Boolean resultCreate = arangoDB.createDatabase(new DBCreateOptions() .name(dbName) @@ -233,502 +198,499 @@ public void createDatabaseWithUsers() throws InterruptedException { .extra(extra) )) ); - assertThat(resultCreate, is(true)); + assertThat(resultCreate).isTrue(); DatabaseEntity info = arangoDB.db(dbName).getInfo(); - assertThat(info.getName(), is(dbName.get())); + assertThat(info.getName()).isEqualTo(dbName.get()); Optional retrievedUserOptional = arangoDB.getUsers().stream() .filter(it -> it.getUser().equals("testUser")) .findFirst(); - assertThat(retrievedUserOptional.isPresent(), is(true)); + assertThat(retrievedUserOptional).isPresent(); UserEntity retrievedUser = retrievedUserOptional.get(); - assertThat(retrievedUser.getActive(), is(true)); - assertThat(retrievedUser.getExtra(), is(extra)); + assertThat(retrievedUser.getActive()).isTrue(); + assertThat(retrievedUser.getExtra()).isEqualTo(extra); // needed for active-failover tests only Thread.sleep(1_000); ArangoDB arangoDBTestUser = new ArangoDB.Builder() + .serializer(new ArangoJack()) .user("testUser") .password("testPasswd") .build(); // check if testUser has been created and can access the created db - ArangoCollection collection = arangoDBTestUser.db(dbName).collection("col-" + UUID.randomUUID().toString()); + ArangoCollection collection = arangoDBTestUser.db(dbName).collection("col-" + UUID.randomUUID()); collection.create(); arangoDBTestUser.shutdown(); final Boolean resultDelete = arangoDB.db(dbName).drop(); - assertThat(resultDelete, is(true)); + assertThat(resultDelete).isTrue(); } - @Test - public void getDatabases() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getDatabases(ArangoDB arangoDB) { Collection dbs = arangoDB.getDatabases(); - assertThat(dbs, is(notNullValue())); - assertThat(dbs.size(), is(greaterThan(0))); - assertThat(dbs.contains("_system"), is(true)); - assertThat(dbs, hasItem(DB1.get())); + assertThat(dbs).contains("_system", DB1.get()); } - @Test - public void getAccessibleDatabases() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getAccessibleDatabases(ArangoDB arangoDB) { final Collection dbs = arangoDB.getAccessibleDatabases(); - assertThat(dbs, is(notNullValue())); - assertThat(dbs.size(), greaterThan(0)); - assertThat(dbs, hasItem("_system")); + assertThat(dbs).contains("_system"); } - @Test - public void getAccessibleDatabasesFor() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getAccessibleDatabasesFor(ArangoDB arangoDB) { final Collection dbs = arangoDB.getAccessibleDatabasesFor("root"); - assertThat(dbs, is(notNullValue())); - assertThat(dbs.size(), greaterThan(0)); - assertThat(dbs, hasItem("_system")); + assertThat(dbs).contains("_system"); } - @Test - public void createUser() { - String username = "user-" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void createUser(ArangoDB arangoDB) { + String username = "user-" + UUID.randomUUID(); final UserEntity result = arangoDB.createUser(username, PW, null); - assertThat(result, is(notNullValue())); - assertThat(result.getUser(), is(username)); + assertThat(result.getUser()).isEqualTo(username); } - @Test - public void deleteUser() { - String username = "user-" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void deleteUser(ArangoDB arangoDB) { + String username = "user-" + UUID.randomUUID(); arangoDB.createUser(username, PW, null); arangoDB.deleteUser(username); } - @Test - public void getUserRoot() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getUserRoot(ArangoDB arangoDB) { final UserEntity user = arangoDB.getUser(ROOT); - assertThat(user, is(notNullValue())); - assertThat(user.getUser(), is(ROOT)); + assertThat(user.getUser()).isEqualTo(ROOT); } - @Test - public void getUser() { - String username = "user-" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getUser(ArangoDB arangoDB) { + String username = "user-" + UUID.randomUUID(); arangoDB.createUser(username, PW, null); final UserEntity user = arangoDB.getUser(username); - assertThat(user.getUser(), is(username)); - + assertThat(user.getUser()).isEqualTo(username); } - @Test - public void getUsersOnlyRoot() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getUsersOnlyRoot(ArangoDB arangoDB) { final Collection users = arangoDB.getUsers(); - assertThat(users, is(notNullValue())); - assertThat(users.size(), greaterThan(0)); + assertThat(users).isNotEmpty(); } - @Test - public void getUsers() { - String username = "user-" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getUsers(ArangoDB arangoDB) { + String username = "user-" + UUID.randomUUID(); // Allow & account for pre-existing users other than ROOT: final Collection initialUsers = arangoDB.getUsers(); arangoDB.createUser(username, PW, null); final Collection users = arangoDB.getUsers(); - assertThat(users, is(notNullValue())); - assertThat(users.size(), is(initialUsers.size() + 1)); + assertThat(users).hasSize(initialUsers.size() + 1); - final List> matchers = new ArrayList<>(users.size()); + final List expected = new ArrayList<>(users.size()); // Add initial users, including root: for (final UserEntity userEntity : initialUsers) { - matchers.add(is(userEntity.getUser())); + expected.add(userEntity.getUser()); } // Add username: - matchers.add(is(username)); + expected.add(username); for (final UserEntity user : users) { - assertThat(user.getUser(), anyOf(matchers)); + assertThat(user.getUser()).isIn(expected); } } - @Test - public void updateUserNoOptions() { - String username = "user-" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void updateUserNoOptions(ArangoDB arangoDB) { + String username = "user-" + UUID.randomUUID(); arangoDB.createUser(username, PW, null); arangoDB.updateUser(username, null); } - @Test - public void updateUser() { - String username = "user-" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void updateUser(ArangoDB arangoDB) { + String username = "user-" + UUID.randomUUID(); final Map extra = new HashMap<>(); extra.put("hund", false); arangoDB.createUser(username, PW, new UserCreateOptions().extra(extra)); extra.put("hund", true); extra.put("mund", true); final UserEntity user = arangoDB.updateUser(username, new UserUpdateOptions().extra(extra)); - assertThat(user, is(notNullValue())); - assertThat(user.getExtra().size(), is(2)); - assertThat(user.getExtra().get("hund"), is(notNullValue())); - assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("hund"))), is(true)); + assertThat(user.getExtra()).hasSize(2); + assertThat(user.getExtra()).containsKey("hund"); + assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("hund")))).isTrue(); final UserEntity user2 = arangoDB.getUser(username); - assertThat(user2.getExtra().size(), is(2)); - assertThat(user2.getExtra().get("hund"), is(notNullValue())); - assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("hund"))), is(true)); + assertThat(user2.getExtra()).hasSize(2); + assertThat(user2.getExtra()).containsKey("hund"); + assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("hund")))).isTrue(); } - @Test - public void replaceUser() { - String username = "user-" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void replaceUser(ArangoDB arangoDB) { + String username = "user-" + UUID.randomUUID(); final Map extra = new HashMap<>(); extra.put("hund", false); arangoDB.createUser(username, PW, new UserCreateOptions().extra(extra)); extra.remove("hund"); extra.put("mund", true); final UserEntity user = arangoDB.replaceUser(username, new UserUpdateOptions().extra(extra)); - assertThat(user, is(notNullValue())); - assertThat(user.getExtra().size(), is(1)); - assertThat(user.getExtra().get("mund"), is(notNullValue())); - assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("mund"))), is(true)); + assertThat(user.getExtra()).hasSize(1); + assertThat(user.getExtra()).containsKey("mund"); + assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("mund")))).isTrue(); final UserEntity user2 = arangoDB.getUser(username); - assertThat(user2.getExtra().size(), is(1)); - assertThat(user2.getExtra().get("mund"), is(notNullValue())); - assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("mund"))), is(true)); + assertThat(user2.getExtra()).hasSize(1); + assertThat(user2.getExtra()).containsKey("mund"); + assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("mund")))).isTrue(); } - @Test - public void updateUserDefaultDatabaseAccess() { - String username = "user-" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void updateUserDefaultDatabaseAccess(ArangoDB arangoDB) { + String username = "user-" + UUID.randomUUID(); arangoDB.createUser(username, PW); arangoDB.grantDefaultDatabaseAccess(username, Permissions.RW); } - @Test - public void updateUserDefaultCollectionAccess() { - String username = "user-" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void updateUserDefaultCollectionAccess(ArangoDB arangoDB) { + String username = "user-" + UUID.randomUUID(); arangoDB.createUser(username, PW); arangoDB.grantDefaultCollectionAccess(username, Permissions.RW); } @Test - public void authenticationFailPassword() { - final ArangoDB arangoDB = new ArangoDB.Builder().password("no").jwt(null).build(); - try { - arangoDB.getVersion(); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(401)); - } + void authenticationFailPassword() { + final ArangoDB arangoDB = new ArangoDB.Builder().password("no").jwt(null).serializer(new ArangoJack()).build(); + Throwable thrown = catchThrowable(arangoDB::getVersion); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + assertThat(((ArangoDBException) thrown).getResponseCode()).isEqualTo(401); } - @Test - public void authenticationFailUser() { - final ArangoDB arangoDB = new ArangoDB.Builder().user("no").jwt(null).build(); - try { - arangoDB.getVersion(); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(401)); - } + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void authenticationFailUser() { + final ArangoDB arangoDB = new ArangoDB.Builder().user("no").jwt(null).serializer(new ArangoJack()).build(); + Throwable thrown = catchThrowable(arangoDB::getVersion); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + assertThat(((ArangoDBException) thrown).getResponseCode()).isEqualTo(401); } - @Test - public void execute() throws VPackException { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void execute(ArangoDB arangoDB) throws VPackException { final Response response = arangoDB.execute(new Request(DbName.SYSTEM, RequestType.GET, "/_api/version")); - assertThat(response.getBody(), is(notNullValue())); - assertThat(response.getBody().get("version").isString(), is(true)); + assertThat(response.getBody().get("version").isString()).isTrue(); } - @Test - public void getLogs() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogs(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(null); - assertThat(logs, is(notNullValue())); - assertThat(logs.getTotalAmount(), greaterThan(0L)); - assertThat((long) logs.getLid().size(), is(logs.getTotalAmount())); - assertThat((long) logs.getLevel().size(), is(logs.getTotalAmount())); - assertThat((long) logs.getTimestamp().size(), is(logs.getTotalAmount())); - assertThat((long) logs.getText().size(), is(logs.getTotalAmount())); + assertThat(logs.getTotalAmount()).isPositive(); + assertThat(logs.getLid()).hasSize(logs.getTotalAmount().intValue()); + assertThat(logs.getLevel()).hasSize(logs.getTotalAmount().intValue()); + assertThat(logs.getTimestamp()).hasSize(logs.getTotalAmount().intValue()); + assertThat(logs.getText()).hasSize(logs.getTotalAmount().intValue()); } - @Test - public void getLogsUpto() { + @Disabled + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogsUpto(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logsUpto = arangoDB.getLogs(new LogOptions().upto(LogLevel.WARNING)); - assertThat(logsUpto, is(notNullValue())); - assertThat(logsUpto.getLevel(), not(contains(LogLevel.INFO))); + assertThat(logsUpto.getLevel()) + .isNotEmpty() + .doesNotContain(LogLevel.INFO); } - @Test - public void getLogsLevel() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogsLevel(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logsInfo = arangoDB.getLogs(new LogOptions().level(LogLevel.INFO)); - assertThat(logsInfo, is(notNullValue())); - assertThat(logsInfo.getLevel(), everyItem(is(LogLevel.INFO))); + assertThat(logsInfo.getLevel()).containsOnly(LogLevel.INFO); } - @Test - public void getLogsStart() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogsStart(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(null); - assertThat(logs.getLid(), not(empty())); + assertThat(logs.getLid()).isNotEmpty(); final LogEntity logsStart = arangoDB.getLogs(new LogOptions().start(logs.getLid().get(0) + 1)); - assertThat(logsStart, is(notNullValue())); - assertThat(logsStart.getLid(), not(contains(logs.getLid().get(0)))); + assertThat(logsStart.getLid()) + .isNotEmpty() + .doesNotContain(logs.getLid().get(0)); } - @Test - public void getLogsSize() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogsSize(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(null); - assertThat(logs.getLid().size(), greaterThan(0)); + assertThat(logs.getLid()).isNotEmpty(); final LogEntity logsSize = arangoDB.getLogs(new LogOptions().size(logs.getLid().size() - 1)); - assertThat(logsSize, is(notNullValue())); - assertThat(logsSize.getLid().size(), is(logs.getLid().size() - 1)); + assertThat(logsSize.getLid()).hasSize(logs.getLid().size() - 1); } - @Test - public void getLogsOffset() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogsOffset(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(null); - assertThat(logs.getTotalAmount(), greaterThan(0L)); + assertThat(logs.getTotalAmount()).isPositive(); final LogEntity logsOffset = arangoDB.getLogs(new LogOptions().offset(1)); - assertThat(logsOffset, is(notNullValue())); - assertThat(logsOffset.getLid(), not(hasItem(logs.getLid().get(0)))); + assertThat(logsOffset.getLid()) + .isNotEmpty() + .doesNotContain(logs.getLid().get(0)); } - @Test - public void getLogsSearch() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogsSearch(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(null); - final LogEntity logsSearch = arangoDB.getLogs(new LogOptions().search(BaseTest.TEST_DB.get())); - assertThat(logsSearch, is(notNullValue())); - assertThat(logs.getTotalAmount(), greaterThan(logsSearch.getTotalAmount())); + final LogEntity logsSearch = arangoDB.getLogs(new LogOptions().search(TEST_DB.get())); + assertThat(logs.getTotalAmount()).isGreaterThan(logsSearch.getTotalAmount()); } - @Test - public void getLogsSortAsc() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogsSortAsc(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(new LogOptions().sort(SortOrder.asc)); - assertThat(logs, is(notNullValue())); long lastId = -1; for (final Long id : logs.getLid()) { - assertThat(id, greaterThan(lastId)); + assertThat(id).isGreaterThan(lastId); lastId = id; } } - @Test - public void getLogsSortDesc() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogsSortDesc(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(new LogOptions().sort(SortOrder.desc)); - assertThat(logs, is(notNullValue())); long lastId = Long.MAX_VALUE; for (final Long id : logs.getLid()) { - assertThat(lastId, greaterThan(id)); + assertThat(lastId).isGreaterThan(id); lastId = id; } } - @Test - public void getLogEntries() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogEntries(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 8)); final LogEntriesEntity logs = arangoDB.getLogEntries(null); - assertThat(logs, is(notNullValue())); - assertThat(logs.getTotal(), greaterThan(0L)); - assertThat((long) logs.getMessages().size(), is(logs.getTotal())); + assertThat(logs.getTotal()).isPositive(); + assertThat(logs.getMessages()).hasSize(logs.getTotal().intValue()); } - @Test - public void getLogEntriesUpto() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogEntriesUpto(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 8)); final LogEntriesEntity logsUpto = arangoDB.getLogEntries(new LogOptions().upto(LogLevel.WARNING)); - assertThat(logsUpto, is(notNullValue())); - assertThat( - logsUpto.getMessages().stream() - .map(LogEntriesEntity.Message::getLevel) - .noneMatch("INFO"::equals), - is(true) - ); + assertThat(logsUpto.getMessages()) + .map(LogEntriesEntity.Message::getLevel) + .doesNotContain("INFO"); } - @Test - public void getLogEntriesLevel() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogEntriesLevel(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 8)); final LogEntriesEntity logsInfo = arangoDB.getLogEntries(new LogOptions().level(LogLevel.INFO)); - assertThat(logsInfo, is(notNullValue())); - assertThat( - logsInfo.getMessages().stream() - .map(LogEntriesEntity.Message::getLevel) - .allMatch("INFO"::equals), - is(true) - ); + assertThat(logsInfo.getMessages()) + .map(LogEntriesEntity.Message::getLevel) + .containsOnly("INFO"); } - @Test - public void getLogEntriesStart() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogEntriesStart(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 8)); final LogEntriesEntity logs = arangoDB.getLogEntries(null); final Long firstId = logs.getMessages().get(0).getId(); final LogEntriesEntity logsStart = arangoDB.getLogEntries(new LogOptions().start(firstId + 1)); - assertThat(logsStart, is(notNullValue())); - assertThat( - logsStart.getMessages().stream() - .map(LogEntriesEntity.Message::getId) - .filter(firstId::equals) - .count(), - is(0L)); + assertThat(logsStart.getMessages()) + .map(LogEntriesEntity.Message::getId) + .doesNotContain(firstId); } - @Test - public void getLogEntriesSize() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogEntriesSize(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 8)); final LogEntriesEntity logs = arangoDB.getLogEntries(null); int count = logs.getMessages().size(); - assertThat(count, greaterThan(0)); + assertThat(count).isPositive(); final LogEntriesEntity logsSize = arangoDB.getLogEntries(new LogOptions().size(count - 1)); - assertThat(logsSize, is(notNullValue())); - assertThat(logsSize.getMessages().size(), is(count - 1)); + assertThat(logsSize.getMessages()).hasSize(count - 1); } - @Test - public void getLogEntriesOffset() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogEntriesOffset(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 8)); final LogEntriesEntity logs = arangoDB.getLogEntries(null); - assertThat(logs.getTotal(), greaterThan(0L)); + assertThat(logs.getTotal()).isPositive(); Long firstId = logs.getMessages().get(0).getId(); final LogEntriesEntity logsOffset = arangoDB.getLogEntries(new LogOptions().offset(1)); - assertThat(logsOffset, is(notNullValue())); - assertThat(logsOffset.getMessages().stream() - .map(LogEntriesEntity.Message::getId) - .filter(firstId::equals) - .count() - , is(0L)); + assertThat(logsOffset.getMessages()) + .map(LogEntriesEntity.Message::getId) + .doesNotContain(firstId); } - @Test - public void getLogEntriesSearch() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogEntriesSearch(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 8)); final LogEntriesEntity logs = arangoDB.getLogEntries(null); - final LogEntriesEntity logsSearch = arangoDB.getLogEntries(new LogOptions().search(BaseTest.TEST_DB.get())); - assertThat(logsSearch, is(notNullValue())); - assertThat(logs.getTotal(), greaterThan(logsSearch.getTotal())); + final LogEntriesEntity logsSearch = arangoDB.getLogEntries(new LogOptions().search(TEST_DB.get())); + assertThat(logs.getTotal()).isGreaterThan(logsSearch.getTotal()); } - @Test - public void getLogEntriesSortAsc() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogEntriesSortAsc(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 8)); final LogEntriesEntity logs = arangoDB.getLogEntries(new LogOptions().sort(SortOrder.asc)); - assertThat(logs, is(notNullValue())); long lastId = -1; List ids = logs.getMessages().stream() .map(LogEntriesEntity.Message::getId) .collect(Collectors.toList()); for (final Long id : ids) { - assertThat(id, greaterThan(lastId)); + assertThat(id).isGreaterThan(lastId); lastId = id; } } - @Test - public void getLogEntriesSortDesc() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogEntriesSortDesc(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 8)); final LogEntriesEntity logs = arangoDB.getLogEntries(new LogOptions().sort(SortOrder.desc)); - assertThat(logs, is(notNullValue())); long lastId = Long.MAX_VALUE; List ids = logs.getMessages().stream() .map(LogEntriesEntity.Message::getId) .collect(Collectors.toList()); for (final Long id : ids) { - assertThat(lastId, greaterThan(id)); + assertThat(lastId).isGreaterThan(id); lastId = id; } } - @Test - public void getLogLevel() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void getLogLevel(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogLevelEntity logLevel = arangoDB.getLogLevel(); - assertThat(logLevel, is(notNullValue())); - assertThat(logLevel.getAgency(), is(LogLevelEntity.LogLevel.INFO)); + assertThat(logLevel.getAgency()).isEqualTo(LogLevelEntity.LogLevel.INFO); } - @Test - public void setLogLevel() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void setLogLevel(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogLevelEntity entity = new LogLevelEntity(); try { entity.setAgency(LogLevelEntity.LogLevel.ERROR); final LogLevelEntity logLevel = arangoDB.setLogLevel(entity); - assertThat(logLevel, is(notNullValue())); - assertThat(logLevel.getAgency(), is(LogLevelEntity.LogLevel.ERROR)); + assertThat(logLevel.getAgency()).isEqualTo(LogLevelEntity.LogLevel.ERROR); } finally { entity.setAgency(LogLevelEntity.LogLevel.INFO); arangoDB.setLogLevel(entity); } } - @Test - public void setAllLogLevel() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void setAllLogLevel(ArangoDB arangoDB) { assumeTrue(isAtLeastVersion(3, 9)); final LogLevelEntity entity = new LogLevelEntity(); try { entity.setAll(LogLevelEntity.LogLevel.ERROR); final LogLevelEntity logLevel = arangoDB.setLogLevel(entity); - assertThat(logLevel, is(notNullValue())); - assertThat(logLevel.getAgency(), is(LogLevelEntity.LogLevel.ERROR)); - assertThat(logLevel.getAgency(), is(LogLevelEntity.LogLevel.ERROR)); - + assertThat(logLevel.getAgency()).isEqualTo(LogLevelEntity.LogLevel.ERROR); + assertThat(logLevel.getQueries()).isEqualTo(LogLevelEntity.LogLevel.ERROR); LogLevelEntity retrievedLevels = arangoDB.getLogLevel(); - assertThat(retrievedLevels.getAgency(), is(LogLevelEntity.LogLevel.ERROR)); - assertThat(retrievedLevels.getAgency(), is(LogLevelEntity.LogLevel.ERROR)); - - assertThat(logLevel.getAgency(), is(LogLevelEntity.LogLevel.ERROR)); - assertThat(logLevel.getQueries(), is(LogLevelEntity.LogLevel.ERROR)); + assertThat(retrievedLevels.getAgency()).isEqualTo(LogLevelEntity.LogLevel.ERROR); } finally { entity.setAll(LogLevelEntity.LogLevel.INFO); arangoDB.setLogLevel(entity); } } - @Test - public void arangoDBException() { - try { - arangoDB.db(DbName.of("no")).getInfo(); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(404)); - assertThat(e.getErrorNum(), is(1228)); - } + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void arangoDBException(ArangoDB arangoDB) { + Throwable thrown = catchThrowable(() -> arangoDB.db(DbName.of("no")).getInfo()); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(404); + assertThat(e.getErrorNum()).isEqualTo(1228); } - @Test - public void fallbackHost() { - final ArangoDB arangoDB = new ArangoDB.Builder().host("not-accessible", 8529).host("127.0.0.1", 8529).build(); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void fallbackHost() { + final ArangoDB arangoDB = new ArangoDB.Builder().host("not-accessible", 8529).host("127.0.0.1", 8529).serializer(new ArangoJack()).build(); final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); + assertThat(version).isNotNull(); } - @Test(expected = ArangoDBException.class) - public void loadproperties() { - new ArangoDB.Builder().loadProperties(ArangoDBTest.class.getResourceAsStream("/arangodb-bad.properties")); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void loadproperties() { + Throwable thrown = catchThrowable(() -> + new ArangoDB.Builder().loadProperties(ArangoDBTest.class.getResourceAsStream("/arangodb-bad.properties")) + ); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test(expected = ArangoDBException.class) - public void loadproperties2() { - new ArangoDB.Builder().loadProperties(ArangoDBTest.class.getResourceAsStream("/arangodb-bad2.properties")); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void loadproperties2() { + Throwable thrown = catchThrowable(() -> + new ArangoDB.Builder().loadProperties(ArangoDBTest.class.getResourceAsStream("/arangodb-bad2.properties")) + ); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void accessMultipleDatabases() { - final ArangoDBVersion version1 = db1.getVersion(); - assertThat(version1, is(notNullValue())); - final ArangoDBVersion version2 = db2.getVersion(); - assertThat(version2, is(notNullValue())); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void accessMultipleDatabases(ArangoDB arangoDB) { + final ArangoDBVersion version1 = arangoDB.db(DB1).getVersion(); + assertThat(version1).isNotNull(); + final ArangoDBVersion version2 = arangoDB.db(DB2).getVersion(); + assertThat(version2).isNotNull(); } - @Test - public void queueTime() throws InterruptedException, ExecutionException { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void queueTime(ArangoDB arangoDB) throws InterruptedException, ExecutionException { List> futures = IntStream.range(0, 80) .mapToObj(i -> CompletableFuture.runAsync( () -> arangoDB.db().query("RETURN SLEEP(1)", Void.class), @@ -743,12 +705,11 @@ public void queueTime() throws InterruptedException, ExecutionException { double avg = qt.getAvg(); QueueTimeSample[] values = qt.getValues(); if (isAtLeastVersion(3, 9)) { - assertThat(values.length, is(20)); + assertThat(values).hasSize(20); for (int i = 0; i < values.length; i++) { - assertThat(values[i], is(notNullValue())); - assertThat(values[i].value, is(greaterThanOrEqualTo(0.0))); + assertThat(values[i].value).isNotNegative(); if (i > 0) { - assertThat(values[i].timestamp, greaterThanOrEqualTo(values[i - 1].timestamp)); + assertThat(values[i].timestamp).isGreaterThanOrEqualTo(values[i - 1].timestamp); } } @@ -759,10 +720,10 @@ public void queueTime() throws InterruptedException, ExecutionException { System.err.println(v.value); } } - assertThat(avg, is(greaterThan(0.0))); + assertThat(avg).isPositive(); } else { - assertThat(avg, is(0.0)); - assertThat(values, is(emptyArray())); + assertThat(avg).isEqualTo(0.0); + assertThat(values).isEmpty(); } } diff --git a/src/test/java/com/arangodb/ArangoDatabaseTest.java b/src/test/java/com/arangodb/ArangoDatabaseTest.java index b1e74ac0d..915cd7a36 100644 --- a/src/test/java/com/arangodb/ArangoDatabaseTest.java +++ b/src/test/java/com/arangodb/ArangoDatabaseTest.java @@ -31,10 +31,9 @@ import com.arangodb.velocypack.VPackSlice; import com.arangodb.velocypack.ValueType; import com.arangodb.velocypack.exception.VPackException; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; import java.util.*; @@ -44,108 +43,103 @@ import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + /** * @author Mark Vollmary * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class ArangoDatabaseTest extends BaseTest { +class ArangoDatabaseTest extends BaseJunit5 { private static final String CNAME1 = "ArangoDatabaseTest_collection_1"; private static final String CNAME2 = "ArangoDatabaseTest_collection_2"; private static final String ENAMES = "ArangoDatabaseTest_edge_collection"; - private final ArangoCollection collection1; - private final ArangoCollection edges; - - @BeforeClass - public static void init() { - BaseTest.initDB(); - BaseTest.initCollections(CNAME1, CNAME2); - BaseTest.initEdgeCollections(ENAMES); - } - - public ArangoDatabaseTest(final ArangoDB arangoDB) { - super(arangoDB); - collection1 = db.collection(CNAME1); - edges = db.collection(ENAMES); + @BeforeAll + static void init() { + BaseJunit5.initDB(); + BaseJunit5.initCollections(CNAME1, CNAME2); + BaseJunit5.initEdgeCollections(ENAMES); } - @Test - public void getVersion() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getVersion(ArangoDatabase db) { final ArangoDBVersion version = db.getVersion(); - assertThat(version, is(notNullValue())); - assertThat(version.getServer(), is(notNullValue())); - assertThat(version.getVersion(), is(notNullValue())); + assertThat(version).isNotNull(); + assertThat(version.getServer()).isNotNull(); + assertThat(version.getVersion()).isNotNull(); } - @Test - public void getEngine() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getEngine(ArangoDatabase db) { final ArangoDBEngine engine = db.getEngine(); - assertThat(engine, is(notNullValue())); - assertThat(engine.getName(), is(notNullValue())); + assertThat(engine).isNotNull(); + assertThat(engine.getName()).isNotNull(); } - @Test - public void exists() { - assertThat(db.exists(), is(true)); - assertThat(arangoDB.db("no").exists(), is(false)); + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void exists(ArangoDB arangoDB) { + assertThat(arangoDB.db(TEST_DB).exists()).isTrue(); + assertThat(arangoDB.db(DbName.of("no")).exists()).isFalse(); } - @Test - public void getAccessibleDatabases() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getAccessibleDatabases(ArangoDatabase db) { final Collection dbs = db.getAccessibleDatabases(); - assertThat(dbs, is(notNullValue())); - assertThat(dbs.size(), greaterThan(0)); - assertThat(dbs, hasItem("_system")); + assertThat(dbs).contains("_system"); } - @Test - public void createCollection() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollection(ArangoDatabase db) { String name = "collection-" + rnd(); final CollectionEntity result = db.createCollection(name, null); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); } - @Test - public void createCollectionWithReplicationFactor() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithReplicationFactor(ArangoDatabase db) { assumeTrue(isCluster()); String name = "collection-" + rnd(); final CollectionEntity result = db .createCollection(name, new CollectionCreateOptions().replicationFactor(2)); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); CollectionPropertiesEntity props = db.collection(name).getProperties(); - assertThat(props.getReplicationFactor(), is(2)); - assertThat(props.getSatellite(), is(nullValue())); + assertThat(props.getReplicationFactor()).isEqualTo(2); + assertThat(props.getSatellite()).isNull(); } - @Test - public void createCollectionWithMinReplicationFactor() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithMinReplicationFactor(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isCluster()); String name = "collection-" + rnd(); final CollectionEntity result = db.createCollection(name, new CollectionCreateOptions().replicationFactor(2).minReplicationFactor(2)); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); CollectionPropertiesEntity props = db.collection(name).getProperties(); - assertThat(props.getReplicationFactor(), is(2)); - assertThat(props.getMinReplicationFactor(), is(2)); - assertThat(props.getSatellite(), is(nullValue())); + assertThat(props.getReplicationFactor()).isEqualTo(2); + assertThat(props.getMinReplicationFactor()).isEqualTo(2); + assertThat(props.getSatellite()).isNull(); } - @Test - public void createSatelliteCollection() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createSatelliteCollection(ArangoDatabase db) { assumeTrue(isEnterprise()); assumeTrue(isCluster()); @@ -153,28 +147,30 @@ public void createSatelliteCollection() { final CollectionEntity result = db .createCollection(name, new CollectionCreateOptions().satellite(true)); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); CollectionPropertiesEntity props = db.collection(name).getProperties(); - assertThat(props.getReplicationFactor(), is(nullValue())); - assertThat(props.getSatellite(), is(true)); + assertThat(props.getReplicationFactor()).isNull(); + assertThat(props.getSatellite()).isTrue(); } - @Test - public void createCollectionWithNumberOfShards() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithNumberOfShards(ArangoDatabase db) { assumeTrue(isCluster()); String name = "collection-" + rnd(); final CollectionEntity result = db .createCollection(name, new CollectionCreateOptions().numberOfShards(2)); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); CollectionPropertiesEntity props = db.collection(name).getProperties(); - assertThat(props.getNumberOfShards(), is(2)); + assertThat(props.getNumberOfShards()).isEqualTo(2); } - @Test - public void createCollectionWithShardingStrategys() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithShardingStrategys(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); assumeTrue(isCluster()); @@ -182,14 +178,15 @@ public void createCollectionWithShardingStrategys() { final CollectionEntity result = db.createCollection(name, new CollectionCreateOptions() .shardingStrategy(ShardingStrategy.COMMUNITY_COMPAT.getInternalName())); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); CollectionPropertiesEntity props = db.collection(name).getProperties(); - assertThat(props.getShardingStrategy(), is(ShardingStrategy.COMMUNITY_COMPAT.getInternalName())); + assertThat(props.getShardingStrategy()).isEqualTo(ShardingStrategy.COMMUNITY_COMPAT.getInternalName()); } - @Test - public void createCollectionWithSmartJoinAttribute() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithSmartJoinAttribute(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isEnterprise()); assumeTrue(isCluster()); @@ -197,13 +194,14 @@ public void createCollectionWithSmartJoinAttribute() { String name = "collection-" + rnd(); final CollectionEntity result = db.createCollection(name, new CollectionCreateOptions().smartJoinAttribute("test123").shardKeys("_key:")); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - assertThat(db.collection(name).getProperties().getSmartJoinAttribute(), is("test123")); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); + assertThat(db.collection(name).getProperties().getSmartJoinAttribute()).isEqualTo("test123"); } - @Test - public void createCollectionWithSmartJoinAttributeWrong() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithSmartJoinAttributeWrong(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isEnterprise()); assumeTrue(isCluster()); @@ -213,43 +211,46 @@ public void createCollectionWithSmartJoinAttributeWrong() { try { db.createCollection(name, new CollectionCreateOptions().smartJoinAttribute("test123")); } catch (ArangoDBException e) { - assertThat(e.getErrorNum(), is(4006)); + assertThat(e.getErrorNum()).isEqualTo(4006); // TODO: // at the moment older server versions reply with response code 500, which is a misbehavior // when the fix has been backported to all the supported db versions uncomment the following: - // assertThat(e.getResponseCode(), is(400)); + // assertThat(e.getResponseCode()).isEqualTo(400)); } } - @Test - public void createCollectionWithNumberOfShardsAndShardKey() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithNumberOfShardsAndShardKey(ArangoDatabase db) { assumeTrue(isCluster()); String name = "collection-" + rnd(); final CollectionEntity result = db .createCollection(name, new CollectionCreateOptions().numberOfShards(2).shardKeys("a")); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); final CollectionPropertiesEntity properties = db.collection(name).getProperties(); - assertThat(properties.getNumberOfShards(), is(2)); - assertThat(properties.getShardKeys().size(), is(1)); + assertThat(properties.getNumberOfShards()).isEqualTo(2); + assertThat(properties.getShardKeys()).hasSize(1); } - @Test - public void createCollectionWithNumberOfShardsAndShardKeys() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithNumberOfShardsAndShardKeys(ArangoDatabase db) { assumeTrue(isCluster()); String name = "collection-" + rnd(); final CollectionEntity result = db.createCollection(name, new CollectionCreateOptions().numberOfShards(2).shardKeys("a", "b")); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); final CollectionPropertiesEntity properties = db.collection(name).getProperties(); - assertThat(properties.getNumberOfShards(), is(2)); - assertThat(properties.getShardKeys().size(), is(2)); + assertThat(properties.getNumberOfShards()).isEqualTo(2); + assertThat(properties.getShardKeys()).hasSize(2); } - @Test - public void createCollectionWithDistributeShardsLike() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithDistributeShardsLike(ArangoDatabase db) { assumeTrue(isEnterprise()); assumeTrue(isCluster()); @@ -260,11 +261,11 @@ public void createCollectionWithDistributeShardsLike() { db.createCollection(name1, new CollectionCreateOptions().numberOfShards(numberOfShards)); db.createCollection(name2, new CollectionCreateOptions().distributeShardsLike(name1)); - assertThat(db.collection(name1).getProperties().getNumberOfShards(), is(numberOfShards)); - assertThat(db.collection(name2).getProperties().getNumberOfShards(), is(numberOfShards)); + assertThat(db.collection(name1).getProperties().getNumberOfShards()).isEqualTo(numberOfShards); + assertThat(db.collection(name2).getProperties().getNumberOfShards()).isEqualTo(numberOfShards); } - private void createCollectionWithKeyType(KeyType keyType) { + private void createCollectionWithKeyType(ArangoDatabase db, KeyType keyType) { String name = "collection-" + rnd(); db.createCollection(name, new CollectionCreateOptions().keyOptions( false, @@ -272,34 +273,39 @@ private void createCollectionWithKeyType(KeyType keyType) { null, null )); - assertThat(db.collection(name).getProperties().getKeyOptions().getType(), is(keyType)); + assertThat(db.collection(name).getProperties().getKeyOptions().getType()).isEqualTo(keyType); } - @Test - public void createCollectionWithKeyTypeAutoincrement() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithKeyTypeAutoincrement(ArangoDatabase db) { assumeTrue(isSingleServer()); - createCollectionWithKeyType(KeyType.autoincrement); + createCollectionWithKeyType(db, KeyType.autoincrement); } - @Test - public void createCollectionWithKeyTypePadded() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithKeyTypePadded(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); - createCollectionWithKeyType(KeyType.padded); + createCollectionWithKeyType(db, KeyType.padded); } - @Test - public void createCollectionWithKeyTypeTraditional() { - createCollectionWithKeyType(KeyType.traditional); + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithKeyTypeTraditional(ArangoDatabase db) { + createCollectionWithKeyType(db, KeyType.traditional); } - @Test - public void createCollectionWithKeyTypeUuid() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithKeyTypeUuid(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); - createCollectionWithKeyType(KeyType.uuid); + createCollectionWithKeyType(db, KeyType.uuid); } - @Test - public void createCollectionWithJsonSchema() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCollectionWithJsonSchema(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 7)); String name = "collection-" + rnd(); String rule = ("{ " + @@ -321,54 +327,56 @@ public void createCollectionWithJsonSchema() { .setRule(rule) ) ); - assertThat(result.getSchema().getLevel(), is(CollectionSchema.Level.NEW)); - assertThat(result.getSchema().getRule(), is(rule)); - assertThat(result.getSchema().getMessage(), is(message)); + assertThat(result.getSchema().getLevel()).isEqualTo(CollectionSchema.Level.NEW); + assertThat(result.getSchema().getRule()).isEqualTo(rule); + assertThat(result.getSchema().getMessage()).isEqualTo(message); CollectionPropertiesEntity props = db.collection(name).getProperties(); - assertThat(props.getSchema().getLevel(), is(CollectionSchema.Level.NEW)); - assertThat(props.getSchema().getRule(), is(rule)); - assertThat(props.getSchema().getMessage(), is(message)); + assertThat(props.getSchema().getLevel()).isEqualTo(CollectionSchema.Level.NEW); + assertThat(props.getSchema().getRule()).isEqualTo(rule); + assertThat(props.getSchema().getMessage()).isEqualTo(message); BaseDocument doc = new BaseDocument(); doc.addAttribute("number", 33); db.collection(name).insertDocument(doc); - try { - BaseDocument wrongDoc = new BaseDocument(); - doc.addAttribute("number", "notANumber"); - db.collection(name).insertDocument(doc); - fail(); - } catch (ArangoDBException e) { - assertThat(e.getMessage(), containsString(message)); - assertThat(e.getResponseCode(), is(400)); - assertThat(e.getErrorNum(), is(1620)); - } + BaseDocument wrongDoc = new BaseDocument(); + wrongDoc.addAttribute("number", "notANumber"); + Throwable thrown = catchThrowable(() -> db.collection(name).insertDocument(wrongDoc)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + + assertThat(e).hasMessageContaining(message); + assertThat(e.getResponseCode()).isEqualTo(400); + assertThat(e.getErrorNum()).isEqualTo(1620); } - @Test(expected = ArangoDBException.class) - public void deleteCollection() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void deleteCollection(ArangoDatabase db) { String name = "collection-" + rnd(); db.createCollection(name, null); db.collection(name).drop(); - db.collection(name).getInfo(); + Throwable thrown = catchThrowable(() -> db.collection(name).getInfo()); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void deleteSystemCollection() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void deleteSystemCollection(ArangoDatabase db) { final String name = "_system_test"; db.createCollection(name, new CollectionCreateOptions().isSystem(true)); db.collection(name).drop(true); - try { - db.collection(name).getInfo(); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(404)); - } + Throwable thrown = catchThrowable(() -> db.collection(name).getInfo()); + assertThat(thrown) + .isInstanceOf(ArangoDBException.class) + .extracting(it -> ((ArangoDBException) it).getResponseCode()) + .isEqualTo(404); } - @Test - public void deleteSystemCollectionFail() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void deleteSystemCollectionFail(ArangoDatabase db) { final String name = "_system_test"; ArangoCollection collection = db.collection(name); if (collection.exists()) @@ -379,229 +387,253 @@ public void deleteSystemCollectionFail() { collection.drop(); fail(); } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(403)); + assertThat(e.getResponseCode()).isEqualTo(403); } collection.drop(true); try { collection.getInfo(); fail(); } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(404)); + assertThat(e.getResponseCode()).isEqualTo(404); } } - @Test - public void getIndex() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getIndex(ArangoDatabase db) { final Collection fields = Collections.singletonList("field-" + rnd()); - final IndexEntity createResult = collection1.ensureHashIndex(fields, null); + final IndexEntity createResult = db.collection(CNAME1).ensureHashIndex(fields, null); final IndexEntity readResult = db.getIndex(createResult.getId()); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getType(), is(createResult.getType())); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getType()).isEqualTo(createResult.getType()); } - @Test - public void deleteIndex() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void deleteIndex(ArangoDatabase db) { final Collection fields = Collections.singletonList("field-" + rnd()); - final IndexEntity createResult = collection1.ensureHashIndex(fields, null); + final IndexEntity createResult = db.collection(CNAME1).ensureHashIndex(fields, null); final String id = db.deleteIndex(createResult.getId()); - assertThat(id, is(createResult.getId())); + assertThat(id).isEqualTo(createResult.getId()); try { db.getIndex(id); fail(); } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(404)); + assertThat(e.getResponseCode()).isEqualTo(404); } } - @Test - public void getCollections() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getCollections(ArangoDatabase db) { final Collection collections = db.getCollections(null); long count = collections.stream().map(CollectionEntity::getName).filter(it -> it.equals(CNAME1)).count(); - assertThat(count, is(1L)); + assertThat(count).isEqualTo(1L); } - @Test - public void getCollectionsExcludeSystem() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getCollectionsExcludeSystem(ArangoDatabase db) { final CollectionsReadOptions options = new CollectionsReadOptions().excludeSystem(true); final Collection nonSystemCollections = db.getCollections(options); final Collection allCollections = db.getCollections(null); - assertThat(allCollections.size(), is(greaterThan(nonSystemCollections.size()))); + assertThat(allCollections).hasSizeGreaterThan(nonSystemCollections.size()); } - @Test - public void grantAccess() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void grantAccess(ArangoDB arangoDB) { String user = "user-" + rnd(); arangoDB.createUser(user, "1234", null); - db.grantAccess(user); + arangoDB.db(TEST_DB).grantAccess(user); } - @Test - public void grantAccessRW() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void grantAccessRW(ArangoDB arangoDB) { String user = "user-" + rnd(); arangoDB.createUser(user, "1234", null); - db.grantAccess(user, Permissions.RW); + arangoDB.db(TEST_DB).grantAccess(user, Permissions.RW); } - @Test - public void grantAccessRO() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void grantAccessRO(ArangoDB arangoDB) { String user = "user-" + rnd(); arangoDB.createUser(user, "1234", null); - db.grantAccess(user, Permissions.RO); + arangoDB.db(TEST_DB).grantAccess(user, Permissions.RO); } - @Test - public void grantAccessNONE() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void grantAccessNONE(ArangoDB arangoDB) { String user = "user-" + rnd(); arangoDB.createUser(user, "1234", null); - db.grantAccess(user, Permissions.NONE); + arangoDB.db(TEST_DB).grantAccess(user, Permissions.NONE); } - @Test(expected = ArangoDBException.class) - public void grantAccessUserNotFound() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void grantAccessUserNotFound(ArangoDatabase db) { String user = "user-" + rnd(); - db.grantAccess(user, Permissions.RW); + Throwable thrown = catchThrowable(() -> db.grantAccess(user, Permissions.RW)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void revokeAccess() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void revokeAccess(ArangoDB arangoDB) { String user = "user-" + rnd(); arangoDB.createUser(user, "1234", null); - db.revokeAccess(user); + arangoDB.db(TEST_DB).revokeAccess(user); } - @Test(expected = ArangoDBException.class) - public void revokeAccessUserNotFound() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void revokeAccessUserNotFound(ArangoDatabase db) { String user = "user-" + rnd(); - db.revokeAccess(user); + Throwable thrown = catchThrowable(() -> db.revokeAccess(user)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void resetAccess() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void resetAccess(ArangoDB arangoDB) { String user = "user-" + rnd(); arangoDB.createUser(user, "1234", null); - db.resetAccess(user); + arangoDB.db(TEST_DB).resetAccess(user); } - @Test(expected = ArangoDBException.class) - public void resetAccessUserNotFound() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void resetAccessUserNotFound(ArangoDatabase db) { String user = "user-" + rnd(); - db.resetAccess(user); + Throwable thrown = catchThrowable(() -> db.resetAccess(user)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void grantDefaultCollectionAccess() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void grantDefaultCollectionAccess(ArangoDB arangoDB) { String user = "user-" + rnd(); arangoDB.createUser(user, "1234"); - db.grantDefaultCollectionAccess(user, Permissions.RW); + arangoDB.db(TEST_DB).grantDefaultCollectionAccess(user, Permissions.RW); } - @Test - public void getPermissions() { - assertThat(Permissions.RW, is(db.getPermissions("root"))); + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getPermissions(ArangoDatabase db) { + assertThat(db.getPermissions("root")).isEqualTo(Permissions.RW); } - @Test - public void query() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void query(ArangoDatabase db) { for (int i = 0; i < 10; i++) { - collection1.insertDocument(new BaseDocument(), null); + db.collection(CNAME1).insertDocument(new BaseDocument(), null); } final ArangoCursor cursor = db.query("for i in " + CNAME1 + " return i._id", null, null, String.class); - assertThat(cursor, is(notNullValue())); + assertThat((Object) cursor).isNotNull(); for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat((Iterator) cursor).hasNext(); } } - @Test - public void queryForEach() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryForEach(ArangoDatabase db) { for (int i = 0; i < 10; i++) { - collection1.insertDocument(new BaseDocument(), null); + db.collection(CNAME1).insertDocument(new BaseDocument(), null); } final ArangoCursor cursor = db.query("for i in " + CNAME1 + " return i._id", null, null, String.class); - assertThat(cursor, is(notNullValue())); + assertThat((Object) cursor).isNotNull(); int i = 0; while (cursor.hasNext()) { cursor.next(); i++; } - assertThat(i, is(greaterThanOrEqualTo(10))); + assertThat(i).isGreaterThanOrEqualTo(10); } - @Test - public void queryWithCount() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryWithCount(ArangoDatabase db) { for (int i = 0; i < 10; i++) { - collection1.insertDocument(new BaseDocument(), null); + db.collection(CNAME1).insertDocument(new BaseDocument(), null); } final ArangoCursor cursor = db .query("for i in " + CNAME1 + " Limit 6 return i._id", null, new AqlQueryOptions().count(true), String.class); - assertThat(cursor, is(notNullValue())); + assertThat((Object) cursor).isNotNull(); for (int i = 1; i <= 6; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat(cursor.hasNext()).isTrue(); } - assertThat(cursor.getCount(), is(6)); + assertThat(cursor.getCount()).isEqualTo(6); } - @Test - public void queryWithLimitAndFullCount() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryWithLimitAndFullCount(ArangoDatabase db) { for (int i = 0; i < 10; i++) { - collection1.insertDocument(new BaseDocument(), null); + db.collection(CNAME1).insertDocument(new BaseDocument(), null); } final ArangoCursor cursor = db .query("for i in " + CNAME1 + " Limit 5 return i._id", null, new AqlQueryOptions().fullCount(true), String.class); - assertThat(cursor, is(notNullValue())); + assertThat((Object) cursor).isNotNull(); for (int i = 0; i < 5; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat((Iterator) cursor).hasNext(); } - assertThat(cursor.getStats(), is(notNullValue())); - assertThat(cursor.getStats().getFullCount(), is(greaterThanOrEqualTo(10L))); + assertThat(cursor.getStats()).isNotNull(); + assertThat(cursor.getStats().getFullCount()).isGreaterThanOrEqualTo(10L); } - @Test - public void queryWithBatchSize() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryWithBatchSize(ArangoDatabase db) { for (int i = 0; i < 10; i++) { - collection1.insertDocument(new BaseDocument(), null); + db.collection(CNAME1).insertDocument(new BaseDocument(), null); } final ArangoCursor cursor = db .query("for i in " + CNAME1 + " return i._id", null, new AqlQueryOptions().batchSize(5).count(true), String.class); - assertThat(cursor, is(notNullValue())); + assertThat((Object) cursor).isNotNull(); for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat((Iterator) cursor).hasNext(); } } - @Test - public void queryIterateWithBatchSize() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryIterateWithBatchSize(ArangoDatabase db) { for (int i = 0; i < 10; i++) { - collection1.insertDocument(new BaseDocument(), null); + db.collection(CNAME1).insertDocument(new BaseDocument(), null); } final ArangoCursor cursor = db .query("for i in " + CNAME1 + " return i._id", null, new AqlQueryOptions().batchSize(5).count(true), String.class); - assertThat(cursor, is(notNullValue())); + assertThat((Object) cursor).isNotNull(); final AtomicInteger i = new AtomicInteger(0); for (; cursor.hasNext(); cursor.next()) { i.incrementAndGet(); } - assertThat(i.get(), is(greaterThanOrEqualTo(10))); + assertThat(i.get()).isGreaterThanOrEqualTo(10); } -// FIXME + // FIXME // /** // * ignored. takes to long // */ // @Test // @Ignore -// public void queryWithTTL() throws InterruptedException { +// void queryWithTTL() throws InterruptedException { // // set TTL to 1 seconds and get the second batch after 2 seconds! // final int ttl = 1; // final int wait = 2; @@ -615,47 +647,49 @@ public void queryIterateWithBatchSize() { // .query("for i in db_test return i._id", null, new AqlQueryOptions().batchSize(5).ttl(ttl), // String.class); // -// assertThat(cursor, is(notNullValue())); +// assertThat(cursor).isNotNull(); // // for (int i = 0; i < 10; i++, cursor.next()) { -// assertThat(cursor.hasNext(), is(true)); +// assertThat(cursor.hasNext()).isEqualTo(true)); // if (i == 1) { // Thread.sleep(wait * 1000); // } // } // fail("this should fail"); // } catch (final ArangoDBException ex) { -// assertThat(ex.getMessage(), is("Response: 404, Error: 1600 - cursor not found")); +// assertThat(ex.getMessage()).isEqualTo("Response: 404, Error: 1600 - cursor not found")); // } finally { // db.collection(COLLECTION_NAME).drop(); // } // } - @Test - public void changeQueryCache() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void changeQueryCache(ArangoDatabase db) { QueryCachePropertiesEntity properties = db.getQueryCacheProperties(); - assertThat(properties, is(notNullValue())); - assertThat(properties.getMode(), is(CacheMode.off)); - assertThat(properties.getMaxResults(), greaterThan(0L)); + assertThat(properties).isNotNull(); + assertThat(properties.getMode()).isEqualTo(CacheMode.off); + assertThat(properties.getMaxResults()).isPositive(); properties.setMode(CacheMode.on); properties = db.setQueryCacheProperties(properties); - assertThat(properties, is(notNullValue())); - assertThat(properties.getMode(), is(CacheMode.on)); + assertThat(properties).isNotNull(); + assertThat(properties.getMode()).isEqualTo(CacheMode.on); properties = db.getQueryCacheProperties(); - assertThat(properties.getMode(), is(CacheMode.on)); + assertThat(properties.getMode()).isEqualTo(CacheMode.on); final QueryCachePropertiesEntity properties2 = new QueryCachePropertiesEntity(); properties2.setMode(CacheMode.off); db.setQueryCacheProperties(properties2); } - @Test - public void queryWithCache() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryWithCache(ArangoDatabase db) { assumeTrue(isSingleServer()); for (int i = 0; i < 10; i++) { - collection1.insertDocument(new BaseDocument(), null); + db.collection(CNAME1).insertDocument(new BaseDocument(), null); } final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); @@ -666,106 +700,106 @@ public void queryWithCache() { .query("FOR t IN " + CNAME1 + " FILTER t.age >= 10 SORT t.age RETURN t._id", null, new AqlQueryOptions().cache(true), String.class); - assertThat(cursor, is(notNullValue())); - assertThat(cursor.isCached(), is(false)); + assertThat((Object) cursor).isNotNull(); + assertThat(cursor.isCached()).isFalse(); final ArangoCursor cachedCursor = db .query("FOR t IN " + CNAME1 + " FILTER t.age >= 10 SORT t.age RETURN t._id", null, new AqlQueryOptions().cache(true), String.class); - assertThat(cachedCursor, is(notNullValue())); - assertThat(cachedCursor.isCached(), is(true)); + assertThat((Object) cachedCursor).isNotNull(); + assertThat(cachedCursor.isCached()).isTrue(); final QueryCachePropertiesEntity properties2 = new QueryCachePropertiesEntity(); properties2.setMode(CacheMode.off); db.setQueryCacheProperties(properties2); } - @Test - public void queryWithMemoryLimit() { - try { - db.query("RETURN 1..100000", null, new AqlQueryOptions().memoryLimit(32 * 1024L), String.class); - fail("Memory limit not honored."); - } catch (final ArangoDBException e) { - assertThat(e.getErrorNum(), is(32)); - } + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryWithMemoryLimit(ArangoDatabase db) { + Throwable thrown = catchThrowable(() -> db.query("RETURN 1..100000", null, new AqlQueryOptions().memoryLimit(32 * 1024L), String.class)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + assertThat(((ArangoDBException) thrown).getErrorNum()).isEqualTo(32); } - @Test(expected = ArangoDBException.class) - public void queryWithFailOnWarningTrue() { - db.query("RETURN 1 / 0", null, new AqlQueryOptions().failOnWarning(true), String.class); + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryWithFailOnWarningTrue(ArangoDatabase db) { + Throwable thrown = catchThrowable(() -> db.query("RETURN 1 / 0", null, new AqlQueryOptions().failOnWarning(true), String.class)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void queryWithFailOnWarningFalse() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryWithFailOnWarningFalse(ArangoDatabase db) { final ArangoCursor cursor = db .query("RETURN 1 / 0", null, new AqlQueryOptions().failOnWarning(false), String.class); - assertThat(cursor.next(), nullValue()); + assertThat(cursor.next()).isNull(); } - @Test - public void queryWithTimeout() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryWithTimeout(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 6)); - try { - db.query("RETURN SLEEP(1)", null, new AqlQueryOptions().maxRuntime(0.1), String.class).next(); - fail(); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(410)); - } + Throwable thrown = catchThrowable(() -> db.query("RETURN SLEEP(1)", null, new AqlQueryOptions().maxRuntime(0.1), String.class).next()); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + assertThat(((ArangoDBException) thrown).getResponseCode()).isEqualTo(410); } - @Test - public void queryWithMaxWarningCount() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryWithMaxWarningCount(ArangoDatabase db) { final ArangoCursor cursorWithWarnings = db .query("RETURN 1 / 0", null, new AqlQueryOptions(), String.class); - assertThat(cursorWithWarnings.getWarnings().size(), is(1)); + assertThat(cursorWithWarnings.getWarnings()).hasSize(1); final ArangoCursor cursorWithLimitedWarnings = db .query("RETURN 1 / 0", null, new AqlQueryOptions().maxWarningCount(0L), String.class); final Collection warnings = cursorWithLimitedWarnings.getWarnings(); - if (warnings != null) { - assertThat(warnings.size(), is(0)); - } + assertThat(warnings).isNullOrEmpty(); } - @Test - public void queryCursor() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryCursor(ArangoDatabase db) { final int numbDocs = 10; for (int i = 0; i < numbDocs; i++) { - collection1.insertDocument(new BaseDocument(), null); + db.collection(CNAME1).insertDocument(new BaseDocument(), null); } final int batchSize = 5; final ArangoCursor cursor = db.query("for i in " + CNAME1 + " return i._id", null, new AqlQueryOptions().batchSize(batchSize).count(true), String.class); - assertThat(cursor, is(notNullValue())); - assertThat(cursor.getCount(), is(greaterThanOrEqualTo(numbDocs))); + assertThat((Object) cursor).isNotNull(); + assertThat(cursor.getCount()).isGreaterThanOrEqualTo(numbDocs); final ArangoCursor cursor2 = db.cursor(cursor.getId(), String.class); - assertThat(cursor2, is(notNullValue())); - assertThat(cursor2.getCount(), is(greaterThanOrEqualTo(numbDocs))); - assertThat(cursor2.hasNext(), is(true)); + assertThat((Object) cursor2).isNotNull(); + assertThat(cursor2.getCount()).isGreaterThanOrEqualTo(numbDocs); + assertThat((Iterator) cursor2).hasNext(); for (int i = 0; i < batchSize; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat((Iterator) cursor).hasNext(); } } - @Test - public void changeQueryTrackingProperties() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void changeQueryTrackingProperties(ArangoDatabase db) { try { QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties(); - assertThat(properties, is(notNullValue())); - assertThat(properties.getEnabled(), is(true)); - assertThat(properties.getTrackSlowQueries(), is(true)); - assertThat(properties.getMaxQueryStringLength(), greaterThan(0L)); - assertThat(properties.getMaxSlowQueries(), greaterThan(0L)); - assertThat(properties.getSlowQueryThreshold(), greaterThan(0L)); + assertThat(properties).isNotNull(); + assertThat(properties.getEnabled()).isTrue(); + assertThat(properties.getTrackSlowQueries()).isTrue(); + assertThat(properties.getMaxQueryStringLength()).isPositive(); + assertThat(properties.getMaxSlowQueries()).isPositive(); + assertThat(properties.getSlowQueryThreshold()).isPositive(); properties.setEnabled(false); properties = db.setQueryTrackingProperties(properties); - assertThat(properties, is(notNullValue())); - assertThat(properties.getEnabled(), is(false)); + assertThat(properties).isNotNull(); + assertThat(properties.getEnabled()).isFalse(); properties = db.getQueryTrackingProperties(); - assertThat(properties.getEnabled(), is(false)); + assertThat(properties.getEnabled()).isFalse(); } finally { final QueryTrackingPropertiesEntity properties = new QueryTrackingPropertiesEntity(); properties.setEnabled(true); @@ -773,12 +807,13 @@ public void changeQueryTrackingProperties() { } } - @Test - public void queryWithBindVars() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryWithBindVars(ArangoDatabase db) { for (int i = 0; i < 10; i++) { final BaseDocument baseDocument = new BaseDocument(); baseDocument.addAttribute("age", 20 + i); - collection1.insertDocument(baseDocument, null); + db.collection(CNAME1).insertDocument(baseDocument, null); } final Map bindVars = new HashMap<>(); bindVars.put("@coll", CNAME1); @@ -788,89 +823,96 @@ public void queryWithBindVars() { .query("FOR t IN @@coll FILTER t.age >= @age SORT t.age RETURN t._id", bindVars, null, String.class); - assertThat(cursor, is(notNullValue())); + assertThat((Object) cursor).isNotNull(); for (int i = 0; i < 5; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat((Iterator) cursor).hasNext(); } } - @Test - public void queryWithWarning() { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void queryWithWarning(ArangoDB arangoDB) { final ArangoCursor cursor = arangoDB.db().query("return 1/0", null, null, String.class); - assertThat(cursor, is(notNullValue())); - assertThat(cursor.getWarnings(), is(notNullValue())); + assertThat((Object) cursor).isNotNull(); + assertThat(cursor.getWarnings()).isNotNull(); } - @Test - public void queryStream() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryStream(ArangoDatabase db) { if (isAtLeastVersion(3, 4)) { final ArangoCursor cursor = db .query("FOR i IN 1..2 RETURN i", null, new AqlQueryOptions().stream(true).count(true), VPackSlice.class); - assertThat(cursor, is(notNullValue())); - assertThat(cursor.getCount(), is(nullValue())); + assertThat((Object) cursor).isNotNull(); + assertThat(cursor.getCount()).isNull(); } } - @Test - public void queryClose() throws IOException { + @ParameterizedTest(name = "{index}") + @MethodSource("arangos") + void queryClose(ArangoDB arangoDB) throws IOException { final ArangoCursor cursor = arangoDB.db() .query("for i in 1..2 return i", null, new AqlQueryOptions().batchSize(1), String.class); cursor.close(); - int count = 0; - try { + AtomicInteger count = new AtomicInteger(); + Throwable thrown = catchThrowable(() -> { while (cursor.hasNext()) { cursor.next(); - count++; + count.incrementAndGet(); } - fail(); - } catch (final ArangoDBException e) { - assertThat(count, is(1)); - } + }); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + assertThat(count).hasValue(1); } - @Test - public void queryNoResults() throws IOException { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryNoResults(ArangoDatabase db) throws IOException { final ArangoCursor cursor = db .query("FOR i IN @@col RETURN i", new MapBuilder().put("@col", CNAME1).get(), null, BaseDocument.class); cursor.close(); } - @Test - public void queryWithNullBindParam() throws IOException { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryWithNullBindParam(ArangoDatabase db) throws IOException { final ArangoCursor cursor = db.query("FOR i IN @@col FILTER i.test == @test RETURN i", new MapBuilder().put("@col", CNAME1).put("test", null).get(), null, BaseDocument.class); cursor.close(); } - @Test - public void queryAllowDirtyRead() throws IOException { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void queryAllowDirtyRead(ArangoDatabase db) throws IOException { final ArangoCursor cursor = db.query("FOR i IN @@col FILTER i.test == @test RETURN i", new MapBuilder().put("@col", CNAME1).put("test", null).get(), new AqlQueryOptions().allowDirtyRead(true), BaseDocument.class); cursor.close(); } - @Test - public void explainQuery() { - final AqlExecutionExplainEntity explain = arangoDB.db().explainQuery("for i in 1..1 return i", null, null); - assertThat(explain, is(notNullValue())); - assertThat(explain.getPlan(), is(notNullValue())); - assertThat(explain.getPlans(), is(nullValue())); + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void explainQuery(ArangoDatabase db) { + final AqlExecutionExplainEntity explain = db.explainQuery("for i in 1..1 return i", null, null); + assertThat(explain).isNotNull(); + assertThat(explain.getPlan()).isNotNull(); + assertThat(explain.getPlans()).isNull(); final ExecutionPlan plan = explain.getPlan(); - assertThat(plan.getCollections().size(), is(0)); - assertThat(plan.getEstimatedCost(), greaterThan(0)); - assertThat(plan.getEstimatedNrItems(), greaterThan(0)); - assertThat(plan.getVariables().size(), is(2)); - assertThat(plan.getNodes().size(), is(greaterThan(0))); + assertThat(plan.getCollections()).isEmpty(); + assertThat(plan.getEstimatedCost()).isPositive(); + assertThat(plan.getEstimatedNrItems()).isPositive(); + assertThat(plan.getVariables()).hasSize(2); + assertThat(plan.getNodes()).isNotEmpty(); } - @Test - public void explainQueryWithIndexNode() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void explainQueryWithIndexNode(ArangoDatabase db) { ArangoCollection character = db.collection("got_characters"); ArangoCollection actor = db.collection("got_actors"); @@ -891,66 +933,69 @@ public void explainQueryWithIndexNode() { .filter(it -> "IndexNode".equals(it.getType())) .flatMap(it -> it.getIndexes().stream()) .forEach(it -> { - assertThat(it.getType(), is(IndexType.primary)); - assertThat(it.getFields(), contains("_key")); + assertThat(it.getType()).isEqualTo(IndexType.primary); + assertThat(it.getFields()).contains("_key"); }); } - @Test - public void parseQuery() { - final AqlParseEntity parse = arangoDB.db().parseQuery("for i in 1..1 return i"); - assertThat(parse, is(notNullValue())); - assertThat(parse.getBindVars(), is(empty())); - assertThat(parse.getCollections().size(), is(0)); - assertThat(parse.getAst().size(), is(1)); + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void parseQuery(ArangoDatabase db) { + final AqlParseEntity parse = db.parseQuery("for i in 1..1 return i"); + assertThat(parse).isNotNull(); + assertThat(parse.getBindVars()).isEmpty(); + assertThat(parse.getCollections()).isEmpty(); + assertThat(parse.getAst()).hasSize(1); } - @Test - public void getCurrentlyRunningQueries() throws InterruptedException { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getCurrentlyRunningQueries(ArangoDatabase db) throws InterruptedException { String query = "return sleep(1)"; Thread t = new Thread(() -> db.query(query, null, null, Void.class)); t.start(); Thread.sleep(300); final Collection currentlyRunningQueries = db.getCurrentlyRunningQueries(); - assertThat(currentlyRunningQueries, is(notNullValue())); - assertThat(currentlyRunningQueries.size(), is(1)); + assertThat(currentlyRunningQueries).hasSize(1); final QueryEntity queryEntity = currentlyRunningQueries.iterator().next(); - assertThat(queryEntity.getQuery(), is(query)); - assertThat(queryEntity.getState(), is(QueryExecutionState.EXECUTING)); + assertThat(queryEntity.getQuery()).isEqualTo(query); + assertThat(queryEntity.getState()).isEqualTo(QueryExecutionState.EXECUTING); t.join(); } - @Test - public void killQuery() throws InterruptedException, ExecutionException { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void killQuery(ArangoDatabase db) throws InterruptedException, ExecutionException { ExecutorService es = Executors.newSingleThreadExecutor(); Future future = es.submit(() -> { try { db.query("return sleep(5)", null, null, Void.class); fail(); } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(410)); - assertThat(e.getErrorNum(), is(1500)); - assertThat(e.getErrorMessage(), containsString("query killed")); + assertThat(e.getResponseCode()).isEqualTo(410); + assertThat(e.getErrorNum()).isEqualTo(1500); + assertThat(e.getErrorMessage()).contains("query killed"); } }); Thread.sleep(500); Collection currentlyRunningQueries = db.getCurrentlyRunningQueries(); - assertThat(currentlyRunningQueries.size(), is(1)); + assertThat(currentlyRunningQueries).hasSize(1); QueryEntity queryEntity = currentlyRunningQueries.iterator().next(); - assertThat(queryEntity.getState(), is(QueryExecutionState.EXECUTING)); + assertThat(queryEntity.getState()).isEqualTo(QueryExecutionState.EXECUTING); db.killQuery(queryEntity.getId()); db.getCurrentlyRunningQueries().forEach(q -> - assertThat(q.getState(), is(QueryExecutionState.KILLED)) + assertThat(q.getState()).isEqualTo(QueryExecutionState.KILLED) ); future.get(); es.shutdown(); } - @Test - public void getAndClearSlowQueries() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getAndClearSlowQueries(ArangoDatabase db) { db.clearSlowQueries(); final QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties(); @@ -960,44 +1005,45 @@ public void getAndClearSlowQueries() { db.query("return sleep(1.1)", null, null, Void.class); final Collection slowQueries = db.getSlowQueries(); - assertThat(slowQueries, is(notNullValue())); - assertThat(slowQueries.size(), is(1)); + assertThat(slowQueries).hasSize(1); final QueryEntity queryEntity = slowQueries.iterator().next(); - assertThat(queryEntity.getQuery(), is("return sleep(1.1)")); + assertThat(queryEntity.getQuery()).isEqualTo("return sleep(1.1)"); db.clearSlowQueries(); - assertThat(db.getSlowQueries().size(), is(0)); + assertThat(db.getSlowQueries()).isEmpty(); properties.setSlowQueryThreshold(slowQueryThreshold); db.setQueryTrackingProperties(properties); } - @Test - public void createGetDeleteAqlFunction() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createGetDeleteAqlFunction(ArangoDatabase db) { final Collection aqlFunctionsInitial = db.getAqlFunctions(null); - assertThat(aqlFunctionsInitial, is(empty())); + assertThat(aqlFunctionsInitial).isEmpty(); try { db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit", "function (celsius) { return celsius * 1.8 + 32; }", null); final Collection aqlFunctions = db.getAqlFunctions(null); - assertThat(aqlFunctions.size(), is(greaterThan(aqlFunctionsInitial.size()))); + assertThat(aqlFunctions).hasSizeGreaterThan(aqlFunctionsInitial.size()); } finally { final Integer deleteCount = db.deleteAqlFunction("myfunctions::temperature::celsiustofahrenheit", null); // compatibility with ArangoDB < 3.4 if (isAtLeastVersion(3, 4)) { - assertThat(deleteCount, is(1)); + assertThat(deleteCount).isEqualTo(1); } else { - assertThat(deleteCount, is(nullValue())); + assertThat(deleteCount).isNull(); } final Collection aqlFunctions = db.getAqlFunctions(null); - assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size())); + assertThat(aqlFunctions).hasSize(aqlFunctionsInitial.size()); } } - @Test - public void createGetDeleteAqlFunctionWithNamespace() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createGetDeleteAqlFunctionWithNamespace(ArangoDatabase db) { final Collection aqlFunctionsInitial = db.getAqlFunctions(null); - assertThat(aqlFunctionsInitial, is(empty())); + assertThat(aqlFunctionsInitial).isEmpty(); try { db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit1", "function (celsius) { return celsius * 1.8 + 32; }", null); @@ -1009,41 +1055,44 @@ public void createGetDeleteAqlFunctionWithNamespace() { .deleteAqlFunction("myfunctions::temperature", new AqlFunctionDeleteOptions().group(true)); // compatibility with ArangoDB < 3.4 if (isAtLeastVersion(3, 4)) { - assertThat(deleteCount, is(2)); + assertThat(deleteCount).isEqualTo(2); } else { - assertThat(deleteCount, is(nullValue())); + assertThat(deleteCount).isNull(); } final Collection aqlFunctions = db.getAqlFunctions(null); - assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size())); + assertThat(aqlFunctions).hasSize(aqlFunctionsInitial.size()); } } - @Test - public void createGraph() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createGraph(ArangoDatabase db) { String name = "graph-" + rnd(); final GraphEntity result = db.createGraph(name, null, null); - assertThat(result.getName(), is(name)); + assertThat(result.getName()).isEqualTo(name); } - @Test - public void createGraphSatellite() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createGraphSatellite(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 7)); assumeTrue(isCluster()); assumeTrue(isEnterprise()); String name = "graph-" + rnd(); final GraphEntity result = db.createGraph(name, null, new GraphCreateOptions().satellite(true)); - assertThat(result.getSatellite(), is(true)); + assertThat(result.getSatellite()).isTrue(); GraphEntity info = db.graph(name).getInfo(); - assertThat(info.getSatellite(), is(true)); + assertThat(info.getSatellite()).isTrue(); GraphEntity graph = db.getGraphs().stream().filter(g -> name.equals(g.getName())).findFirst().get(); - assertThat(graph.getSatellite(), is(true)); + assertThat(graph.getSatellite()).isTrue(); } - @Test - public void createGraphReplicationFaktor() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createGraphReplicationFaktor(ArangoDatabase db) { assumeTrue(isCluster()); String name = "graph-" + rnd(); final String edgeCollection = "edge-" + rnd(); @@ -1051,15 +1100,16 @@ public void createGraphReplicationFaktor() { final String toCollection = "to-" + rnd(); final Collection edgeDefinitions = Collections.singletonList(new EdgeDefinition().collection(edgeCollection).from(fromCollection).to(toCollection)); final GraphEntity result = db.createGraph(name, edgeDefinitions, new GraphCreateOptions().replicationFactor(2)); - assertThat(result, is(notNullValue())); + assertThat(result).isNotNull(); for (final String collection : Arrays.asList(edgeCollection, fromCollection, toCollection)) { final CollectionPropertiesEntity properties = db.collection(collection).getProperties(); - assertThat(properties.getReplicationFactor(), is(2)); + assertThat(properties.getReplicationFactor()).isEqualTo(2); } } - @Test - public void createGraphNumberOfShards() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createGraphNumberOfShards(ArangoDatabase db) { assumeTrue(isCluster()); String name = "graph-" + rnd(); final String edgeCollection = "edge-" + rnd(); @@ -1068,96 +1118,105 @@ public void createGraphNumberOfShards() { final Collection edgeDefinitions = Collections.singletonList(new EdgeDefinition().collection(edgeCollection).from(fromCollection).to(toCollection)); final GraphEntity result = db .createGraph(name, edgeDefinitions, new GraphCreateOptions().numberOfShards(2)); - assertThat(result, is(notNullValue())); + assertThat(result).isNotNull(); for (final String collection : Arrays.asList(edgeCollection, fromCollection, toCollection)) { final CollectionPropertiesEntity properties = db.collection(collection).getProperties(); - assertThat(properties.getNumberOfShards(), is(2)); + assertThat(properties.getNumberOfShards()).isEqualTo(2); } } - @Test - public void getGraphs() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getGraphs(ArangoDatabase db) { String name = "graph-" + rnd(); db.createGraph(name, null, null); final Collection graphs = db.getGraphs(); - assertThat(graphs, is(notNullValue())); - assertThat(graphs.size(), is(greaterThanOrEqualTo(1))); + assertThat(graphs).hasSizeGreaterThanOrEqualTo(1); long count = graphs.stream().map(GraphEntity::getName).filter(name::equals).count(); - assertThat(count, is(1L)); + assertThat(count).isEqualTo(1L); } - @Test - public void transactionString() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionString(ArangoDatabase db) { final TransactionOptions options = new TransactionOptions().params("test"); final String result = db.transaction("function (params) {return params;}", String.class, options); - assertThat(result, is("test")); + assertThat(result).isEqualTo("test"); } - @Test - public void transactionNumber() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionNumber(ArangoDatabase db) { final TransactionOptions options = new TransactionOptions().params(5); final Integer result = db.transaction("function (params) {return params;}", Integer.class, options); - assertThat(result, is(5)); + assertThat(result).isEqualTo(5); } - @Test - public void transactionVPack() throws VPackException { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionVPack(ArangoDatabase db) throws VPackException { final TransactionOptions options = new TransactionOptions().params(new VPackBuilder().add("test").slice()); final VPackSlice result = db.transaction("function (params) {return params;}", VPackSlice.class, options); - assertThat(result.isString(), is(true)); - assertThat(result.getAsString(), is("test")); + assertThat(result.isString()).isTrue(); + assertThat(result.getAsString()).isEqualTo("test"); } - @Test - public void transactionVPackObject() throws VPackException { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionVPackObject(ArangoDatabase db) throws VPackException { final VPackSlice params = new VPackBuilder().add(ValueType.OBJECT).add("foo", "hello").add("bar", "world") .close().slice(); final TransactionOptions options = new TransactionOptions().params(params); final String result = db .transaction("function (params) { return params['foo'] + ' ' + params['bar'];}", String.class, options); - assertThat(result, is("hello world")); + assertThat(result).isEqualTo("hello world"); } - @Test - public void transactionVPackArray() throws VPackException { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionVPackArray(ArangoDatabase db) throws VPackException { final VPackSlice params = new VPackBuilder().add(ValueType.ARRAY).add("hello").add("world").close().slice(); final TransactionOptions options = new TransactionOptions().params(params); final String result = db .transaction("function (params) { return params[0] + ' ' + params[1];}", String.class, options); - assertThat(result, is("hello world")); + assertThat(result).isEqualTo("hello world"); } - @Test - public void transactionMap() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionMap(ArangoDatabase db) { final Map params = new MapBuilder().put("foo", "hello").put("bar", "world").get(); final TransactionOptions options = new TransactionOptions().params(params); final String result = db .transaction("function (params) { return params['foo'] + ' ' + params['bar'];}", String.class, options); - assertThat(result, is("hello world")); + assertThat(result).isEqualTo("hello world"); } - @Test - public void transactionArray() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionArray(ArangoDatabase db) { final String[] params = new String[]{"hello", "world"}; final TransactionOptions options = new TransactionOptions().params(params); final String result = db .transaction("function (params) { return params[0] + ' ' + params[1];}", String.class, options); - assertThat(result, is("hello world")); + assertThat(result).isEqualTo("hello world"); } - @Test - public void transactionCollection() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionCollection(ArangoDatabase db) { final Collection params = new ArrayList<>(); params.add("hello"); params.add("world"); final TransactionOptions options = new TransactionOptions().params(params); final String result = db .transaction("function (params) { return params[0] + ' ' + params[1];}", String.class, options); - assertThat(result, is("hello world")); + assertThat(result).isEqualTo("hello world"); } - @Test - public void transactionInsertJson() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionInsertJson(ArangoDatabase db) { String key = "key-" + rnd(); final TransactionOptions options = new TransactionOptions().params("{\"_key\":\"" + key + "\"}") .writeCollections(CNAME1); @@ -1165,11 +1224,12 @@ public void transactionInsertJson() { + "var db = require('internal').db;" + "db." + CNAME1 + ".save(JSON.parse(params));" + "}", Void.class, options); - assertThat(db.collection(CNAME1).getDocument(key, String.class), is(notNullValue())); + assertThat(db.collection(CNAME1).getDocument(key, String.class)).isNotNull(); } - @Test - public void transactionExclusiveWrite() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionExclusiveWrite(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); String key = "key-" + rnd(); final TransactionOptions options = new TransactionOptions().params("{\"_key\":\"" + key + "\"}") @@ -1178,64 +1238,68 @@ public void transactionExclusiveWrite() { + "var db = require('internal').db;" + "db." + CNAME1 + ".save(JSON.parse(params));" + "}", Void.class, options); - assertThat(db.collection(CNAME1).getDocument(key, String.class), is(notNullValue())); + assertThat(db.collection(CNAME1).getDocument(key, String.class)).isNotNull(); } - @Test - public void transactionEmpty() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionEmpty(ArangoDatabase db) { db.transaction("function () {}", null, null); } - @Test - public void transactionAllowImplicit() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionAllowImplicit(ArangoDatabase db) { final String action = "function (params) {" + "var db = require('internal').db;" + "return {'a':db." + CNAME1 + ".all().toArray()[0], 'b':db." + CNAME2 + ".all().toArray()[0]};" + "}"; final TransactionOptions options = new TransactionOptions().readCollections(CNAME1); db.transaction(action, VPackSlice.class, options); - try { - options.allowImplicit(false); - db.transaction(action, VPackSlice.class, options); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(400)); - } + options.allowImplicit(false); + Throwable thrown = catchThrowable(() -> db.transaction(action, VPackSlice.class, options)); + assertThat(thrown) + .isInstanceOf(ArangoDBException.class) + .extracting(it -> ((ArangoDBException) it).getResponseCode()) + .isEqualTo(400); } - protected static class TransactionTestEntity { + static class TransactionTestEntity { private String value; - public TransactionTestEntity() { + TransactionTestEntity() { super(); } } - @Test - public void transactionPojoReturn() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionPojoReturn(ArangoDatabase db) { final String action = "function() { return {'value':'hello world'}; }"; final TransactionTestEntity res = db.transaction(action, TransactionTestEntity.class, new TransactionOptions()); - assertThat(res, is(notNullValue())); - assertThat(res.value, is("hello world")); + assertThat(res).isNotNull(); + assertThat(res.value).isEqualTo("hello world"); } - @Test - public void getInfo() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getInfo(ArangoDatabase db) { final DatabaseEntity info = db.getInfo(); - assertThat(info, is(notNullValue())); - assertThat(info.getId(), is(notNullValue())); - assertThat(info.getName(), is(BaseTest.TEST_DB.get())); - assertThat(info.getPath(), is(notNullValue())); - assertThat(info.getIsSystem(), is(false)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(TEST_DB.get()); + assertThat(info.getPath()).isNotNull(); + assertThat(info.getIsSystem()).isFalse(); if (isAtLeastVersion(3, 6) && isCluster()) { - assertThat(info.getSharding(), notNullValue()); - assertThat(info.getWriteConcern(), notNullValue()); - assertThat(info.getReplicationFactor(), notNullValue()); + assertThat(info.getSharding()).isNotNull(); + assertThat(info.getWriteConcern()).isNotNull(); + assertThat(info.getReplicationFactor()).isNotNull(); } } - @Test - public void executeTraversal() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void executeTraversal(ArangoDatabase db) { String k1 = "key-" + rnd(); String k2 = "key-" + rnd(); String k3 = "key-" + rnd(); @@ -1245,7 +1309,7 @@ public void executeTraversal() { for (final String e : new String[]{ k1, k2, k3, k4, k5 }) { - collection1.insertDocument(new BaseDocument(e), null); + db.collection(CNAME1).insertDocument(new BaseDocument(e), null); } for (final String[] e : new String[][]{ new String[]{k1, k2}, new String[]{k2, k3}, @@ -1255,46 +1319,44 @@ public void executeTraversal() { edge.setKey(e[0] + "_knows_" + e[1]); edge.setFrom(CNAME1 + "/" + e[0]); edge.setTo(CNAME1 + "/" + e[1]); - edges.insertDocument(edge, null); + db.collection(ENAMES).insertDocument(edge, null); } final TraversalOptions options = new TraversalOptions().edgeCollection(ENAMES).startVertex(CNAME1 + "/" + k1).direction(Direction.outbound); final TraversalEntity traversal = db.executeTraversal(BaseDocument.class, BaseEdgeDocument.class, options); - assertThat(traversal, is(notNullValue())); + assertThat(traversal).isNotNull(); final Collection vertices = traversal.getVertices(); - assertThat(vertices, is(notNullValue())); - assertThat(vertices.size(), is(4)); + assertThat(vertices).hasSize(4); final Iterator verticesIterator = vertices.iterator(); final Collection v = Arrays.asList(k1, k2, k3, k4); while (verticesIterator.hasNext()) { - assertThat(v.contains(verticesIterator.next().getKey()), is(true)); + assertThat(v).contains(verticesIterator.next().getKey()); } final Collection> paths = traversal.getPaths(); - assertThat(paths, is(notNullValue())); - assertThat(paths.size(), is(4)); - assertThat(paths.iterator().hasNext(), is(true)); + assertThat(paths).hasSize(4); final PathEntity first = paths.iterator().next(); - assertThat(first, is(notNullValue())); - assertThat(first.getEdges().size(), is(0)); - assertThat(first.getVertices().size(), is(1)); - assertThat(first.getVertices().iterator().next().getKey(), is(k1)); + assertThat(first.getEdges()).isEmpty(); + assertThat(first.getVertices()).hasSize(1); + assertThat(first.getVertices().iterator().next().getKey()).isEqualTo(k1); } - @Test - public void getDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getDocument(ArangoDatabase db) { String key = "key-" + rnd(); final BaseDocument value = new BaseDocument(key); - collection1.insertDocument(value); + db.collection(CNAME1).insertDocument(value); final BaseDocument document = db.getDocument(CNAME1 + "/" + key, BaseDocument.class); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(key)); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(key); } - @Test - public void shouldIncludeExceptionMessage() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void shouldIncludeExceptionMessage(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); final String exceptionMessage = "My error context"; @@ -1303,17 +1365,20 @@ public void shouldIncludeExceptionMessage() { db.transaction(action, VPackSlice.class, null); fail(); } catch (final ArangoDBException e) { - assertThat(e.getErrorMessage(), is(exceptionMessage)); + assertThat(e.getErrorMessage()).isEqualTo(exceptionMessage); } } - @Test(expected = ArangoDBException.class) - public void getDocumentWrongId() { - db.getDocument("123", BaseDocument.class); + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getDocumentWrongId(ArangoDatabase db) { + Throwable thrown = catchThrowable(() -> db.getDocument("123", BaseDocument.class)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void reloadRouting() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void reloadRouting(ArangoDatabase db) { db.reloadRouting(); } } diff --git a/src/test/java/com/arangodb/ArangoDocumentUtilTest.java b/src/test/java/com/arangodb/ArangoDocumentUtilTest.java index d8b5c8dd3..224aea3cc 100644 --- a/src/test/java/com/arangodb/ArangoDocumentUtilTest.java +++ b/src/test/java/com/arangodb/ArangoDocumentUtilTest.java @@ -21,15 +21,19 @@ package com.arangodb; import com.arangodb.internal.util.DocumentUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; /** * @author Mark Vollmary + * @author Michele Rastelli */ -public class ArangoDocumentUtilTest { +class ArangoDocumentUtilTest { @Test - public void validateDocumentKeyValid() { + void validateDocumentKeyValid() { checkDocumentKey("1test"); checkDocumentKey("test1"); checkDocumentKey("test-1"); @@ -37,14 +41,16 @@ public void validateDocumentKeyValid() { checkDocumentKey("_test"); } - @Test(expected = ArangoDBException.class) - public void validateDocumentKeyInvalidSlash() { - checkDocumentKey("test/test"); + @Test + void validateDocumentKeyInvalidSlash() { + Throwable thrown = catchThrowable(() -> checkDocumentKey("test/test")); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test(expected = ArangoDBException.class) - public void validateDocumentKeyEmpty() { - checkDocumentKey(""); + @Test + void validateDocumentKeyEmpty() { + Throwable thrown = catchThrowable(() -> checkDocumentKey("")); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } private void checkDocumentKey(final String key) throws ArangoDBException { @@ -52,7 +58,7 @@ private void checkDocumentKey(final String key) throws ArangoDBException { } @Test - public void validateDocumentIdValid() { + void validateDocumentIdValid() { checkDocumentId("1test/1test"); checkDocumentId("test1/test1"); checkDocumentId("test-1/test-1"); @@ -60,14 +66,16 @@ public void validateDocumentIdValid() { checkDocumentId("_test/_test"); } - @Test(expected = ArangoDBException.class) - public void validateDocumentIdInvalidWithoutSlash() { - checkDocumentId("test"); + @Test + void validateDocumentIdInvalidWithoutSlash() { + Throwable thrown = catchThrowable(() -> checkDocumentId("test")); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test(expected = ArangoDBException.class) - public void validateDocumentIdEmpty() { - checkDocumentId(""); + @Test + void validateDocumentIdEmpty() { + Throwable thrown = catchThrowable(() -> checkDocumentId("")); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } private void checkDocumentId(final String id) throws ArangoDBException { diff --git a/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java index 756f2758e..3baaab078 100644 --- a/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoEdgeCollectionTest.java @@ -22,43 +22,44 @@ import com.arangodb.entity.*; import com.arangodb.model.*; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collections; import java.util.UUID; +import java.util.stream.Stream; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; /** * @author Mark Vollmary + * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class ArangoEdgeCollectionTest extends BaseTest { +class ArangoEdgeCollectionTest extends BaseJunit5 { private static final String GRAPH_NAME = "EdgeCollectionTest_graph"; private static final String VERTEX_COLLECTION_NAME = "EdgeCollectionTest_vertex_collection"; private static final String EDGE_COLLECTION_NAME = "EdgeCollectionTest_edge_collection"; - private final ArangoCollection vertexCollection; - private final ArangoCollection edgeCollection; - - private final ArangoGraph graph; - private final ArangoVertexCollection vertices; - private final ArangoEdgeCollection edges; + private static Stream args() { + return dbsStream() + .map(db -> new Object[]{ + db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME), + db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) + }) + .map(Arguments::of); + } - @BeforeClass - public static void init() { - BaseTest.initCollections(VERTEX_COLLECTION_NAME); - BaseTest.initEdgeCollections(EDGE_COLLECTION_NAME); - BaseTest.initGraph( + @BeforeAll + static void init() { + initCollections(VERTEX_COLLECTION_NAME); + initEdgeCollections(EDGE_COLLECTION_NAME); + initGraph( GRAPH_NAME, Collections.singletonList(new EdgeDefinition() .collection(EDGE_COLLECTION_NAME) @@ -69,22 +70,9 @@ public static void init() { ); } - public ArangoEdgeCollectionTest(final ArangoDB arangoDB) { - super(arangoDB); - - vertexCollection = db.collection(VERTEX_COLLECTION_NAME); - edgeCollection = db.collection(EDGE_COLLECTION_NAME); - - graph = db.graph(GRAPH_NAME); - vertices = graph.vertexCollection(VERTEX_COLLECTION_NAME); - edges = graph.edgeCollection(EDGE_COLLECTION_NAME); - } - - private BaseEdgeDocument createEdgeValue() { - final VertexEntity v1 = vertices - .insertVertex(new BaseDocument(), null); - final VertexEntity v2 = vertices - .insertVertex(new BaseDocument(), null); + private BaseEdgeDocument createEdgeValue(ArangoVertexCollection vertices) { + final VertexEntity v1 = vertices.insertVertex(new BaseDocument()); + final VertexEntity v2 = vertices.insertVertex(new BaseDocument()); final BaseEdgeDocument value = new BaseEdgeDocument(); value.setFrom(v1.getId()); @@ -92,366 +80,362 @@ private BaseEdgeDocument createEdgeValue() { return value; } - @Test - public void insertEdge() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = edges.insertEdge(value, null); - assertThat(edge, is(notNullValue())); - final BaseEdgeDocument document = edgeCollection.getDocument(edge.getKey(), - BaseEdgeDocument.class, null); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); - assertThat(document.getFrom(), is(notNullValue())); - assertThat(document.getTo(), is(notNullValue())); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void insertEdge(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument value = createEdgeValue(vertices); + final EdgeEntity edge = edges.insertEdge(value); + assertThat(edge).isNotNull(); + final BaseEdgeDocument document = edges.getEdge(edge.getKey(), BaseEdgeDocument.class); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(edge.getKey()); + assertThat(document.getFrom()).isNotNull(); + assertThat(document.getTo()).isNotNull(); } - @Test - public void insertEdgeUpdateRev() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = edges.insertEdge(value, null); - assertThat(value.getRevision(), is(edge.getRev())); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void insertEdgeUpdateRev(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument value = createEdgeValue(vertices); + final EdgeEntity edge = edges.insertEdge(value); + assertThat(value.getRevision()).isEqualTo(edge.getRev()); } - @Test - public void insertEdgeViolatingUniqueConstraint() { - // FIXME: remove once fix is backported to 3.4 - assumeTrue(isAtLeastVersion(3, 5)); - - edgeCollection - .ensureSkiplistIndex(Arrays.asList("_from", "_to"), new SkiplistIndexOptions().unique(true)); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void insertEdgeViolatingUniqueConstraint(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + edges.graph().db().collection(EDGE_COLLECTION_NAME) + .ensurePersistentIndex(Arrays.asList("_from", "_to"), new PersistentIndexOptions().unique(true)); - BaseEdgeDocument edge = createEdgeValue(); - edges.insertEdge(edge, null); + BaseEdgeDocument edge = createEdgeValue(vertices); + edges.insertEdge(edge); try { - edges.insertEdge(edge, null); + edges.insertEdge(edge); } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(409)); - assertThat(e.getErrorNum(), is(1210)); + assertThat(e.getResponseCode()).isEqualTo(409); + assertThat(e.getErrorNum()).isEqualTo(1210); } } - @Test - public void getEdge() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = edges.insertEdge(value, null); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void getEdge(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument value = createEdgeValue(vertices); + final EdgeEntity edge = edges.insertEdge(value); final BaseEdgeDocument document = edges - .getEdge(edge.getKey(), BaseEdgeDocument.class, null); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); - assertThat(document.getFrom(), is(notNullValue())); - assertThat(document.getTo(), is(notNullValue())); + .getEdge(edge.getKey(), BaseEdgeDocument.class); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(edge.getKey()); + assertThat(document.getFrom()).isNotNull(); + assertThat(document.getTo()).isNotNull(); } - @Test - public void getEdgeIfMatch() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = edges.insertEdge(value, null); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void getEdgeIfMatch(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument value = createEdgeValue(vertices); + final EdgeEntity edge = edges.insertEdge(value); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch(edge.getRev()); final BaseDocument document = edges.getEdge(edge.getKey(), BaseDocument.class, options); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(edge.getKey()); } - @Test - public void getEdgeIfMatchFail() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = edges.insertEdge(value, null); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void getEdgeIfMatchFail(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument value = createEdgeValue(vertices); + final EdgeEntity edge = edges.insertEdge(value); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch("no"); final BaseEdgeDocument edge2 = edges.getEdge(edge.getKey(), BaseEdgeDocument.class, options); - assertThat(edge2, is(nullValue())); + assertThat(edge2).isNull(); } - @Test - public void getEdgeIfNoneMatch() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = edges.insertEdge(value, null); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void getEdgeIfNoneMatch(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument value = createEdgeValue(vertices); + final EdgeEntity edge = edges.insertEdge(value); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch("no"); final BaseDocument document = edges.getEdge(edge.getKey(), BaseDocument.class, options); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(edge.getKey()); } - @Test - public void getEdgeIfNoneMatchFail() { - final BaseEdgeDocument value = createEdgeValue(); - final EdgeEntity edge = edges.insertEdge(value, null); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void getEdgeIfNoneMatchFail(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument value = createEdgeValue(vertices); + final EdgeEntity edge = edges.insertEdge(value); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch(edge.getRev()); final BaseEdgeDocument edge2 = edges.getEdge(edge.getKey(), BaseEdgeDocument.class, options); - assertThat(edge2, is(nullValue())); + assertThat(edge2).isNull(); } - @Test - public void replaceEdge() { - final BaseEdgeDocument doc = createEdgeValue(); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void replaceEdge(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); doc.addAttribute("a", "test"); - final EdgeEntity createResult = edges.insertEdge(doc, null); + final EdgeEntity createResult = edges.insertEdge(doc); doc.getProperties().clear(); doc.addAttribute("b", "test"); final EdgeUpdateEntity replaceResult = edges - .replaceEdge(createResult.getKey(), doc, null); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + .replaceEdge(createResult.getKey(), doc); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = edges - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + .getEdge(createResult.getKey(), BaseEdgeDocument.class); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } - @Test - public void replaceEdgeUpdateRev() { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = edges.insertEdge(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void replaceEdgeUpdateRev(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); + final EdgeEntity createResult = edges.insertEdge(doc); + assertThat(doc.getRevision()).isEqualTo(createResult.getRev()); final EdgeUpdateEntity replaceResult = edges - .replaceEdge(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(replaceResult.getRev())); + .replaceEdge(createResult.getKey(), doc); + assertThat(doc.getRevision()).isEqualTo(replaceResult.getRev()); } - @Test - public void replaceEdgeIfMatch() { - final BaseEdgeDocument doc = createEdgeValue(); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void replaceEdgeIfMatch(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); doc.addAttribute("a", "test"); - final EdgeEntity createResult = edges.insertEdge(doc, null); + final EdgeEntity createResult = edges.insertEdge(doc); doc.getProperties().clear(); doc.addAttribute("b", "test"); final EdgeReplaceOptions options = new EdgeReplaceOptions().ifMatch(createResult.getRev()); final EdgeUpdateEntity replaceResult = edges .replaceEdge(createResult.getKey(), doc, options); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = edges - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + .getEdge(createResult.getKey(), BaseEdgeDocument.class); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } - @Test - public void replaceEdgeIfMatchFail() { - final BaseEdgeDocument doc = createEdgeValue(); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void replaceEdgeIfMatchFail(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); doc.addAttribute("a", "test"); - final EdgeEntity createResult = edges.insertEdge(doc, null); + final EdgeEntity createResult = edges.insertEdge(doc); doc.getProperties().clear(); doc.addAttribute("b", "test"); - try { - final EdgeReplaceOptions options = new EdgeReplaceOptions().ifMatch("no"); - edges.replaceEdge(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - if (isAtLeastVersion(3, 4)) { - // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK - // assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1200)); - } else { - assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1903)); - } - } + final EdgeReplaceOptions options = new EdgeReplaceOptions().ifMatch("no"); + Throwable thrown = catchThrowable(() -> edges.replaceEdge(createResult.getKey(), doc, options)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode()).isEqualTo(412)); + assertThat(e.getErrorNum()).isEqualTo(1200); } - @Test - public void updateEdge() { - final BaseEdgeDocument doc = createEdgeValue(); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void updateEdge(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); - final EdgeEntity createResult = edges.insertEdge(doc, null); + final EdgeEntity createResult = edges.insertEdge(doc); doc.updateAttribute("a", "test1"); doc.addAttribute("b", "test"); doc.updateAttribute("c", null); final EdgeUpdateEntity updateResult = edges - .updateEdge(createResult.getKey(), doc, null); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + .updateEdge(createResult.getKey(), doc); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = edges - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); + .getEdge(createResult.getKey(), BaseEdgeDocument.class); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); } - @Test - public void updateEdgeUpdateRev() { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = edges.insertEdge(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void updateEdgeUpdateRev(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); + final EdgeEntity createResult = edges.insertEdge(doc); + assertThat(doc.getRevision()).isEqualTo(createResult.getRev()); final EdgeUpdateEntity updateResult = edges - .updateEdge(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(updateResult.getRev())); + .updateEdge(createResult.getKey(), doc); + assertThat(doc.getRevision()).isEqualTo(updateResult.getRev()); } - @Test - public void updateEdgeIfMatch() { - final BaseEdgeDocument doc = createEdgeValue(); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void updateEdgeIfMatch(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); - final EdgeEntity createResult = edges.insertEdge(doc, null); + final EdgeEntity createResult = edges.insertEdge(doc); doc.updateAttribute("a", "test1"); doc.addAttribute("b", "test"); doc.updateAttribute("c", null); final EdgeUpdateOptions options = new EdgeUpdateOptions().ifMatch(createResult.getRev()); final EdgeUpdateEntity updateResult = edges .updateEdge(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = edges - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); + .getEdge(createResult.getKey(), BaseEdgeDocument.class); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); } - @Test - public void updateEdgeIfMatchFail() { - final BaseEdgeDocument doc = createEdgeValue(); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void updateEdgeIfMatchFail(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); - final EdgeEntity createResult = edges.insertEdge(doc, null); + final EdgeEntity createResult = edges.insertEdge(doc); doc.updateAttribute("a", "test1"); doc.addAttribute("b", "test"); doc.updateAttribute("c", null); - try { - final EdgeUpdateOptions options = new EdgeUpdateOptions().ifMatch("no"); - edges.updateEdge(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - if (isAtLeastVersion(3, 4)) { - // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK - // assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1200)); - } else { - assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1903)); - } - } + final EdgeUpdateOptions options = new EdgeUpdateOptions().ifMatch("no"); + Throwable thrown = catchThrowable(() -> edges.updateEdge(createResult.getKey(), doc, options)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode()).isEqualTo(412)); + assertThat(e.getErrorNum()).isEqualTo(1200); } - @Test - public void updateEdgeKeepNullTrue() { - final BaseEdgeDocument doc = createEdgeValue(); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void updateEdgeKeepNullTrue(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); doc.addAttribute("a", "test"); - final EdgeEntity createResult = edges.insertEdge(doc, null); + final EdgeEntity createResult = edges.insertEdge(doc); doc.updateAttribute("a", null); final EdgeUpdateOptions options = new EdgeUpdateOptions().keepNull(true); final EdgeUpdateEntity updateResult = edges .updateEdge(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = edges - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet().size(), is(1)); - assertThat(readResult.getProperties().keySet(), hasItem("a")); + .getEdge(createResult.getKey(), BaseEdgeDocument.class); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getProperties().keySet()).hasSize(1); + assertThat(readResult.getProperties()).containsKey("a"); } - @Test - public void updateEdgeKeepNullFalse() { - final BaseEdgeDocument doc = createEdgeValue(); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void updateEdgeKeepNullFalse(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); doc.addAttribute("a", "test"); - final EdgeEntity createResult = edges.insertEdge(doc, null); + final EdgeEntity createResult = edges.insertEdge(doc); doc.updateAttribute("a", null); final EdgeUpdateOptions options = new EdgeUpdateOptions().keepNull(false); final EdgeUpdateEntity updateResult = edges .updateEdge(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = edges - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getRevision(), is(notNullValue())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + .getEdge(createResult.getKey(), BaseEdgeDocument.class); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getRevision()).isNotNull(); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); } - @Test - public void deleteEdge() { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = edges.insertEdge(doc, null); - edges.deleteEdge(createResult.getKey(), null); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void deleteEdge(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); + final EdgeEntity createResult = edges.insertEdge(doc); + edges.deleteEdge(createResult.getKey()); final BaseEdgeDocument edge = edges - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(edge, is(nullValue())); + .getEdge(createResult.getKey(), BaseEdgeDocument.class); + assertThat(edge).isNull(); } - @Test - public void deleteEdgeIfMatch() { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = edges.insertEdge(doc, null); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void deleteEdgeIfMatch(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); + final EdgeEntity createResult = edges.insertEdge(doc); final EdgeDeleteOptions options = new EdgeDeleteOptions().ifMatch(createResult.getRev()); edges.deleteEdge(createResult.getKey(), options); final BaseEdgeDocument edge = edges - .getEdge(createResult.getKey(), BaseEdgeDocument.class, null); - assertThat(edge, is(nullValue())); + .getEdge(createResult.getKey(), BaseEdgeDocument.class); + assertThat(edge).isNull(); } - @Test - public void deleteEdgeIfMatchFail() { - final BaseEdgeDocument doc = createEdgeValue(); - final EdgeEntity createResult = edges.insertEdge(doc, null); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void deleteEdgeIfMatchFail(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument doc = createEdgeValue(vertices); + final EdgeEntity createResult = edges.insertEdge(doc); final EdgeDeleteOptions options = new EdgeDeleteOptions().ifMatch("no"); - try { - edges.deleteEdge(createResult.getKey(), options); - fail(); - } catch (final ArangoDBException e) { - if (isAtLeastVersion(3, 4)) { - // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK - // assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1200)); - } else { - assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1903)); - } - } + Throwable thrown = catchThrowable(() -> edges.deleteEdge(createResult.getKey(), options)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode()).isEqualTo(412)); + assertThat(e.getErrorNum()).isEqualTo(1200); } - @Test - public void edgeKeyWithSpecialChars() { - final BaseEdgeDocument value = createEdgeValue(); - final String key = "_-:.@()+,=;$!*'%" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("args") + void edgeKeyWithSpecialChars(ArangoVertexCollection vertices, ArangoEdgeCollection edges) { + final BaseEdgeDocument value = createEdgeValue(vertices); + final String key = "_-:.@()+,=;$!*'%" + UUID.randomUUID(); value.setKey(key); - final EdgeEntity edge = edges.insertEdge(value, null); - assertThat(edge, is(notNullValue())); - final BaseEdgeDocument document = edgeCollection.getDocument(edge.getKey(), - BaseEdgeDocument.class, null); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(key)); - assertThat(document.getFrom(), is(notNullValue())); - assertThat(document.getTo(), is(notNullValue())); + final EdgeEntity edge = edges.insertEdge(value); + assertThat(edge).isNotNull(); + final BaseEdgeDocument document = edges.getEdge(edge.getKey(), BaseEdgeDocument.class); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(key); + assertThat(document.getFrom()).isNotNull(); + assertThat(document.getTo()).isNotNull(); } } diff --git a/src/test/java/com/arangodb/ArangoGraphTest.java b/src/test/java/com/arangodb/ArangoGraphTest.java index ffa5f7651..731be3a54 100644 --- a/src/test/java/com/arangodb/ArangoGraphTest.java +++ b/src/test/java/com/arangodb/ArangoGraphTest.java @@ -25,23 +25,23 @@ import com.arangodb.entity.GraphEntity; import com.arangodb.model.GraphCreateOptions; import com.arangodb.model.VertexCollectionCreateOptions; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.util.*; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assume.assumeTrue; /** * @author Mark Vollmary + * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class ArangoGraphTest extends BaseTest { +class ArangoGraphTest extends BaseJunit5 { private static final String GRAPH_NAME = "ArangoGraphTest_graph"; @@ -60,134 +60,104 @@ public class ArangoGraphTest extends BaseTest { private static final EdgeDefinition ed1 = new EdgeDefinition().collection(EDGE_COL_1).from(VERTEX_COL_1).to(VERTEX_COL_2); private static final EdgeDefinition ed2 = new EdgeDefinition().collection(EDGE_COL_2).from(VERTEX_COL_2).to(VERTEX_COL_1, VERTEX_COL_3); - private final ArangoCollection vertexCollection1; - private final ArangoCollection vertexCollection2; - private final ArangoCollection vertexCollection3; - private final ArangoCollection vertexCollection4; - - private final ArangoCollection edgeCollection1; - private final ArangoCollection edgeCollection2; - private final ArangoCollection edgeCollection3; - - private final ArangoGraph graph; - - private final ArangoVertexCollection vertices1; - private final ArangoVertexCollection vertices2; - private final ArangoVertexCollection vertices3; - private final ArangoVertexCollection vertices4; - - private final ArangoEdgeCollection edges1; - private final ArangoEdgeCollection edges2; - private final ArangoEdgeCollection edges3; + private static Stream graphs() { + return dbsStream() + .map(db -> db.graph(GRAPH_NAME)) + .map(Arguments::of); + } - @BeforeClass - public static void init() { + @BeforeAll + static void init() { final Collection edgeDefinitions = Arrays.asList(ed1, ed2); final GraphCreateOptions options = new GraphCreateOptions() .replicationFactor(REPLICATION_FACTOR) .numberOfShards(NUMBER_OF_SHARDS); - BaseTest.initGraph(GRAPH_NAME, edgeDefinitions, options); + initGraph(GRAPH_NAME, edgeDefinitions, options); } - public ArangoGraphTest(final ArangoDB arangoDB) { - super(arangoDB); - - vertexCollection1 = db.collection(VERTEX_COL_1); - vertexCollection2 = db.collection(VERTEX_COL_2); - vertexCollection3 = db.collection(VERTEX_COL_3); - vertexCollection4 = db.collection(VERTEX_COL_4); - - edgeCollection1 = db.collection(EDGE_COL_1); - edgeCollection2 = db.collection(EDGE_COL_2); - edgeCollection3 = db.collection(EDGE_COL_3); - - graph = db.graph(GRAPH_NAME); - - vertices1 = graph.vertexCollection(VERTEX_COL_1); - vertices2 = graph.vertexCollection(VERTEX_COL_2); - vertices3 = graph.vertexCollection(VERTEX_COL_3); - vertices4 = graph.vertexCollection(VERTEX_COL_4); - - edges1 = graph.edgeCollection(EDGE_COL_1); - edges2 = graph.edgeCollection(EDGE_COL_2); - edges3 = graph.edgeCollection(EDGE_COL_3); - } - @Test - public void exists() { - assertThat(graph.exists(), is(true)); - assertThat(db.graph(GRAPH_NAME + "no").exists(), is(false)); + @ParameterizedTest(name = "{index}") + @MethodSource("graphs") + void exists(ArangoGraph graph) { + assertThat(graph.exists()).isTrue(); + assertThat(graph.db().graph(GRAPH_NAME + "no").exists()).isFalse(); } - @Test - public void createWithReplicationAndMinReplicationFactor() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createWithReplicationAndMinReplicationFactor(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isCluster()); final Collection edgeDefinitions = new ArrayList<>(); final GraphEntity graph = db.createGraph(GRAPH_NAME + "_1", edgeDefinitions, new GraphCreateOptions().isSmart(true).replicationFactor(2).minReplicationFactor(2)); - assertThat(graph, is(notNullValue())); - assertThat(graph.getName(), is(GRAPH_NAME + "_1")); - assertThat(graph.getMinReplicationFactor(), is(2)); - assertThat(graph.getReplicationFactor(), is(2)); + assertThat(graph).isNotNull(); + assertThat(graph.getName()).isEqualTo(GRAPH_NAME + "_1"); + assertThat(graph.getMinReplicationFactor()).isEqualTo(2); + assertThat(graph.getReplicationFactor()).isEqualTo(2); db.graph(GRAPH_NAME + "_1").drop(); } - @Test - public void getGraphs() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getGraphs(ArangoDatabase db) { final Collection graphs = db.getGraphs(); - assertThat(graphs.stream().anyMatch(it -> it.getName().equals(GRAPH_NAME)), is(true)); + assertThat(graphs.stream().anyMatch(it -> it.getName().equals(GRAPH_NAME))).isTrue(); } - @Test - public void getInfo() { + @ParameterizedTest(name = "{index}") + @MethodSource("graphs") + void getInfo(ArangoGraph graph) { final GraphEntity info = graph.getInfo(); - assertThat(info, is(notNullValue())); - assertThat(info.getName(), is(GRAPH_NAME)); - assertThat(info.getEdgeDefinitions().size(), is(2)); + assertThat(info).isNotNull(); + assertThat(info.getName()).isEqualTo(GRAPH_NAME); + assertThat(info.getEdgeDefinitions()).hasSize(2); final Iterator iterator = info.getEdgeDefinitions().iterator(); final EdgeDefinition e1 = iterator.next(); - assertThat(e1.getCollection(), is(EDGE_COL_1)); - assertThat(e1.getFrom(), hasItem(VERTEX_COL_1)); - assertThat(e1.getTo(), hasItem(VERTEX_COL_2)); + assertThat(e1.getCollection()).isEqualTo(EDGE_COL_1); + assertThat(e1.getFrom()).contains(VERTEX_COL_1); + assertThat(e1.getTo()).contains(VERTEX_COL_2); final EdgeDefinition e2 = iterator.next(); - assertThat(e2.getCollection(), is(EDGE_COL_2)); - assertThat(e2.getFrom(), hasItem(VERTEX_COL_2)); - assertThat(e2.getTo(), hasItems(VERTEX_COL_1, VERTEX_COL_3)); - assertThat(info.getOrphanCollections(), is(empty())); + assertThat(e2.getCollection()).isEqualTo(EDGE_COL_2); + assertThat(e2.getFrom()).contains(VERTEX_COL_2); + assertThat(e2.getTo()).contains(VERTEX_COL_1, VERTEX_COL_3); + assertThat(info.getOrphanCollections()).isEmpty(); if (isCluster()) { for (final String collection : new String[]{EDGE_COL_1, EDGE_COL_2, VERTEX_COL_1, VERTEX_COL_2}) { - final CollectionPropertiesEntity properties = db.collection(collection).getProperties(); - assertThat(properties.getReplicationFactor(), is(REPLICATION_FACTOR)); - assertThat(properties.getNumberOfShards(), is(NUMBER_OF_SHARDS)); + final CollectionPropertiesEntity properties = graph.db().collection(collection).getProperties(); + assertThat(properties.getReplicationFactor()).isEqualTo(REPLICATION_FACTOR); + assertThat(properties.getNumberOfShards()).isEqualTo(NUMBER_OF_SHARDS); } } } - @Test - public void getVertexCollections() { + @ParameterizedTest(name = "{index}") + @MethodSource("graphs") + void getVertexCollections(ArangoGraph graph) { final Collection vertexCollections = graph.getVertexCollections(); - assertThat(vertexCollections, is(notNullValue())); - assertThat(vertexCollections.size(), is(3)); - assertThat(vertexCollections, hasItems(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3)); + assertThat(vertexCollections) + .hasSize(3) + .contains(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3); } - @Test - public void addVertexCollection() { + @ParameterizedTest(name = "{index}") + @MethodSource("graphs") + void addVertexCollection(ArangoGraph graph) { final GraphEntity g = graph.addVertexCollection(VERTEX_COL_4); - assertThat(g, is(notNullValue())); + assertThat(g).isNotNull(); final Collection vertexCollections = graph.getVertexCollections(); - assertThat(vertexCollections, hasItems(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, VERTEX_COL_4)); + assertThat(vertexCollections).contains(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, VERTEX_COL_4); // revert graph.vertexCollection(VERTEX_COL_4).drop(); } - @Test - public void addSatelliteVertexCollection() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void addSatelliteVertexCollection(ArangoDatabase db) { assumeTrue(isCluster()); assumeTrue(isEnterprise()); assumeTrue(isAtLeastVersion(3, 9)); @@ -199,53 +169,56 @@ public void addSatelliteVertexCollection() { g.addVertexCollection(v1Name, new VertexCollectionCreateOptions().satellites(v1Name)); Collection vertexCollections = g.getVertexCollections(); - assertThat(vertexCollections, hasItems(v1Name)); - assertThat(db.collection(v1Name).getProperties().getSatellite(), is(true)); + assertThat(vertexCollections).contains(v1Name); + assertThat(db.collection(v1Name).getProperties().getSatellite()).isTrue(); // revert g.drop(); } - @Test - public void getEdgeCollections() { + @ParameterizedTest(name = "{index}") + @MethodSource("graphs") + void getEdgeCollections(ArangoGraph graph) { final Collection edgeCollections = graph.getEdgeDefinitions(); - assertThat(edgeCollections, is(notNullValue())); - assertThat(edgeCollections.size(), is(2)); - assertThat(edgeCollections, hasItems(EDGE_COL_1, EDGE_COL_2)); + assertThat(edgeCollections) + .hasSize(2) + .contains(EDGE_COL_1, EDGE_COL_2); } - @Test - public void addEdgeDefinition() { + @ParameterizedTest(name = "{index}") + @MethodSource("graphs") + void addEdgeDefinition(ArangoGraph graph) { EdgeDefinition ed = new EdgeDefinition().collection(EDGE_COL_3).from(VERTEX_COL_1).to(VERTEX_COL_2); final GraphEntity g = graph.addEdgeDefinition(ed); - assertThat(g, is(notNullValue())); + assertThat(g).isNotNull(); final Collection edgeDefinitions = g.getEdgeDefinitions(); - assertThat(edgeDefinitions.size(), is(3)); + assertThat(edgeDefinitions).hasSize(3); int count = 0; for (final EdgeDefinition e : edgeDefinitions) { if (e.getCollection().equals(EDGE_COL_3)) { count++; } } - assertThat(count, is(1)); + assertThat(count).isEqualTo(1); for (final EdgeDefinition e : edgeDefinitions) { if (e.getCollection().equals(EDGE_COL_3)) { - assertThat(e.getFrom(), hasItem(VERTEX_COL_1)); - assertThat(e.getTo(), hasItem(VERTEX_COL_2)); + assertThat(e.getFrom()).contains(VERTEX_COL_1); + assertThat(e.getTo()).contains(VERTEX_COL_2); } } if (isCluster()) { - final CollectionPropertiesEntity properties = db.collection(EDGE_COL_3).getProperties(); - assertThat(properties.getReplicationFactor(), is(REPLICATION_FACTOR)); - assertThat(properties.getNumberOfShards(), is(NUMBER_OF_SHARDS)); + final CollectionPropertiesEntity properties = graph.db().collection(EDGE_COL_3).getProperties(); + assertThat(properties.getReplicationFactor()).isEqualTo(REPLICATION_FACTOR); + assertThat(properties.getNumberOfShards()).isEqualTo(NUMBER_OF_SHARDS); } // revert graph.removeEdgeDefinition(EDGE_COL_3); } - @Test - public void addSatelliteEdgeDefinition() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void addSatelliteEdgeDefinition(ArangoDatabase db) { assumeTrue(isCluster()); assumeTrue(isEnterprise()); assumeTrue(isAtLeastVersion(3, 9)); @@ -259,37 +232,38 @@ public void addSatelliteEdgeDefinition() { g.create(Collections.emptyList(), new GraphCreateOptions().isSmart(true).smartGraphAttribute("test")); g.addEdgeDefinition(ed); final GraphEntity ge = g.getInfo(); - assertThat(ge, is(notNullValue())); + assertThat(ge).isNotNull(); final Collection edgeDefinitions = ge.getEdgeDefinitions(); - assertThat(edgeDefinitions.size(), is(1)); + assertThat(edgeDefinitions).hasSize(1); EdgeDefinition e = edgeDefinitions.iterator().next(); - assertThat(e.getCollection(), is(eName)); - assertThat(e.getFrom(), hasItem(v1Name)); - assertThat(e.getTo(), hasItem(v2Name)); + assertThat(e.getCollection()).isEqualTo(eName); + assertThat(e.getFrom()).contains(v1Name); + assertThat(e.getTo()).contains(v2Name); - assertThat(db.collection(v1Name).getProperties().getSatellite(), is(true)); + assertThat(db.collection(v1Name).getProperties().getSatellite()).isTrue(); // revert g.drop(); } - @Test - public void replaceEdgeDefinition() { + @ParameterizedTest(name = "{index}") + @MethodSource("graphs") + void replaceEdgeDefinition(ArangoGraph graph) { final GraphEntity g = graph .replaceEdgeDefinition(new EdgeDefinition().collection(EDGE_COL_1).from(VERTEX_COL_3).to(VERTEX_COL_4)); final Collection edgeDefinitions = g.getEdgeDefinitions(); - assertThat(edgeDefinitions.size(), is(2)); + assertThat(edgeDefinitions).hasSize(2); int count = 0; for (final EdgeDefinition e : edgeDefinitions) { if (e.getCollection().equals(EDGE_COL_1)) { count++; } } - assertThat(count, is(1)); + assertThat(count).isEqualTo(1); for (final EdgeDefinition e : edgeDefinitions) { if (e.getCollection().equals(EDGE_COL_1)) { - assertThat(e.getFrom(), hasItem(VERTEX_COL_3)); - assertThat(e.getTo(), hasItem(VERTEX_COL_4)); + assertThat(e.getFrom()).contains(VERTEX_COL_3); + assertThat(e.getTo()).contains(VERTEX_COL_4); } } @@ -299,19 +273,21 @@ public void replaceEdgeDefinition() { graph.addEdgeDefinition(ed1); } - @Test - public void removeEdgeDefinition() { + @ParameterizedTest(name = "{index}") + @MethodSource("graphs") + void removeEdgeDefinition(ArangoGraph graph) { final GraphEntity g = graph.removeEdgeDefinition(EDGE_COL_1); final Collection edgeDefinitions = g.getEdgeDefinitions(); - assertThat(edgeDefinitions.size(), is(1)); - assertThat(edgeDefinitions.iterator().next().getCollection(), is(EDGE_COL_2)); + assertThat(edgeDefinitions).hasSize(1); + assertThat(edgeDefinitions.iterator().next().getCollection()).isEqualTo(EDGE_COL_2); //revert graph.addEdgeDefinition(ed1); } - @Test - public void smartGraph() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void smartGraph(ArangoDatabase db) { assumeTrue(isEnterprise()); assumeTrue(isCluster()); @@ -321,14 +297,15 @@ public void smartGraph() { String graphId = GRAPH_NAME + rnd(); final GraphEntity g = db.createGraph(graphId, edgeDefinitions, new GraphCreateOptions().isSmart(true).smartGraphAttribute("test").numberOfShards(2)); - assertThat(g, is(notNullValue())); - assertThat(g.getIsSmart(), is(true)); - assertThat(g.getSmartGraphAttribute(), is("test")); - assertThat(g.getNumberOfShards(), is(2)); + assertThat(g).isNotNull(); + assertThat(g.getIsSmart()).isTrue(); + assertThat(g.getSmartGraphAttribute()).isEqualTo("test"); + assertThat(g.getNumberOfShards()).isEqualTo(2); } - @Test - public void hybridSmartGraph() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void hybridSmartGraph(ArangoDatabase db) { assumeTrue(isEnterprise()); assumeTrue(isCluster()); assumeTrue((isAtLeastVersion(3, 9))); @@ -344,18 +321,19 @@ public void hybridSmartGraph() { .satellites(eName, v1Name) .isSmart(true).smartGraphAttribute("test").replicationFactor(2).numberOfShards(2)); - assertThat(g, is(notNullValue())); - assertThat(g.getIsSmart(), is(true)); - assertThat(g.getSmartGraphAttribute(), is("test")); - assertThat(g.getNumberOfShards(), is(2)); + assertThat(g).isNotNull(); + assertThat(g.getIsSmart()).isTrue(); + assertThat(g.getSmartGraphAttribute()).isEqualTo("test"); + assertThat(g.getNumberOfShards()).isEqualTo(2); - assertThat(db.collection(eName).getProperties().getSatellite(), is(true)); - assertThat(db.collection(v1Name).getProperties().getSatellite(), is(true)); - assertThat(db.collection(v2Name).getProperties().getReplicationFactor(), is(2)); + assertThat(db.collection(eName).getProperties().getSatellite()).isTrue(); + assertThat(db.collection(v1Name).getProperties().getSatellite()).isTrue(); + assertThat(db.collection(v2Name).getProperties().getReplicationFactor()).isEqualTo(2); } - @Test - public void disjointSmartGraph() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void disjointSmartGraph(ArangoDatabase db) { assumeTrue(isEnterprise()); assumeTrue(isCluster()); assumeTrue((isAtLeastVersion(3, 7))); @@ -367,15 +345,16 @@ public void disjointSmartGraph() { final GraphEntity g = db.createGraph(graphId, edgeDefinitions, new GraphCreateOptions() .isSmart(true).isDisjoint(true).smartGraphAttribute("test").numberOfShards(2)); - assertThat(g, is(notNullValue())); - assertThat(g.getIsSmart(), is(true)); - assertThat(g.getIsDisjoint(), is(true)); - assertThat(g.getSmartGraphAttribute(), is("test")); - assertThat(g.getNumberOfShards(), is(2)); + assertThat(g).isNotNull(); + assertThat(g.getIsSmart()).isTrue(); + assertThat(g.getIsDisjoint()).isTrue(); + assertThat(g.getSmartGraphAttribute()).isEqualTo("test"); + assertThat(g.getNumberOfShards()).isEqualTo(2); } - @Test - public void hybridDisjointSmartGraph() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void hybridDisjointSmartGraph(ArangoDatabase db) { assumeTrue(isEnterprise()); assumeTrue(isCluster()); assumeTrue((isAtLeastVersion(3, 9))); @@ -391,40 +370,42 @@ public void hybridDisjointSmartGraph() { .satellites(v1Name) .isSmart(true).isDisjoint(true).smartGraphAttribute("test").replicationFactor(2).numberOfShards(2)); - assertThat(g, is(notNullValue())); - assertThat(g.getIsSmart(), is(true)); - assertThat(g.getIsDisjoint(), is(true)); - assertThat(g.getSmartGraphAttribute(), is("test")); - assertThat(g.getNumberOfShards(), is(2)); + assertThat(g).isNotNull(); + assertThat(g.getIsSmart()).isTrue(); + assertThat(g.getIsDisjoint()).isTrue(); + assertThat(g.getSmartGraphAttribute()).isEqualTo("test"); + assertThat(g.getNumberOfShards()).isEqualTo(2); - assertThat(db.collection(v1Name).getProperties().getSatellite(), is(true)); - assertThat(db.collection(v2Name).getProperties().getReplicationFactor(), is(2)); + assertThat(db.collection(v1Name).getProperties().getSatellite()).isTrue(); + assertThat(db.collection(v2Name).getProperties().getReplicationFactor()).isEqualTo(2); } - @Test - public void drop() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void drop(ArangoDatabase db) { final String edgeCollection = "edge_" + rnd(); final String vertexCollection = "vertex_" + rnd(); final String graphId = GRAPH_NAME + rnd(); final GraphEntity result = db.graph(graphId).create(Collections .singleton(new EdgeDefinition().collection(edgeCollection).from(vertexCollection).to(vertexCollection))); - assertThat(result, is(notNullValue())); + assertThat(result).isNotNull(); db.graph(graphId).drop(); - assertThat(db.collection(edgeCollection).exists(), is(true)); - assertThat(db.collection(vertexCollection).exists(), is(true)); + assertThat(db.collection(edgeCollection).exists()).isTrue(); + assertThat(db.collection(vertexCollection).exists()).isTrue(); } - @Test - public void dropPlusDropCollections() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void dropPlusDropCollections(ArangoDatabase db) { final String edgeCollection = "edge_dropC" + rnd(); final String vertexCollection = "vertex_dropC" + rnd(); final String graphId = GRAPH_NAME + "_dropC" + rnd(); final GraphEntity result = db.graph(graphId).create(Collections .singleton(new EdgeDefinition().collection(edgeCollection).from(vertexCollection).to(vertexCollection))); - assertThat(result, is(notNullValue())); + assertThat(result).isNotNull(); db.graph(graphId).drop(true); - assertThat(db.collection(edgeCollection).exists(), is(false)); - assertThat(db.collection(vertexCollection).exists(), is(false)); + assertThat(db.collection(edgeCollection).exists()).isFalse(); + assertThat(db.collection(vertexCollection).exists()).isFalse(); } } diff --git a/src/test/java/com/arangodb/ArangoRouteTest.java b/src/test/java/com/arangodb/ArangoRouteTest.java index ce9a78de5..6bcd38f41 100644 --- a/src/test/java/com/arangodb/ArangoRouteTest.java +++ b/src/test/java/com/arangodb/ArangoRouteTest.java @@ -23,64 +23,55 @@ import com.arangodb.entity.BaseDocument; import com.arangodb.internal.ArangoRequestParam; import com.arangodb.velocystream.Response; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; /** * @author Mark Vollmary + * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class ArangoRouteTest extends BaseTest { +class ArangoRouteTest extends BaseJunit5 { private static final String COLLECTION_NAME = "ArangoRouteTest_collection"; - private final ArangoCollection collection; - @BeforeClass - public static void init() { - BaseTest.initCollections(COLLECTION_NAME); + @BeforeAll + static void init() { + initCollections(COLLECTION_NAME); } - public ArangoRouteTest(final ArangoDB arangoDB) { - super(arangoDB); - collection = db.collection(COLLECTION_NAME); - } - - @Test - public void get() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void get(ArangoDatabase db) { final Response res = db.route("/_api/version").get(); - assertThat(res.getBody().get("version").isString(), is(true)); + assertThat(res.getBody().get("version").isString()).isTrue(); } - @Test - public void withHeader() { - try { - final BaseDocument doc = new BaseDocument(); - collection.insertDocument(doc); - db.route("/_api/document", doc.getId()).withHeader(ArangoRequestParam.IF_NONE_MATCH, doc.getRevision()) - .get(); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(304)); - } + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void withHeader(ArangoDatabase db) { + final BaseDocument doc = new BaseDocument(); + db.collection(COLLECTION_NAME).insertDocument(doc); + Throwable thrown = catchThrowable(() -> + db.route("/_api/document", doc.getId()).withHeader(ArangoRequestParam.IF_NONE_MATCH, doc.getRevision()).get()); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(304); } - @Test - public void withParentHeader() { - try { - final BaseDocument doc = new BaseDocument(); - collection.insertDocument(doc); - db.route("/_api/document").withHeader(ArangoRequestParam.IF_NONE_MATCH, doc.getRevision()) - .route(doc.getId()).get(); - fail(); - } catch (final ArangoDBException e) { - assertThat(e.getResponseCode(), is(304)); - } + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void withParentHeader(ArangoDatabase db) { + final BaseDocument doc = new BaseDocument(); + db.collection(COLLECTION_NAME).insertDocument(doc); + Throwable thrown = catchThrowable(() -> + db.route("/_api/document").withHeader(ArangoRequestParam.IF_NONE_MATCH, doc.getRevision()).route(doc.getId()).get()); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(304); } } diff --git a/src/test/java/com/arangodb/ArangoSearchTest.java b/src/test/java/com/arangodb/ArangoSearchTest.java index 75d49f19d..173c0a47e 100644 --- a/src/test/java/com/arangodb/ArangoSearchTest.java +++ b/src/test/java/com/arangodb/ArangoSearchTest.java @@ -22,128 +22,111 @@ import com.arangodb.entity.ViewEntity; import com.arangodb.entity.ViewType; -import com.arangodb.entity.arangosearch.AnalyzerEntity; -import com.arangodb.entity.arangosearch.AnalyzerFeature; -import com.arangodb.entity.arangosearch.AnalyzerType; -import com.arangodb.entity.arangosearch.ArangoSearchCompression; -import com.arangodb.entity.arangosearch.ArangoSearchPropertiesEntity; -import com.arangodb.entity.arangosearch.CollectionLink; -import com.arangodb.entity.arangosearch.ConsolidationPolicy; -import com.arangodb.entity.arangosearch.ConsolidationType; -import com.arangodb.entity.arangosearch.FieldLink; -import com.arangodb.entity.arangosearch.PrimarySort; -import com.arangodb.entity.arangosearch.StoreValuesType; -import com.arangodb.entity.arangosearch.StoredValue; +import com.arangodb.entity.arangosearch.*; import com.arangodb.entity.arangosearch.analyzer.*; import com.arangodb.model.arangosearch.AnalyzerDeleteOptions; import com.arangodb.model.arangosearch.ArangoSearchCreateOptions; import com.arangodb.model.arangosearch.ArangoSearchPropertiesOptions; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Mark Vollmary + * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class ArangoSearchTest extends BaseTest { +class ArangoSearchTest extends BaseJunit5 { private static final String COLL_1 = "ArangoSearchTest_view_replace_prop"; private static final String COLL_2 = "ArangoSearchTest_view_update_prop"; - @BeforeClass - public static void init() { - BaseTest.initCollections(COLL_1, COLL_2); - } - - public ArangoSearchTest(final ArangoDB arangoDB) { - super(arangoDB); + @BeforeAll + static void init() { + initCollections(COLL_1, COLL_2); } - @Test - public void exists() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void exists(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); String viewName = "view-" + rnd(); db.createArangoSearch(viewName, new ArangoSearchCreateOptions()); - assertThat(db.arangoSearch(viewName).exists(), is(true)); + assertThat(db.arangoSearch(viewName).exists()).isTrue(); } - @Test - public void getInfo() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getInfo(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); String viewName = "view-" + rnd(); db.createArangoSearch(viewName, new ArangoSearchCreateOptions()); final ViewEntity info = db.arangoSearch(viewName).getInfo(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(viewName)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(viewName); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); } - @Test - public void drop() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void drop(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); String viewName = "view-" + rnd(); db.createArangoSearch(viewName, new ArangoSearchCreateOptions()); final ArangoView view = db.arangoSearch(viewName); view.drop(); - assertThat(view.exists(), is(false)); + assertThat(view.exists()).isFalse(); } - @Test - public void rename() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void rename(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 4)); String viewName = "view-" + rnd(); final String name = viewName + "_new"; db.createArangoSearch(name, new ArangoSearchCreateOptions()); db.arangoSearch(name).rename(viewName); - assertThat(db.arangoSearch(name).exists(), is(false)); - assertThat(db.arangoSearch(viewName).exists(), is(true)); + assertThat(db.arangoSearch(name).exists()).isFalse(); + assertThat(db.arangoSearch(viewName).exists()).isTrue(); } - @Test - public void create() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void create(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); String viewName = "view-" + rnd(); final ViewEntity info = db.arangoSearch(viewName).create(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(viewName)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(viewName).exists(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(viewName); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); + assertThat(db.arangoSearch(viewName).exists()).isTrue(); } - @Test - public void createWithOptions() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createWithOptions(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); String viewName = "view-" + rnd(); final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); final ViewEntity info = db.arangoSearch(viewName).create(options); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(viewName)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(viewName).exists(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(viewName); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); + assertThat(db.arangoSearch(viewName).exists()).isTrue(); } - @Test - public void createWithPrimarySort() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createWithPrimarySort(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); String viewName = "view-" + rnd(); final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); @@ -158,66 +141,69 @@ public void createWithPrimarySort() { final ArangoSearch view = db.arangoSearch(viewName); final ViewEntity info = view.create(options); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(viewName)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(viewName).exists(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(viewName); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); + assertThat(db.arangoSearch(viewName).exists()).isTrue(); if (isAtLeastVersion(3, 7)) { final ArangoSearchPropertiesEntity properties = view.getProperties(); - assertThat(properties.getPrimarySortCompression(), is(ArangoSearchCompression.none)); + assertThat(properties.getPrimarySortCompression()).isEqualTo(ArangoSearchCompression.none); Collection retrievedStoredValues = properties.getStoredValues(); - assertThat(retrievedStoredValues, is(notNullValue())); - assertThat(retrievedStoredValues.size(), is(1)); + assertThat(retrievedStoredValues).isNotNull(); + assertThat(retrievedStoredValues).hasSize(1); StoredValue retrievedStoredValue = retrievedStoredValues.iterator().next(); - assertThat(retrievedStoredValue, is(notNullValue())); - assertThat(retrievedStoredValue.getFields(), is(storedValue.getFields())); - assertThat(retrievedStoredValue.getCompression(), is(storedValue.getCompression())); + assertThat(retrievedStoredValue).isNotNull(); + assertThat(retrievedStoredValue.getFields()).isEqualTo(storedValue.getFields()); + assertThat(retrievedStoredValue.getCompression()).isEqualTo(storedValue.getCompression()); } } - @Test - public void createWithCommitIntervalMsec() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createWithCommitIntervalMsec(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); String viewName = "view-" + rnd(); final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); options.commitIntervalMsec(666666L); final ViewEntity info = db.arangoSearch(viewName).create(options); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(viewName)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(viewName).exists(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(viewName); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); + assertThat(db.arangoSearch(viewName).exists()).isTrue(); // check commit interval msec property final ArangoSearch view = db.arangoSearch(viewName); final ArangoSearchPropertiesEntity properties = view.getProperties(); - assertThat(properties.getCommitIntervalMsec(), is(666666L)); + assertThat(properties.getCommitIntervalMsec()).isEqualTo(666666L); } - @Test - public void getProperties() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getProperties(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); String viewName = "view-" + rnd(); final ArangoSearch view = db.arangoSearch(viewName); view.create(new ArangoSearchCreateOptions()); final ArangoSearchPropertiesEntity properties = view.getProperties(); - assertThat(properties, is(not(nullValue()))); - assertThat(properties.getId(), is(not(nullValue()))); - assertThat(properties.getName(), is(viewName)); - assertThat(properties.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(properties.getConsolidationIntervalMsec(), is(not(nullValue()))); - assertThat(properties.getCleanupIntervalStep(), is(not(nullValue()))); + assertThat(properties).isNotNull(); + assertThat(properties.getId()).isNotNull(); + assertThat(properties.getName()).isEqualTo(viewName); + assertThat(properties.getType()).isEqualTo(ViewType.ARANGO_SEARCH); + assertThat(properties.getConsolidationIntervalMsec()).isNotNull(); + assertThat(properties.getCleanupIntervalStep()).isNotNull(); final ConsolidationPolicy consolidate = properties.getConsolidationPolicy(); - assertThat(consolidate, is(is(not(nullValue())))); + assertThat(consolidate).isNotNull(); final Collection links = properties.getLinks(); - assertThat(links.isEmpty(), is(true)); + assertThat(links).isEmpty(); } - @Test - public void updateProperties() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void updateProperties(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); String viewName = "view-" + rnd(); final ArangoSearch view = db.arangoSearch(viewName); @@ -230,26 +216,27 @@ public void updateProperties() { .fields(FieldLink.on("value").analyzers("identity").trackListPositions(true).includeAllFields(true) .storeValues(StoreValuesType.ID))); final ArangoSearchPropertiesEntity properties = view.updateProperties(options); - assertThat(properties, is(not(nullValue()))); - assertThat(properties.getCleanupIntervalStep(), is(15L)); - assertThat(properties.getConsolidationIntervalMsec(), is(65000L)); + assertThat(properties).isNotNull(); + assertThat(properties.getCleanupIntervalStep()).isEqualTo(15L); + assertThat(properties.getConsolidationIntervalMsec()).isEqualTo(65000L); final ConsolidationPolicy consolidate = properties.getConsolidationPolicy(); - assertThat(consolidate, is(not(nullValue()))); - assertThat(consolidate.getType(), is(ConsolidationType.BYTES_ACCUM)); - assertThat(consolidate.getThreshold(), is(1.)); - assertThat(properties.getLinks().size(), is(1)); + assertThat(consolidate).isNotNull(); + assertThat(consolidate.getType()).isEqualTo(ConsolidationType.BYTES_ACCUM); + assertThat(consolidate.getThreshold()).isEqualTo(1.); + assertThat(properties.getLinks()).hasSize(1); final CollectionLink link = properties.getLinks().iterator().next(); - assertThat(link.getName(), is(COLL_2)); - assertThat(link.getFields().size(), is(1)); + assertThat(link.getName()).isEqualTo(COLL_2); + assertThat(link.getFields()).hasSize(1); final FieldLink next = link.getFields().iterator().next(); - assertThat(next.getName(), is("value")); - assertThat(next.getIncludeAllFields(), is(true)); - assertThat(next.getTrackListPositions(), is(true)); - assertThat(next.getStoreValues(), is(StoreValuesType.ID)); + assertThat(next.getName()).isEqualTo("value"); + assertThat(next.getIncludeAllFields()).isTrue(); + assertThat(next.getTrackListPositions()).isTrue(); + assertThat(next.getStoreValues()).isEqualTo(StoreValuesType.ID); } - @Test - public void replaceProperties() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void replaceProperties(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); String viewName = "view-" + rnd(); final ArangoSearch view = db.arangoSearch(viewName); @@ -258,31 +245,31 @@ public void replaceProperties() { options.link(CollectionLink.on(COLL_1) .fields(FieldLink.on("value").analyzers("identity"))); final ArangoSearchPropertiesEntity properties = view.replaceProperties(options); - assertThat(properties, is(not(nullValue()))); - assertThat(properties.getLinks().size(), is(1)); + assertThat(properties).isNotNull(); + assertThat(properties.getLinks()).hasSize(1); final CollectionLink link = properties.getLinks().iterator().next(); - assertThat(link.getName(), is(COLL_1)); - assertThat(link.getFields().size(), is(1)); - assertThat(link.getFields().iterator().next().getName(), is("value")); + assertThat(link.getName()).isEqualTo(COLL_1); + assertThat(link.getFields()).hasSize(1); + assertThat(link.getFields().iterator().next().getName()).isEqualTo("value"); } - private void createGetAndDeleteAnalyzer(AnalyzerEntity options) { + private void createGetAndDeleteAnalyzer(ArangoDatabase db, AnalyzerEntity options) { String fullyQualifiedName = db.dbName().get() + "::" + options.getName(); // createAnalyzer AnalyzerEntity createdAnalyzer = db.createAnalyzer(options); - assertThat(createdAnalyzer.getName(), is(fullyQualifiedName)); - assertThat(createdAnalyzer.getType(), is(options.getType())); - assertThat(createdAnalyzer.getFeatures(), is(options.getFeatures())); + assertThat(createdAnalyzer.getName()).isEqualTo(fullyQualifiedName); + assertThat(createdAnalyzer.getType()).isEqualTo(options.getType()); + assertThat(createdAnalyzer.getFeatures()).isEqualTo(options.getFeatures()); compareProperties(createdAnalyzer.getProperties(), options.getProperties()); // getAnalyzer AnalyzerEntity gotAnalyzer = db.getAnalyzer(options.getName()); - assertThat(gotAnalyzer.getName(), is(fullyQualifiedName)); - assertThat(gotAnalyzer.getType(), is(options.getType())); - assertThat(gotAnalyzer.getFeatures(), is(options.getFeatures())); + assertThat(gotAnalyzer.getName()).isEqualTo(fullyQualifiedName); + assertThat(gotAnalyzer.getType()).isEqualTo(options.getType()); + assertThat(gotAnalyzer.getFeatures()).isEqualTo(options.getFeatures()); compareProperties(gotAnalyzer.getProperties(), options.getProperties()); // getAnalyzers @@ -290,9 +277,9 @@ private void createGetAndDeleteAnalyzer(AnalyzerEntity options) { AnalyzerEntity foundAnalyzer = db.getAnalyzers().stream().filter(it -> it.getName().equals(fullyQualifiedName)) .findFirst().get(); - assertThat(foundAnalyzer.getName(), is(fullyQualifiedName)); - assertThat(foundAnalyzer.getType(), is(options.getType())); - assertThat(foundAnalyzer.getFeatures(), is(options.getFeatures())); + assertThat(foundAnalyzer.getName()).isEqualTo(fullyQualifiedName); + assertThat(foundAnalyzer.getType()).isEqualTo(options.getType()); + assertThat(foundAnalyzer.getFeatures()).isEqualTo(options.getFeatures()); compareProperties(foundAnalyzer.getProperties(), options.getProperties()); AnalyzerDeleteOptions deleteOptions = new AnalyzerDeleteOptions(); @@ -301,33 +288,28 @@ private void createGetAndDeleteAnalyzer(AnalyzerEntity options) { // deleteAnalyzer db.deleteAnalyzer(options.getName(), deleteOptions); - try { - db.getAnalyzer(options.getName()); - fail("deleted analyzer should not be found!"); - } catch (ArangoDBException e) { - // ok - } - + Throwable thrown = catchThrowable(() -> db.getAnalyzer(options.getName())); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - private void createGetAndDeleteTypedAnalyzer(SearchAnalyzer analyzer) { + private void createGetAndDeleteTypedAnalyzer(ArangoDatabase db, SearchAnalyzer analyzer) { String fullyQualifiedName = db.dbName().get() + "::" + analyzer.getName(); analyzer.setName(fullyQualifiedName); // createAnalyzer SearchAnalyzer createdAnalyzer = db.createSearchAnalyzer(analyzer); - assertThat(createdAnalyzer, is(analyzer)); + assertThat(createdAnalyzer).isEqualTo(analyzer); // getAnalyzer SearchAnalyzer gotAnalyzer = db.getSearchAnalyzer(analyzer.getName()); - assertThat(gotAnalyzer, is(analyzer)); + assertThat(gotAnalyzer).isEqualTo(analyzer); // getAnalyzers @SuppressWarnings("OptionalGetWithoutIsPresent") SearchAnalyzer foundAnalyzer = db.getSearchAnalyzers().stream().filter(it -> it.getName().equals(fullyQualifiedName)) .findFirst().get(); - assertThat(foundAnalyzer, is(analyzer)); + assertThat(foundAnalyzer).isEqualTo(analyzer); // deleteAnalyzer AnalyzerDeleteOptions deleteOptions = new AnalyzerDeleteOptions(); @@ -335,33 +317,32 @@ private void createGetAndDeleteTypedAnalyzer(SearchAnalyzer analyzer) { db.deleteSearchAnalyzer(analyzer.getName(), deleteOptions); - try { - db.getAnalyzer(analyzer.getName()); - fail("deleted analyzer should not be found!"); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(404)); - assertThat(e.getErrorNum(), is(1202)); - } - + Throwable thrown = catchThrowable(() -> db.getAnalyzer(analyzer.getName())); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(404); + assertThat(e.getErrorNum()).isEqualTo(1202); } + @SuppressWarnings("unchecked") private void compareProperties(Map actualProperties, Map expectedProperties) { expectedProperties.forEach((key, expectedValue) -> { Object actualValue = actualProperties.get(key); if (expectedValue instanceof Map) { - assertThat(actualValue, notNullValue()); - assertThat(actualValue, instanceOf(Map.class)); - compareProperties((Map) actualValue, (Map) expectedValue); + assertThat(actualValue).isNotNull(); + assertThat(actualValue).isInstanceOf(Map.class); + compareProperties((Map) actualValue, (Map) expectedValue); } else if (expectedValue instanceof Number) { - assertThat(Double.valueOf(actualValue.toString()), is(Double.valueOf(expectedValue.toString()))); + assertThat(Double.valueOf(actualValue.toString())).isEqualTo(Double.valueOf(expectedValue.toString())); } else { - assertThat(actualValue, is(expectedValue)); + assertThat(actualValue).isEqualTo(expectedValue); } }); } - @Test - public void identityAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void identityAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + rnd(); @@ -377,14 +358,15 @@ public void identityAnalyzer() { options.setType(AnalyzerType.identity); options.setProperties(Collections.emptyMap()); - createGetAndDeleteAnalyzer(options); + createGetAndDeleteAnalyzer(db, options); } - @Test - public void identityAnalyzerTyped() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void identityAnalyzerTyped(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -395,11 +377,12 @@ public void identityAnalyzerTyped() { analyzer.setFeatures(features); analyzer.setName(name); - createGetAndDeleteTypedAnalyzer(analyzer); + createGetAndDeleteTypedAnalyzer(db, analyzer); } - @Test - public void delimiterAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void delimiterAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + rnd(); @@ -415,14 +398,15 @@ public void delimiterAnalyzer() { options.setType(AnalyzerType.delimiter); options.setProperties(Collections.singletonMap("delimiter", "-")); - createGetAndDeleteAnalyzer(options); + createGetAndDeleteAnalyzer(db, options); } - @Test - public void delimiterAnalyzerTyped() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void delimiterAnalyzerTyped(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -437,11 +421,12 @@ public void delimiterAnalyzerTyped() { analyzer.setName(name); analyzer.setProperties(properties); - createGetAndDeleteTypedAnalyzer(analyzer); + createGetAndDeleteTypedAnalyzer(db, analyzer); } - @Test - public void stemAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void stemAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + rnd(); @@ -457,14 +442,15 @@ public void stemAnalyzer() { options.setType(AnalyzerType.stem); options.setProperties(Collections.singletonMap("locale", "ru")); - createGetAndDeleteAnalyzer(options); + createGetAndDeleteAnalyzer(db, options); } - @Test - public void stemAnalyzerTyped() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void stemAnalyzerTyped(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -479,11 +465,12 @@ public void stemAnalyzerTyped() { options.setName(name); options.setProperties(properties); - createGetAndDeleteTypedAnalyzer(options); + createGetAndDeleteTypedAnalyzer(db, options); } - @Test - public void normAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void normAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + rnd(); @@ -504,14 +491,15 @@ public void normAnalyzer() { options.setType(AnalyzerType.norm); options.setProperties(properties); - createGetAndDeleteAnalyzer(options); + createGetAndDeleteAnalyzer(db, options); } - @Test - public void normAnalyzerTyped() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void normAnalyzerTyped(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -528,11 +516,12 @@ public void normAnalyzerTyped() { options.setName(name); options.setProperties(properties); - createGetAndDeleteTypedAnalyzer(options); + createGetAndDeleteTypedAnalyzer(db, options); } - @Test - public void ngramAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void ngramAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + rnd(); @@ -553,14 +542,15 @@ public void ngramAnalyzer() { options.setType(AnalyzerType.ngram); options.setProperties(properties); - createGetAndDeleteAnalyzer(options); + createGetAndDeleteAnalyzer(db, options); } - @Test - public void ngramAnalyzerTyped() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void ngramAnalyzerTyped(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -578,14 +568,15 @@ public void ngramAnalyzerTyped() { analyzer.setType(AnalyzerType.ngram); analyzer.setProperties(properties); - createGetAndDeleteTypedAnalyzer(analyzer); + createGetAndDeleteTypedAnalyzer(db, analyzer); } - @Test - public void enhancedNgramAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void enhancedNgramAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 6)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -606,14 +597,15 @@ public void enhancedNgramAnalyzer() { options.setType(AnalyzerType.ngram); options.setProperties(properties); - createGetAndDeleteAnalyzer(options); + createGetAndDeleteAnalyzer(db, options); } - @Test - public void enhancedNgramAnalyzerTyped() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void enhancedNgramAnalyzerTyped(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 6)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -633,11 +625,12 @@ public void enhancedNgramAnalyzerTyped() { analyzer.setName(name); analyzer.setProperties(properties); - createGetAndDeleteTypedAnalyzer(analyzer); + createGetAndDeleteTypedAnalyzer(db, analyzer); } - @Test - public void textAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void textAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); String name = "test-" + rnd(); @@ -660,14 +653,15 @@ public void textAnalyzer() { options.setType(AnalyzerType.text); options.setProperties(properties); - createGetAndDeleteAnalyzer(options); + createGetAndDeleteAnalyzer(db, options); } - @Test - public void textAnalyzerTyped() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void textAnalyzerTyped(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -686,14 +680,15 @@ public void textAnalyzerTyped() { analyzer.setType(AnalyzerType.text); analyzer.setProperties(properties); - createGetAndDeleteTypedAnalyzer(analyzer); + createGetAndDeleteTypedAnalyzer(db, analyzer); } - @Test - public void enhancedTextAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void enhancedTextAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 6)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -719,14 +714,15 @@ public void enhancedTextAnalyzer() { options.setType(AnalyzerType.text); options.setProperties(properties); - createGetAndDeleteAnalyzer(options); + createGetAndDeleteAnalyzer(db, options); } - @Test - public void enhancedTextAnalyzerTyped() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void enhancedTextAnalyzerTyped(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 6)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -750,11 +746,12 @@ public void enhancedTextAnalyzerTyped() { analyzer.setName(name); analyzer.setProperties(properties); - createGetAndDeleteTypedAnalyzer(analyzer); + createGetAndDeleteTypedAnalyzer(db, analyzer); } - @Test - public void arangoSearchOptions() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void arangoSearchOptions(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 4)); String viewName = "view-" + rnd(); ArangoSearchCreateOptions options = new ArangoSearchCreateOptions() @@ -775,21 +772,22 @@ public void arangoSearchOptions() { view.create(options); final ArangoSearchPropertiesEntity properties = view.getProperties(); - assertThat(properties, is(not(nullValue()))); - assertThat(properties.getId(), is(not(nullValue()))); - assertThat(properties.getName(), is(viewName)); - assertThat(properties.getType(), is(ViewType.ARANGO_SEARCH)); + assertThat(properties).isNotNull(); + assertThat(properties.getId()).isNotNull(); + assertThat(properties.getName()).isEqualTo(viewName); + assertThat(properties.getType()).isEqualTo(ViewType.ARANGO_SEARCH); CollectionLink link = properties.getLinks().iterator().next(); - assertThat(link.getAnalyzers(), contains("identity")); - assertThat(link.getName(), is(COLL_1)); - assertThat(link.getIncludeAllFields(), is(true)); - assertThat(link.getStoreValues(), is(StoreValuesType.ID)); - assertThat(link.getTrackListPositions(), is(false)); + assertThat(link.getAnalyzers()).contains("identity"); + assertThat(link.getName()).isEqualTo(COLL_1); + assertThat(link.getIncludeAllFields()).isTrue(); + assertThat(link.getStoreValues()).isEqualTo(StoreValuesType.ID); + assertThat(link.getTrackListPositions()).isFalse(); } - @Test - public void pipelineAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void pipelineAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 8)); // comma delimiter @@ -825,15 +823,16 @@ public void pipelineAnalyzer() { .addAnalyzer(stemAnalyzer); PipelineAnalyzer pipelineAnalyzer = new PipelineAnalyzer(); - pipelineAnalyzer.setName("test-" + UUID.randomUUID().toString()); + pipelineAnalyzer.setName("test-" + UUID.randomUUID()); pipelineAnalyzer.setProperties(properties); pipelineAnalyzer.setFeatures(features); - createGetAndDeleteTypedAnalyzer(pipelineAnalyzer); + createGetAndDeleteTypedAnalyzer(db, pipelineAnalyzer); } - @Test - public void stopwordsAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void stopwordsAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 8)); Set features = new HashSet<>(); @@ -845,25 +844,26 @@ public void stopwordsAnalyzer() { .addStopwordAsHex("616e64") .addStopwordAsString("the"); - assertThat(properties.getStopwordsAsStringList(), hasItem("and")); - assertThat(properties.getStopwordsAsHexList(), hasItem("746865")); + assertThat(properties.getStopwordsAsStringList()).contains("and"); + assertThat(properties.getStopwordsAsHexList()).contains("746865"); StopwordsAnalyzer analyzer = new StopwordsAnalyzer(); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); analyzer.setName(name); analyzer.setProperties(properties); analyzer.setFeatures(features); - createGetAndDeleteTypedAnalyzer(analyzer); + createGetAndDeleteTypedAnalyzer(db, analyzer); db.createSearchAnalyzer(analyzer); String res = db.query("RETURN FLATTEN(TOKENS(SPLIT('the fox and the dog and a theater', ' '), @aName))", Collections.singletonMap("aName", name), String.class).next(); - assertThat(res, is("[\"fox\",\"dog\",\"a\",\"theater\"]")); + assertThat(res).isEqualTo("[\"fox\",\"dog\",\"a\",\"theater\"]"); db.deleteSearchAnalyzer(name); } - @Test - public void aqlAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void aqlAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 8)); AQLAnalyzerProperties properties = new AQLAnalyzerProperties(); @@ -880,15 +880,16 @@ public void aqlAnalyzer() { features.add(AnalyzerFeature.position); AQLAnalyzer aqlAnalyzer = new AQLAnalyzer(); - aqlAnalyzer.setName("test-" + UUID.randomUUID().toString()); + aqlAnalyzer.setName("test-" + UUID.randomUUID()); aqlAnalyzer.setProperties(properties); aqlAnalyzer.setFeatures(features); - createGetAndDeleteTypedAnalyzer(aqlAnalyzer); + createGetAndDeleteTypedAnalyzer(db, aqlAnalyzer); } - @Test - public void geoJsonAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void geoJsonAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 8)); GeoAnalyzerOptions options = new GeoAnalyzerOptions(); @@ -906,16 +907,17 @@ public void geoJsonAnalyzer() { features.add(AnalyzerFeature.position); GeoJSONAnalyzer geoJSONAnalyzer = new GeoJSONAnalyzer(); - geoJSONAnalyzer.setName("test-" + UUID.randomUUID().toString()); + geoJSONAnalyzer.setName("test-" + UUID.randomUUID()); geoJSONAnalyzer.setProperties(properties); geoJSONAnalyzer.setFeatures(features); - createGetAndDeleteTypedAnalyzer(geoJSONAnalyzer); + createGetAndDeleteTypedAnalyzer(db, geoJSONAnalyzer); } - @Test - public void geoPointAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void geoPointAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 8)); GeoAnalyzerOptions options = new GeoAnalyzerOptions(); @@ -934,16 +936,17 @@ public void geoPointAnalyzer() { features.add(AnalyzerFeature.position); GeoPointAnalyzer geoPointAnalyzer = new GeoPointAnalyzer(); - geoPointAnalyzer.setName("test-" + UUID.randomUUID().toString()); + geoPointAnalyzer.setName("test-" + UUID.randomUUID()); geoPointAnalyzer.setProperties(properties); geoPointAnalyzer.setFeatures(features); - createGetAndDeleteTypedAnalyzer(geoPointAnalyzer); + createGetAndDeleteTypedAnalyzer(db, geoPointAnalyzer); } - @Test - public void segmentationAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void segmentationAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 9)); SegmentationAnalyzerProperties properties = new SegmentationAnalyzerProperties(); @@ -956,15 +959,16 @@ public void segmentationAnalyzer() { features.add(AnalyzerFeature.position); SegmentationAnalyzer segmentationAnalyzer = new SegmentationAnalyzer(); - segmentationAnalyzer.setName("test-" + UUID.randomUUID().toString()); + segmentationAnalyzer.setName("test-" + UUID.randomUUID()); segmentationAnalyzer.setProperties(properties); segmentationAnalyzer.setFeatures(features); - createGetAndDeleteTypedAnalyzer(segmentationAnalyzer); + createGetAndDeleteTypedAnalyzer(db, segmentationAnalyzer); } - @Test - public void collationAnalyzer() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void collationAnalyzer(ArangoDatabase db) { assumeTrue(isAtLeastVersion(3, 9)); CollationAnalyzerProperties properties = new CollationAnalyzerProperties(); @@ -976,11 +980,11 @@ public void collationAnalyzer() { features.add(AnalyzerFeature.position); CollationAnalyzer collationAnalyzer = new CollationAnalyzer(); - collationAnalyzer.setName("test-" + UUID.randomUUID().toString()); + collationAnalyzer.setName("test-" + UUID.randomUUID()); collationAnalyzer.setProperties(properties); collationAnalyzer.setFeatures(features); - createGetAndDeleteTypedAnalyzer(collationAnalyzer); + createGetAndDeleteTypedAnalyzer(db, collationAnalyzer); } diff --git a/src/test/java/com/arangodb/ArangoSslTest.java b/src/test/java/com/arangodb/ArangoSslTest.java index 1c8af8074..613f1632c 100644 --- a/src/test/java/com/arangodb/ArangoSslTest.java +++ b/src/test/java/com/arangodb/ArangoSslTest.java @@ -21,8 +21,9 @@ package com.arangodb; import com.arangodb.entity.ArangoDBVersion; -import org.junit.Ignore; -import org.junit.Test; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; @@ -31,16 +32,18 @@ import java.security.KeyStore; import java.util.List; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + /** * @author Mark Vollmary + * @author Michele Rastelli */ -public class ArangoSslTest { +@EnabledIfSystemProperty(named = "SslTest", matches = "true") +class ArangoSslTest { - /*- + /* * a SSL trust store * * create the trust store for the self signed certificate: @@ -53,8 +56,7 @@ public class ArangoSslTest { private static final String SSL_TRUSTSTORE_PASSWORD = "12345678"; @Test - @Ignore - public void connect() throws Exception { + void connect() throws Exception { final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray()); @@ -69,25 +71,22 @@ public void connect() throws Exception { final ArangoDB arangoDB = new ArangoDB.Builder() .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) - .sslContext(sc).build(); + .sslContext(sc).serializer(new ArangoJack()).build(); final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); + assertThat(version).isNotNull(); } @Test - @Ignore - public void connectWithoutValidSslContext() { - try { - final ArangoDB arangoDB = new ArangoDB.Builder() - .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) - .build(); - arangoDB.getVersion(); - fail("this should fail"); - } catch (final ArangoDBException ex) { - assertThat(ex.getCause(), is(instanceOf(ArangoDBMultipleException.class))); - List exceptions = ((ArangoDBMultipleException) ex.getCause()).getExceptions(); - exceptions.forEach(e -> assertThat(e, is(instanceOf(SSLHandshakeException.class)))); - } + void connectWithoutValidSslContext() { + final ArangoDB arangoDB = new ArangoDB.Builder() + .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) + .serializer(new ArangoJack()).build(); + Throwable thrown = catchThrowable(arangoDB::getVersion); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException ex = (ArangoDBException) thrown; + assertThat(ex.getCause()).isInstanceOf(ArangoDBMultipleException.class); + List exceptions = ((ArangoDBMultipleException) ex.getCause()).getExceptions(); + exceptions.forEach(e -> assertThat(e).isInstanceOf(SSLHandshakeException.class)); } } diff --git a/src/test/java/com/arangodb/ArangoVertexCollectionTest.java b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java index f46803098..84283f19f 100644 --- a/src/test/java/com/arangodb/ArangoVertexCollectionTest.java +++ b/src/test/java/com/arangodb/ArangoVertexCollectionTest.java @@ -24,76 +24,74 @@ import com.arangodb.entity.VertexEntity; import com.arangodb.entity.VertexUpdateEntity; import com.arangodb.model.*; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Collection; import java.util.Collections; import java.util.UUID; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; /** * @author Mark Vollmary + * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class ArangoVertexCollectionTest extends BaseTest { +class ArangoVertexCollectionTest extends BaseJunit5 { private static final String GRAPH_NAME = "ArangoVertexCollectionTest_graph"; private static final String COLLECTION_NAME = "ArangoVertexCollectionTest_vertex_collection"; - private final ArangoGraph graph; - private final ArangoCollection collection; - private final ArangoVertexCollection vertices; + private static Stream vertices() { + return dbsStream() + .map(db -> db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME)) + .map(Arguments::of); + } - @BeforeClass - public static void init() { - BaseTest.initCollections(COLLECTION_NAME); - BaseTest.initGraph( + @BeforeAll + static void init() { + initCollections(COLLECTION_NAME); + initGraph( GRAPH_NAME, null, new GraphCreateOptions().orphanCollections(COLLECTION_NAME) ); } - public ArangoVertexCollectionTest(final ArangoDB arangoDB) { - super(arangoDB); - collection = db.collection(COLLECTION_NAME); - graph = db.graph(GRAPH_NAME); - vertices = graph.vertexCollection(COLLECTION_NAME); - } - - @Test - public void dropVertexCollection() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void dropVertexCollection(ArangoVertexCollection vertices) { + ArangoGraph graph = vertices.graph(); vertices.drop(); final Collection vertexCollections = graph.getVertexCollections(); - assertThat(vertexCollections, not(hasItem(COLLECTION_NAME))); + assertThat(vertexCollections).isEmpty(); // revert graph.addVertexCollection(COLLECTION_NAME); } - @Test - public void insertVertex() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void insertVertex(ArangoVertexCollection vertices) { final VertexEntity vertex = vertices .insertVertex(new BaseDocument(), null); - assertThat(vertex, is(notNullValue())); + assertThat(vertex).isNotNull(); + ArangoCollection collection = vertices.graph().db().collection(vertices.name()); final BaseDocument document = collection .getDocument(vertex.getKey(), BaseDocument.class, null); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(vertex.getKey()); } - @Test - public void insertVertexViolatingUniqueConstraint() { - // FIXME: remove once fix is backported to 3.4 - assumeTrue(isAtLeastVersion(3, 5)); - + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void insertVertexViolatingUniqueConstraint(ArangoVertexCollection vertices) { + ArangoCollection collection = vertices.graph().db().collection(vertices.name()); collection .ensureSkiplistIndex(Collections.singletonList("field"), new SkiplistIndexOptions().unique(true).sparse(true)); @@ -102,18 +100,17 @@ public void insertVertexViolatingUniqueConstraint() { try { vertices.insertVertex("{\"field\": 99}", null); } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(409)); - assertThat(e.getErrorNum(), is(1210)); + assertThat(e.getResponseCode()).isEqualTo(409); + assertThat(e.getErrorNum()).isEqualTo(1210); } // revert vertices.deleteVertex(inserted.getKey()); } - @Test - public void duplicateInsertSameObjectVertex() { - - final ArangoVertexCollection vertexCollection = vertices; + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void duplicateInsertSameObjectVertex(ArangoVertexCollection vertices) { // ######################################################### // Create a new BaseDocument @@ -124,77 +121,84 @@ public void duplicateInsertSameObjectVertex() { bd.setKey(uuid.toString()); bd.addAttribute("name", "Paul"); - vertexCollection.insertVertex(bd); + vertices.insertVertex(bd); UUID uuid2 = UUID.randomUUID(); BaseDocument bd2 = new BaseDocument(); bd2.setKey(uuid2.toString()); bd2.addAttribute("name", "Paul"); - vertexCollection.insertVertex(bd2); + vertices.insertVertex(bd2); } - @Test - public void insertVertexUpdateRev() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void insertVertexUpdateRev(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); final VertexEntity vertex = vertices.insertVertex(doc, null); - assertThat(doc.getRevision(), is(vertex.getRev())); + assertThat(doc.getRevision()).isEqualTo(vertex.getRev()); } - @Test - public void getVertex() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void getVertex(ArangoVertexCollection vertices) { final VertexEntity vertex = vertices .insertVertex(new BaseDocument(), null); final BaseDocument document = vertices .getVertex(vertex.getKey(), BaseDocument.class, null); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(vertex.getKey()); } - @Test - public void getVertexIfMatch() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void getVertexIfMatch(ArangoVertexCollection vertices) { final VertexEntity vertex = vertices .insertVertex(new BaseDocument(), null); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch(vertex.getRev()); final BaseDocument document = vertices .getVertex(vertex.getKey(), BaseDocument.class, options); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(vertex.getKey()); } - @Test - public void getVertexIfMatchFail() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void getVertexIfMatchFail(ArangoVertexCollection vertices) { final VertexEntity vertex = vertices .insertVertex(new BaseDocument(), null); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch("no"); final BaseDocument vertex2 = vertices .getVertex(vertex.getKey(), BaseDocument.class, options); - assertThat(vertex2, is(nullValue())); + assertThat(vertex2).isNull(); } - @Test - public void getVertexIfNoneMatch() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void getVertexIfNoneMatch(ArangoVertexCollection vertices) { final VertexEntity vertex = vertices .insertVertex(new BaseDocument(), null); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch("no"); final BaseDocument document = vertices .getVertex(vertex.getKey(), BaseDocument.class, options); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(vertex.getKey()); } - @Test - public void getVertexIfNoneMatchFail() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void getVertexIfNoneMatchFail(ArangoVertexCollection vertices) { final VertexEntity vertex = vertices .insertVertex(new BaseDocument(), null); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch(vertex.getRev()); final BaseDocument vertex2 = vertices .getVertex(vertex.getKey(), BaseDocument.class, options); - assertThat(vertex2, is(nullValue())); + assertThat(vertex2).isNull(); } - @Test - public void replaceVertex() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void replaceVertex(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final VertexEntity createResult = vertices @@ -203,33 +207,35 @@ public void replaceVertex() { doc.addAttribute("b", "test"); final VertexUpdateEntity replaceResult = vertices .replaceVertex(createResult.getKey(), doc, null); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = vertices .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } - @Test - public void replaceVertexUpdateRev() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void replaceVertexUpdateRev(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); final VertexEntity createResult = vertices .insertVertex(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); + assertThat(doc.getRevision()).isEqualTo(createResult.getRev()); final VertexUpdateEntity replaceResult = vertices .replaceVertex(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(replaceResult.getRev())); + assertThat(doc.getRevision()).isEqualTo(replaceResult.getRev()); } - @Test - public void replaceVertexIfMatch() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void replaceVertexIfMatch(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final VertexEntity createResult = vertices @@ -239,46 +245,41 @@ public void replaceVertexIfMatch() { final VertexReplaceOptions options = new VertexReplaceOptions().ifMatch(createResult.getRev()); final VertexUpdateEntity replaceResult = vertices .replaceVertex(createResult.getKey(), doc, options); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = vertices .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } - @Test - public void replaceVertexIfMatchFail() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void replaceVertexIfMatchFail(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final VertexEntity createResult = vertices .insertVertex(doc, null); doc.getProperties().clear(); doc.addAttribute("b", "test"); - try { - final VertexReplaceOptions options = new VertexReplaceOptions().ifMatch("no"); - vertices.replaceVertex(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - if (isAtLeastVersion(3, 4)) { - // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK - // assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1200)); - } else { - assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1903)); - } - } + final VertexReplaceOptions options = new VertexReplaceOptions().ifMatch("no"); + Throwable thrown = catchThrowable(() -> vertices.replaceVertex(createResult.getKey(), doc, options)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode()).isEqualTo(412)); + assertThat(e.getErrorNum()).isEqualTo(1200); } - @Test - public void updateVertex() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void updateVertex(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -289,35 +290,37 @@ public void updateVertex() { doc.updateAttribute("c", null); final VertexUpdateEntity updateResult = vertices .updateVertex(createResult.getKey(), doc, null); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = vertices .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); } - @Test - public void updateVertexUpdateRev() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void updateVertexUpdateRev(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); final VertexEntity createResult = vertices .insertVertex(doc, null); - assertThat(doc.getRevision(), is(createResult.getRev())); + assertThat(doc.getRevision()).isEqualTo(createResult.getRev()); final VertexUpdateEntity updateResult = vertices .updateVertex(createResult.getKey(), doc, null); - assertThat(doc.getRevision(), is(updateResult.getRev())); + assertThat(doc.getRevision()).isEqualTo(updateResult.getRev()); } - @Test - public void updateVertexIfMatch() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void updateVertexIfMatch(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -329,24 +332,25 @@ public void updateVertexIfMatch() { final VertexUpdateOptions options = new VertexUpdateOptions().ifMatch(createResult.getRev()); final VertexUpdateEntity updateResult = vertices .updateVertex(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = vertices .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); } - @Test - public void updateVertexIfMatchFail() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void updateVertexIfMatchFail(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -355,24 +359,19 @@ public void updateVertexIfMatchFail() { doc.updateAttribute("a", "test1"); doc.addAttribute("b", "test"); doc.updateAttribute("c", null); - try { - final VertexUpdateOptions options = new VertexUpdateOptions().ifMatch("no"); - vertices.updateVertex(createResult.getKey(), doc, options); - fail(); - } catch (final ArangoDBException e) { - if (isAtLeastVersion(3, 4)) { - // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK - // assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1200)); - } else { - assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1903)); - } - } + final VertexUpdateOptions options = new VertexUpdateOptions().ifMatch("no"); + + Throwable thrown = catchThrowable(() -> vertices.updateVertex(createResult.getKey(), doc, options)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode()).isEqualTo(412)); + assertThat(e.getErrorNum()).isEqualTo(1200); } - @Test - public void updateVertexKeepNullTrue() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void updateVertexKeepNullTrue(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final VertexEntity createResult = vertices @@ -381,20 +380,21 @@ public void updateVertexKeepNullTrue() { final VertexUpdateOptions options = new VertexUpdateOptions().keepNull(true); final VertexUpdateEntity updateResult = vertices .updateVertex(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = vertices .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet().size(), is(1)); - assertThat(readResult.getProperties().keySet(), hasItem("a")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getProperties().keySet()).hasSize(1); + assertThat(readResult.getProperties()).containsKey("a"); } - @Test - public void updateVertexKeepNullFalse() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void updateVertexKeepNullFalse(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final VertexEntity createResult = vertices @@ -403,32 +403,34 @@ public void updateVertexKeepNullFalse() { final VertexUpdateOptions options = new VertexUpdateOptions().keepNull(false); final VertexUpdateEntity updateResult = vertices .updateVertex(createResult.getKey(), doc, options); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = vertices .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getRevision(), is(notNullValue())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getRevision()).isNotNull(); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); } - @Test - public void deleteVertex() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void deleteVertex(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); final VertexEntity createResult = vertices .insertVertex(doc, null); vertices.deleteVertex(createResult.getKey(), null); final BaseDocument vertex = vertices .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(vertex, is(nullValue())); + assertThat(vertex).isNull(); } - @Test - public void deleteVertexIfMatch() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void deleteVertexIfMatch(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); final VertexEntity createResult = vertices .insertVertex(doc, null); @@ -436,40 +438,36 @@ public void deleteVertexIfMatch() { vertices.deleteVertex(createResult.getKey(), options); final BaseDocument vertex = vertices .getVertex(createResult.getKey(), BaseDocument.class, null); - assertThat(vertex, is(nullValue())); + assertThat(vertex).isNull(); } - @Test - public void deleteVertexIfMatchFail() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void deleteVertexIfMatchFail(ArangoVertexCollection vertices) { final BaseDocument doc = new BaseDocument(); final VertexEntity createResult = vertices .insertVertex(doc, null); final VertexDeleteOptions options = new VertexDeleteOptions().ifMatch("no"); - try { - vertices.deleteVertex(createResult.getKey(), options); - fail(); - } catch (final ArangoDBException e) { - if (isAtLeastVersion(3, 4)) { - // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK - // assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1200)); - } else { - assertThat(e.getResponseCode(), is(412)); - assertThat(e.getErrorNum(), is(1903)); - } - } + Throwable thrown = catchThrowable(() -> vertices.deleteVertex(createResult.getKey(), options)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + // FIXME: atm the server replies 409 for HTTP_JSON or HTTP_VPACK + // assertThat(e.getResponseCode()).isEqualTo(412)); + assertThat(e.getErrorNum()).isEqualTo(1200); } - @Test - public void vertexKeyWithSpecialChars() { - final String key = "_-:.@()+,=;$!*'%" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void vertexKeyWithSpecialChars(ArangoVertexCollection vertices) { + final String key = "_-:.@()+,=;$!*'%" + UUID.randomUUID(); final VertexEntity vertex = vertices .insertVertex(new BaseDocument(key), null); - assertThat(vertex, is(notNullValue())); + assertThat(vertex).isNotNull(); + ArangoCollection collection = vertices.graph().db().collection(vertices.name()); final BaseDocument document = collection .getDocument(vertex.getKey(), BaseDocument.class, null); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(key)); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(key); } } diff --git a/src/test/java/com/arangodb/ArangoViewTest.java b/src/test/java/com/arangodb/ArangoViewTest.java index 4de891e76..5d63b02ac 100644 --- a/src/test/java/com/arangodb/ArangoViewTest.java +++ b/src/test/java/com/arangodb/ArangoViewTest.java @@ -22,72 +22,66 @@ import com.arangodb.entity.ViewEntity; import com.arangodb.entity.ViewType; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; -import static org.junit.Assume.assumeTrue; /** * @author Mark Vollmary + * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class ArangoViewTest extends BaseTest { +class ArangoViewTest extends BaseJunit5 { - @BeforeClass - public static void init() { - BaseTest.initDB(); + @BeforeAll + static void init() { + initDB(); } - public ArangoViewTest(final ArangoDB arangoDB) { - super(arangoDB); - } - - @Test - public void exists() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void exists(ArangoDatabase db) { String name = "view-" + rnd(); - assumeTrue(isAtLeastVersion(3, 4)); db.createView(name, ViewType.ARANGO_SEARCH); - assertThat(db.view(name).exists(), is(true)); + assertThat(db.view(name).exists()).isTrue(); } - @Test - public void getInfo() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getInfo(ArangoDatabase db) { String name = "view-" + rnd(); - assumeTrue(isAtLeastVersion(3, 4)); db.createView(name, ViewType.ARANGO_SEARCH); final ViewEntity info = db.view(name).getInfo(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(name)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(name); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); } - @Test - public void drop() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void drop(ArangoDatabase db) { String name = "view-" + rnd(); - assumeTrue(isAtLeastVersion(3, 4)); db.createView(name, ViewType.ARANGO_SEARCH); final ArangoView view = db.view(name); view.drop(); - assertThat(view.exists(), is(false)); + assertThat(view.exists()).isFalse(); } - @Test - public void rename() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void rename(ArangoDatabase db) { + assumeTrue(isSingleServer()); String oldName = "view-" + rnd(); String newName = "view-" + rnd(); - assumeTrue(isSingleServer()); - assumeTrue(isAtLeastVersion(3, 4)); db.createView(oldName, ViewType.ARANGO_SEARCH); db.view(oldName).rename(newName); - assertThat(db.view(oldName).exists(), is(false)); - assertThat(db.view(newName).exists(), is(true)); + assertThat(db.view(oldName).exists()).isFalse(); + assertThat(db.view(newName).exists()).isTrue(); } } diff --git a/src/test/java/com/arangodb/BaseDocumentTest.java b/src/test/java/com/arangodb/BaseDocumentTest.java index 5435d11ec..8bb1ed0c4 100644 --- a/src/test/java/com/arangodb/BaseDocumentTest.java +++ b/src/test/java/com/arangodb/BaseDocumentTest.java @@ -27,50 +27,49 @@ import com.arangodb.velocypack.VPackBuilder; import com.arangodb.velocypack.VPackSlice; import com.arangodb.velocypack.ValueType; -import com.arangodb.velocypack.exception.VPackException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; /** * @author Mark Vollmary + * @author Michele Rastelli */ -public class BaseDocumentTest { +class BaseDocumentTest { @Test - public void serialize() throws VPackException { - final BaseDocument entity = new BaseDocument(); + void serialize() { + BaseDocument entity = new BaseDocument(); entity.setKey("test"); entity.setRevision("test"); entity.addAttribute("a", "a"); - final Builder builder = new VPack.Builder(); + Builder builder = new VPack.Builder(); builder.registerModule(new VPackDriverModule()); - final VPack vpacker = builder.build(); + VPack vpacker = builder.build(); - final VPackSlice vpack = vpacker.serialize(entity); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - assertThat(vpack.size(), is(3)); + VPackSlice vpack = vpacker.serialize(entity); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + assertThat(vpack.size()).isEqualTo(3); - final VPackSlice key = vpack.get("_key"); - assertThat(key.isString(), is(true)); - assertThat(key.getAsString(), is("test")); + VPackSlice key = vpack.get("_key"); + assertThat(key.isString()).isTrue(); + assertThat(key.getAsString()).isEqualTo("test"); - final VPackSlice rev = vpack.get("_rev"); - assertThat(rev.isString(), is(true)); - assertThat(rev.getAsString(), is("test")); + VPackSlice rev = vpack.get("_rev"); + assertThat(rev.isString()).isTrue(); + assertThat(rev.getAsString()).isEqualTo("test"); - final VPackSlice a = vpack.get("a"); - assertThat(a.isString(), is(true)); - assertThat(a.getAsString(), is("a")); + VPackSlice a = vpack.get("a"); + assertThat(a.isString()).isTrue(); + assertThat(a.getAsString()).isEqualTo("a"); } @Test - public void deserialize() throws VPackException { - final VPackBuilder builder = new VPackBuilder(); + void deserialize() { + VPackBuilder builder = new VPackBuilder(); builder.add(ValueType.OBJECT); builder.add("_id", "test/test"); builder.add("_key", "test"); @@ -78,19 +77,19 @@ public void deserialize() throws VPackException { builder.add("a", "a"); builder.close(); - final VPack.Builder vbuilder = new VPack.Builder(); + VPack.Builder vbuilder = new VPack.Builder(); vbuilder.registerModule(new VPackDriverModule()); - final VPack vpacker = vbuilder.build(); + VPack vpacker = vbuilder.build(); - final BaseDocument entity = vpacker.deserialize(builder.slice(), BaseDocument.class); - assertThat(entity.getId(), is(notNullValue())); - assertThat(entity.getId(), is("test/test")); - assertThat(entity.getKey(), is(notNullValue())); - assertThat(entity.getKey(), is("test")); - assertThat(entity.getRevision(), is(notNullValue())); - assertThat(entity.getRevision(), is("test")); - assertThat(entity.getProperties().size(), is(1)); - assertThat(String.valueOf(entity.getAttribute("a")), is("a")); + BaseDocument entity = vpacker.deserialize(builder.slice(), BaseDocument.class); + assertThat(entity.getId()).isNotNull(); + assertThat(entity.getId()).isEqualTo("test/test"); + assertThat(entity.getKey()).isNotNull(); + assertThat(entity.getKey()).isEqualTo("test"); + assertThat(entity.getRevision()).isNotNull(); + assertThat(entity.getRevision()).isEqualTo("test"); + assertThat(entity.getProperties()).hasSize(1); + assertThat(String.valueOf(entity.getAttribute("a"))).isEqualTo("a"); } } diff --git a/src/test/java/com/arangodb/BaseJunit5.java b/src/test/java/com/arangodb/BaseJunit5.java new file mode 100644 index 000000000..a695f4b29 --- /dev/null +++ b/src/test/java/com/arangodb/BaseJunit5.java @@ -0,0 +1,121 @@ +package com.arangodb; + +import com.arangodb.entity.*; +import com.arangodb.mapping.ArangoJack; +import com.arangodb.model.CollectionCreateOptions; +import com.arangodb.model.GraphCreateOptions; +import com.arangodb.util.TestUtils; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.provider.Arguments; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +class BaseJunit5 { + protected static final DbName TEST_DB = DbName.of("java_driver_test_db"); + + private static final List adbs = Arrays.stream(Protocol.values()) + .map(p -> new ArangoDB.Builder() + .useProtocol(p) + .serializer(new ArangoJack()) + .build()) + .collect(Collectors.toList()); + + protected static Stream dbsStream() { + return adbs.stream().map(adb -> adb.db(TEST_DB)); + } + + protected static Stream arangos() { + return adbs.stream().map(Arguments::of); + } + + protected static Stream dbs() { + return dbsStream().map(Arguments::of); + } + + static ArangoDatabase initDB(DbName name) { + ArangoDatabase database = adbs.get(0).db(name); + if (!database.exists()) + database.create(); + return database; + } + + static ArangoDatabase initDB() { + return initDB(TEST_DB); + } + + static void dropDB(DbName name) { + ArangoDatabase database = adbs.get(0).db(name); + if (database.exists()) + database.drop(); + } + + static void initGraph(String name, Collection edgeDefinitions, GraphCreateOptions options) { + ArangoDatabase db = initDB(); + db.createGraph(name, edgeDefinitions, options); + } + + static void initCollections(String... collections) { + ArangoDatabase db = initDB(); + for (String collection : collections) { + if (db.collection(collection).exists()) + db.collection(collection).drop(); + db.createCollection(collection, null); + } + } + + static void initEdgeCollections(String... collections) { + ArangoDatabase db = initDB(); + for (String collection : collections) { + if (db.collection(collection).exists()) + db.collection(collection).drop(); + db.createCollection(collection, new CollectionCreateOptions().type(CollectionType.EDGES)); + } + } + + @BeforeAll + static void init() { + dropDB(TEST_DB); + } + + @AfterAll + static void shutdown() { + dropDB(TEST_DB); + adbs.forEach(ArangoDB::shutdown); + } + + static String rnd() { + return UUID.randomUUID().toString(); + } + + boolean isAtLeastVersion(final int major, final int minor) { + return isAtLeastVersion(major, minor, 0); + } + + boolean isAtLeastVersion(final int major, final int minor, final int patch) { + return TestUtils.isAtLeastVersion(adbs.get(0).getVersion().getVersion(), major, minor, patch); + } + + boolean isStorageEngine(ArangoDBEngine.StorageEngineName name) { + return name.equals(adbs.get(0).getEngine().getName()); + } + + boolean isSingleServer() { + return adbs.get(0).getRole() == ServerRole.SINGLE; + } + + boolean isCluster() { + return adbs.get(0).getRole() == ServerRole.COORDINATOR; + } + + boolean isEnterprise() { + return adbs.get(0).getVersion().getLicense() == License.ENTERPRISE; + } + + +} diff --git a/src/test/java/com/arangodb/BaseTest.java b/src/test/java/com/arangodb/BaseTest.java deleted file mode 100644 index 2248d600c..000000000 --- a/src/test/java/com/arangodb/BaseTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * 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 - * - * 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. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb; - -import com.arangodb.entity.*; -import com.arangodb.mapping.ArangoJack; -import com.arangodb.model.CollectionCreateOptions; -import com.arangodb.model.GraphCreateOptions; -import com.arangodb.util.TestUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.runners.Parameterized.Parameters; - -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.UUID; - -/** - * @author Mark Vollmary - * @author Michele Rastelli - */ -public abstract class BaseTest { - - static final DbName TEST_DB = DbName.of("java_driver_test_db"); - - // TODO: make configurable - static final List arangos = Arrays.asList( - new ArangoDB.Builder().useProtocol(Protocol.VST).build(), - new ArangoDB.Builder().useProtocol(Protocol.HTTP_JSON).build(), - new ArangoDB.Builder().useProtocol(Protocol.HTTP_VPACK).build(), - new ArangoDB.Builder().serializer(new ArangoJack()).build() - ); - - @Parameters - public static List builders() { - return arangos; - } - - protected final ArangoDB arangoDB; - protected final ArangoDatabase db; - - BaseTest(final ArangoDB arangoDB) { - this.arangoDB = arangoDB; - db = arangoDB.db(TEST_DB); - } - - static ArangoDatabase initDB() { - ArangoDatabase database = arangos.get(0).db(TEST_DB); - if (!database.exists()) - database.create(); - return database; - } - - static void initGraph(String name, Collection edgeDefinitions, GraphCreateOptions options) { - ArangoDatabase db = initDB(); - db.createGraph(name, edgeDefinitions, options); - } - - static void initCollections(String... collections) { - ArangoDatabase db = initDB(); - for (String collection : collections) { - if (db.collection(collection).exists()) - db.collection(collection).drop(); - db.createCollection(collection, null); - } - } - - static void initEdgeCollections(String... collections) { - ArangoDatabase db = initDB(); - for (String collection : collections) { - if (db.collection(collection).exists()) - db.collection(collection).drop(); - db.createCollection(collection, new CollectionCreateOptions().type(CollectionType.EDGES)); - } - } - - @BeforeClass - public static void init() { - ArangoDatabase database = arangos.get(0).db(TEST_DB); - if (database.exists()) - database.drop(); - } - - @AfterClass - public static void shutdown() { - ArangoDatabase database = arangos.get(0).db(TEST_DB); - if (database.exists()) - database.drop(); - arangos.forEach(ArangoDB::shutdown); - } - - static String rnd() { - return UUID.randomUUID().toString(); - } - - boolean isAtLeastVersion(final int major, final int minor) { - return isAtLeastVersion(major, minor, 0); - } - - boolean isAtLeastVersion(final int major, final int minor, final int patch) { - return TestUtils.isAtLeastVersion(arangoDB.getVersion().getVersion(), major, minor, patch); - } - - boolean isStorageEngine(ArangoDBEngine.StorageEngineName name) { - return name.equals(arangoDB.getEngine().getName()); - } - - boolean isSingleServer() { - return arangoDB.getRole() == ServerRole.SINGLE; - } - - boolean isCluster() { - return arangoDB.getRole() == ServerRole.COORDINATOR; - } - - boolean isEnterprise() { - return arangoDB.getVersion().getLicense() == License.ENTERPRISE; - } - -} diff --git a/src/test/java/com/arangodb/ConcurrencyTests.java b/src/test/java/com/arangodb/ConcurrencyTests.java index 62645cb82..16c26ac08 100644 --- a/src/test/java/com/arangodb/ConcurrencyTests.java +++ b/src/test/java/com/arangodb/ConcurrencyTests.java @@ -1,43 +1,32 @@ package com.arangodb; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; import java.util.stream.IntStream; -@RunWith(Parameterized.class) -public class ConcurrencyTests { +class ConcurrencyTests { - final Protocol protocol; - - public ConcurrencyTests(Protocol protocol) { - this.protocol = protocol; - } - - @Parameterized.Parameters - public static Protocol[] protocols() { - return Protocol.values(); - } - - @Test - public void concurrentPendingRequests() throws ExecutionException, InterruptedException { - ArangoDB adb = new ArangoDB.Builder().useProtocol(protocol).build(); + @ParameterizedTest + @EnumSource(Protocol.class) + void concurrentPendingRequests(Protocol protocol) throws ExecutionException, InterruptedException { + ExecutorService es = Executors.newFixedThreadPool(10); + ArangoDB adb = new ArangoDB.Builder().useProtocol(protocol).serializer(new ArangoJack()).build(); List> futures = IntStream.range(0, 10) - .mapToObj(i -> CompletableFuture.runAsync( - () -> adb.db().query("RETURN SLEEP(1)", Void.class), - Executors.newFixedThreadPool(10)) - ) + .mapToObj(__ -> CompletableFuture.runAsync(() -> adb.db().query("RETURN SLEEP(1)", Void.class), es)) .collect(Collectors.toList()); for (CompletableFuture f : futures) { f.get(); } adb.shutdown(); + es.shutdown(); } } diff --git a/src/test/java/com/arangodb/DocumentTest.java b/src/test/java/com/arangodb/DocumentTest.java index 692a5c81f..327f07bb8 100644 --- a/src/test/java/com/arangodb/DocumentTest.java +++ b/src/test/java/com/arangodb/DocumentTest.java @@ -22,41 +22,42 @@ import com.arangodb.entity.BaseDocument; import com.arangodb.entity.DocumentCreateEntity; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Map; import java.util.UUID; +import java.util.stream.Stream; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Vollmary + * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class DocumentTest extends BaseTest { +class DocumentTest extends BaseJunit5 { private static final String COLLECTION_NAME = "DocumentTest_collection"; - private final ArangoCollection collection; - @BeforeClass - public static void init() { - BaseTest.initCollections(COLLECTION_NAME); + private static Stream cols() { + return dbsStream() + .map(db -> db.collection(COLLECTION_NAME)) + .map(Arguments::of); } - public DocumentTest(final ArangoDB arangoDB) { - super(arangoDB); - collection = db.collection(COLLECTION_NAME); + + @BeforeAll + static void init() { + initCollections(COLLECTION_NAME); } @SuppressWarnings("unchecked") - @Test - public void insertAsJson() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertAsJson(ArangoCollection collection) { //@formatter:off final String json = "{" @@ -82,17 +83,18 @@ public void insertAsJson() { //@formatter:on final DocumentCreateEntity createResult = collection.insertDocument(json); final BaseDocument doc = collection.getDocument(createResult.getKey(), BaseDocument.class); - assertThat(doc, is(notNullValue())); + assertThat(doc).isNotNull(); final Object article = doc.getAttribute("article"); - assertThat(article, is(notNullValue())); + assertThat(article).isNotNull(); final Object artist = ((Map) article).get("artist"); - assertThat(artist, is(notNullValue())); - assertThat(artist.toString(), is("PREGARDIEN/RHEINISCHE KANTOREI/DAS")); + assertThat(artist).isNotNull(); + assertThat(artist.toString()).isEqualTo("PREGARDIEN/RHEINISCHE KANTOREI/DAS"); } @SuppressWarnings("unchecked") - @Test - public void insertAsBaseDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void insertAsBaseDocument(ArangoCollection collection) { final BaseDocument document = new BaseDocument(); { final BaseDocument article = new BaseDocument(); @@ -114,22 +116,23 @@ public void insertAsBaseDocument() { } final DocumentCreateEntity createResult = collection.insertDocument(document); final BaseDocument doc = collection.getDocument(createResult.getKey(), BaseDocument.class); - assertThat(doc, is(notNullValue())); + assertThat(doc).isNotNull(); final Object article = doc.getAttribute("article"); - assertThat(article, is(notNullValue())); + assertThat(article).isNotNull(); final Object artist = ((Map) article).get("artist"); - assertThat(artist, is(notNullValue())); - assertThat(artist.toString(), is("PREGARDIEN/RHEINISCHE KANTOREI/DAS")); + assertThat(artist).isNotNull(); + assertThat(artist.toString()).isEqualTo("PREGARDIEN/RHEINISCHE KANTOREI/DAS"); } - @Test - public void documentKeyWithSpecialChars() { - final String key = "_-:.@()+,=;$!*'%" + UUID.randomUUID().toString(); + @ParameterizedTest(name = "{index}") + @MethodSource("cols") + void documentKeyWithSpecialChars(ArangoCollection collection) { + final String key = "_-:.@()+,=;$!*'%" + UUID.randomUUID(); final BaseDocument document = new BaseDocument(key); final DocumentCreateEntity createResult = collection.insertDocument(document); final BaseDocument doc = collection.getDocument(createResult.getKey(), BaseDocument.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getKey(), is(key)); + assertThat(doc).isNotNull(); + assertThat(doc.getKey()).isEqualTo(key); } } diff --git a/src/test/java/com/arangodb/JwtAuthTest.java b/src/test/java/com/arangodb/JwtAuthTest.java index 9c2532fa7..6c0c3029f 100644 --- a/src/test/java/com/arangodb/JwtAuthTest.java +++ b/src/test/java/com/arangodb/JwtAuthTest.java @@ -1,84 +1,60 @@ package com.arangodb; +import com.arangodb.mapping.ArangoJack; import com.arangodb.util.ArangoSerialization; import com.arangodb.velocystream.Request; import com.arangodb.velocystream.RequestType; import com.arangodb.velocystream.Response; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; -import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + /** * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class JwtAuthTest { +class JwtAuthTest { - private static String jwt; - private final Protocol protocol; - private ArangoDB arangoDB; + private volatile static String jwt; - @BeforeClass - public static void init() { - ArangoDB arangoDB = new ArangoDB.Builder().build(); + @BeforeAll + static void init() { + ArangoDB arangoDB = new ArangoDB.Builder().serializer(new ArangoJack()).build(); jwt = getJwt(arangoDB); arangoDB.shutdown(); } - @After - public void after() { - if (arangoDB != null) - arangoDB.shutdown(); - } - - @Parameterized.Parameters - public static List builders() { - return Arrays.asList( - Protocol.VST, - Protocol.HTTP_JSON, - Protocol.HTTP_VPACK - ); - } - - public JwtAuthTest(Protocol protocol) { - this.protocol = protocol; - } - - @Test - public void notAuthenticated() { - arangoDB = getBuilder().build(); - try { - arangoDB.getVersion(); - fail(); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(401)); - } + @ParameterizedTest + @EnumSource(Protocol.class) + void notAuthenticated(Protocol protocol) { + ArangoDB arangoDB = getBuilder(protocol).build(); + Throwable thrown = catchThrowable(arangoDB::getVersion); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(401); arangoDB.shutdown(); } - @Test - public void authenticated() { - arangoDB = getBuilder() + @ParameterizedTest + @EnumSource(Protocol.class) + void authenticated(Protocol protocol) { + ArangoDB arangoDB = getBuilder(protocol) .jwt(jwt) .build(); arangoDB.getVersion(); arangoDB.shutdown(); } - @Test - public void updateJwt() { - arangoDB = getBuilder() + @ParameterizedTest + @EnumSource(Protocol.class) + void updateJwt(Protocol protocol) { + ArangoDB arangoDB = getBuilder(protocol) .jwt(jwt) .build(); arangoDB.getVersion(); @@ -86,21 +62,21 @@ public void updateJwt() { arangoDB.shutdown(); } arangoDB.updateJwt("bla"); - try { - arangoDB.getVersion(); - fail(); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(401)); - } + + Throwable thrown = catchThrowable(arangoDB::getVersion); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(401); arangoDB.updateJwt(jwt); arangoDB.getVersion(); arangoDB.shutdown(); } - private ArangoDB.Builder getBuilder() { + private ArangoDB.Builder getBuilder(Protocol protocol) { return new ArangoDB.Builder() .useProtocol(protocol) + .serializer(new ArangoJack()) .jwt(null) // unset credentials from properties file .user(null) // unset credentials from properties file .password(null); // unset credentials from properties file @@ -112,7 +88,7 @@ private static String getJwt(ArangoDB arangoDB) { reqBody.put("username", "root"); reqBody.put("password", "test"); - Request req = new Request("_system", RequestType.POST, "/_open/auth"); + Request req = new Request(DbName.SYSTEM, RequestType.POST, "/_open/auth"); req.setBody(serde.serialize(reqBody)); Response resp = arangoDB.execute(req); diff --git a/src/test/java/com/arangodb/StreamTransactionConflictsTest.java b/src/test/java/com/arangodb/StreamTransactionConflictsTest.java index 3744b3f8e..1e5ed62df 100644 --- a/src/test/java/com/arangodb/StreamTransactionConflictsTest.java +++ b/src/test/java/com/arangodb/StreamTransactionConflictsTest.java @@ -25,37 +25,32 @@ import com.arangodb.entity.StreamTransactionEntity; import com.arangodb.model.DocumentCreateOptions; import com.arangodb.model.StreamTransactionOptions; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.UUID; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + /** * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class StreamTransactionConflictsTest extends BaseTest { +class StreamTransactionConflictsTest extends BaseJunit5 { private static final String COLLECTION_NAME = "db_concurrent_stream_transactions_test-" + UUID.randomUUID(); - @BeforeClass - public static void init() { - BaseTest.initCollections(COLLECTION_NAME); - } - - public StreamTransactionConflictsTest(final ArangoDB arangoDB) { - super(arangoDB); + @BeforeAll + static void init() { + initCollections(COLLECTION_NAME); } - @Test - public void conflictOnInsertDocumentWithNotYetCommittedTx() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void conflictOnInsertDocumentWithNotYetCommittedTx(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -72,25 +67,24 @@ public void conflictOnInsertDocumentWithNotYetCommittedTx() { db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument(key), new DocumentCreateOptions().streamTransactionId(tx1.getId())); - try { - // insert conflicting document from within tx2 - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key), - new DocumentCreateOptions().streamTransactionId(tx2.getId())); - - fail(); - } catch (ArangoDBException e) { - if (isAtLeastVersion(3, 8)) { - assertThat(e.getResponseCode(), is(409)); - assertThat(e.getErrorNum(), is(1200)); - } + // insert conflicting document from within tx2 + Throwable thrown = catchThrowable(() -> db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key), + new DocumentCreateOptions().streamTransactionId(tx2.getId()))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + + if (isAtLeastVersion(3, 8)) { + assertThat(e.getResponseCode()).isEqualTo(409); + assertThat(e.getErrorNum()).isEqualTo(1200); } db.abortStreamTransaction(tx1.getId()); db.abortStreamTransaction(tx2.getId()); } - @Test - public void conflictOnInsertDocumentWithAlreadyCommittedTx() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void conflictOnInsertDocumentWithAlreadyCommittedTx(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -110,17 +104,14 @@ public void conflictOnInsertDocumentWithAlreadyCommittedTx() { // commit tx1 db.commitStreamTransaction(tx1.getId()); - try { - // insert conflicting document from within tx2 - db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key), - new DocumentCreateOptions().streamTransactionId(tx2.getId())); - - fail(); - } catch (ArangoDBException e) { - if (isAtLeastVersion(3, 8)) { - assertThat(e.getResponseCode(), is(409)); - assertThat(e.getErrorNum(), is(1200)); - } + // insert conflicting document from within tx2 + Throwable thrown = catchThrowable(() -> db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(key), + new DocumentCreateOptions().streamTransactionId(tx2.getId()))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + if (isAtLeastVersion(3, 8)) { + assertThat(e.getResponseCode()).isEqualTo(409); + assertThat(e.getErrorNum()).isEqualTo(1200); } db.abortStreamTransaction(tx2.getId()); diff --git a/src/test/java/com/arangodb/StreamTransactionGraphTest.java b/src/test/java/com/arangodb/StreamTransactionGraphTest.java index 4a3c856dd..039d2d86c 100644 --- a/src/test/java/com/arangodb/StreamTransactionGraphTest.java +++ b/src/test/java/com/arangodb/StreamTransactionGraphTest.java @@ -22,82 +22,67 @@ import com.arangodb.entity.*; import com.arangodb.model.*; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Collections; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assume.assumeTrue; /** * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class StreamTransactionGraphTest extends BaseTest { +class StreamTransactionGraphTest extends BaseJunit5 { private static final String GRAPH_NAME = "graph_stream_transaction_graph_test"; private static final String EDGE_COLLECTION = "edge_collection_stream_transaction_graph_test"; private static final String VERTEX_COLLECTION_1 = "vertex_collection_1_stream_transaction_graph_test"; private static final String VERTEX_COLLECTION_2 = "vertex_collection_2_stream_transaction_graph_test"; - private final ArangoGraph graph; - private final ArangoVertexCollection vertexCollection1; - private final ArangoVertexCollection vertexCollection2; - private final ArangoEdgeCollection edgeCollection; - - @BeforeClass - public static void init() { - BaseTest.initDB(); + private static Stream vertices() { + return dbsStream() + .map(db -> db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_1)) + .map(Arguments::of); } - public StreamTransactionGraphTest(final ArangoDB arangoDB) { - super(arangoDB); - graph = db.graph(GRAPH_NAME); - - if (graph.exists()) - graph.drop(); - - graph.create(Collections.singletonList(new EdgeDefinition().collection(EDGE_COLLECTION).from(VERTEX_COLLECTION_1).to(VERTEX_COLLECTION_2))); - - vertexCollection1 = graph.vertexCollection(VERTEX_COLLECTION_1); - vertexCollection2 = graph.vertexCollection(VERTEX_COLLECTION_2); - edgeCollection = graph.edgeCollection(EDGE_COLLECTION); + private static Stream edges() { + return dbsStream() + .map(db -> db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION)) + .map(Arguments::of); } - @After - public void teardown() { - if (graph.exists()) - graph.drop(); - if (db.collection(EDGE_COLLECTION).exists()) - db.collection(EDGE_COLLECTION).drop(); - if (db.collection(VERTEX_COLLECTION_1).exists()) - db.collection(VERTEX_COLLECTION_1).drop(); - if (db.collection(VERTEX_COLLECTION_2).exists()) - db.collection(VERTEX_COLLECTION_2).drop(); + @BeforeAll + static void init() { + initDB(); + initGraph(GRAPH_NAME, Collections.singletonList(new EdgeDefinition() + .collection(EDGE_COLLECTION).from(VERTEX_COLLECTION_1).to(VERTEX_COLLECTION_2) + ), null); } - private BaseEdgeDocument createEdgeValue(String streamTransactionId) { - final VertexEntity v1 = vertexCollection1.insertVertex(new BaseDocument(), new VertexCreateOptions().streamTransactionId(streamTransactionId)); - final VertexEntity v2 = vertexCollection2.insertVertex(new BaseDocument(), new VertexCreateOptions().streamTransactionId(streamTransactionId)); - final BaseEdgeDocument value = new BaseEdgeDocument(); + private BaseEdgeDocument createEdgeValue(String streamTransactionId, ArangoGraph graph) { + ArangoVertexCollection vertexCollection1 = graph.vertexCollection(VERTEX_COLLECTION_1); + ArangoVertexCollection vertexCollection2 = graph.vertexCollection(VERTEX_COLLECTION_2); + VertexEntity v1 = vertexCollection1.insertVertex(new BaseDocument(), new VertexCreateOptions().streamTransactionId(streamTransactionId)); + VertexEntity v2 = vertexCollection2.insertVertex(new BaseDocument(), new VertexCreateOptions().streamTransactionId(streamTransactionId)); + BaseEdgeDocument value = new BaseEdgeDocument(); value.setFrom(v1.getId()); value.setTo(v2.getId()); return value; } - @Test - public void getVertex() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void getVertex(ArangoVertexCollection vertexCollection1) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + ArangoDatabase db = vertexCollection1.graph().db(); StreamTransactionEntity tx = db .beginStreamTransaction(new StreamTransactionOptions() .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) @@ -108,18 +93,20 @@ public void getVertex() { // assert that the vertex is not found from within the tx assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())), is(nullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId()))).isNull(); db.abortStreamTransaction(tx.getId()); } - @Test - public void createVertex() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void createVertex(ArangoVertexCollection vertexCollection1) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + ArangoDatabase db = vertexCollection1.graph().db(); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions() .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) @@ -129,20 +116,21 @@ public void createVertex() { VertexEntity createdVertex = vertexCollection1.insertVertex(new BaseDocument(), new VertexCreateOptions().streamTransactionId(tx.getId())); // assert that the vertex is not found from outside the tx - assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null), is(nullValue())); + assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null)).isNull(); // assert that the vertex is found from within the tx assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())), is(notNullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId()))).isNotNull(); db.commitStreamTransaction(tx.getId()); // assert that the vertex is found after commit - assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null), is(notNullValue())); + assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null)).isNotNull(); } - @Test - public void replaceVertex() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void replaceVertex(ArangoVertexCollection vertexCollection1) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -152,6 +140,7 @@ public void replaceVertex() { VertexEntity createdVertex = vertexCollection1.insertVertex(doc, null); + ArangoDatabase db = vertexCollection1.graph().db(); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions() .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) @@ -165,21 +154,22 @@ public void replaceVertex() { // assert that the vertex has not been replaced from outside the tx assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("foo")); + .getProperties()).containsEntry("test", "foo"); // assert that the vertex has been replaced from within the tx assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).getProperties().get("test"), is("bar")); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).getProperties()).containsEntry("test", "bar"); db.commitStreamTransaction(tx.getId()); // assert that the vertex has been replaced after commit assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("bar")); + .getProperties()).containsEntry("test", "bar"); } - @Test - public void updateVertex() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void updateVertex(ArangoVertexCollection vertexCollection1) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -189,6 +179,7 @@ public void updateVertex() { VertexEntity createdDoc = vertexCollection1.insertVertex(doc, null); + ArangoDatabase db = vertexCollection1.graph().db(); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions() .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) @@ -201,27 +192,29 @@ public void updateVertex() { // assert that the vertex has not been updated from outside the tx assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("foo")); + .getProperties()).containsEntry("test", "foo"); // assert that the vertex has been updated from within the tx assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).getProperties().get("test"), is("bar")); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).getProperties()).containsEntry("test", "bar"); db.commitStreamTransaction(tx.getId()); // assert that the vertex has been updated after commit assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("bar")); + .getProperties()).containsEntry("test", "bar"); } - @Test - public void deleteVertex() { + @ParameterizedTest(name = "{index}") + @MethodSource("vertices") + void deleteVertex(ArangoVertexCollection vertexCollection1) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); VertexEntity createdDoc = vertexCollection1.insertVertex(new BaseDocument(), null); + ArangoDatabase db = vertexCollection1.graph().db(); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions() .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) @@ -231,80 +224,85 @@ public void deleteVertex() { vertexCollection1.deleteVertex(createdDoc.getKey(), new VertexDeleteOptions().streamTransactionId(tx.getId())); // assert that the vertex has not been deleted from outside the tx - assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null), is(notNullValue())); + assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null)).isNotNull(); // assert that the vertex has been deleted from within the tx assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())), is(nullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId()))).isNull(); db.commitStreamTransaction(tx.getId()); // assert that the vertex has been deleted after commit - assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null), - is(nullValue())); + assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null)).isNull(); } - @Test - public void getEdge() { + @ParameterizedTest(name = "{index}") + @MethodSource("edges") + void getEdge(ArangoEdgeCollection edgeCollection) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + ArangoDatabase db = edgeCollection.graph().db(); StreamTransactionEntity tx = db .beginStreamTransaction(new StreamTransactionOptions() .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)); - // insert a edge from outside the tx - EdgeEntity createdEdge = edgeCollection.insertEdge(createEdgeValue(null)); + // insert an edge from outside the tx + EdgeEntity createdEdge = edgeCollection.insertEdge(createEdgeValue(null, edgeCollection.graph())); // assert that the edge is not found from within the tx assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())), is(nullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId()))).isNull(); db.abortStreamTransaction(tx.getId()); } - @Test - public void createEdge() { + @ParameterizedTest(name = "{index}") + @MethodSource("edges") + void createEdge(ArangoEdgeCollection edgeCollection) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + ArangoDatabase db = edgeCollection.graph().db(); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions() .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)); - // insert a edge from within the tx - EdgeEntity createdEdge = edgeCollection.insertEdge(createEdgeValue(tx.getId()), new EdgeCreateOptions().streamTransactionId(tx.getId())); + // insert an edge from within the tx + EdgeEntity createdEdge = edgeCollection.insertEdge(createEdgeValue(tx.getId(), edgeCollection.graph()), new EdgeCreateOptions().streamTransactionId(tx.getId())); // assert that the edge is not found from outside the tx - assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null), is(nullValue())); + assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null)).isNull(); // assert that the edge is found from within the tx assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())), is(notNullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId()))).isNotNull(); db.commitStreamTransaction(tx.getId()); // assert that the edge is found after commit - assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null), is(notNullValue())); + assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null)).isNotNull(); } - @Test - public void replaceEdge() { + @ParameterizedTest(name = "{index}") + @MethodSource("edges") + void replaceEdge(ArangoEdgeCollection edgeCollection) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - BaseEdgeDocument doc = createEdgeValue(null); + BaseEdgeDocument doc = createEdgeValue(null, edgeCollection.graph()); doc.addAttribute("test", "foo"); EdgeEntity createdEdge = edgeCollection.insertEdge(doc, null); + ArangoDatabase db = edgeCollection.graph().db(); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions() .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) @@ -318,30 +316,32 @@ public void replaceEdge() { // assert that the edge has not been replaced from outside the tx assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null) - .getProperties().get("test"), is("foo")); + .getProperties()).containsEntry("test", "foo"); // assert that the edge has been replaced from within the tx assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).getProperties().get("test"), is("bar")); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).getProperties()).containsEntry("test", "bar"); db.commitStreamTransaction(tx.getId()); // assert that the edge has been replaced after commit assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null) - .getProperties().get("test"), is("bar")); + .getProperties()).containsEntry("test", "bar"); } - @Test - public void updateEdge() { + @ParameterizedTest(name = "{index}") + @MethodSource("edges") + void updateEdge(ArangoEdgeCollection edgeCollection) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - BaseEdgeDocument doc = createEdgeValue(null); + BaseEdgeDocument doc = createEdgeValue(null, edgeCollection.graph()); doc.addAttribute("test", "foo"); EdgeEntity createdDoc = edgeCollection.insertEdge(doc, null); + ArangoDatabase db = edgeCollection.graph().db(); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions() .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) @@ -354,27 +354,29 @@ public void updateEdge() { // assert that the edge has not been updated from outside the tx assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null) - .getProperties().get("test"), is("foo")); + .getProperties()).containsEntry("test", "foo"); // assert that the edge has been updated from within the tx assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).getProperties().get("test"), is("bar")); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).getProperties()).containsEntry("test", "bar"); db.commitStreamTransaction(tx.getId()); // assert that the edge has been updated after commit assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null) - .getProperties().get("test"), is("bar")); + .getProperties()).containsEntry("test", "bar"); } - @Test - public void deleteEdge() { + @ParameterizedTest(name = "{index}") + @MethodSource("edges") + void deleteEdge(ArangoEdgeCollection edgeCollection) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - EdgeEntity createdDoc = edgeCollection.insertEdge(createEdgeValue(null), null); + EdgeEntity createdDoc = edgeCollection.insertEdge(createEdgeValue(null, edgeCollection.graph()), null); + ArangoDatabase db = edgeCollection.graph().db(); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions() .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) @@ -384,17 +386,16 @@ public void deleteEdge() { edgeCollection.deleteEdge(createdDoc.getKey(), new EdgeDeleteOptions().streamTransactionId(tx.getId())); // assert that the edge has not been deleted from outside the tx - assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null), is(notNullValue())); + assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null)).isNotNull(); // assert that the edge has been deleted from within the tx assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())), is(nullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId()))).isNull(); db.commitStreamTransaction(tx.getId()); // assert that the edge has been deleted after commit - assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null), - is(nullValue())); + assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null)).isNull(); } } diff --git a/src/test/java/com/arangodb/StreamTransactionTest.java b/src/test/java/com/arangodb/StreamTransactionTest.java index 0666d9456..4330b13fd 100644 --- a/src/test/java/com/arangodb/StreamTransactionTest.java +++ b/src/test/java/com/arangodb/StreamTransactionTest.java @@ -22,63 +22,57 @@ import com.arangodb.entity.*; import com.arangodb.model.*; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Michele Rastelli */ -@RunWith(Parameterized.class) -public class StreamTransactionTest extends BaseTest { +class StreamTransactionTest extends BaseJunit5 { private static final String COLLECTION_NAME = "StreamTransactionTest_collection"; - private final ArangoCollection collection; - @BeforeClass - public static void init() { - BaseTest.initCollections(COLLECTION_NAME); + @BeforeAll + static void init() { + initCollections(COLLECTION_NAME); } - public StreamTransactionTest(final ArangoDB arangoDB) { - super(arangoDB); - collection = db.collection(COLLECTION_NAME); - } - - @Test - public void beginStreamTransaction() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void beginStreamTransaction(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db.beginStreamTransaction(null); - assertThat(tx.getId(), is(notNullValue())); - assertThat(tx.getStatus(), is(StreamTransactionStatus.running)); + assertThat(tx.getId()).isNotNull(); + assertThat(tx.getStatus()).isEqualTo(StreamTransactionStatus.running); db.abortStreamTransaction(tx.getId()); } - @Test(expected = ArangoDBException.class) - public void beginStreamTransactionWithNonExistingCollectionsShouldThrow() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void beginStreamTransactionWithNonExistingCollectionsShouldThrow(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.beginStreamTransaction(new StreamTransactionOptions().writeCollections("notExistingCollection")); + Throwable thrown = catchThrowable(() -> + db.beginStreamTransaction(new StreamTransactionOptions().writeCollections("notExistingCollection"))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void abortStreamTransaction() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void abortStreamTransaction(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -86,13 +80,14 @@ public void abortStreamTransaction() { StreamTransactionEntity begunTx = db.beginStreamTransaction(null); StreamTransactionEntity abortedTx = db.abortStreamTransaction(begunTx.getId()); - assertThat(abortedTx.getId(), is(notNullValue())); - assertThat(abortedTx.getId(), is(begunTx.getId())); - assertThat(abortedTx.getStatus(), is(StreamTransactionStatus.aborted)); + assertThat(abortedTx.getId()).isNotNull(); + assertThat(abortedTx.getId()).isEqualTo(begunTx.getId()); + assertThat(abortedTx.getStatus()).isEqualTo(StreamTransactionStatus.aborted); } - @Test - public void abortStreamTransactionTwice() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void abortStreamTransactionTwice(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -102,37 +97,42 @@ public void abortStreamTransactionTwice() { db.abortStreamTransaction(begunTx.getId()); } - @Test(expected = ArangoDBException.class) - public void abortStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void abortStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.abortStreamTransaction("000000"); + Throwable thrown = catchThrowable(() -> db.abortStreamTransaction("000000")); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test(expected = ArangoDBException.class) - public void abortStreamTransactionWithInvalidTransactionIdShouldThrow() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void abortStreamTransactionWithInvalidTransactionIdShouldThrow(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - - db.abortStreamTransaction("invalidTransactionId"); + Throwable thrown = catchThrowable(() -> db.abortStreamTransaction("invalidTransactionId")); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test(expected = ArangoDBException.class) - public void abortCommittedStreamTransactionShouldThrow() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void abortCommittedStreamTransactionShouldThrow(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity createdTx = db.beginStreamTransaction(null); db.commitStreamTransaction(createdTx.getId()); - db.abortStreamTransaction(createdTx.getId()); + Throwable thrown = catchThrowable(() -> db.abortStreamTransaction(createdTx.getId())); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void getStreamTransaction() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getStreamTransaction(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -140,33 +140,38 @@ public void getStreamTransaction() { StreamTransactionEntity createdTx = db.beginStreamTransaction(null); StreamTransactionEntity gotTx = db.getStreamTransaction(createdTx.getId()); - assertThat(gotTx.getId(), is(notNullValue())); - assertThat(gotTx.getId(), is(createdTx.getId())); - assertThat(gotTx.getStatus(), is(StreamTransactionStatus.running)); + assertThat(gotTx.getId()).isNotNull(); + assertThat(gotTx.getId()).isEqualTo(createdTx.getId()); + assertThat(gotTx.getStatus()).isEqualTo(StreamTransactionStatus.running); db.abortStreamTransaction(createdTx.getId()); } - @Test(expected = ArangoDBException.class) - public void getStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - db.getStreamTransaction("000000"); + Throwable thrown = catchThrowable(() -> db.getStreamTransaction("000000")); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test(expected = ArangoDBException.class) - public void getStreamTransactionWithInvalidTransactionIdShouldThrow() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getStreamTransactionWithInvalidTransactionIdShouldThrow(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - db.getStreamTransaction("invalidTransactionId"); + Throwable thrown = catchThrowable(() -> db.getStreamTransaction("invalidTransactionId")); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void commitStreamTransaction() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void commitStreamTransaction(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -174,13 +179,14 @@ public void commitStreamTransaction() { StreamTransactionEntity createdTx = db.beginStreamTransaction(null); StreamTransactionEntity committedTx = db.commitStreamTransaction(createdTx.getId()); - assertThat(committedTx.getId(), is(notNullValue())); - assertThat(committedTx.getId(), is(createdTx.getId())); - assertThat(committedTx.getStatus(), is(StreamTransactionStatus.committed)); + assertThat(committedTx.getId()).isNotNull(); + assertThat(committedTx.getId()).isEqualTo(createdTx.getId()); + assertThat(committedTx.getStatus()).isEqualTo(StreamTransactionStatus.committed); } - @Test - public void commitStreamTransactionTwice() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void commitStreamTransactionTwice(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -190,43 +196,51 @@ public void commitStreamTransactionTwice() { db.commitStreamTransaction(createdTx.getId()); } - @Test(expected = ArangoDBException.class) - public void commitStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void commitStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - db.commitStreamTransaction("000000"); + Throwable thrown = catchThrowable(() -> db.commitStreamTransaction("000000")); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test(expected = ArangoDBException.class) - public void commitStreamTransactionWithInvalidTransactionIdShouldThrow() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void commitStreamTransactionWithInvalidTransactionIdShouldThrow(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - db.commitStreamTransaction("invalidTransactionId"); + Throwable thrown = catchThrowable(() -> db.commitStreamTransaction("invalidTransactionId")); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test(expected = ArangoDBException.class) - public void commitAbortedStreamTransactionShouldThrow() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void commitAbortedStreamTransactionShouldThrow(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity createdTx = db.beginStreamTransaction(null); db.abortStreamTransaction(createdTx.getId()); - db.commitStreamTransaction(createdTx.getId()); + Throwable thrown = catchThrowable(() -> db.commitStreamTransaction(createdTx.getId())); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void getDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getDocument(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); + ArangoCollection collection = db.collection(COLLECTION_NAME); // insert a document from outside the tx DocumentCreateEntity externalDoc = collection @@ -234,39 +248,48 @@ public void getDocument() { // assert that the document is not found from within the tx assertThat(collection.getDocument(externalDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())), is(nullValue())); + new DocumentReadOptions().streamTransactionId(tx.getId()))).isNull(); db.abortStreamTransaction(tx.getId()); } - @Test(expected = ArangoDBException.class) - public void getDocumentWithNonExistingTransactionIdShouldThrow() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getDocumentWithNonExistingTransactionIdShouldThrow(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - collection - .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("123456")); + ArangoCollection collection = db.collection(COLLECTION_NAME); + + Throwable thrown = catchThrowable(() -> collection + .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("123456"))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test(expected = ArangoDBException.class) - public void getDocumentWithInvalidTransactionIdShouldThrow() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getDocumentWithInvalidTransactionIdShouldThrow(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); - collection - .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("abcde")); + ArangoCollection collection = db.collection(COLLECTION_NAME); + Throwable thrown = catchThrowable(() -> collection + .getDocument("docId", BaseDocument.class, new DocumentReadOptions().streamTransactionId("abcde"))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } - @Test - public void getDocuments() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getDocuments(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); + ArangoCollection collection = db.collection(COLLECTION_NAME); // insert documents from outside the tx DocumentCreateEntity externalDoc1 = collection @@ -280,47 +303,49 @@ public void getDocuments() { .getDocuments(Arrays.asList(externalDoc1.getId(), externalDoc2.getId()), BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())); - assertThat(documents.getDocuments(), is(empty())); + assertThat(documents.getDocuments()).isEmpty(); db.abortStreamTransaction(tx.getId()); } - @Test - public void insertDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void insertDocument(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + ArangoCollection collection = db.collection(COLLECTION_NAME); // insert a document from within the tx DocumentCreateEntity txDoc = collection .insertDocument(new BaseDocument(), new DocumentCreateOptions().streamTransactionId(tx.getId())); // assert that the document is not found from outside the tx - assertThat(collection.getDocument(txDoc.getKey(), BaseDocument.class, null), - is(nullValue())); + assertThat(collection.getDocument(txDoc.getKey(), BaseDocument.class, null)).isNull(); // assert that the document is found from within the tx assertThat(collection.getDocument(txDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())), is(notNullValue())); + new DocumentReadOptions().streamTransactionId(tx.getId()))).isNotNull(); db.commitStreamTransaction(tx.getId()); // assert that the document is found after commit - assertThat(collection.getDocument(txDoc.getKey(), BaseDocument.class, null), - is(notNullValue())); + assertThat(collection.getDocument(txDoc.getKey(), BaseDocument.class, null)).isNotNull(); } - @Test - public void insertDocuments() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void insertDocuments(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + ArangoCollection collection = db.collection(COLLECTION_NAME); // insert documents from within the tx MultiDocumentEntity> txDocs = collection @@ -330,23 +355,22 @@ public void insertDocuments() { List keys = txDocs.getDocuments().stream().map(DocumentEntity::getKey).collect(Collectors.toList()); // assert that the documents are not found from outside the tx - assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments(), - is(empty())); + assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments()).isEmpty(); // assert that the documents are found from within the tx assertThat(collection .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) - .getDocuments(), hasSize(keys.size())); + .getDocuments()).hasSize(keys.size()); db.commitStreamTransaction(tx.getId()); // assert that the document is found after commit - assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments(), - hasSize(keys.size())); + assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments()).hasSize(keys.size()); } - @Test - public void replaceDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void replaceDocument(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -354,6 +378,7 @@ public void replaceDocument() { BaseDocument doc = new BaseDocument(); doc.addAttribute("test", "foo"); + ArangoCollection collection = db.collection(COLLECTION_NAME); DocumentCreateEntity createdDoc = collection.insertDocument(doc, null); StreamTransactionEntity tx = db.beginStreamTransaction( @@ -367,21 +392,22 @@ public void replaceDocument() { // assert that the document has not been replaced from outside the tx assertThat(collection.getDocument(createdDoc.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("foo")); + .getProperties()).containsEntry("test", "foo"); // assert that the document has been replaced from within the tx assertThat(collection.getDocument(createdDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())).getProperties().get("test"), is("bar")); + new DocumentReadOptions().streamTransactionId(tx.getId())).getProperties()).containsEntry("test", "bar"); db.commitStreamTransaction(tx.getId()); // assert that the document has been replaced after commit assertThat(collection.getDocument(createdDoc.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("bar")); + .getProperties()).containsEntry("test", "bar"); } - @Test - public void replaceDocuments() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void replaceDocuments(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -389,6 +415,7 @@ public void replaceDocuments() { List docs = IntStream.range(0, 3).mapToObj(it -> new BaseDocument()) .peek(doc -> doc.addAttribute("test", "foo")).collect(Collectors.toList()); + ArangoCollection collection = db.collection(COLLECTION_NAME); List createdDocs = collection .insertDocuments(docs, new DocumentCreateOptions().returnNew(true)).getDocuments().stream() .map(DocumentCreateEntity::getNew).collect(Collectors.toList()); @@ -408,24 +435,27 @@ public void replaceDocuments() { .replaceDocuments(modifiedDocs, new DocumentReplaceOptions().streamTransactionId(tx.getId())); // assert that the documents has not been replaced from outside the tx - assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments().stream() - .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("foo"))); + collection.getDocuments(keys, BaseDocument.class, null).getDocuments().stream() + .map(it -> ((String) it.getAttribute("test"))) + .forEach(it -> assertThat(it).isEqualTo("foo")); // assert that the document has been replaced from within the tx - assertThat(collection - .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) - .getDocuments().stream().map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), - everyItem(is("bar"))); + collection + .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) + .getDocuments().stream().map(it -> ((String) it.getAttribute("test"))) + .forEach(it -> assertThat(it).isEqualTo("bar")); db.commitStreamTransaction(tx.getId()); // assert that the document has been replaced after commit - assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments().stream() - .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("bar"))); + collection.getDocuments(keys, BaseDocument.class, null).getDocuments().stream() + .map(it -> ((String) it.getAttribute("test"))) + .forEach(it -> assertThat(it).isEqualTo("bar")); } - @Test - public void updateDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void updateDocument(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -433,6 +463,7 @@ public void updateDocument() { BaseDocument doc = new BaseDocument(); doc.addAttribute("test", "foo"); + ArangoCollection collection = db.collection(COLLECTION_NAME); DocumentCreateEntity createdDoc = collection.insertDocument(doc, null); StreamTransactionEntity tx = db.beginStreamTransaction( @@ -446,22 +477,24 @@ public void updateDocument() { // assert that the document has not been updated from outside the tx assertThat(collection.getDocument(createdDoc.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("foo")); + .getProperties()).containsEntry("test", "foo"); // assert that the document has been updated from within the tx assertThat(collection.getDocument(createdDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())).getProperties().get("test"), is("bar")); + new DocumentReadOptions().streamTransactionId(tx.getId())).getProperties()).containsEntry("test", "bar") + ; db.commitStreamTransaction(tx.getId()); // assert that the document has been updated after commit assertThat(collection.getDocument(createdDoc.getKey(), BaseDocument.class, null) - .getProperties().get("test"), is("bar")); + .getProperties()).containsEntry("test", "bar"); } - @Test - public void updateDocuments() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void updateDocuments(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -469,6 +502,7 @@ public void updateDocuments() { List docs = IntStream.range(0, 3).mapToObj(it -> new BaseDocument()) .peek(doc -> doc.addAttribute("test", "foo")).collect(Collectors.toList()); + ArangoCollection collection = db.collection(COLLECTION_NAME); List createdDocs = collection .insertDocuments(docs, new DocumentCreateOptions().returnNew(true)).getDocuments().stream() .map(DocumentCreateEntity::getNew).collect(Collectors.toList()); @@ -488,28 +522,32 @@ public void updateDocuments() { .updateDocuments(modifiedDocs, new DocumentUpdateOptions().streamTransactionId(tx.getId())); // assert that the documents have not been updated from outside the tx - assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments().stream() - .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("foo"))); + collection.getDocuments(keys, BaseDocument.class, null).getDocuments().stream() + .map(it -> ((String) it.getAttribute("test"))) + .forEach(it -> assertThat(it).isEqualTo("foo")); // assert that the documents have been updated from within the tx - List values = collection + collection .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) - .getDocuments().stream().map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()); - assertThat(values, everyItem(is("bar"))); + .getDocuments().stream().map(it -> ((String) it.getAttribute("test"))) + .forEach(it -> assertThat(it).isEqualTo("bar")); db.commitStreamTransaction(tx.getId()); // assert that the document has been updated after commit - assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments().stream() - .map(it -> ((String) it.getAttribute("test"))).collect(Collectors.toList()), everyItem(is("bar"))); + collection.getDocuments(keys, BaseDocument.class, null).getDocuments().stream() + .map(it -> ((String) it.getAttribute("test"))) + .forEach(it -> assertThat(it).isEqualTo("bar")); } - @Test - public void deleteDocument() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void deleteDocument(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + ArangoCollection collection = db.collection(COLLECTION_NAME); DocumentCreateEntity createdDoc = collection .insertDocument(new BaseDocument(), null); @@ -521,26 +559,26 @@ public void deleteDocument() { .deleteDocument(createdDoc.getKey(), null, new DocumentDeleteOptions().streamTransactionId(tx.getId())); // assert that the document has not been deleted from outside the tx - assertThat(collection.getDocument(createdDoc.getKey(), BaseDocument.class, null), - is(notNullValue())); + assertThat(collection.getDocument(createdDoc.getKey(), BaseDocument.class, null)).isNotNull(); // assert that the document has been deleted from within the tx assertThat(collection.getDocument(createdDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())), is(nullValue())); + new DocumentReadOptions().streamTransactionId(tx.getId()))).isNull(); db.commitStreamTransaction(tx.getId()); // assert that the document has been deleted after commit - assertThat(collection.getDocument(createdDoc.getKey(), BaseDocument.class, null), - is(nullValue())); + assertThat(collection.getDocument(createdDoc.getKey(), BaseDocument.class, null)).isNull(); } - @Test - public void deleteDocuments() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void deleteDocuments(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + ArangoCollection collection = db.collection(COLLECTION_NAME); List keys = collection .insertDocuments(Arrays.asList(new BaseDocument(), new BaseDocument(), new BaseDocument()), null) .getDocuments().stream().map(DocumentEntity::getKey).collect(Collectors.toList()); @@ -553,29 +591,29 @@ public void deleteDocuments() { .deleteDocuments(keys, null, new DocumentDeleteOptions().streamTransactionId(tx.getId())); // assert that the documents has not been deleted from outside the tx - assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments(), - hasSize(keys.size())); + assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments()).hasSize(keys.size()); // assert that the document has been deleted from within the tx assertThat(collection .getDocuments(keys, BaseDocument.class, new DocumentReadOptions().streamTransactionId(tx.getId())) - .getDocuments(), is(empty())); + .getDocuments()).isEmpty(); db.commitStreamTransaction(tx.getId()); // assert that the document has been deleted after commit - assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments(), - is(empty())); + assertThat(collection.getDocuments(keys, BaseDocument.class, null).getDocuments()).isEmpty(); } - @Test - public void documentExists() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void documentExists(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); + ArangoCollection collection = db.collection(COLLECTION_NAME); // insert a document from outside the tx DocumentCreateEntity externalDoc = collection @@ -583,18 +621,19 @@ public void documentExists() { // assert that the document is not found from within the tx assertThat(collection - .documentExists(externalDoc.getKey(), new DocumentExistsOptions().streamTransactionId(tx.getId())), - is(false)); + .documentExists(externalDoc.getKey(), new DocumentExistsOptions().streamTransactionId(tx.getId()))).isFalse(); db.abortStreamTransaction(tx.getId()); } - @Test - public void count() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void count(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + ArangoCollection collection = db.collection(COLLECTION_NAME); Long initialCount = collection.count().getCount(); StreamTransactionEntity tx = db @@ -605,17 +644,19 @@ public void count() { // assert that the document is not counted from within the tx assertThat(collection.count(new CollectionCountOptions().streamTransactionId(tx.getId())) - .getCount(), is(initialCount)); + .getCount()).isEqualTo(initialCount); db.abortStreamTransaction(tx.getId()); } - @Test - public void truncate() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void truncate(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); + ArangoCollection collection = db.collection(COLLECTION_NAME); collection.insertDocument(new BaseDocument(), null); StreamTransactionEntity tx = db.beginStreamTransaction( @@ -625,26 +666,28 @@ public void truncate() { collection.truncate(new CollectionTruncateOptions().streamTransactionId(tx.getId())); // assert that the collection has not been truncated from outside the tx - assertThat(collection.count().getCount(), is(greaterThan(0L))); + assertThat(collection.count().getCount()).isPositive(); // assert that the collection has been truncated from within the tx assertThat(collection.count(new CollectionCountOptions().streamTransactionId(tx.getId())) - .getCount(), is(0L)); + .getCount()).isZero(); db.commitStreamTransaction(tx.getId()); // assert that the collection has been truncated after commit - assertThat(collection.count().getCount(), is(0L)); + assertThat(collection.count().getCount()).isZero(); } - @Test - public void createCursor() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void createCursor(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db .beginStreamTransaction(new StreamTransactionOptions().readCollections(COLLECTION_NAME)); + ArangoCollection collection = db.collection(COLLECTION_NAME); // insert a document from outside the tx DocumentCreateEntity externalDoc = collection @@ -659,19 +702,21 @@ public void createCursor() { new AqlQueryOptions().streamTransactionId(tx.getId()), BaseDocument.class); // assert that the document is not found from within the tx - assertThat(cursor.hasNext(), is(false)); + assertThat(cursor.hasNext()).isFalse(); db.abortStreamTransaction(tx.getId()); } - @Test - public void nextCursor() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void nextCursor(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db.beginStreamTransaction( new StreamTransactionOptions().readCollections(COLLECTION_NAME).writeCollections(COLLECTION_NAME)); + ArangoCollection collection = db.collection(COLLECTION_NAME); // insert documents from within the tx List keys = collection @@ -690,14 +735,14 @@ public void nextCursor() { List docs = cursor.asListRemaining(); // assert that all the keys are returned from the query - assertThat(docs.stream().map(BaseDocument::getKey).collect(Collectors.toList()), - containsInAnyOrder(keys.toArray())); + assertThat(docs.stream().map(BaseDocument::getKey).collect(Collectors.toList())).containsAll(keys); db.abortStreamTransaction(tx.getId()); } - @Test - public void getStreamTransactions() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void getStreamTransactions(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -709,37 +754,37 @@ public void getStreamTransactions() { Set gotTxs = db.getStreamTransactions().stream(). filter(it -> createdIds.contains(it.getId())).collect(Collectors.toSet()); - assertThat(gotTxs.size(), is(createdIds.size())); + assertThat(gotTxs).hasSameSizeAs(createdIds); assertThat(gotTxs.stream() - .allMatch(it -> it.getStatus() == StreamTransactionStatus.running), is(true)); + .allMatch(it -> it.getStatus() == StreamTransactionStatus.running)).isTrue(); db.abortStreamTransaction(tx1.getId()); db.abortStreamTransaction(tx2.getId()); } - @Test - public void transactionAllowImplicitFalse() { + @ParameterizedTest(name = "{index}") + @MethodSource("dbs") + void transactionAllowImplicitFalse(ArangoDatabase db) { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db .beginStreamTransaction(new StreamTransactionOptions().allowImplicit(false)); + ArangoCollection collection = db.collection(COLLECTION_NAME); // insert a document from outside the tx DocumentCreateEntity externalDoc = collection .insertDocument(new BaseDocument(), null); // assert that we cannot read from collection - try { - collection.getDocument(externalDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())); - fail(); - } catch (ArangoDBException e) { - assertThat(e.getResponseCode(), is(400)); - assertThat(e.getErrorNum(), is(1652)); - assertThat(e.getMessage(), containsString("unregistered collection used in transaction")); - } + Throwable thrown = catchThrowable(() -> collection.getDocument(externalDoc.getKey(), BaseDocument.class, + new DocumentReadOptions().streamTransactionId(tx.getId()))); + assertThat(thrown).isInstanceOf(ArangoDBException.class); + ArangoDBException e = (ArangoDBException) thrown; + assertThat(e.getResponseCode()).isEqualTo(400); + assertThat(e.getErrorNum()).isEqualTo(1652); + assertThat(e.getMessage()).contains("unregistered collection used in transaction"); db.abortStreamTransaction(tx.getId()); } diff --git a/src/test/java/com/arangodb/UserAuthTest.java b/src/test/java/com/arangodb/UserAuthTest.java deleted file mode 100644 index 6b3d604d8..000000000 --- a/src/test/java/com/arangodb/UserAuthTest.java +++ /dev/null @@ -1,898 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2017 ArangoDB GmbH, Cologne, Germany - * - * 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 - * - * 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. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb; - -import com.arangodb.entity.*; -import com.arangodb.model.AqlQueryOptions; -import com.arangodb.model.CollectionPropertiesOptions; -import com.arangodb.model.HashIndexOptions; -import com.arangodb.model.UserUpdateOptions; -import com.arangodb.util.MapBuilder; -import org.junit.AfterClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.fail; - -/** - * @author Mark Vollmary - */ -@SuppressWarnings("ALL") -@RunWith(Parameterized.class) -@Ignore -public class UserAuthTest { - - private static final DbName DB_NAME = DbName.of("AuthUnitTestDB"); - private static final DbName DB_NAME_NEW = DB_NAME.of(DB_NAME.get() + "new"); - private static final String COLLECTION_NAME = "AuthUnitTestCollection"; - private static final String COLLECTION_NAME_NEW = COLLECTION_NAME + "new"; - private static final String USER_NAME = "AuthUnitTestUser"; - private static final String USER_NAME_NEW = USER_NAME + "new"; - - static class UserAuthParam { - final Protocol protocol; - final Permissions systemPermission; - final Permissions dbPermission; - final Permissions colPermission; - - UserAuthParam(final Protocol protocol, final Permissions systemPermission, - final Permissions dbPermission, final Permissions colPermission) { - super(); - this.protocol = protocol; - this.systemPermission = systemPermission; - this.dbPermission = dbPermission; - this.colPermission = colPermission; - } - - } - - @Parameters - public static Collection params() { - final Collection params = new ArrayList<>(); - final Permissions[] permissions = new Permissions[]{Permissions.RW, Permissions.RO, Permissions.NONE}; - for (final Protocol protocol : new Protocol[]{Protocol.VST, Protocol.HTTP_JSON, Protocol.HTTP_VPACK}) { - for (final Permissions systemPermission : permissions) { - for (final Permissions dbPermission : permissions) { - for (final Permissions colPermission : permissions) { - params.add(new UserAuthParam(protocol, systemPermission, dbPermission, colPermission)); - } - } - } - } - return params; - } - - private static ArangoDB arangoDB; - private static ArangoDB arangoDBRoot; - private final UserAuthParam param; - private final String details; - - public UserAuthTest(final UserAuthParam param) { - super(); - this.param = param; - if (arangoDB != null || arangoDBRoot != null) { - shutdown(); - } - arangoDBRoot = new ArangoDB.Builder().useProtocol(param.protocol).build(); - arangoDBRoot.createUser(USER_NAME, ""); - arangoDB = new ArangoDB.Builder().useProtocol(param.protocol).user(USER_NAME).build(); - arangoDBRoot.createDatabase(DB_NAME); - arangoDBRoot.db(DB_NAME).createCollection(COLLECTION_NAME); - arangoDBRoot.db().grantAccess(USER_NAME, param.systemPermission); - arangoDBRoot.db(DB_NAME).grantAccess(USER_NAME, param.dbPermission); - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).grantAccess(USER_NAME, param.colPermission); - details = param.protocol + "_" + param.systemPermission + "_" + - param.dbPermission + "_" + param.colPermission; - } - - @AfterClass - public static void shutdown() { - arangoDBRoot.deleteUser(USER_NAME); - if (arangoDBRoot.db(DB_NAME).exists()) - arangoDBRoot.db(DB_NAME).drop(); - if (arangoDB != null) { - arangoDB.shutdown(); - } - arangoDBRoot.shutdown(); - arangoDB = null; - arangoDBRoot = null; - } - - @Test - public void createDatabase() { - try { - if (Permissions.RW.equals(param.systemPermission)) { - try { - assertThat(details, arangoDB.createDatabase(DB_NAME_NEW), is(true)); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.getDatabases(), hasItem(DB_NAME_NEW.get())); - } else { - try { - arangoDB.createDatabase(DB_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.getDatabases(), not(hasItem(DB_NAME_NEW.get()))); - } - } finally { - try { - arangoDBRoot.db(DB_NAME_NEW).drop(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void dropDatabase() { - try { - arangoDBRoot.createDatabase(DB_NAME_NEW); - if (Permissions.RW.equals(param.systemPermission)) { - try { - assertThat(details, arangoDB.db(DB_NAME).drop(), is(true)); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.getDatabases(), not(hasItem(DB_NAME.get()))); - } else { - try { - arangoDB.db(DB_NAME).drop(); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.getDatabases(), hasItem(DB_NAME.get())); - } - } finally { - try { - arangoDBRoot.db(DB_NAME_NEW).drop(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void createUser() { - try { - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.createUser(USER_NAME_NEW, ""); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.getUsers(), is(notNullValue())); - } else { - try { - arangoDB.createUser(USER_NAME_NEW, ""); - fail(details); - } catch (final ArangoDBException e) { - } - try { - arangoDBRoot.getUser(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void deleteUser() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - fail(details); - } - try { - arangoDBRoot.getUser(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - } else { - try { - arangoDB.deleteUser(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.getUsers(), is(notNullValue())); - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void updateUser() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.updateUser(USER_NAME_NEW, new UserUpdateOptions().active(false)); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.getUser(USER_NAME_NEW).getActive(), is(false)); - } else { - try { - arangoDB.updateUser(USER_NAME_NEW, new UserUpdateOptions().active(false)); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.getUser(USER_NAME_NEW).getActive(), is(true)); - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void grantUserDBAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.db().grantAccess(USER_NAME_NEW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db().grantAccess(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void resetUserDBAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - arangoDBRoot.db().grantAccess(USER_NAME_NEW); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.db(DB_NAME).resetAccess(USER_NAME_NEW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).resetAccess(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void grantUserCollcetionAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).grantAccess(USER_NAME_NEW, Permissions.RW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).grantAccess(USER_NAME_NEW, Permissions.RW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void resetUserCollectionAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - arangoDBRoot.db().grantAccess(USER_NAME_NEW); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).resetAccess(USER_NAME_NEW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).resetAccess(USER_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void updateUserDefaultDatabaseAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - arangoDBRoot.db().grantAccess(USER_NAME_NEW); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.grantDefaultDatabaseAccess(USER_NAME_NEW, Permissions.RW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.grantDefaultDatabaseAccess(USER_NAME_NEW, Permissions.RW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void updateUserDefaultCollectionAccess() { - try { - arangoDBRoot.createUser(USER_NAME_NEW, ""); - arangoDBRoot.db().grantAccess(USER_NAME_NEW); - if (Permissions.RW.equals(param.systemPermission)) { - try { - arangoDB.grantDefaultCollectionAccess(USER_NAME_NEW, Permissions.RW); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.grantDefaultCollectionAccess(USER_NAME_NEW, Permissions.RW); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.deleteUser(USER_NAME_NEW); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void createCollection() { - try { - if (Permissions.RW.equals(param.dbPermission)) { - try { - arangoDB.db(DB_NAME).createCollection(COLLECTION_NAME_NEW); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(), - is(notNullValue())); - } else { - try { - arangoDB.db(DB_NAME).createCollection(COLLECTION_NAME_NEW); - fail(details); - } catch (final ArangoDBException e) { - } - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(); - fail(details); - } catch (final ArangoDBException e) { - } - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void dropCollection() { - try { - arangoDBRoot.db(DB_NAME).createCollection(COLLECTION_NAME_NEW); - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).grantAccess(USER_NAME, param.colPermission); - if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); - } catch (final ArangoDBException e) { - fail(details); - } - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(); - fail(details); - } catch (final ArangoDBException e) { - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).getInfo(), - is(notNullValue())); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME_NEW).drop(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void seeCollection() { - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - try { - final Collection collections = arangoDB.db(DB_NAME).getCollections(); - boolean found = false; - for (final CollectionEntity collection : collections) { - if (collection.getName().equals(COLLECTION_NAME)) { - found = true; - break; - } - } - assertThat(details, found, is(true)); - } catch (final ArangoDBException e) { - fail(details); - } - } else if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission))) { - final Collection collections = arangoDB.db(DB_NAME).getCollections(); - boolean found = false; - for (final CollectionEntity collection : collections) { - if (collection.getName().equals(COLLECTION_NAME)) { - found = true; - break; - } - } - assertThat(details, found, is(false)); - } - } - - @Test - public void readCollectionInfo() { - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - try { - assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getInfo(), is(notNullValue())); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getInfo(); - fail(details); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void readCollectionProperties() { - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - try { - assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getProperties(), - is(notNullValue())); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getProperties(); - fail(details); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void writeCollectionProperties() { - if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { - try { - assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME) - .changeProperties(new CollectionPropertiesOptions().waitForSync(true)), - is(notNullValue())); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getProperties().getWaitForSync(), - is(true)); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME) - .changeProperties(new CollectionPropertiesOptions().waitForSync(true)); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getProperties().getWaitForSync(), - is(false)); - } - } - - @Test - public void readCollectionIndexes() { - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - try { - assertThat(details, arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getIndexes(), is(notNullValue())); - } catch (final ArangoDBException e) { - fail(details); - } - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getIndexes(); - fail(details); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void createCollectionIndex() { - String id = null; - try { - if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { - try { - final IndexEntity createHashIndex = arangoDB.db(DB_NAME).collection(COLLECTION_NAME) - .ensureHashIndex(Collections.singletonList("a"), new HashIndexOptions()); - assertThat(details, createHashIndex, is(notNullValue())); - id = createHashIndex.getId(); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(2)); - } else { - try { - final IndexEntity createHashIndex = arangoDB.db(DB_NAME).collection(COLLECTION_NAME) - .ensureHashIndex(Collections.singletonList("a"), new HashIndexOptions()); - id = createHashIndex.getId(); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(1)); - } - } finally { - if (id != null) { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); - } - } - } - - @Test - public void dropCollectionIndex() { - final String id = arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) - .ensureHashIndex(Collections.singletonList("a"), new HashIndexOptions()).getId(); - try { - if (Permissions.RW.equals(param.dbPermission) && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(1)); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).getIndexes().size(), is(2)); - } - } finally { - if (id != null) { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteIndex(id); - } catch (final ArangoDBException e) { - } - } - } - } - - @Test - public void truncateCollection() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).truncate(); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(false)); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).truncate(); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(true)); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).truncate(); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void readDocumentByKey() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - assertThat(details, - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getDocument("123", BaseDocument.class), - is(notNullValue())); - } else { - assertThat(details, - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getDocument("123", BaseDocument.class), - is(nullValue())); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void readDocumentByAql() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && (Permissions.RW.equals(param.colPermission) || Permissions.RO.equals(param.colPermission))) { - assertThat(details, - arangoDB.db(DB_NAME).query("FOR i IN @@col RETURN i", - new MapBuilder().put("@col", COLLECTION_NAME).get(), new AqlQueryOptions(), BaseDocument.class) - .asListRemaining().size(), - is(1)); - } else { - assertThat(details, - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).getDocument("123", BaseDocument.class), - is(nullValue())); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void insertDocument() { - try { - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(true)); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(false)); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void updateDocumentByKey() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).updateDocument("123", - new BaseDocument(new MapBuilder().put("test", "test").get())); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) - .getDocument("123", BaseDocument.class).getAttribute("test").toString(), - is("test")); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).updateDocument("123", - new BaseDocument(new MapBuilder().put("test", "test").get())); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) - .getDocument("123", BaseDocument.class).getAttribute("test"), - is(nullValue())); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void updateDocumentByAql() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).query("FOR i IN @@col UPDATE i WITH @newDoc IN @@col", - new MapBuilder().put("@col", COLLECTION_NAME) - .put("newDoc", new BaseDocument(new MapBuilder().put("test", "test").get())).get(), - new AqlQueryOptions(), Void.class); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) - .getDocument("123", BaseDocument.class).getAttribute("test").toString(), - is("test")); - } else { - try { - arangoDB.db(DB_NAME).query("FOR i IN @@col UPDATE i WITH @newDoc IN @@col", - new MapBuilder().put("@col", COLLECTION_NAME) - .put("newDoc", new BaseDocument(new MapBuilder().put("test", "test").get())).get(), - new AqlQueryOptions(), Void.class); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME) - .getDocument("123", BaseDocument.class).getAttribute("test"), - is(nullValue())); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void deleteDocumentByKey() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(false)); - } else { - try { - arangoDB.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(true)); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - - @Test - public void deleteDocumentByAql() { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).insertDocument(new BaseDocument("123")); - if ((Permissions.RW.equals(param.dbPermission) || Permissions.RO.equals(param.dbPermission)) - && Permissions.RW.equals(param.colPermission)) { - try { - arangoDB.db(DB_NAME).query("REMOVE @key IN @@col", - new MapBuilder().put("key", "123").put("@col", COLLECTION_NAME).get(), new AqlQueryOptions(), - Void.class); - } catch (final ArangoDBException e) { - fail(details); - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(false)); - } else { - try { - arangoDB.db(DB_NAME).query("REMOVE @key IN @@col", - new MapBuilder().put("key", "123").put("@col", COLLECTION_NAME).get(), new AqlQueryOptions(), - Void.class); - fail(details); - } catch (final ArangoDBException e) { - } - assertThat(details, arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).documentExists("123"), - is(true)); - } - } finally { - try { - arangoDBRoot.db(DB_NAME).collection(COLLECTION_NAME).deleteDocument("123"); - } catch (final ArangoDBException e) { - } - } - } - -} diff --git a/src/test/java/com/arangodb/async/ArangoCollectionTest.java b/src/test/java/com/arangodb/async/ArangoCollectionTest.java index a3fb6390f..e3a675f96 100644 --- a/src/test/java/com/arangodb/async/ArangoCollectionTest.java +++ b/src/test/java/com/arangodb/async/ArangoCollectionTest.java @@ -24,9 +24,9 @@ import com.arangodb.entity.*; import com.arangodb.model.*; import com.arangodb.model.DocumentImportOptions.OnDuplicate; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.*; import java.util.concurrent.CompletableFuture; @@ -34,191 +34,191 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Mark Vollmary * @author Michele Rastelli */ -public class ArangoCollectionTest extends BaseTest { +class ArangoCollectionTest extends BaseTest { private static final String COLLECTION_NAME = "db_collection_test"; - public ArangoCollectionTest() throws ExecutionException, InterruptedException { + ArangoCollectionTest() throws ExecutionException, InterruptedException { ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); if (!collection.exists().get()) { collection.create().get(); } } - @BeforeClass - public static void setup() throws InterruptedException, ExecutionException { + @BeforeAll + static void setup() throws InterruptedException, ExecutionException { db.createCollection(COLLECTION_NAME, null).get(); } - @After - public void teardown() throws InterruptedException, ExecutionException { + @AfterEach + void teardown() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).drop().get(); } @Test - public void create() throws InterruptedException, ExecutionException { + void create() throws InterruptedException, ExecutionException { final CollectionEntity result = db.collection(COLLECTION_NAME + "_1").create().get(); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); db.collection(COLLECTION_NAME + "_1").drop().get(); } @Test - public void insertDocument() throws InterruptedException, ExecutionException { + void insertDocument() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument(), null) .whenComplete((doc, ex) -> { - assertThat(ex, is(nullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); - assertThat(doc.getNew(), is(nullValue())); - assertThat(doc.getId(), is(COLLECTION_NAME + "/" + doc.getKey())); + assertThat(ex).isNull(); + assertThat(doc.getId()).isNotNull(); + assertThat(doc.getKey()).isNotNull(); + assertThat(doc.getRev()).isNotNull(); + assertThat(doc.getNew()).isNull(); + assertThat(doc.getId()).isEqualTo(COLLECTION_NAME + "/" + doc.getKey()); }) .get(); } @Test - public void insertDocumentReturnNew() throws InterruptedException, ExecutionException { + void insertDocumentReturnNew() throws InterruptedException, ExecutionException { final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument(), options) .whenComplete((doc, ex) -> { - assertThat(doc, is(notNullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); - assertThat(doc.getNew(), is(notNullValue())); + assertThat(doc).isNotNull(); + assertThat(doc.getId()).isNotNull(); + assertThat(doc.getKey()).isNotNull(); + assertThat(doc.getRev()).isNotNull(); + assertThat(doc.getNew()).isNotNull(); }) .get(); } @Test - public void insertDocumentWaitForSync() throws InterruptedException, ExecutionException { + void insertDocumentWaitForSync() throws InterruptedException, ExecutionException { final DocumentCreateOptions options = new DocumentCreateOptions().waitForSync(true); db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument(), options) .whenComplete((doc, ex) -> { - assertThat(doc, is(notNullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); - assertThat(doc.getNew(), is(nullValue())); + assertThat(doc).isNotNull(); + assertThat(doc.getId()).isNotNull(); + assertThat(doc.getKey()).isNotNull(); + assertThat(doc.getRev()).isNotNull(); + assertThat(doc.getNew()).isNull(); }) .get(); } @Test - public void insertDocumentAsJson() throws InterruptedException, ExecutionException { + void insertDocumentAsJson() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME) .insertDocument("{\"_key\":\"docRaw\",\"a\":\"test\"}", null) .whenComplete((doc, ex) -> { - assertThat(doc, is(notNullValue())); - assertThat(doc.getId(), is(notNullValue())); - assertThat(doc.getKey(), is(notNullValue())); - assertThat(doc.getRev(), is(notNullValue())); + assertThat(doc).isNotNull(); + assertThat(doc.getId()).isNotNull(); + assertThat(doc.getKey()).isNotNull(); + assertThat(doc.getRev()).isNotNull(); }) .get(); } @Test - public void getDocument() throws InterruptedException, ExecutionException { + void getDocument() throws InterruptedException, ExecutionException { final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument(), null).get(); - assertThat(createResult.getKey(), is(notNullValue())); + assertThat(createResult.getKey()).isNotNull(); db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, null) .whenComplete((readResult, ex) -> { - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(COLLECTION_NAME + "/" + createResult.getKey()); }) .get(); } @Test - public void getDocumentIfMatch() throws InterruptedException, ExecutionException { + void getDocumentIfMatch() throws InterruptedException, ExecutionException { final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument(), null).get(); - assertThat(createResult.getKey(), is(notNullValue())); + assertThat(createResult.getKey()).isNotNull(); final DocumentReadOptions options = new DocumentReadOptions().ifMatch(createResult.getRev()); db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, options) .whenComplete((readResult, ex) -> { - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(COLLECTION_NAME + "/" + createResult.getKey()); }) .get(); } @Test - public void getDocumentIfMatchFail() throws InterruptedException, ExecutionException { + void getDocumentIfMatchFail() throws InterruptedException, ExecutionException { final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument(), null).get(); - assertThat(createResult.getKey(), is(notNullValue())); + assertThat(createResult.getKey()).isNotNull(); final DocumentReadOptions options = new DocumentReadOptions().ifMatch("no"); db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, options) - .whenComplete((doc, ex) -> assertThat(doc, is(nullValue()))) + .whenComplete((doc, ex) -> assertThat(doc).isNull()) .get(); } @Test - public void getDocumentIfNoneMatch() throws InterruptedException, ExecutionException { + void getDocumentIfNoneMatch() throws InterruptedException, ExecutionException { final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument(), null).get(); - assertThat(createResult.getKey(), is(notNullValue())); + assertThat(createResult.getKey()).isNotNull(); final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch("no"); db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, options) .whenComplete((readResult, ex) -> { - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(COLLECTION_NAME + "/" + createResult.getKey())); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(COLLECTION_NAME + "/" + createResult.getKey()); }) .get(); } @Test - public void getDocumentIfNoneMatchFail() throws InterruptedException, ExecutionException { + void getDocumentIfNoneMatchFail() throws InterruptedException, ExecutionException { final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument(new BaseDocument(), null).get(); - assertThat(createResult.getKey(), is(notNullValue())); + assertThat(createResult.getKey()).isNotNull(); final DocumentReadOptions options = new DocumentReadOptions().ifNoneMatch(createResult.getRev()); db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, options) - .whenComplete((doc, ex) -> assertThat(doc, is(nullValue()))) + .whenComplete((doc, ex) -> assertThat(doc).isNull()) .get(); } @Test - public void getDocumentAsJson() throws InterruptedException, ExecutionException { + void getDocumentAsJson() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"docRaw\",\"a\":\"test\"}", null).get(); db.collection(COLLECTION_NAME).getDocument("docRaw", String.class, null) .whenComplete((readResult, ex) -> { - assertThat(readResult.contains("\"_key\":\"docRaw\""), is(true)); - assertThat(readResult.contains("\"_id\":\"db_collection_test/docRaw\""), is(true)); + assertThat(readResult.contains("\"_key\":\"docRaw\"")).isEqualTo(true); + assertThat(readResult.contains("\"_id\":\"db_collection_test/docRaw\"")).isEqualTo(true); }) .get(); } @Test - public void getDocumentNotFound() throws InterruptedException, ExecutionException { + void getDocumentNotFound() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).getDocument("no", BaseDocument.class) - .whenComplete((doc, ex) -> assertThat(doc, is(nullValue()))) + .whenComplete((doc, ex) -> assertThat(doc).isNull()) .get(); } - @Test(expected = ArangoDBException.class) - public void getDocumentWrongKey() { - db.collection(COLLECTION_NAME).getDocument("no/no", BaseDocument.class); + @Test + void getDocumentWrongKey() { + Throwable thrown = catchThrowable(() -> db.collection(COLLECTION_NAME).getDocument("no/no", BaseDocument.class)); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } @Test - public void getDocuments() throws InterruptedException, ExecutionException { + void getDocuments() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); @@ -226,34 +226,33 @@ public void getDocuments() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).insertDocuments(values).get(); final MultiDocumentEntity documents = db.collection(COLLECTION_NAME) .getDocuments(Arrays.asList("1", "2", "3"), BaseDocument.class).get(); - assertThat(documents, is(notNullValue())); - assertThat(documents.getDocuments().size(), is(3)); + assertThat(documents).isNotNull(); + assertThat(documents.getDocuments()).hasSize(3); for (final BaseDocument document : documents.getDocuments()) { - assertThat(document.getId(), - isOneOf(COLLECTION_NAME + "/" + "1", COLLECTION_NAME + "/" + "2", COLLECTION_NAME + "/" + "3")); + assertThat(document.getId()).isIn(COLLECTION_NAME + "/" + "1", COLLECTION_NAME + "/" + "2", COLLECTION_NAME + "/" + "3"); } } @Test - public void getDocumentsNotFound() throws InterruptedException, ExecutionException { + void getDocumentsNotFound() throws InterruptedException, ExecutionException { final MultiDocumentEntity readResult = db.collection(COLLECTION_NAME) .getDocuments(Collections.singleton("no"), BaseDocument.class).get(); - assertThat(readResult, is(notNullValue())); - assertThat(readResult.getDocuments().size(), is(0)); - assertThat(readResult.getErrors().size(), is(1)); + assertThat(readResult).isNotNull(); + assertThat(readResult.getDocuments()).isEmpty(); + assertThat(readResult.getErrors()).hasSize(1); } @Test - public void getDocumentsWrongKey() throws InterruptedException, ExecutionException { + void getDocumentsWrongKey() throws InterruptedException, ExecutionException { final MultiDocumentEntity readResult = db.collection(COLLECTION_NAME) .getDocuments(Collections.singleton("no/no"), BaseDocument.class).get(); - assertThat(readResult, is(notNullValue())); - assertThat(readResult.getDocuments().size(), is(0)); - assertThat(readResult.getErrors().size(), is(1)); + assertThat(readResult).isNotNull(); + assertThat(readResult.getDocuments()).isEmpty(); + assertThat(readResult.getErrors()).hasSize(1); } @Test - public void updateDocument() throws InterruptedException, ExecutionException { + void updateDocument() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -266,46 +265,46 @@ public void updateDocument() throws InterruptedException, ExecutionException { final CompletableFuture> f = db.collection(COLLECTION_NAME) .updateDocument(createResult.getKey(), doc, null); f.whenComplete((updateResult, ex) -> { - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getNew(), is(nullValue())); - assertThat(updateResult.getOld(), is(nullValue())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getNew()).isNull(); + assertThat(updateResult.getOld()).isNull(); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); }).get(); final DocumentUpdateEntity updateResult = f.get(); final BaseDocument readResult = db.collection(COLLECTION_NAME) .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); } @Test - public void updateDocumentWithDifferentReturnType() throws ExecutionException, InterruptedException { + void updateDocumentWithDifferentReturnType() throws ExecutionException, InterruptedException { ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - final String key = "key-" + UUID.randomUUID().toString(); + final String key = "key-" + UUID.randomUUID(); final BaseDocument doc = new BaseDocument(key); doc.addAttribute("a", "test"); collection.insertDocument(doc).get(); final DocumentUpdateEntity updateResult = collection .updateDocument(key, Collections.singletonMap("b", "test"), new DocumentUpdateOptions().returnNew(true), BaseDocument.class).get(); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getKey(), is(key)); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getKey()).isEqualTo(key); BaseDocument updated = updateResult.getNew(); - assertThat(updated, is(notNullValue())); - assertThat(updated.getAttribute("a"), is("test")); - assertThat(updated.getAttribute("b"), is("test")); + assertThat(updated).isNotNull(); + assertThat(updated.getAttribute("a")).isEqualTo("test"); + assertThat(updated.getAttribute("b")).isEqualTo("test"); } @Test - public void updateDocumentIfMatch() throws InterruptedException, ExecutionException { + void updateDocumentIfMatch() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -317,28 +316,28 @@ public void updateDocumentIfMatch() throws InterruptedException, ExecutionExcept final DocumentUpdateOptions options = new DocumentUpdateOptions().ifMatch(createResult.getRev()); final CompletableFuture> f = db.collection(COLLECTION_NAME) .updateDocument(createResult.getKey(), doc, options); - assertThat(f, is(notNullValue())); + assertThat(f).isNotNull(); f.whenComplete((updateResult, ex) -> { - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); }).get(); final DocumentUpdateEntity updateResult = f.get(); final BaseDocument readResult = db.collection(COLLECTION_NAME) .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); } @Test - public void updateDocumentIfMatchFail() throws InterruptedException, ExecutionException { + void updateDocumentIfMatchFail() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -352,12 +351,12 @@ public void updateDocumentIfMatchFail() throws InterruptedException, ExecutionEx db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void updateDocumentReturnNew() throws InterruptedException, ExecutionException { + void updateDocumentReturnNew() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -367,22 +366,22 @@ public void updateDocumentReturnNew() throws InterruptedException, ExecutionExce final DocumentUpdateOptions options = new DocumentUpdateOptions().returnNew(true); db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) .whenComplete((updateResult, ex) -> { - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - assertThat(updateResult.getNew(), is(notNullValue())); - assertThat(updateResult.getNew().getKey(), is(createResult.getKey())); - assertThat(updateResult.getNew().getRevision(), is(not(createResult.getRev()))); - assertThat(updateResult.getNew().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(updateResult.getNew().getAttribute("a")), is("test1")); - assertThat(updateResult.getNew().getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(updateResult.getNew().getAttribute("b")), is("test")); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); + assertThat(updateResult.getNew()).isNotNull(); + assertThat(updateResult.getNew().getKey()).isEqualTo(createResult.getKey()); + assertThat(updateResult.getNew().getRevision()).isNotEqualTo(createResult.getRev()); + assertThat(updateResult.getNew().getAttribute("a")).isNotNull(); + assertThat(String.valueOf(updateResult.getNew().getAttribute("a"))).isEqualTo("test1"); + assertThat(updateResult.getNew().getAttribute("b")).isNotNull(); + assertThat(String.valueOf(updateResult.getNew().getAttribute("b"))).isEqualTo("test"); }) .get(); } @Test - public void updateDocumentReturnOld() throws InterruptedException, ExecutionException { + void updateDocumentReturnOld() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -392,21 +391,21 @@ public void updateDocumentReturnOld() throws InterruptedException, ExecutionExce final DocumentUpdateOptions options = new DocumentUpdateOptions().returnOld(true); db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) .whenComplete((updateResult, ex) -> { - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); - assertThat(updateResult.getOld(), is(notNullValue())); - assertThat(updateResult.getOld().getKey(), is(createResult.getKey())); - assertThat(updateResult.getOld().getRevision(), is(createResult.getRev())); - assertThat(updateResult.getOld().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(updateResult.getOld().getAttribute("a")), is("test")); - assertThat(updateResult.getOld().getProperties().keySet(), not(hasItem("b"))); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); + assertThat(updateResult.getOld()).isNotNull(); + assertThat(updateResult.getOld().getKey()).isEqualTo(createResult.getKey()); + assertThat(updateResult.getOld().getRevision()).isEqualTo(createResult.getRev()); + assertThat(updateResult.getOld().getAttribute("a")).isNotNull(); + assertThat(String.valueOf(updateResult.getOld().getAttribute("a"))).isEqualTo("test"); + assertThat(updateResult.getOld().getProperties().keySet()).doesNotContain("b"); }) .get(); } @Test - public void updateDocumentKeepNullTrue() throws InterruptedException, ExecutionException { + void updateDocumentKeepNullTrue() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -415,21 +414,21 @@ public void updateDocumentKeepNullTrue() throws InterruptedException, ExecutionE final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(true); db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) .whenComplete((updateResult, ex) -> { - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); }) .get(); final BaseDocument readResult = db.collection(COLLECTION_NAME) .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet(), hasItem("a")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getProperties()).containsKey("a"); } @Test - public void updateDocumentKeepNullFalse() throws InterruptedException, ExecutionException { + void updateDocumentKeepNullFalse() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -438,24 +437,24 @@ public void updateDocumentKeepNullFalse() throws InterruptedException, Execution final DocumentUpdateOptions options = new DocumentUpdateOptions().keepNull(false); db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) .whenComplete((updateResult, ex) -> { - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); }) .get(); final BaseDocument readResult = db.collection(COLLECTION_NAME) .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getRevision(), is(notNullValue())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getRevision()).isNotNull(); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); } @SuppressWarnings("unchecked") @Test - public void updateDocumentMergeObjectsTrue() throws InterruptedException, ExecutionException { + void updateDocumentMergeObjectsTrue() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); final Map a = new HashMap<>(); a.put("a", "test"); @@ -468,26 +467,26 @@ public void updateDocumentMergeObjectsTrue() throws InterruptedException, Execut final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(true); db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) .whenComplete((updateResult, ex) -> { - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); }) .get(); final BaseDocument readResult = db.collection(COLLECTION_NAME) .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); final Object aResult = readResult.getAttribute("a"); - assertThat(aResult, instanceOf(Map.class)); + assertThat(aResult).isInstanceOf(Map.class); final Map aMap = (Map) aResult; - assertThat(aMap.keySet(), hasItem("a")); - assertThat(aMap.keySet(), hasItem("b")); + assertThat(aMap).containsKey("a"); + assertThat(aMap).containsKey("b"); } @SuppressWarnings("unchecked") @Test - public void updateDocumentMergeObjectsFalse() throws InterruptedException, ExecutionException { + void updateDocumentMergeObjectsFalse() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); final Map a = new HashMap<>(); a.put("a", "test"); @@ -500,25 +499,25 @@ public void updateDocumentMergeObjectsFalse() throws InterruptedException, Execu final DocumentUpdateOptions options = new DocumentUpdateOptions().mergeObjects(false); db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options) .whenComplete((updateResult, ex) -> { - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); }) .get(); final BaseDocument readResult = db.collection(COLLECTION_NAME) .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); final Object aResult = readResult.getAttribute("a"); - assertThat(aResult, instanceOf(Map.class)); + assertThat(aResult).isInstanceOf(Map.class); final Map aMap = (Map) aResult; - assertThat(aMap.keySet(), not(hasItem("a"))); - assertThat(aMap.keySet(), hasItem("b")); + assertThat(aMap.keySet()).doesNotContain("a"); + assertThat(aMap).containsKey("b"); } @Test - public void updateDocumentIgnoreRevsFalse() throws InterruptedException, ExecutionException { + void updateDocumentIgnoreRevsFalse() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -530,12 +529,12 @@ public void updateDocumentIgnoreRevsFalse() throws InterruptedException, Executi db.collection(COLLECTION_NAME).updateDocument(createResult.getKey(), doc, options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void replaceDocument() throws InterruptedException, ExecutionException { + void replaceDocument() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -545,26 +544,26 @@ public void replaceDocument() throws InterruptedException, ExecutionException { final CompletableFuture> f = db.collection(COLLECTION_NAME) .replaceDocument(createResult.getKey(), doc, null); f.whenComplete((replaceResult, ex) -> { - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getNew(), is(nullValue())); - assertThat(replaceResult.getOld(), is(nullValue())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getNew()).isNull(); + assertThat(replaceResult.getOld()).isNull(); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); }).get(); final DocumentUpdateEntity replaceResult = f.get(); final BaseDocument readResult = db.collection(COLLECTION_NAME) .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } @Test - public void replaceDocumentIfMatch() throws InterruptedException, ExecutionException { + void replaceDocumentIfMatch() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -575,24 +574,24 @@ public void replaceDocumentIfMatch() throws InterruptedException, ExecutionExcep final CompletableFuture> f = db.collection(COLLECTION_NAME) .replaceDocument(createResult.getKey(), doc, options); f.whenComplete((replaceResult, ex) -> { - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); }).get(); final DocumentUpdateEntity replaceResult = f.get(); final BaseDocument readResult = db.collection(COLLECTION_NAME) .getDocument(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } @Test - public void replaceDocumentIfMatchFail() throws InterruptedException, ExecutionException { + void replaceDocumentIfMatchFail() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -604,12 +603,12 @@ public void replaceDocumentIfMatchFail() throws InterruptedException, ExecutionE db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void replaceDocumentIgnoreRevsFalse() throws InterruptedException, ExecutionException { + void replaceDocumentIgnoreRevsFalse() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -622,12 +621,12 @@ public void replaceDocumentIgnoreRevsFalse() throws InterruptedException, Execut db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void replaceDocumentReturnNew() throws InterruptedException, ExecutionException { + void replaceDocumentReturnNew() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -637,21 +636,21 @@ public void replaceDocumentReturnNew() throws InterruptedException, ExecutionExc final DocumentReplaceOptions options = new DocumentReplaceOptions().returnNew(true); db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options) .whenComplete((replaceResult, ex) -> { - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - assertThat(replaceResult.getNew(), is(notNullValue())); - assertThat(replaceResult.getNew().getKey(), is(createResult.getKey())); - assertThat(replaceResult.getNew().getRevision(), is(not(createResult.getRev()))); - assertThat(replaceResult.getNew().getProperties().keySet(), not(hasItem("a"))); - assertThat(replaceResult.getNew().getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(replaceResult.getNew().getAttribute("b")), is("test")); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); + assertThat(replaceResult.getNew()).isNotNull(); + assertThat(replaceResult.getNew().getKey()).isEqualTo(createResult.getKey()); + assertThat(replaceResult.getNew().getRevision()).isNotEqualTo(createResult.getRev()); + assertThat(replaceResult.getNew().getProperties().keySet()).doesNotContain("a"); + assertThat(replaceResult.getNew().getAttribute("b")).isNotNull(); + assertThat(String.valueOf(replaceResult.getNew().getAttribute("b"))).isEqualTo("test"); }) .get(); } @Test - public void replaceDocumentReturnOld() throws InterruptedException, ExecutionException { + void replaceDocumentReturnOld() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -661,32 +660,32 @@ public void replaceDocumentReturnOld() throws InterruptedException, ExecutionExc final DocumentReplaceOptions options = new DocumentReplaceOptions().returnOld(true); db.collection(COLLECTION_NAME).replaceDocument(createResult.getKey(), doc, options) .whenComplete((replaceResult, ex) -> { - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); - assertThat(replaceResult.getOld(), is(notNullValue())); - assertThat(replaceResult.getOld().getKey(), is(createResult.getKey())); - assertThat(replaceResult.getOld().getRevision(), is(createResult.getRev())); - assertThat(replaceResult.getOld().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(replaceResult.getOld().getAttribute("a")), is("test")); - assertThat(replaceResult.getOld().getProperties().keySet(), not(hasItem("b"))); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); + assertThat(replaceResult.getOld()).isNotNull(); + assertThat(replaceResult.getOld().getKey()).isEqualTo(createResult.getKey()); + assertThat(replaceResult.getOld().getRevision()).isEqualTo(createResult.getRev()); + assertThat(replaceResult.getOld().getAttribute("a")).isNotNull(); + assertThat(String.valueOf(replaceResult.getOld().getAttribute("a"))).isEqualTo("test"); + assertThat(replaceResult.getOld().getProperties().keySet()).doesNotContain("b"); }) .get(); } @Test - public void deleteDocument() throws InterruptedException, ExecutionException { + void deleteDocument() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) .get(); db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, null).get(); db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, null) - .whenComplete((document, ex) -> assertThat(document, is(nullValue()))) + .whenComplete((document, ex) -> assertThat(document).isNull()) .get(); } @Test - public void deleteDocumentReturnOld() throws InterruptedException, ExecutionException { + void deleteDocumentReturnOld() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) @@ -694,28 +693,28 @@ public void deleteDocumentReturnOld() throws InterruptedException, ExecutionExce final DocumentDeleteOptions options = new DocumentDeleteOptions().returnOld(true); db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), BaseDocument.class, options) .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult.getOld(), is(notNullValue())); - assertThat(deleteResult.getOld(), instanceOf(BaseDocument.class)); - assertThat(deleteResult.getOld().getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(deleteResult.getOld().getAttribute("a")), is("test")); + assertThat(deleteResult.getOld()).isNotNull(); + assertThat(deleteResult.getOld()).isInstanceOf(BaseDocument.class); + assertThat(deleteResult.getOld().getAttribute("a")).isNotNull(); + assertThat(String.valueOf(deleteResult.getOld().getAttribute("a"))).isEqualTo("test"); }) .get(); } @Test - public void deleteDocumentIfMatch() throws InterruptedException, ExecutionException { + void deleteDocumentIfMatch() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) .get(); final DocumentDeleteOptions options = new DocumentDeleteOptions().ifMatch(createResult.getRev()); db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, options).get(); db.collection(COLLECTION_NAME).getDocument(createResult.getKey(), BaseDocument.class, null) - .whenComplete((document, ex) -> assertThat(document, is(nullValue()))) + .whenComplete((document, ex) -> assertThat(document).isNull()) .get(); } @Test - public void deleteDocumentIfMatchFail() throws InterruptedException, ExecutionException { + void deleteDocumentIfMatchFail() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME).insertDocument(doc, null) .get(); @@ -724,45 +723,45 @@ public void deleteDocumentIfMatchFail() throws InterruptedException, ExecutionEx db.collection(COLLECTION_NAME).deleteDocument(createResult.getKey(), null, options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void getIndex() throws InterruptedException, ExecutionException { + void getIndex() throws InterruptedException, ExecutionException { final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null).get(); db.collection(COLLECTION_NAME).getIndex(createResult.getId()) .whenComplete((readResult, ex) -> { - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getType(), is(createResult.getType())); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getType()).isEqualTo(createResult.getType()); }) .get(); } @Test - public void getIndexByKey() throws InterruptedException, ExecutionException { + void getIndexByKey() throws InterruptedException, ExecutionException { final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null).get(); db.collection(COLLECTION_NAME).getIndex(createResult.getId().split("/")[1]) .whenComplete((readResult, ex) -> { - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getType(), is(createResult.getType())); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getType()).isEqualTo(createResult.getType()); }) .get(); } @Test - public void deleteIndex() throws InterruptedException, ExecutionException { + void deleteIndex() throws InterruptedException, ExecutionException { final Collection fields = new ArrayList<>(); fields.add("deleteIndexField"); final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null).get(); db.getIndex(createResult.getId()).get(); db.collection(COLLECTION_NAME).deleteIndex(createResult.getId()) .whenComplete((id, ex) -> { - assertThat(id, is(createResult.getId())); + assertThat(id).isEqualTo(createResult.getId()); try { db.getIndex(id).get(); fail(); @@ -770,21 +769,21 @@ public void deleteIndex() throws InterruptedException, ExecutionException { exception.printStackTrace(); fail(); } catch (final ExecutionException exception) { - assertThat(exception.getCause(), instanceOf(ArangoDBException.class)); + assertThat(exception.getCause()).isInstanceOf(ArangoDBException.class); } }) .get(); } @Test - public void deleteIndexByKey() throws InterruptedException, ExecutionException { + void deleteIndexByKey() throws InterruptedException, ExecutionException { final Collection fields = new ArrayList<>(); fields.add("deleteIndexByKeyField"); final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null).get(); db.getIndex(createResult.getId()).get(); db.collection(COLLECTION_NAME).deleteIndex(createResult.getId().split("/")[1]) .whenComplete((id, ex) -> { - assertThat(id, is(createResult.getId())); + assertThat(id).isEqualTo(createResult.getId()); try { db.getIndex(id).get(); fail(); @@ -792,40 +791,40 @@ public void deleteIndexByKey() throws InterruptedException, ExecutionException { exception.printStackTrace(); fail(); } catch (final ExecutionException exception) { - assertThat(exception.getCause(), instanceOf(ArangoDBException.class)); + assertThat(exception.getCause()).isInstanceOf(ArangoDBException.class); } }) .get(); } @Test - public void createHashIndex() throws InterruptedException, ExecutionException { + void createHashIndex() throws InterruptedException, ExecutionException { final boolean singleServer = isSingleServer(); final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); db.collection(COLLECTION_NAME).ensureHashIndex(fields, null) .whenComplete((indexResult, ex) -> { - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getGeoJson(), is(nullValue())); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getFields()).contains("b"); + assertThat(indexResult.getGeoJson()).isNull(); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isEqualTo(true); + assertThat(indexResult.getMinLength()).isNull(); if (singleServer) { - assertThat(indexResult.getSelectivityEstimate(), is(1.0)); + assertThat(indexResult.getSelectivityEstimate()).isEqualTo(1.0); } - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.hash)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult.getSparse()).isEqualTo(false); + assertThat(indexResult.getType()).isEqualTo(IndexType.hash); + assertThat(indexResult.getUnique()).isEqualTo(false); }) .get(); } @Test - public void createHashIndexWithOptions() throws ExecutionException, InterruptedException { + void createHashIndexWithOptions() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); final HashIndexOptions options = new HashIndexOptions(); options.name("myHashIndex"); @@ -834,44 +833,44 @@ public void createHashIndexWithOptions() throws ExecutionException, InterruptedE fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, options).get(); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getFields()).contains("b"); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); if (isSingleServer()) { - assertThat(indexResult.getSelectivityEstimate(), is(1.)); + assertThat(indexResult.getSelectivityEstimate()).isEqualTo(1.); } - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.hash)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is("myHashIndex")); + assertThat(indexResult.getSparse()).isFalse(); + assertThat(indexResult.getType()).isEqualTo(IndexType.hash); + assertThat(indexResult.getUnique()).isFalse(); + assertThat(indexResult.getName()).isEqualTo("myHashIndex"); } @Test - public void createGeoIndex() throws InterruptedException, ExecutionException { + void createGeoIndex() throws InterruptedException, ExecutionException { final Collection fields = new ArrayList<>(); fields.add("a"); db.collection(COLLECTION_NAME).ensureGeoIndex(fields, null) .whenComplete((indexResult, ex) -> { - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getGeoJson(), is(false)); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSelectivityEstimate(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getType(), anyOf(is(IndexType.geo), is(IndexType.geo1))); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getGeoJson()).isEqualTo(false); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isEqualTo(true); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSelectivityEstimate()).isNull(); + assertThat(indexResult.getSparse()).isEqualTo(true); + assertThat(indexResult.getType()).isIn(IndexType.geo, IndexType.geo1); + assertThat(indexResult.getUnique()).isEqualTo(false); }) .get(); } @Test - public void createGeoIndexWithOptions() throws ExecutionException, InterruptedException { + void createGeoIndexWithOptions() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); final GeoIndexOptions options = new GeoIndexOptions(); options.name("myGeoIndex1"); @@ -879,40 +878,40 @@ public void createGeoIndexWithOptions() throws ExecutionException, InterruptedEx final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, options).get(); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isTrue(); + assertThat(indexResult.getUnique()).isFalse(); if (isAtLeastVersion(3, 4)) { - assertThat(indexResult.getType(), is(IndexType.geo)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo); } else { - assertThat(indexResult.getType(), is(IndexType.geo1)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo1); } - assertThat(indexResult.getName(), is("myGeoIndex1")); + assertThat(indexResult.getName()).isEqualTo("myGeoIndex1"); } @Test - public void createGeo2Index() throws ExecutionException, InterruptedException { + void createGeo2Index() throws ExecutionException, InterruptedException { final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); db.collection(COLLECTION_NAME).ensureGeoIndex(fields, null).whenComplete((indexResult, ex) -> { - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getFields()).contains("b"); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isEqualTo(true); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isEqualTo(true); + assertThat(indexResult.getUnique()).isEqualTo(false); try { if (isAtLeastVersion(3, 4)) { - assertThat(indexResult.getType(), is(IndexType.geo)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo); } else { - assertThat(indexResult.getType(), is(IndexType.geo2)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo2); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); @@ -922,7 +921,7 @@ public void createGeo2Index() throws ExecutionException, InterruptedException { } @Test - public void createGeo2IndexWithOptions() throws ExecutionException, InterruptedException { + void createGeo2IndexWithOptions() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); final GeoIndexOptions options = new GeoIndexOptions(); options.name("myGeoIndex2"); @@ -931,46 +930,46 @@ public void createGeo2IndexWithOptions() throws ExecutionException, InterruptedE fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureGeoIndex(fields, options).get(); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getFields()).contains("b"); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isTrue(); + assertThat(indexResult.getUnique()).isFalse(); if (isAtLeastVersion(3, 4)) { - assertThat(indexResult.getType(), is(IndexType.geo)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo); } else { - assertThat(indexResult.getType(), is(IndexType.geo2)); + assertThat(indexResult.getType()).isEqualTo(IndexType.geo2); } - assertThat(indexResult.getName(), is("myGeoIndex2")); + assertThat(indexResult.getName()).isEqualTo("myGeoIndex2"); } @Test - public void createSkiplistIndex() throws InterruptedException, ExecutionException { + void createSkiplistIndex() throws InterruptedException, ExecutionException { final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); db.collection(COLLECTION_NAME).ensureSkiplistIndex(fields, null) .whenComplete((indexResult, ex) -> { - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getGeoJson(), is(nullValue())); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.skiplist)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getFields()).contains("b"); + assertThat(indexResult.getGeoJson()).isNull(); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isEqualTo(true); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isEqualTo(false); + assertThat(indexResult.getType()).isEqualTo(IndexType.skiplist); + assertThat(indexResult.getUnique()).isEqualTo(false); }) .get(); } @Test - public void createSkiplistIndexWithOptions() throws ExecutionException, InterruptedException { + void createSkiplistIndexWithOptions() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); final SkiplistIndexOptions options = new SkiplistIndexOptions(); options.name("mySkiplistIndex"); @@ -979,43 +978,43 @@ public void createSkiplistIndexWithOptions() throws ExecutionException, Interrup fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureSkiplistIndex(fields, options).get(); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.skiplist)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is("mySkiplistIndex")); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getFields()).contains("b"); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isFalse(); + assertThat(indexResult.getType()).isEqualTo(IndexType.skiplist); + assertThat(indexResult.getUnique()).isFalse(); + assertThat(indexResult.getName()).isEqualTo("mySkiplistIndex"); } @Test - public void createPersistentIndex() throws InterruptedException, ExecutionException { + void createPersistentIndex() throws InterruptedException, ExecutionException { final Collection fields = new ArrayList<>(); fields.add("a"); fields.add("b"); db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, null) .whenComplete((indexResult, ex) -> { - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getGeoJson(), is(nullValue())); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.persistent)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getFields()).contains("b"); + assertThat(indexResult.getGeoJson()).isNull(); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isEqualTo(true); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isEqualTo(false); + assertThat(indexResult.getType()).isEqualTo(IndexType.persistent); + assertThat(indexResult.getUnique()).isEqualTo(false); }) .get(); } @Test - public void createPersistentIndexWithOptions() throws ExecutionException, InterruptedException { + void createPersistentIndexWithOptions() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); final PersistentIndexOptions options = new PersistentIndexOptions(); options.name("myPersistentIndex"); @@ -1024,41 +1023,41 @@ public void createPersistentIndexWithOptions() throws ExecutionException, Interr fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensurePersistentIndex(fields, options).get(); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getSparse(), is(false)); - assertThat(indexResult.getType(), is(IndexType.persistent)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is("myPersistentIndex")); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getFields()).contains("b"); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getSparse()).isFalse(); + assertThat(indexResult.getType()).isEqualTo(IndexType.persistent); + assertThat(indexResult.getUnique()).isFalse(); + assertThat(indexResult.getName()).isEqualTo("myPersistentIndex"); } @Test - public void createFulltextIndex() throws InterruptedException, ExecutionException { + void createFulltextIndex() throws InterruptedException, ExecutionException { final Collection fields = new ArrayList<>(); fields.add("a"); db.collection(COLLECTION_NAME).ensureFulltextIndex(fields, null) .whenComplete((indexResult, ex) -> { - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getGeoJson(), is(nullValue())); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getSelectivityEstimate(), is(nullValue())); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getType(), is(IndexType.fulltext)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getGeoJson()).isNull(); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isEqualTo(true); + assertThat(indexResult.getSelectivityEstimate()).isNull(); + assertThat(indexResult.getSparse()).isEqualTo(true); + assertThat(indexResult.getType()).isEqualTo(IndexType.fulltext); + assertThat(indexResult.getUnique()).isEqualTo(false); }) .get(); } @Test - public void createFulltextIndexWithOptions() throws ExecutionException, InterruptedException { + void createFulltextIndexWithOptions() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); final FulltextIndexOptions options = new FulltextIndexOptions(); options.name("myFulltextIndex"); @@ -1066,19 +1065,19 @@ public void createFulltextIndexWithOptions() throws ExecutionException, Interrup final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureFulltextIndex(fields, options).get(); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getSparse(), is(true)); - assertThat(indexResult.getType(), is(IndexType.fulltext)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is("myFulltextIndex")); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getSparse()).isTrue(); + assertThat(indexResult.getType()).isEqualTo(IndexType.fulltext); + assertThat(indexResult.getUnique()).isFalse(); + assertThat(indexResult.getName()).isEqualTo("myFulltextIndex"); } @Test - public void createTtlIndexWithoutOptions() throws ExecutionException, InterruptedException { + void createTtlIndexWithoutOptions() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); final Collection fields = new ArrayList<>(); fields.add("a"); @@ -1086,15 +1085,15 @@ public void createTtlIndexWithoutOptions() throws ExecutionException, Interrupte db.collection(COLLECTION_NAME).ensureTtlIndex(fields, null).get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); - assertThat(e.getCause().getMessage(), containsString("expireAfter attribute must be a number")); - assertThat(((ArangoDBException) e.getCause()).getResponseCode(), is(400)); - assertThat(((ArangoDBException) e.getCause()).getErrorNum(), is(10)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); + assertThat(e.getCause().getMessage()).contains("expireAfter attribute must be a number"); + assertThat(((ArangoDBException) e.getCause()).getResponseCode()).isEqualTo(400); + assertThat(((ArangoDBException) e.getCause()).getErrorNum()).isEqualTo(10); } } @Test - public void createTtlIndexWithOptions() throws ExecutionException, InterruptedException { + void createTtlIndexWithOptions() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); final Collection fields = new ArrayList<>(); fields.add("a"); @@ -1104,17 +1103,17 @@ public void createTtlIndexWithOptions() throws ExecutionException, InterruptedEx options.expireAfter(3600); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureTtlIndex(fields, options).get(); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getType(), is(IndexType.ttl)); - assertThat(indexResult.getExpireAfter(), is(3600)); - assertThat(indexResult.getName(), is("myTtlIndex")); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getType()).isEqualTo(IndexType.ttl); + assertThat(indexResult.getExpireAfter()).isEqualTo(3600); + assertThat(indexResult.getName()).isEqualTo("myTtlIndex"); } @Test - public void createZKDIndex() throws InterruptedException, ExecutionException { + void createZKDIndex() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 9)); db.collection(COLLECTION_NAME).truncate().get(); @@ -1122,21 +1121,21 @@ public void createZKDIndex() throws InterruptedException, ExecutionException { fields.add("a"); fields.add("b"); IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureZKDIndex(fields, null).get(); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getGeoJson(), is(nullValue())); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getType(), is(IndexType.zkd)); - assertThat(indexResult.getUnique(), is(false)); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getFields()).contains("b"); + assertThat(indexResult.getGeoJson()).isNull(); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getType()).isEqualTo(IndexType.zkd); + assertThat(indexResult.getUnique()).isFalse(); db.collection(COLLECTION_NAME).deleteIndex(indexResult.getId()).get(); } @Test - public void createZKDIndexWithOptions() throws ExecutionException, InterruptedException { + void createZKDIndexWithOptions() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 9)); db.collection(COLLECTION_NAME).truncate().get(); @@ -1148,33 +1147,33 @@ public void createZKDIndexWithOptions() throws ExecutionException, InterruptedEx fields.add("a"); fields.add("b"); final IndexEntity indexResult = db.collection(COLLECTION_NAME).ensureZKDIndex(fields, options).get(); - assertThat(indexResult, is(notNullValue())); - assertThat(indexResult.getConstraint(), is(nullValue())); - assertThat(indexResult.getFields(), hasItem("a")); - assertThat(indexResult.getFields(), hasItem("b")); - assertThat(indexResult.getId(), startsWith(COLLECTION_NAME)); - assertThat(indexResult.getIsNewlyCreated(), is(true)); - assertThat(indexResult.getMinLength(), is(nullValue())); - assertThat(indexResult.getType(), is(IndexType.zkd)); - assertThat(indexResult.getUnique(), is(false)); - assertThat(indexResult.getName(), is("myZKDIndex")); + assertThat(indexResult).isNotNull(); + assertThat(indexResult.getConstraint()).isNull(); + assertThat(indexResult.getFields()).contains("a"); + assertThat(indexResult.getFields()).contains("b"); + assertThat(indexResult.getId()).startsWith(COLLECTION_NAME); + assertThat(indexResult.getIsNewlyCreated()).isTrue(); + assertThat(indexResult.getMinLength()).isNull(); + assertThat(indexResult.getType()).isEqualTo(IndexType.zkd); + assertThat(indexResult.getUnique()).isFalse(); + assertThat(indexResult.getName()).isEqualTo("myZKDIndex"); db.collection(COLLECTION_NAME).deleteIndex(indexResult.getId()).get(); } @Test - public void getIndexes() throws InterruptedException, ExecutionException { + void getIndexes() throws InterruptedException, ExecutionException { final int initialIndexCount = db.collection(COLLECTION_NAME).getIndexes().get().size(); final Collection fields = new ArrayList<>(); fields.add("a"); db.collection(COLLECTION_NAME).ensureHashIndex(fields, null).get(); db.collection(COLLECTION_NAME).getIndexes() .whenComplete((indexes, ex) -> { - assertThat(indexes, is(notNullValue())); - assertThat(indexes.size(), is(initialIndexCount + 1)); + assertThat(indexes).isNotNull(); + assertThat(indexes.size()).isEqualTo(initialIndexCount + 1); for (final IndexEntity i : indexes) { if (i.getType() == IndexType.hash) { - assertThat(i.getFields().size(), is(1)); - assertThat(i.getFields(), hasItem("a")); + assertThat(i.getFields().size()).isEqualTo(1); + assertThat(i.getFields()).contains("a"); } } }) @@ -1182,144 +1181,144 @@ public void getIndexes() throws InterruptedException, ExecutionException { } @Test - public void exists() throws InterruptedException, ExecutionException { - assertThat(db.collection(COLLECTION_NAME).exists().get(), is(true)); - assertThat(db.collection(COLLECTION_NAME + "no").exists().get(), is(false)); + void exists() throws InterruptedException, ExecutionException { + assertThat(db.collection(COLLECTION_NAME).exists().get()).isTrue(); + assertThat(db.collection(COLLECTION_NAME + "no").exists().get()).isFalse(); } @Test - public void truncate() throws InterruptedException, ExecutionException { + void truncate() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); db.collection(COLLECTION_NAME).insertDocument(doc, null).get(); final BaseDocument readResult = db.collection(COLLECTION_NAME) .getDocument(doc.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(doc.getKey())); + assertThat(readResult.getKey()).isEqualTo(doc.getKey()); db.collection(COLLECTION_NAME).truncate() .whenComplete((truncateResult, ex) -> { - assertThat(truncateResult, is(notNullValue())); - assertThat(truncateResult.getId(), is(notNullValue())); + assertThat(truncateResult).isNotNull(); + assertThat(truncateResult.getId()).isNotNull(); }) .get(); final BaseDocument document = db.collection(COLLECTION_NAME).getDocument(doc.getKey(), BaseDocument.class, null) .get(); - assertThat(document, is(nullValue())); + assertThat(document).isNull(); } @Test - public void getCount() throws InterruptedException, ExecutionException { + void getCount() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).count() .whenComplete((countEmpty, ex) -> { - assertThat(countEmpty, is(notNullValue())); - assertThat(countEmpty.getCount(), is(0L)); + assertThat(countEmpty).isNotNull(); + assertThat(countEmpty.getCount()).isEqualTo(0L); }) .get(); db.collection(COLLECTION_NAME).insertDocument("{}", null).get(); db.collection(COLLECTION_NAME).count() - .whenComplete((count, ex) -> assertThat(count.getCount(), is(1L))) + .whenComplete((count, ex) -> assertThat(count.getCount()).isEqualTo(1L)) .get(); } @Test - public void documentExists() throws InterruptedException, ExecutionException { + void documentExists() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).documentExists("no", null) - .whenComplete((existsNot, ex) -> assertThat(existsNot, is(false))) + .whenComplete((existsNot, ex) -> assertThat(existsNot).isEqualTo(false)) .get(); db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null).get(); db.collection(COLLECTION_NAME).documentExists("abc", null) - .whenComplete((exists, ex) -> assertThat(exists, is(true))) + .whenComplete((exists, ex) -> assertThat(exists).isEqualTo(true)) .get(); } @Test - public void documentExistsIfMatch() throws InterruptedException, ExecutionException { + void documentExistsIfMatch() throws InterruptedException, ExecutionException { final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument("{\"_key\":\"abc\"}", null).get(); final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch(createResult.getRev()); db.collection(COLLECTION_NAME).documentExists("abc", options) - .whenComplete((exists, ex) -> assertThat(exists, is(true))) + .whenComplete((exists, ex) -> assertThat(exists).isEqualTo(true)) .get(); } @Test - public void documentExistsIfMatchFail() throws InterruptedException, ExecutionException { + void documentExistsIfMatchFail() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null).get(); final DocumentExistsOptions options = new DocumentExistsOptions().ifMatch("no"); db.collection(COLLECTION_NAME).documentExists("abc", options) - .whenComplete((exists, ex) -> assertThat(exists, is(false))) + .whenComplete((exists, ex) -> assertThat(exists).isEqualTo(false)) .get(); } @Test - public void documentExistsIfNoneMatch() throws InterruptedException, ExecutionException { + void documentExistsIfNoneMatch() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).insertDocument("{\"_key\":\"abc\"}", null).get(); final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch("no"); db.collection(COLLECTION_NAME).documentExists("abc", options) - .whenComplete((exists, ex) -> assertThat(exists, is(true))) + .whenComplete((exists, ex) -> assertThat(exists).isEqualTo(true)) .get(); } @Test - public void documentExistsIfNoneMatchFail() throws InterruptedException, ExecutionException { + void documentExistsIfNoneMatchFail() throws InterruptedException, ExecutionException { final DocumentCreateEntity createResult = db.collection(COLLECTION_NAME) .insertDocument("{\"_key\":\"abc\"}", null).get(); final DocumentExistsOptions options = new DocumentExistsOptions().ifNoneMatch(createResult.getRev()); db.collection(COLLECTION_NAME).documentExists("abc", options) - .whenComplete((exists, ex) -> assertThat(exists, is(false))) + .whenComplete((exists, ex) -> assertThat(exists).isEqualTo(false)) .get(); } @Test - public void insertDocuments() throws InterruptedException, ExecutionException { + void insertDocuments() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); values.add(new BaseDocument()); db.collection(COLLECTION_NAME).insertDocuments(values, null) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(3)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); + assertThat(docs).isNotNull(); + assertThat(docs.getDocuments()).isNotNull(); + assertThat(docs.getDocuments().size()).isEqualTo(3); + assertThat(docs.getErrors()).isNotNull(); + assertThat(docs.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void insertDocumentsOne() throws InterruptedException, ExecutionException { + void insertDocumentsOne() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument()); db.collection(COLLECTION_NAME).insertDocuments(values, null) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(1)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); + assertThat(docs).isNotNull(); + assertThat(docs.getDocuments()).isNotNull(); + assertThat(docs.getDocuments().size()).isEqualTo(1); + assertThat(docs.getErrors()).isNotNull(); + assertThat(docs.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void insertDocumentsEmpty() throws InterruptedException, ExecutionException { + void insertDocumentsEmpty() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); db.collection(COLLECTION_NAME).insertDocuments(values, null) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(0)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); + assertThat(docs).isNotNull(); + assertThat(docs.getDocuments()).isNotNull(); + assertThat(docs.getDocuments().size()).isEqualTo(0); + assertThat(docs.getErrors()).isNotNull(); + assertThat(docs.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void insertDocumentsReturnNew() throws InterruptedException, ExecutionException { + void insertDocumentsReturnNew() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); @@ -1327,154 +1326,154 @@ public void insertDocumentsReturnNew() throws InterruptedException, ExecutionExc final DocumentCreateOptions options = new DocumentCreateOptions().returnNew(true); db.collection(COLLECTION_NAME).insertDocuments(values, options) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(3)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(0)); + assertThat(docs).isNotNull(); + assertThat(docs.getDocuments()).isNotNull(); + assertThat(docs.getDocuments().size()).isEqualTo(3); + assertThat(docs.getErrors()).isNotNull(); + assertThat(docs.getErrors().size()).isEqualTo(0); for (final DocumentCreateEntity doc : docs.getDocuments()) { - assertThat(doc.getNew(), is(notNullValue())); + assertThat(doc.getNew()).isNotNull(); final BaseDocument baseDocument = doc.getNew(); - assertThat(baseDocument.getKey(), is(notNullValue())); + assertThat(baseDocument.getKey()).isNotNull(); } }) .get(); } @Test - public void insertDocumentsFail() throws InterruptedException, ExecutionException { + void insertDocumentsFail() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); db.collection(COLLECTION_NAME).insertDocuments(values) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getDocuments(), is(notNullValue())); - assertThat(docs.getDocuments().size(), is(2)); - assertThat(docs.getErrors(), is(notNullValue())); - assertThat(docs.getErrors().size(), is(1)); - assertThat(docs.getErrors().iterator().next().getErrorNum(), is(1210)); + assertThat(docs).isNotNull(); + assertThat(docs.getDocuments()).isNotNull(); + assertThat(docs.getDocuments().size()).isEqualTo(2); + assertThat(docs.getErrors()).isNotNull(); + assertThat(docs.getErrors().size()).isEqualTo(1); + assertThat(docs.getErrors().iterator().next().getErrorNum()).isEqualTo(1210); }) .get(); } @Test - public void importDocuments() throws InterruptedException, ExecutionException { + void importDocuments() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); values.add(new BaseDocument()); db.collection(COLLECTION_NAME).importDocuments(values) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(values.size())); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(values.size()); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(0); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(0); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsDuplicateDefaultError() throws InterruptedException, ExecutionException { + void importDocumentsDuplicateDefaultError() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); db.collection(COLLECTION_NAME).importDocuments(values) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(0); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsDuplicateError() throws InterruptedException, ExecutionException { + void importDocumentsDuplicateError() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.error)) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(0); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsDuplicateIgnore() throws InterruptedException, ExecutionException { + void importDocumentsDuplicateIgnore() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.ignore)) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(1)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(0); + assertThat(docs.getIgnored()).isEqualTo(1); + assertThat(docs.getUpdated()).isEqualTo(0); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsDuplicateReplace() throws InterruptedException, ExecutionException { + void importDocumentsDuplicateReplace() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.replace)) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(0); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(1); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsDuplicateUpdate() throws InterruptedException, ExecutionException { + void importDocumentsDuplicateUpdate() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.update)) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(0); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(1); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsCompleteFail() throws InterruptedException { + void importDocumentsCompleteFail() throws InterruptedException { final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); @@ -1483,59 +1482,59 @@ public void importDocumentsCompleteFail() throws InterruptedException { db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().complete(true)).get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); - assertThat(((ArangoDBException) e.getCause()).getErrorNum(), is(1210)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); + assertThat(((ArangoDBException) e.getCause()).getErrorNum()).isEqualTo(1210); } } @Test - public void importDocumentsDetails() throws InterruptedException, ExecutionException { + void importDocumentsDetails() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); values.add(new BaseDocument("1")); values.add(new BaseDocument("2")); values.add(new BaseDocument("2")); db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().details(true)) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails().size(), is(1)); - assertThat(docs.getDetails().iterator().next(), containsString("unique constraint violated")); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(0); + assertThat(docs.getDetails().size()).isEqualTo(1); + assertThat(docs.getDetails().iterator().next()).contains("unique constraint violated"); }) .get(); } @Test - public void importDocumentsOverwriteFalse() throws InterruptedException, ExecutionException { + void importDocumentsOverwriteFalse() throws InterruptedException, ExecutionException { final ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); collection.insertDocument(new BaseDocument()).get(); - assertThat(collection.count().get().getCount(), is(1L)); + assertThat(collection.count().get().getCount()).isEqualTo(1L); final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); collection.importDocuments(values, new DocumentImportOptions().overwrite(false)).get(); - assertThat(collection.count().get().getCount(), is(3L)); + assertThat(collection.count().get().getCount()).isEqualTo(3L); } @Test - public void importDocumentsOverwriteTrue() throws InterruptedException, ExecutionException { + void importDocumentsOverwriteTrue() throws InterruptedException, ExecutionException { final ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); collection.insertDocument(new BaseDocument()).get(); - assertThat(collection.count().get().getCount(), is(1L)); + assertThat(collection.count().get().getCount()).isEqualTo(1L); final Collection values = new ArrayList<>(); values.add(new BaseDocument()); values.add(new BaseDocument()); collection.importDocuments(values, new DocumentImportOptions().overwrite(true)).get(); - assertThat(collection.count().get().getCount(), is(2L)); + assertThat(collection.count().get().getCount()).isEqualTo(2L); } @Test - public void importDocumentsFromToPrefix() throws InterruptedException, ExecutionException { + void importDocumentsFromToPrefix() throws InterruptedException, ExecutionException { db.createCollection(COLLECTION_NAME + "_edge", new CollectionCreateOptions().type(CollectionType.EDGES)).get(); final ArangoCollectionAsync collection = db.collection(COLLECTION_NAME + "_edge"); try { @@ -1544,18 +1543,18 @@ public void importDocumentsFromToPrefix() throws InterruptedException, Execution for (String s : keys) { values.add(new BaseEdgeDocument(s, "from", "to")); } - assertThat(values.size(), is(keys.length)); + assertThat(values).hasSize(keys.length); final DocumentImportEntity importResult = collection .importDocuments(values, new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")).get(); - assertThat(importResult, is(notNullValue())); - assertThat(importResult.getCreated(), is(values.size())); + assertThat(importResult).isNotNull(); + assertThat(importResult.getCreated()).isEqualTo(values.size()); for (String key : keys) { BaseEdgeDocument doc; doc = collection.getDocument(key, BaseEdgeDocument.class).get(); - assertThat(doc, is(notNullValue())); - assertThat(doc.getFrom(), is("foo/from")); - assertThat(doc.getTo(), is("bar/to")); + assertThat(doc).isNotNull(); + assertThat(doc.getFrom()).isEqualTo("foo/from"); + assertThat(doc.getTo()).isEqualTo("bar/to"); } } finally { collection.drop().get(); @@ -1563,154 +1562,154 @@ public void importDocumentsFromToPrefix() throws InterruptedException, Execution } @Test - public void importDocumentsJson() throws InterruptedException, ExecutionException { + void importDocumentsJson() throws InterruptedException, ExecutionException { final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; db.collection(COLLECTION_NAME).importDocuments(values) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(0); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(0); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsJsonDuplicateDefaultError() throws InterruptedException, ExecutionException { + void importDocumentsJsonDuplicateDefaultError() throws InterruptedException, ExecutionException { final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; db.collection(COLLECTION_NAME).importDocuments(values) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(0); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsJsonDuplicateError() throws InterruptedException, ExecutionException { + void importDocumentsJsonDuplicateError() throws InterruptedException, ExecutionException { final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.error)) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(0); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsJsonDuplicateIgnore() throws InterruptedException, ExecutionException { + void importDocumentsJsonDuplicateIgnore() throws InterruptedException, ExecutionException { final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.ignore)) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(1)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(0); + assertThat(docs.getIgnored()).isEqualTo(1); + assertThat(docs.getUpdated()).isEqualTo(0); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsJsonDuplicateReplace() throws InterruptedException, ExecutionException { + void importDocumentsJsonDuplicateReplace() throws InterruptedException, ExecutionException { final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.replace)) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(0); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(1); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsJsonDuplicateUpdate() throws InterruptedException, ExecutionException { + void importDocumentsJsonDuplicateUpdate() throws InterruptedException, ExecutionException { final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().onDuplicate(OnDuplicate.update)) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(0)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(1)); - assertThat(docs.getDetails(), is(empty())); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(0); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(1); + assertThat(docs.getDetails()).isEmpty(); }) .get(); } @Test - public void importDocumentsJsonCompleteFail() throws InterruptedException { + void importDocumentsJsonCompleteFail() throws InterruptedException { final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; try { db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().complete(true)).get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); - assertThat(((ArangoDBException) e.getCause()).getErrorNum(), is(1210)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); + assertThat(((ArangoDBException) e.getCause()).getErrorNum()).isEqualTo(1210); } } @Test - public void importDocumentsJsonDetails() throws InterruptedException, ExecutionException { + void importDocumentsJsonDetails() throws InterruptedException, ExecutionException { final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"},{\"_key\":\"2\"}]"; db.collection(COLLECTION_NAME).importDocuments(values, new DocumentImportOptions().details(true)) .whenComplete((docs, ex) -> { - assertThat(docs, is(notNullValue())); - assertThat(docs.getCreated(), is(2)); - assertThat(docs.getEmpty(), is(0)); - assertThat(docs.getErrors(), is(1)); - assertThat(docs.getIgnored(), is(0)); - assertThat(docs.getUpdated(), is(0)); - assertThat(docs.getDetails().size(), is(1)); - assertThat(docs.getDetails().iterator().next(), containsString("unique constraint violated")); + assertThat(docs).isNotNull(); + assertThat(docs.getCreated()).isEqualTo(2); + assertThat(docs.getEmpty()).isEqualTo(0); + assertThat(docs.getErrors()).isEqualTo(1); + assertThat(docs.getIgnored()).isEqualTo(0); + assertThat(docs.getUpdated()).isEqualTo(0); + assertThat(docs.getDetails().size()).isEqualTo(1); + assertThat(docs.getDetails().iterator().next()).contains("unique constraint violated"); }) .get(); } @Test - public void importDocumentsJsonOverwriteFalse() throws InterruptedException, ExecutionException { + void importDocumentsJsonOverwriteFalse() throws InterruptedException, ExecutionException { final ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); collection.insertDocument(new BaseDocument()).get(); - assertThat(collection.count().get().getCount(), is(1L)); + assertThat(collection.count().get().getCount()).isEqualTo(1L); final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; collection.importDocuments(values, new DocumentImportOptions().overwrite(false)).get(); - assertThat(collection.count().get().getCount(), is(3L)); + assertThat(collection.count().get().getCount()).isEqualTo(3L); } @Test - public void importDocumentsJsonOverwriteTrue() throws InterruptedException, ExecutionException { + void importDocumentsJsonOverwriteTrue() throws InterruptedException, ExecutionException { final ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); collection.insertDocument(new BaseDocument()).get(); - assertThat(collection.count().get().getCount(), is(1L)); + assertThat(collection.count().get().getCount()).isEqualTo(1L); final String values = "[{\"_key\":\"1\"},{\"_key\":\"2\"}]"; collection.importDocuments(values, new DocumentImportOptions().overwrite(true)).get(); - assertThat(collection.count().get().getCount(), is(2L)); + assertThat(collection.count().get().getCount()).isEqualTo(2L); } @Test - public void importDocumentsJsonFromToPrefix() throws InterruptedException, ExecutionException { + void importDocumentsJsonFromToPrefix() throws InterruptedException, ExecutionException { db.createCollection(COLLECTION_NAME + "_edge", new CollectionCreateOptions().type(CollectionType.EDGES)).get(); final ArangoCollectionAsync collection = db.collection(COLLECTION_NAME + "_edge"); try { @@ -1719,14 +1718,14 @@ public void importDocumentsJsonFromToPrefix() throws InterruptedException, Execu final DocumentImportEntity importResult = collection .importDocuments(values, new DocumentImportOptions().fromPrefix("foo").toPrefix("bar")).get(); - assertThat(importResult, is(notNullValue())); - assertThat(importResult.getCreated(), is(2)); + assertThat(importResult).isNotNull(); + assertThat(importResult.getCreated()).isEqualTo(2); for (String key : keys) { BaseEdgeDocument doc; doc = collection.getDocument(key, BaseEdgeDocument.class).get(); - assertThat(doc, is(notNullValue())); - assertThat(doc.getFrom(), is("foo/from")); - assertThat(doc.getTo(), is("bar/to")); + assertThat(doc).isNotNull(); + assertThat(doc.getFrom()).isEqualTo("foo/from"); + assertThat(doc.getTo()).isEqualTo("bar/to"); } } finally { collection.drop().get(); @@ -1734,7 +1733,7 @@ public void importDocumentsJsonFromToPrefix() throws InterruptedException, Execu } @Test - public void deleteDocumentsByKey() throws InterruptedException, ExecutionException { + void deleteDocumentsByKey() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -1752,18 +1751,18 @@ public void deleteDocumentsByKey() throws InterruptedException, ExecutionExcepti keys.add("2"); db.collection(COLLECTION_NAME).deleteDocuments(keys, null, null) .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(2)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments().size()).isEqualTo(2); for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), anyOf(is("1"), is("2"))); + assertThat(i.getKey()).isIn("1", "2"); } - assertThat(deleteResult.getErrors().size(), is(0)); + assertThat(deleteResult.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void deleteDocumentsByDocuments() throws InterruptedException, ExecutionException { + void deleteDocumentsByDocuments() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -1778,18 +1777,18 @@ public void deleteDocumentsByDocuments() throws InterruptedException, ExecutionE db.collection(COLLECTION_NAME).insertDocuments(values, null).get(); db.collection(COLLECTION_NAME).deleteDocuments(values, null, null) .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(2)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments().size()).isEqualTo(2); for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), anyOf(is("1"), is("2"))); + assertThat(i.getKey()).isIn("1", "2"); } - assertThat(deleteResult.getErrors().size(), is(0)); + assertThat(deleteResult.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void deleteDocumentsByKeyOne() throws InterruptedException, ExecutionException { + void deleteDocumentsByKeyOne() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -1801,18 +1800,18 @@ public void deleteDocumentsByKeyOne() throws InterruptedException, ExecutionExce keys.add("1"); db.collection(COLLECTION_NAME).deleteDocuments(keys, null, null) .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(1)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments().size()).isEqualTo(1); for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), is("1")); + assertThat(i.getKey()).isEqualTo("1"); } - assertThat(deleteResult.getErrors().size(), is(0)); + assertThat(deleteResult.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void deleteDocumentsByDocumentOne() throws InterruptedException, ExecutionException { + void deleteDocumentsByDocumentOne() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -1822,32 +1821,32 @@ public void deleteDocumentsByDocumentOne() throws InterruptedException, Executio db.collection(COLLECTION_NAME).insertDocuments(values, null).get(); db.collection(COLLECTION_NAME).deleteDocuments(values, null, null) .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(1)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments().size()).isEqualTo(1); for (final DocumentDeleteEntity i : deleteResult.getDocuments()) { - assertThat(i.getKey(), is("1")); + assertThat(i.getKey()).isEqualTo("1"); } - assertThat(deleteResult.getErrors().size(), is(0)); + assertThat(deleteResult.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void deleteDocumentsEmpty() throws InterruptedException, ExecutionException { + void deleteDocumentsEmpty() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); db.collection(COLLECTION_NAME).insertDocuments(values, null).get(); final Collection keys = new ArrayList<>(); db.collection(COLLECTION_NAME).deleteDocuments(keys, null, null) .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(0)); - assertThat(deleteResult.getErrors().size(), is(0)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments().size()).isEqualTo(0); + assertThat(deleteResult.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void deleteDocumentsByKeyNotExisting() throws InterruptedException, ExecutionException { + void deleteDocumentsByKeyNotExisting() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); db.collection(COLLECTION_NAME).insertDocuments(values, null).get(); final Collection keys = new ArrayList<>(); @@ -1855,15 +1854,15 @@ public void deleteDocumentsByKeyNotExisting() throws InterruptedException, Execu keys.add("2"); db.collection(COLLECTION_NAME).deleteDocuments(keys, null, null) .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(0)); - assertThat(deleteResult.getErrors().size(), is(2)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments().size()).isEqualTo(0); + assertThat(deleteResult.getErrors().size()).isEqualTo(2); }) .get(); } @Test - public void deleteDocumentsByDocumentsNotExisting() throws InterruptedException, ExecutionException { + void deleteDocumentsByDocumentsNotExisting() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -1877,15 +1876,15 @@ public void deleteDocumentsByDocumentsNotExisting() throws InterruptedException, } db.collection(COLLECTION_NAME).deleteDocuments(values, null, null) .whenComplete((deleteResult, ex) -> { - assertThat(deleteResult, is(notNullValue())); - assertThat(deleteResult.getDocuments().size(), is(0)); - assertThat(deleteResult.getErrors().size(), is(2)); + assertThat(deleteResult).isNotNull(); + assertThat(deleteResult.getDocuments().size()).isEqualTo(0); + assertThat(deleteResult.getErrors().size()).isEqualTo(2); }) .get(); } @Test - public void updateDocuments() throws InterruptedException, ExecutionException { + void updateDocuments() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -1905,16 +1904,16 @@ public void updateDocuments() throws InterruptedException, ExecutionException { } db.collection(COLLECTION_NAME).updateDocuments(updatedValues, null) .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size(), is(2)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments().size()).isEqualTo(2); + assertThat(updateResult.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void updateDocumentsWithDifferentReturnType() throws ExecutionException, InterruptedException { + void updateDocumentsWithDifferentReturnType() throws ExecutionException, InterruptedException { ArangoCollectionAsync collection = db.collection(COLLECTION_NAME); - List keys = IntStream.range(0, 3).mapToObj(it -> "key-" + UUID.randomUUID().toString()).collect(Collectors.toList()); + List keys = IntStream.range(0, 3).mapToObj(it -> "key-" + UUID.randomUUID()).collect(Collectors.toList()); List docs = keys.stream() .map(BaseDocument::new) .peek(it -> it.addAttribute("a", "test")) @@ -1935,15 +1934,15 @@ public void updateDocumentsWithDifferentReturnType() throws ExecutionException, final MultiDocumentEntity> updateResult = collection .updateDocuments(modifiedDocs, new DocumentUpdateOptions().returnNew(true), BaseDocument.class).get(); - assertThat(updateResult.getDocuments().size(), is(3)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments()).hasSize(3); + assertThat(updateResult.getErrors()).isEmpty(); assertThat(updateResult.getDocuments().stream().map(DocumentUpdateEntity::getNew) - .allMatch(it -> it.getAttribute("a").equals("test") && it.getAttribute("b").equals("test")), - is(true)); + .allMatch(it -> it.getAttribute("a").equals("test") && it.getAttribute("b").equals("test"))) + .isTrue(); } @Test - public void updateDocumentsOne() throws InterruptedException, ExecutionException { + void updateDocumentsOne() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -1957,25 +1956,25 @@ public void updateDocumentsOne() throws InterruptedException, ExecutionException updatedValues.add(first); db.collection(COLLECTION_NAME).updateDocuments(updatedValues, null) .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments().size()).isEqualTo(1); + assertThat(updateResult.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void updateDocumentsEmpty() throws InterruptedException, ExecutionException { + void updateDocumentsEmpty() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); db.collection(COLLECTION_NAME).updateDocuments(values, null) .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size(), is(0)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments().size()).isEqualTo(0); + assertThat(updateResult.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void updateDocumentsWithoutKey() throws InterruptedException, ExecutionException { + void updateDocumentsWithoutKey() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); { values.add(new BaseDocument("1")); @@ -1989,14 +1988,14 @@ public void updateDocumentsWithoutKey() throws InterruptedException, ExecutionEx updatedValues.add(new BaseDocument()); db.collection(COLLECTION_NAME).updateDocuments(updatedValues, null) .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(1)); + assertThat(updateResult.getDocuments().size()).isEqualTo(1); + assertThat(updateResult.getErrors().size()).isEqualTo(1); }) .get(); } @Test - public void replaceDocuments() throws InterruptedException, ExecutionException { + void replaceDocuments() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); { values.add(new BaseDocument("1")); @@ -2010,14 +2009,14 @@ public void replaceDocuments() throws InterruptedException, ExecutionException { } db.collection(COLLECTION_NAME).replaceDocuments(updatedValues, null) .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size(), is(2)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments().size()).isEqualTo(2); + assertThat(updateResult.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void replaceDocumentsOne() throws InterruptedException, ExecutionException { + void replaceDocumentsOne() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); { final BaseDocument e = new BaseDocument(); @@ -2031,25 +2030,25 @@ public void replaceDocumentsOne() throws InterruptedException, ExecutionExceptio updatedValues.add(first); db.collection(COLLECTION_NAME).updateDocuments(updatedValues, null) .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments().size()).isEqualTo(1); + assertThat(updateResult.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void replaceDocumentsEmpty() throws InterruptedException, ExecutionException { + void replaceDocumentsEmpty() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); db.collection(COLLECTION_NAME).updateDocuments(values, null) .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size(), is(0)); - assertThat(updateResult.getErrors().size(), is(0)); + assertThat(updateResult.getDocuments().size()).isEqualTo(0); + assertThat(updateResult.getErrors().size()).isEqualTo(0); }) .get(); } @Test - public void replaceDocumentsWithoutKey() throws InterruptedException, ExecutionException { + void replaceDocumentsWithoutKey() throws InterruptedException, ExecutionException { final Collection values = new ArrayList<>(); { values.add(new BaseDocument("1")); @@ -2063,57 +2062,57 @@ public void replaceDocumentsWithoutKey() throws InterruptedException, ExecutionE updatedValues.add(new BaseDocument()); db.collection(COLLECTION_NAME).updateDocuments(updatedValues, null) .whenComplete((updateResult, ex) -> { - assertThat(updateResult.getDocuments().size(), is(1)); - assertThat(updateResult.getErrors().size(), is(1)); + assertThat(updateResult.getDocuments().size()).isEqualTo(1); + assertThat(updateResult.getErrors().size()).isEqualTo(1); }) .get(); } @Test - public void load() throws InterruptedException, ExecutionException { + void load() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).load() - .whenComplete((result, ex) -> assertThat(result.getName(), is(COLLECTION_NAME))) + .whenComplete((result, ex) -> assertThat(result.getName()).isEqualTo(COLLECTION_NAME)) .get(); } @Test - public void unload() throws InterruptedException, ExecutionException { + void unload() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).unload() - .whenComplete((result, ex) -> assertThat(result.getName(), is(COLLECTION_NAME))) + .whenComplete((result, ex) -> assertThat(result.getName()).isEqualTo(COLLECTION_NAME)) .get(); } @Test - public void getInfo() throws InterruptedException, ExecutionException { + void getInfo() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).getInfo() - .whenComplete((result, ex) -> assertThat(result.getName(), is(COLLECTION_NAME))) + .whenComplete((result, ex) -> assertThat(result.getName()).isEqualTo(COLLECTION_NAME)) .get(); } @Test - public void getPropeties() throws InterruptedException, ExecutionException { + void getPropeties() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).getProperties() .whenComplete((result, ex) -> { - assertThat(result.getName(), is(COLLECTION_NAME)); - assertThat(result.getCount(), is(nullValue())); + assertThat(result.getName()).isEqualTo(COLLECTION_NAME); + assertThat(result.getCount()).isNull(); }) .get(); } @Test - public void changeProperties() throws InterruptedException, ExecutionException { + void changeProperties() throws InterruptedException, ExecutionException { final String collection = COLLECTION_NAME + "_prop"; try { db.createCollection(collection).get(); final CollectionPropertiesEntity properties = db.collection(collection).getProperties().get(); - assertThat(properties.getWaitForSync(), is(notNullValue())); + assertThat(properties.getWaitForSync()).isNotNull(); final CollectionPropertiesOptions options = new CollectionPropertiesOptions(); options.waitForSync(!properties.getWaitForSync()); options.journalSize(2000000L); db.collection(collection).changeProperties(options) .whenComplete((changedProperties, ex) -> { - assertThat(changedProperties.getWaitForSync(), is(notNullValue())); - assertThat(changedProperties.getWaitForSync(), is(not(properties.getWaitForSync()))); + assertThat(changedProperties.getWaitForSync()).isNotNull(); + assertThat(changedProperties.getWaitForSync()).isNotEqualTo(properties.getWaitForSync()); }) .get(); } finally { @@ -2122,47 +2121,47 @@ public void changeProperties() throws InterruptedException, ExecutionException { } @Test - public void rename() throws InterruptedException, ExecutionException { + void rename() throws InterruptedException, ExecutionException { assumeTrue(isSingleServer()); db.collection(COLLECTION_NAME).rename(COLLECTION_NAME + "1") .whenComplete((result, ex) -> { - assertThat(result, is(notNullValue())); - assertThat(result.getName(), is(COLLECTION_NAME + "1")); + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo(COLLECTION_NAME + "1"); }) .get(); final CollectionEntity info = db.collection(COLLECTION_NAME + "1").getInfo().get(); - assertThat(info.getName(), is(COLLECTION_NAME + "1")); + assertThat(info.getName()).isEqualTo(COLLECTION_NAME + "1"); try { db.collection(COLLECTION_NAME).getInfo().get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } db.collection(COLLECTION_NAME + "1").rename(COLLECTION_NAME).get(); } @Test - public void responsibleShard() throws ExecutionException, InterruptedException { + void responsibleShard() throws ExecutionException, InterruptedException { assumeTrue(isCluster()); assumeTrue(isAtLeastVersion(3, 5)); ShardEntity shard = db.collection(COLLECTION_NAME).getResponsibleShard(new BaseDocument("testKey")).get(); - assertThat(shard, is(notNullValue())); - assertThat(shard.getShardId(), is(notNullValue())); + assertThat(shard).isNotNull(); + assertThat(shard.getShardId()).isNotNull(); } @Test - public void getRevision() throws InterruptedException, ExecutionException { + void getRevision() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).getRevision() .whenComplete((result, ex) -> { - assertThat(result, is(notNullValue())); - assertThat(result.getName(), is(COLLECTION_NAME)); - assertThat(result.getRevision(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo(COLLECTION_NAME); + assertThat(result.getRevision()).isNotNull(); }) .get(); } @Test - public void grantAccessRW() throws InterruptedException, ExecutionException { + void grantAccessRW() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234", null).get(); db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RW).get(); @@ -2172,7 +2171,7 @@ public void grantAccessRW() throws InterruptedException, ExecutionException { } @Test - public void grantAccessRO() throws InterruptedException, ExecutionException { + void grantAccessRO() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234", null).get(); db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RO).get(); @@ -2182,7 +2181,7 @@ public void grantAccessRO() throws InterruptedException, ExecutionException { } @Test - public void grantAccessNONE() throws InterruptedException, ExecutionException { + void grantAccessNONE() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234", null).get(); db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE).get(); @@ -2191,13 +2190,14 @@ public void grantAccessNONE() throws InterruptedException, ExecutionException { } } - @Test(expected = ExecutionException.class) - public void grantAccessUserNotFound() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RW).get(); + @Test + void grantAccessUserNotFound() { + Throwable thrown = catchThrowable(() -> db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.RW).get()); + assertThat(thrown).isInstanceOf(ExecutionException.class); } @Test - public void revokeAccess() throws InterruptedException, ExecutionException { + void revokeAccess() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234", null).get(); db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE).get(); @@ -2206,13 +2206,14 @@ public void revokeAccess() throws InterruptedException, ExecutionException { } } - @Test(expected = ExecutionException.class) - public void revokeAccessUserNotFound() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE).get(); + @Test + void revokeAccessUserNotFound() { + Throwable thrown = catchThrowable(() -> db.collection(COLLECTION_NAME).grantAccess("user1", Permissions.NONE).get()); + assertThat(thrown).isInstanceOf(ExecutionException.class); } @Test - public void resetAccess() throws InterruptedException, ExecutionException { + void resetAccess() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234", null).get(); db.collection(COLLECTION_NAME).resetAccess("user1").get(); @@ -2221,13 +2222,14 @@ public void resetAccess() throws InterruptedException, ExecutionException { } } - @Test(expected = ExecutionException.class) - public void resetAccessUserNotFound() throws InterruptedException, ExecutionException { - db.collection(COLLECTION_NAME).resetAccess("user1").get(); + @Test + void resetAccessUserNotFound() { + Throwable thrown = catchThrowable(() -> db.collection(COLLECTION_NAME).resetAccess("user1").get()); + assertThat(thrown).isInstanceOf(ExecutionException.class); } @Test - public void getPermissions() throws InterruptedException, ExecutionException { - assertThat(Permissions.RW, is(db.collection(COLLECTION_NAME).getPermissions("root").get())); + void getPermissions() throws InterruptedException, ExecutionException { + assertThat(db.collection(COLLECTION_NAME).getPermissions("root").get()).isEqualTo(Permissions.RW); } } diff --git a/src/test/java/com/arangodb/async/ArangoDBTest.java b/src/test/java/com/arangodb/async/ArangoDBTest.java index 581b81615..fcf932045 100644 --- a/src/test/java/com/arangodb/async/ArangoDBTest.java +++ b/src/test/java/com/arangodb/async/ArangoDBTest.java @@ -22,40 +22,42 @@ import com.arangodb.*; import com.arangodb.entity.*; +import com.arangodb.mapping.ArangoJack; import com.arangodb.model.*; import com.arangodb.model.LogOptions.SortOrder; -import com.arangodb.model.UserCreateOptions; -import com.arangodb.model.UserUpdateOptions; import com.arangodb.util.TestUtils; import com.arangodb.velocypack.exception.VPackException; import com.arangodb.velocystream.Request; import com.arangodb.velocystream.RequestType; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; -import java.util.*; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import java.util.stream.IntStream; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Mark Vollmary * @author Michele Rastelli */ -public class ArangoDBTest { +class ArangoDBTest { private static final String ROOT = "root"; private static final String USER = "mit dem mund"; private static final String PW = "machts der hund"; private static Boolean extendedNames; - private final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().build(); - private final ArangoDB arangoDBSync = new ArangoDB.Builder().build(); + private final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().serializer(new ArangoJack()).build(); + private final ArangoDB arangoDBSync = new ArangoDB.Builder().serializer(new ArangoJack()).build(); private boolean isEnterprise() { return arangoDBSync.getVersion().getLicense() == License.ENTERPRISE; @@ -70,7 +72,7 @@ private boolean isAtLeastVersion(final int major, final int minor) { } private boolean supportsExtendedNames() { - final ArangoDB arangoDB = new ArangoDB.Builder().build(); + final ArangoDB arangoDB = new ArangoDB.Builder().serializer(new ArangoJack()).build(); if (extendedNames == null) { try { ArangoDatabase testDb = arangoDB.db(DbName.of("test-" + TestUtils.generateRandomDbName(20, true))); @@ -85,37 +87,38 @@ private boolean supportsExtendedNames() { } @Test - public void getVersion() throws InterruptedException, ExecutionException { + void getVersion() throws InterruptedException, ExecutionException { arangoDB.getVersion() .whenComplete((version, ex) -> { - assertThat(version, is(notNullValue())); - assertThat(version.getServer(), is(notNullValue())); - assertThat(version.getVersion(), is(notNullValue())); + assertThat(version).isNotNull(); + assertThat(version.getServer()).isNotNull(); + assertThat(version.getVersion()).isNotNull(); }) .get(); } - @Test(timeout = 2000) - public void nestedGetVersion() { + @Test + @Timeout(2) + void nestedGetVersion() { for (int i = 0; i < 100; i++) { try { arangoDB.getVersion() .whenComplete((v1, ex1) -> { - assertThat(v1, is(notNullValue())); - assertThat(v1.getServer(), is(notNullValue())); - assertThat(v1.getVersion(), is(notNullValue())); + assertThat(v1).isNotNull(); + assertThat(v1.getServer()).isNotNull(); + assertThat(v1.getVersion()).isNotNull(); try { arangoDB.getVersion() .whenComplete((v2, ex2) -> { - assertThat(v2, is(notNullValue())); - assertThat(v2.getServer(), is(notNullValue())); - assertThat(v2.getVersion(), is(notNullValue())); + assertThat(v2).isNotNull(); + assertThat(v2.getServer()).isNotNull(); + assertThat(v2.getVersion()).isNotNull(); try { arangoDB.getVersion() .whenComplete((v3, ex3) -> { - assertThat(v3, is(notNullValue())); - assertThat(v3.getServer(), is(notNullValue())); - assertThat(v3.getVersion(), is(notNullValue())); + assertThat(v3).isNotNull(); + assertThat(v3.getServer()).isNotNull(); + assertThat(v3.getVersion()).isNotNull(); }) .get(); } catch (InterruptedException | ExecutionException e) { @@ -138,15 +141,15 @@ public void nestedGetVersion() { } @Test - public void createDatabase() throws InterruptedException, ExecutionException { + void createDatabase() throws InterruptedException, ExecutionException { arangoDB.createDatabase(BaseTest.TEST_DB) - .whenComplete((result, ex) -> assertThat(result, is(true))) + .whenComplete((result, ex) -> assertThat(result).isEqualTo(true)) .get(); arangoDB.db(BaseTest.TEST_DB).drop().get(); } @Test - public void createDatabaseWithOptions() throws ExecutionException, InterruptedException { + void createDatabaseWithOptions() throws ExecutionException, InterruptedException { assumeTrue(isCluster()); assumeTrue(isAtLeastVersion(3, 6)); @@ -159,20 +162,20 @@ public void createDatabaseWithOptions() throws ExecutionException, InterruptedEx .sharding("") ) ).get(); - assertThat(resultCreate, is(true)); + assertThat(resultCreate).isTrue(); DatabaseEntity info = arangoDB.db(dbName).getInfo().get(); - assertThat(info.getReplicationFactor(), is(2)); - assertThat(info.getWriteConcern(), is(2)); - assertThat(info.getSharding(), is("")); - assertThat(info.getSatellite(), nullValue()); + assertThat(info.getReplicationFactor()).isEqualTo(2); + assertThat(info.getWriteConcern()).isEqualTo(2); + assertThat(info.getSharding()).isEmpty(); + assertThat(info.getSatellite()).isNull(); final Boolean resultDelete = arangoDB.db(dbName).drop().get(); - assertThat(resultDelete, is(true)); + assertThat(resultDelete).isTrue(); } @Test - public void createDatabaseWithOptionsSatellite() throws ExecutionException, InterruptedException { + void createDatabaseWithOptionsSatellite() throws ExecutionException, InterruptedException { assumeTrue(isCluster()); assumeTrue(isEnterprise()); assumeTrue(isAtLeastVersion(3, 6)); @@ -186,72 +189,72 @@ public void createDatabaseWithOptionsSatellite() throws ExecutionException, Inte .sharding("") ) ).get(); - assertThat(resultCreate, is(true)); + assertThat(resultCreate).isTrue(); DatabaseEntity info = arangoDB.db(dbName).getInfo().get(); - assertThat(info.getReplicationFactor(), nullValue()); - assertThat(info.getSatellite(), is(true)); - assertThat(info.getWriteConcern(), is(2)); - assertThat(info.getSharding(), is("")); + assertThat(info.getReplicationFactor()).isNull(); + assertThat(info.getSatellite()).isTrue(); + assertThat(info.getWriteConcern()).isEqualTo(2); + assertThat(info.getSharding()).isEmpty(); final Boolean resultDelete = arangoDB.db(dbName).drop().get(); - assertThat(resultDelete, is(true)); + assertThat(resultDelete).isTrue(); } @Test - public void deleteDatabase() throws InterruptedException, ExecutionException { + void deleteDatabase() throws InterruptedException, ExecutionException { final Boolean resultCreate = arangoDB.createDatabase(BaseTest.TEST_DB).get(); - assertThat(resultCreate, is(true)); + assertThat(resultCreate).isTrue(); arangoDB.db(BaseTest.TEST_DB).drop() - .whenComplete((resultDelete, ex) -> assertThat(resultDelete, is(true))) + .whenComplete((resultDelete, ex) -> assertThat(resultDelete).isEqualTo(true)) .get(); } @Test - public void getDatabases() throws InterruptedException, ExecutionException { + void getDatabases() throws InterruptedException, ExecutionException { Collection dbs = arangoDB.getDatabases().get(); - assertThat(dbs, is(notNullValue())); - assertThat(dbs.size(), is(greaterThan(0))); + assertThat(dbs).isNotNull(); + assertThat(dbs).isNotEmpty(); final int dbCount = dbs.size(); - assertThat(dbs, hasItem("_system")); + assertThat(dbs).contains("_system"); arangoDB.createDatabase(BaseTest.TEST_DB).get(); dbs = arangoDB.getDatabases().get(); - assertThat(dbs.size(), is(greaterThan(dbCount))); - assertThat(dbs, hasItem("_system")); - assertThat(dbs, hasItem(BaseTest.TEST_DB.get())); + assertThat(dbs).hasSizeGreaterThan(dbCount); + assertThat(dbs).contains("_system"); + assertThat(dbs).contains(BaseTest.TEST_DB.get()); arangoDB.db(BaseTest.TEST_DB).drop().get(); } @Test - public void getAccessibleDatabases() throws InterruptedException, ExecutionException { + void getAccessibleDatabases() throws InterruptedException, ExecutionException { arangoDB.getAccessibleDatabases() .whenComplete((dbs, ex) -> { - assertThat(dbs, is(notNullValue())); - assertThat(dbs.size(), greaterThan(0)); - assertThat(dbs, hasItem("_system")); + assertThat(dbs).isNotNull(); + assertThat(dbs).isNotEmpty(); + assertThat(dbs).contains("_system"); }) .get(); } @Test - public void getAccessibleDatabasesFor() throws InterruptedException, ExecutionException { + void getAccessibleDatabasesFor() throws InterruptedException, ExecutionException { arangoDB.getAccessibleDatabasesFor("root") .whenComplete((dbs, ex) -> { - assertThat(dbs, is(notNullValue())); - assertThat(dbs, is(notNullValue())); - assertThat(dbs.size(), greaterThan(0)); - assertThat(dbs, hasItem("_system")); + assertThat(dbs).isNotNull(); + assertThat(dbs).isNotNull(); + assertThat(dbs).isNotEmpty(); + assertThat(dbs).contains("_system"); }) .get(); } @Test - public void createUser() throws InterruptedException, ExecutionException { + void createUser() throws InterruptedException, ExecutionException { try { arangoDB.createUser(USER, PW, null) .whenComplete((result, ex) -> { - assertThat(result, is(notNullValue())); - assertThat(result.getUser(), is(USER)); + assertThat(result).isNotNull(); + assertThat(result.getUser()).isEqualTo(USER); }) .get(); } finally { @@ -260,27 +263,27 @@ public void createUser() throws InterruptedException, ExecutionException { } @Test - public void deleteUser() throws InterruptedException, ExecutionException { + void deleteUser() throws InterruptedException, ExecutionException { arangoDB.createUser(USER, PW, null).get(); arangoDB.deleteUser(USER).get(); } @Test - public void getUserRoot() throws InterruptedException, ExecutionException { + void getUserRoot() throws InterruptedException, ExecutionException { arangoDB.getUser(ROOT) .whenComplete((user, ex) -> { - assertThat(user, is(notNullValue())); - assertThat(user.getUser(), is(ROOT)); + assertThat(user).isNotNull(); + assertThat(user.getUser()).isEqualTo(ROOT); }) .get(); } @Test - public void getUser() throws InterruptedException, ExecutionException { + void getUser() throws InterruptedException, ExecutionException { try { arangoDB.createUser(USER, PW, null).get(); arangoDB.getUser(USER) - .whenComplete((user, ex) -> assertThat(user.getUser(), is(USER))) + .whenComplete((user, ex) -> assertThat(user.getUser()).isEqualTo(USER)) .get(); } finally { arangoDB.deleteUser(USER).get(); @@ -289,27 +292,26 @@ public void getUser() throws InterruptedException, ExecutionException { } @Test - public void getUsersOnlyRoot() throws InterruptedException, ExecutionException { + void getUsersOnlyRoot() throws InterruptedException, ExecutionException { arangoDB.getUsers() .whenComplete((users, ex) -> { - assertThat(users, is(notNullValue())); - assertThat(users.size(), greaterThan(0)); + assertThat(users).isNotNull(); + assertThat(users).isNotEmpty(); }) .get(); } @Test - public void getUsers() throws InterruptedException, ExecutionException { + void getUsers() throws InterruptedException, ExecutionException { try { arangoDB.createUser(USER, PW, null).get(); arangoDB.getUsers() .whenComplete((users, ex) -> { - assertThat(users, is(notNullValue())); - assertThat(users.size(), greaterThanOrEqualTo(2)); + assertThat(users).isNotNull(); + assertThat(users).hasSizeGreaterThanOrEqualTo(2); assertThat( - users.stream().map(UserEntity::getUser).collect(Collectors.toList()), - hasItems(ROOT, USER) - ); + users.stream().map(UserEntity::getUser).collect(Collectors.toList()) + ).contains(ROOT, USER); }) .get(); } finally { @@ -318,7 +320,7 @@ public void getUsers() throws InterruptedException, ExecutionException { } @Test - public void updateUserNoOptions() throws InterruptedException, ExecutionException { + void updateUserNoOptions() throws InterruptedException, ExecutionException { try { arangoDB.createUser(USER, PW, null).get(); arangoDB.updateUser(USER, null).get(); @@ -328,7 +330,7 @@ public void updateUserNoOptions() throws InterruptedException, ExecutionExceptio } @Test - public void updateUser() throws InterruptedException, ExecutionException { + void updateUser() throws InterruptedException, ExecutionException { try { final Map extra = new HashMap<>(); extra.put("hund", false); @@ -338,18 +340,18 @@ public void updateUser() throws InterruptedException, ExecutionException { { arangoDB.updateUser(USER, new UserUpdateOptions().extra(extra)) .whenComplete((user, ex) -> { - assertThat(user, is(notNullValue())); - assertThat(user.getExtra().size(), is(2)); - assertThat(user.getExtra().get("hund"), is(notNullValue())); - assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("hund"))), is(true)); + assertThat(user).isNotNull(); + assertThat(user.getExtra()).hasSize(2); + assertThat(user.getExtra().get("hund")).isNotNull(); + assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("hund")))).isTrue(); }) .get(); } arangoDB.getUser(USER) .whenComplete((user2, ex) -> { - assertThat(user2.getExtra().size(), is(2)); - assertThat(user2.getExtra().get("hund"), is(notNullValue())); - assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("hund"))), is(true)); + assertThat(user2.getExtra()).hasSize(2); + assertThat(user2.getExtra().get("hund")).isNotNull(); + assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("hund")))).isTrue(); }) .get(); } finally { @@ -358,7 +360,7 @@ public void updateUser() throws InterruptedException, ExecutionException { } @Test - public void replaceUser() throws InterruptedException, ExecutionException { + void replaceUser() throws InterruptedException, ExecutionException { try { final Map extra = new HashMap<>(); extra.put("hund", false); @@ -368,19 +370,19 @@ public void replaceUser() throws InterruptedException, ExecutionException { { arangoDB.replaceUser(USER, new UserUpdateOptions().extra(extra)) .whenComplete((user, ex) -> { - assertThat(user, is(notNullValue())); - assertThat(user.getExtra().size(), is(1)); - assertThat(user.getExtra().get("mund"), is(notNullValue())); - assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("mund"))), is(true)); + assertThat(user).isNotNull(); + assertThat(user.getExtra()).hasSize(1); + assertThat(user.getExtra().get("mund")).isNotNull(); + assertThat(Boolean.valueOf(String.valueOf(user.getExtra().get("mund")))).isTrue(); }) .get(); } { arangoDB.getUser(USER) .whenComplete((user2, ex) -> { - assertThat(user2.getExtra().size(), is(1)); - assertThat(user2.getExtra().get("mund"), is(notNullValue())); - assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("mund"))), is(true)); + assertThat(user2.getExtra()).hasSize(1); + assertThat(user2.getExtra().get("mund")).isNotNull(); + assertThat(Boolean.valueOf(String.valueOf(user2.getExtra().get("mund")))).isTrue(); }) .get(); } @@ -390,7 +392,7 @@ public void replaceUser() throws InterruptedException, ExecutionException { } @Test - public void updateUserDefaultDatabaseAccess() throws InterruptedException, ExecutionException { + void updateUserDefaultDatabaseAccess() throws InterruptedException, ExecutionException { try { arangoDB.createUser(USER, PW).get(); arangoDB.grantDefaultDatabaseAccess(USER, Permissions.RW).get(); @@ -400,7 +402,7 @@ public void updateUserDefaultDatabaseAccess() throws InterruptedException, Execu } @Test - public void updateUserDefaultCollectionAccess() throws InterruptedException, ExecutionException { + void updateUserDefaultCollectionAccess() throws InterruptedException, ExecutionException { try { arangoDB.createUser(USER, PW).get(); arangoDB.grantDefaultCollectionAccess(USER, Permissions.RW).get(); @@ -410,151 +412,151 @@ public void updateUserDefaultCollectionAccess() throws InterruptedException, Exe } @Test - public void authenticationFailPassword() throws InterruptedException { - final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().password("no").jwt(null).build(); + void authenticationFailPassword() throws InterruptedException { + final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().password("no").jwt(null).serializer(new ArangoJack()).build(); try { arangoDB.getVersion().get(); fail(); } catch (final ExecutionException exception) { - assertThat(exception.getCause(), instanceOf(ArangoDBException.class)); + assertThat(exception.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void authenticationFailUser() throws InterruptedException { - final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().user("no").jwt(null).build(); + void authenticationFailUser() throws InterruptedException { + final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().user("no").jwt(null).serializer(new ArangoJack()).build(); try { arangoDB.getVersion().get(); fail(); } catch (final ExecutionException exception) { - assertThat(exception.getCause(), instanceOf(ArangoDBException.class)); + assertThat(exception.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void execute() throws VPackException, InterruptedException, ExecutionException { + void execute() throws VPackException, InterruptedException, ExecutionException { arangoDB .execute(new Request(DbName.SYSTEM, RequestType.GET, "/_api/version")) .whenComplete((response, ex) -> { - assertThat(response.getBody(), is(notNullValue())); - assertThat(response.getBody().get("version").isString(), is(true)); + assertThat(response.getBody()).isNotNull(); + assertThat(response.getBody().get("version").isString()).isTrue(); }) .get(); } @Test - public void execute_acquireHostList_enabled() throws VPackException, InterruptedException, ExecutionException { - final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().acquireHostList(true).build(); + void execute_acquireHostList_enabled() throws VPackException, InterruptedException, ExecutionException { + final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().acquireHostList(true).serializer(new ArangoJack()).build(); arangoDB .execute(new Request(DbName.SYSTEM, RequestType.GET, "/_api/version")) .whenComplete((response, ex) -> { - assertThat(response.getBody(), is(notNullValue())); - assertThat(response.getBody().get("version").isString(), is(true)); + assertThat(response.getBody()).isNotNull(); + assertThat(response.getBody().get("version").isString()).isTrue(); }) .get(); } @Test - public void getLogs() throws InterruptedException, ExecutionException { + void getLogs() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) arangoDB.getLogs(null) .whenComplete((logs, ex) -> { - assertThat(logs, is(notNullValue())); - assertThat(logs.getTotalAmount(), greaterThan(0L)); - assertThat((long) logs.getLid().size(), is(logs.getTotalAmount())); - assertThat((long) logs.getLevel().size(), is(logs.getTotalAmount())); - assertThat((long) logs.getTimestamp().size(), is(logs.getTotalAmount())); - assertThat((long) logs.getText().size(), is(logs.getTotalAmount())); + assertThat(logs).isNotNull(); + assertThat(logs.getTotalAmount()).isPositive(); + assertThat((long) logs.getLid().size()).isEqualTo(logs.getTotalAmount()); + assertThat((long) logs.getLevel().size()).isEqualTo(logs.getTotalAmount()); + assertThat((long) logs.getTimestamp().size()).isEqualTo(logs.getTotalAmount()); + assertThat((long) logs.getText().size()).isEqualTo(logs.getTotalAmount()); }) .get(); } @Test - public void getLogsUpto() throws InterruptedException, ExecutionException { + void getLogsUpto() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(null).get(); arangoDB.getLogs(new LogOptions().upto(LogLevel.WARNING)) .whenComplete((logsUpto, ex) -> { - assertThat(logsUpto, is(notNullValue())); - assertThat(logs.getTotalAmount() >= logsUpto.getTotalAmount(), is(true)); - assertThat(logsUpto.getLevel(), not(contains(LogLevel.INFO))); + assertThat(logsUpto).isNotNull(); + assertThat(logs.getTotalAmount() >= logsUpto.getTotalAmount()).isTrue(); + assertThat(logsUpto.getLevel()).doesNotContain(LogLevel.INFO); }) .get(); } @Test - public void getLogsLevel() throws InterruptedException, ExecutionException { + void getLogsLevel() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(null).get(); arangoDB.getLogs(new LogOptions().level(LogLevel.INFO)) .whenComplete((logsInfo, ex) -> { - assertThat(logsInfo, is(notNullValue())); - assertThat(logs.getTotalAmount() >= logsInfo.getTotalAmount(), is(true)); - assertThat(logsInfo.getLevel(), everyItem(is(LogLevel.INFO))); + assertThat(logsInfo).isNotNull(); + assertThat(logs.getTotalAmount() >= logsInfo.getTotalAmount()).isTrue(); + assertThat(logsInfo.getLevel()).containsOnly(LogLevel.INFO); }) .get(); } @Test - public void getLogsStart() throws InterruptedException, ExecutionException { + void getLogsStart() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(null).get(); - assertThat(logs.getLid(), not(empty())); + assertThat(logs.getLid()).isNotEmpty(); arangoDB.getLogs(new LogOptions().start(logs.getLid().get(0) + 1)) .whenComplete((logsStart, ex) -> { - assertThat(logsStart, is(notNullValue())); - assertThat(logsStart.getLid(), not(contains(logs.getLid().get(0)))); + assertThat(logsStart).isNotNull(); + assertThat(logsStart.getLid()).doesNotContain(logs.getLid().get(0)); }) .get(); } @Test - public void getLogsSize() throws InterruptedException, ExecutionException { + void getLogsSize() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(null).get(); - assertThat(logs.getLid().size(), greaterThan(0)); + assertThat(logs.getLid()).isNotEmpty(); arangoDB.getLogs(new LogOptions().size(logs.getLid().size() - 1)) .whenComplete((logsSize, ex) -> { - assertThat(logsSize, is(notNullValue())); - assertThat(logsSize.getLid().size(), is(logs.getLid().size() - 1)); + assertThat(logsSize).isNotNull(); + assertThat(logsSize.getLid()).hasSize(logs.getLid().size() - 1); }) .get(); } @Test - public void getLogsOffset() throws InterruptedException, ExecutionException { + void getLogsOffset() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(null).get(); - assertThat(logs.getTotalAmount(), greaterThan(0L)); + assertThat(logs.getTotalAmount()).isPositive(); arangoDB.getLogs(new LogOptions().offset((int) (logs.getTotalAmount() - 1))) .whenComplete((logsOffset, ex) -> { - assertThat(logsOffset, is(notNullValue())); - assertThat(logsOffset.getLid().size(), is(1)); + assertThat(logsOffset).isNotNull(); + assertThat(logsOffset.getLid()).hasSize(1); }) .get(); } @Test - public void getLogsSearch() throws InterruptedException, ExecutionException { + void getLogsSearch() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogEntity logs = arangoDB.getLogs(null).get(); arangoDB.getLogs(new LogOptions().search(BaseTest.TEST_DB.get())) .whenComplete((logsSearch, ex) -> { - assertThat(logsSearch, is(notNullValue())); - assertThat(logs.getTotalAmount(), greaterThan(logsSearch.getTotalAmount())); + assertThat(logsSearch).isNotNull(); + assertThat(logs.getTotalAmount()).isGreaterThan(logsSearch.getTotalAmount()); }) .get(); } @Test - public void getLogsSortAsc() throws InterruptedException, ExecutionException { + void getLogsSortAsc() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) arangoDB.getLogs(new LogOptions().sort(SortOrder.asc)) .whenComplete((logs, ex) -> { - assertThat(logs, is(notNullValue())); + assertThat(logs).isNotNull(); long lastId = -1; for (final Long id : logs.getLid()) { - assertThat(id, greaterThan(lastId)); + assertThat(id).isGreaterThan(lastId); lastId = id; } }) @@ -562,14 +564,14 @@ public void getLogsSortAsc() throws InterruptedException, ExecutionException { } @Test - public void getLogsSortDesc() throws InterruptedException, ExecutionException { + void getLogsSortDesc() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) arangoDB.getLogs(new LogOptions().sort(SortOrder.desc)) .whenComplete((logs, ex) -> { - assertThat(logs, is(notNullValue())); + assertThat(logs).isNotNull(); long lastId = Long.MAX_VALUE; for (final Long id : logs.getLid()) { - assertThat(lastId, greaterThan(id)); + assertThat(lastId).isGreaterThan(id); lastId = id; } }) @@ -577,50 +579,50 @@ public void getLogsSortDesc() throws InterruptedException, ExecutionException { } @Test - public void getLogEntries() throws InterruptedException, ExecutionException { + void getLogEntries() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 8)); arangoDB.getLogEntries(null) .whenComplete((logs, ex) -> { - assertThat(logs, is(notNullValue())); - assertThat(logs.getTotal(), greaterThan(0L)); - assertThat((long) logs.getMessages().size(), is(logs.getTotal())); + assertThat(logs).isNotNull(); + assertThat(logs.getTotal()).isPositive(); + assertThat((long) logs.getMessages().size()).isEqualTo(logs.getTotal()); }) .get(); } @Test - public void getLogEntriesSearch() throws InterruptedException, ExecutionException { + void getLogEntriesSearch() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 8)); final LogEntriesEntity logs = arangoDB.getLogEntries(null).get(); arangoDB.getLogs(new LogOptions().search(BaseTest.TEST_DB.get())) .whenComplete((logsSearch, ex) -> { - assertThat(logsSearch, is(notNullValue())); - assertThat(logs.getTotal(), greaterThan(logsSearch.getTotalAmount())); + assertThat(logsSearch).isNotNull(); + assertThat(logs.getTotal()).isGreaterThan(logsSearch.getTotalAmount()); }) .get(); } @Test - public void getLogLevel() throws InterruptedException, ExecutionException { + void getLogLevel() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) arangoDB.getLogLevel() .whenComplete((logLevel, ex) -> { - assertThat(logLevel, is(notNullValue())); - assertThat(logLevel.getAgency(), is(LogLevelEntity.LogLevel.INFO)); + assertThat(logLevel).isNotNull(); + assertThat(logLevel.getAgency()).isEqualTo(LogLevelEntity.LogLevel.INFO); }) .get(); } @Test - public void setLogLevel() throws InterruptedException, ExecutionException { + void setLogLevel() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 7)); // it fails in 3.6 active-failover (BTS-362) final LogLevelEntity entity = new LogLevelEntity(); try { entity.setAgency(LogLevelEntity.LogLevel.ERROR); arangoDB.setLogLevel(entity) .whenComplete((logLevel, ex) -> { - assertThat(logLevel, is(notNullValue())); - assertThat(logLevel.getAgency(), is(LogLevelEntity.LogLevel.ERROR)); + assertThat(logLevel).isNotNull(); + assertThat(logLevel.getAgency()).isEqualTo(LogLevelEntity.LogLevel.ERROR); }) .get(); } finally { @@ -630,7 +632,7 @@ public void setLogLevel() throws InterruptedException, ExecutionException { } @Test - public void queueTime() throws InterruptedException, ExecutionException { + void queueTime() throws InterruptedException, ExecutionException { List>> reqs = IntStream.range(0, 80) .mapToObj(__ -> arangoDB.db().query("RETURN SLEEP(1)", Void.class)) .collect(Collectors.toList()); @@ -642,18 +644,18 @@ public void queueTime() throws InterruptedException, ExecutionException { double avg = qt.getAvg(); QueueTimeSample[] values = qt.getValues(); if (isAtLeastVersion(3, 9)) { - assertThat(values.length, is(20)); + assertThat(values).hasSize(20); for (int i = 0; i < values.length; i++) { - assertThat(values[i], is(notNullValue())); - assertThat(values[i].value, is(greaterThanOrEqualTo(0.0))); + assertThat(values[i]).isNotNull(); + assertThat(values[i].value).isGreaterThanOrEqualTo(0.0); if (i > 0) { - assertThat(values[i].timestamp, greaterThanOrEqualTo(values[i - 1].timestamp)); + assertThat(values[i].timestamp).isGreaterThanOrEqualTo(values[i - 1].timestamp); } } - assertThat(avg, is(greaterThan(0.0))); + assertThat(avg).isGreaterThan(0.0); } else { - assertThat(avg, is(0.0)); - assertThat(values, is(emptyArray())); + assertThat(avg).isEqualTo(0.0); + assertThat(values).isEmpty(); } } diff --git a/src/test/java/com/arangodb/async/ArangoDatabaseTest.java b/src/test/java/com/arangodb/async/ArangoDatabaseTest.java index 8d9426f62..93c0da44b 100644 --- a/src/test/java/com/arangodb/async/ArangoDatabaseTest.java +++ b/src/test/java/com/arangodb/async/ArangoDatabaseTest.java @@ -31,8 +31,8 @@ import com.arangodb.velocypack.VPackBuilder; import com.arangodb.velocypack.VPackSlice; import com.arangodb.velocypack.exception.VPackException; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.*; @@ -40,156 +40,155 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + /** * @author Mark Vollmary * @author Michele Rastelli */ -public class ArangoDatabaseTest extends BaseTest { +class ArangoDatabaseTest extends BaseTest { private static final String COLLECTION_NAME = "db_test"; private static final String GRAPH_NAME = "graph_test"; @Test - public void create() throws InterruptedException, ExecutionException { + void create() throws InterruptedException, ExecutionException { try { final Boolean result = arangoDB.db(DbName.of(BaseTest.TEST_DB.get() + "_1")).create().get(); - assertThat(result, is(true)); + assertThat(result).isTrue(); } finally { arangoDB.db(DbName.of(BaseTest.TEST_DB.get() + "_1")).drop().get(); } } @Test - public void getVersion() throws InterruptedException, ExecutionException { + void getVersion() throws InterruptedException, ExecutionException { db.getVersion() .whenComplete((version, ex) -> { - assertThat(version, is(notNullValue())); - assertThat(version.getServer(), is(notNullValue())); - assertThat(version.getVersion(), is(notNullValue())); + assertThat(version).isNotNull(); + assertThat(version.getServer()).isNotNull(); + assertThat(version.getVersion()).isNotNull(); }) .get(); } @Test - public void getEngine() throws ExecutionException, InterruptedException { + void getEngine() throws ExecutionException, InterruptedException { final ArangoDBEngine engine = db.getEngine().get(); - assertThat(engine, is(notNullValue())); - assertThat(engine.getName(), is(notNullValue())); + assertThat(engine).isNotNull(); + assertThat(engine.getName()).isNotNull(); } @Test - public void exists() throws InterruptedException, ExecutionException { - assertThat(db.exists().get(), is(true)); - assertThat(arangoDB.db(DbName.of("no")).exists().get(), is(false)); + void exists() throws InterruptedException, ExecutionException { + assertThat(db.exists().get()).isTrue(); + assertThat(arangoDB.db(DbName.of("no")).exists().get()).isFalse(); } @Test - public void getAccessibleDatabases() throws InterruptedException, ExecutionException { + void getAccessibleDatabases() throws InterruptedException, ExecutionException { db.getAccessibleDatabases() .whenComplete((dbs, ex) -> { - assertThat(dbs, is(notNullValue())); - assertThat(dbs.size(), greaterThan(0)); - assertThat(dbs, hasItem("_system")); + assertThat(dbs).isNotNull(); + assertThat(dbs.size()).isGreaterThan(0); + assertThat(dbs).contains("_system"); }) .get(); } @Test - public void createCollection() throws InterruptedException, ExecutionException { + void createCollection() throws InterruptedException, ExecutionException { db.createCollection(COLLECTION_NAME, null) .whenComplete((result, ex) -> { - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); }) .get(); db.collection(COLLECTION_NAME).drop().get(); } @Test - public void createCollectionWithReplicationFactor() throws InterruptedException, ExecutionException { + void createCollectionWithReplicationFactor() throws InterruptedException, ExecutionException { assumeTrue(isCluster()); final CollectionEntity result = db .createCollection(COLLECTION_NAME, new CollectionCreateOptions().replicationFactor(2)).get(); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - assertThat(db.collection(COLLECTION_NAME).getProperties().get().getReplicationFactor(), is(2)); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); + assertThat(db.collection(COLLECTION_NAME).getProperties().get().getReplicationFactor()).isEqualTo(2); db.collection(COLLECTION_NAME).drop().get(); } @Test - public void createCollectionWithMinReplicationFactor() throws ExecutionException, InterruptedException { + void createCollectionWithMinReplicationFactor() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isCluster()); final CollectionEntity result = db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().replicationFactor(2).minReplicationFactor(2)).get(); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - assertThat(db.collection(COLLECTION_NAME).getProperties().get().getReplicationFactor(), is(2)); - assertThat(db.collection(COLLECTION_NAME).getProperties().get().getMinReplicationFactor(), is(2)); - assertThat(db.collection(COLLECTION_NAME).getProperties().get().getSatellite(), is(nullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); + assertThat(db.collection(COLLECTION_NAME).getProperties().get().getReplicationFactor()).isEqualTo(2); + assertThat(db.collection(COLLECTION_NAME).getProperties().get().getMinReplicationFactor()).isEqualTo(2); + assertThat(db.collection(COLLECTION_NAME).getProperties().get().getSatellite()).isNull(); db.collection(COLLECTION_NAME).drop(); } @Test - public void createCollectionWithNumberOfShards() throws InterruptedException, ExecutionException { + void createCollectionWithNumberOfShards() throws InterruptedException, ExecutionException { assumeTrue(isCluster()); final CollectionEntity result = db .createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(2)).get(); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); - assertThat(db.collection(COLLECTION_NAME).getProperties().get().getNumberOfShards(), is(2)); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); + assertThat(db.collection(COLLECTION_NAME).getProperties().get().getNumberOfShards()).isEqualTo(2); db.collection(COLLECTION_NAME).drop().get(); } @Test - public void createCollectionWithNumberOfShardsAndShardKey() throws InterruptedException, ExecutionException { + void createCollectionWithNumberOfShardsAndShardKey() throws InterruptedException, ExecutionException { assumeTrue(isCluster()); final CollectionEntity result = db .createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(2).shardKeys("a")) .get(); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); final CollectionPropertiesEntity properties = db.collection(COLLECTION_NAME).getProperties().get(); - assertThat(properties.getNumberOfShards(), is(2)); - assertThat(properties.getShardKeys().size(), is(1)); + assertThat(properties.getNumberOfShards()).isEqualTo(2); + assertThat(properties.getShardKeys()).hasSize(1); db.collection(COLLECTION_NAME).drop().get(); } @Test - public void createCollectionWithNumberOfShardsAndShardKeys() throws InterruptedException, ExecutionException { + void createCollectionWithNumberOfShardsAndShardKeys() throws InterruptedException, ExecutionException { assumeTrue(isCluster()); final CollectionEntity result = db.createCollection(COLLECTION_NAME, new CollectionCreateOptions().numberOfShards(2).shardKeys("a", "b")).get(); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is(notNullValue())); + assertThat(result).isNotNull(); + assertThat(result.getId()).isNotNull(); final CollectionPropertiesEntity properties = db.collection(COLLECTION_NAME).getProperties().get(); - assertThat(properties.getNumberOfShards(), is(2)); - assertThat(properties.getShardKeys().size(), is(2)); + assertThat(properties.getNumberOfShards()).isEqualTo(2); + assertThat(properties.getShardKeys()).hasSize(2); db.collection(COLLECTION_NAME).drop().get(); } @Test - public void deleteCollection() throws InterruptedException, ExecutionException { + void deleteCollection() throws InterruptedException, ExecutionException { db.createCollection(COLLECTION_NAME, null).get(); db.collection(COLLECTION_NAME).drop().get(); try { db.collection(COLLECTION_NAME).getInfo().get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void deleteSystemCollection() throws InterruptedException, ExecutionException { + void deleteSystemCollection() throws InterruptedException, ExecutionException { final String name = "_system_test"; db.createCollection(name, new CollectionCreateOptions().isSystem(true)).get(); db.collection(name).drop(true).get(); @@ -197,46 +196,46 @@ public void deleteSystemCollection() throws InterruptedException, ExecutionExcep db.collection(name).getInfo().get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void deleteSystemCollectionFail() throws InterruptedException, ExecutionException { + void deleteSystemCollectionFail() throws InterruptedException, ExecutionException { final String name = "_system_test"; db.createCollection(name, new CollectionCreateOptions().isSystem(true)).get(); try { db.collection(name).drop().get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } db.collection(name).drop(true).get(); try { db.collection(name).getInfo().get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void getIndex() throws InterruptedException, ExecutionException { + void getIndex() throws InterruptedException, ExecutionException { db.createCollection(COLLECTION_NAME, null).get(); final Collection fields = new ArrayList<>(); fields.add("a"); final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null).get(); db.getIndex(createResult.getId()) .whenComplete((readResult, ex) -> { - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getType(), is(createResult.getType())); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getType()).isEqualTo(createResult.getType()); }) .get(); db.collection(COLLECTION_NAME).drop().get(); } @Test - public void deleteIndex() throws InterruptedException, ExecutionException { + void deleteIndex() throws InterruptedException, ExecutionException { try { db.createCollection(COLLECTION_NAME, null).get(); final Collection fields = new ArrayList<>(); @@ -244,14 +243,14 @@ public void deleteIndex() throws InterruptedException, ExecutionException { final IndexEntity createResult = db.collection(COLLECTION_NAME).ensureHashIndex(fields, null).get(); db.deleteIndex(createResult.getId()) .whenComplete((id, ex) -> { - assertThat(id, is(createResult.getId())); + assertThat(id).isEqualTo(createResult.getId()); try { db.getIndex(id).get(); fail(); } catch (InterruptedException e) { fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } }) .get(); @@ -261,15 +260,15 @@ public void deleteIndex() throws InterruptedException, ExecutionException { } @Test - public void getCollections() throws InterruptedException, ExecutionException { + void getCollections() throws InterruptedException, ExecutionException { try { final Collection systemCollections = db.getCollections(null).get(); db.createCollection(COLLECTION_NAME + "1", null).get(); db.createCollection(COLLECTION_NAME + "2", null).get(); db.getCollections(null) .whenComplete((collections, ex) -> { - assertThat(collections.size(), is(2 + systemCollections.size())); - assertThat(collections, is(notNullValue())); + assertThat(collections.size()).isEqualTo(2 + systemCollections.size()); + assertThat(collections).isNotNull(); }) .get(); } finally { @@ -279,17 +278,17 @@ public void getCollections() throws InterruptedException, ExecutionException { } @Test - public void getCollectionsExcludeSystem() throws InterruptedException, ExecutionException { + void getCollectionsExcludeSystem() throws InterruptedException, ExecutionException { try { final CollectionsReadOptions options = new CollectionsReadOptions().excludeSystem(true); final Collection systemCollections = db.getCollections(options).get(); - assertThat(systemCollections.size(), is(0)); + assertThat(systemCollections).isEmpty(); db.createCollection(COLLECTION_NAME + "1", null).get(); db.createCollection(COLLECTION_NAME + "2", null).get(); db.getCollections(options) .whenComplete((collections, ex) -> { - assertThat(collections.size(), is(2)); - assertThat(collections, is(notNullValue())); + assertThat(collections.size()).isEqualTo(2); + assertThat(collections).isNotNull(); }) .get(); } finally { @@ -299,7 +298,7 @@ public void getCollectionsExcludeSystem() throws InterruptedException, Execution } @Test - public void grantAccess() throws InterruptedException, ExecutionException { + void grantAccess() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234", null).get(); db.grantAccess("user1").get(); @@ -309,7 +308,7 @@ public void grantAccess() throws InterruptedException, ExecutionException { } @Test - public void grantAccessRW() throws InterruptedException, ExecutionException { + void grantAccessRW() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234", null).get(); db.grantAccess("user1", Permissions.RW).get(); @@ -319,7 +318,7 @@ public void grantAccessRW() throws InterruptedException, ExecutionException { } @Test - public void grantAccessRO() throws InterruptedException, ExecutionException { + void grantAccessRO() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234", null).get(); db.grantAccess("user1", Permissions.RO).get(); @@ -329,7 +328,7 @@ public void grantAccessRO() throws InterruptedException, ExecutionException { } @Test - public void grantAccessNONE() throws InterruptedException, ExecutionException { + void grantAccessNONE() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234", null).get(); db.grantAccess("user1", Permissions.NONE).get(); @@ -338,13 +337,14 @@ public void grantAccessNONE() throws InterruptedException, ExecutionException { } } - @Test(expected = ExecutionException.class) - public void grantAccessUserNotFound() throws InterruptedException, ExecutionException { - db.grantAccess("user1", Permissions.RW).get(); + @Test + void grantAccessUserNotFound() { + Throwable thrown = catchThrowable(() -> db.grantAccess("user1", Permissions.RW).get()); + assertThat(thrown).isInstanceOf(ExecutionException.class); } @Test - public void revokeAccess() throws InterruptedException, ExecutionException { + void revokeAccess() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234", null).get(); db.revokeAccess("user1").get(); @@ -353,13 +353,14 @@ public void revokeAccess() throws InterruptedException, ExecutionException { } } - @Test(expected = ExecutionException.class) - public void revokeAccessUserNotFound() throws InterruptedException, ExecutionException { - db.revokeAccess("user1").get(); + @Test + void revokeAccessUserNotFound() { + Throwable thrown = catchThrowable(() -> db.revokeAccess("user1").get()); + assertThat(thrown).isInstanceOf(ExecutionException.class); } @Test - public void resetAccess() throws InterruptedException, ExecutionException { + void resetAccess() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234", null).get(); db.resetAccess("user1").get(); @@ -368,13 +369,14 @@ public void resetAccess() throws InterruptedException, ExecutionException { } } - @Test(expected = ExecutionException.class) - public void resetAccessUserNotFound() throws InterruptedException, ExecutionException { - db.resetAccess("user1").get(); + @Test + void resetAccessUserNotFound() { + Throwable thrown = catchThrowable(() -> db.resetAccess("user1").get()); + assertThat(thrown).isInstanceOf(ExecutionException.class); } @Test - public void grantDefaultCollectionAccess() throws InterruptedException, ExecutionException { + void grantDefaultCollectionAccess() throws InterruptedException, ExecutionException { try { arangoDB.createUser("user1", "1234").get(); db.grantDefaultCollectionAccess("user1", Permissions.RW).get(); @@ -384,12 +386,12 @@ public void grantDefaultCollectionAccess() throws InterruptedException, Executio } @Test - public void getPermissions() throws InterruptedException, ExecutionException { - assertThat(Permissions.RW, is(db.getPermissions("root").get())); + void getPermissions() throws InterruptedException, ExecutionException { + assertThat(db.getPermissions("root").get()).isEqualTo(Permissions.RW); } @Test - public void query() throws InterruptedException, ExecutionException { + void query() throws InterruptedException, ExecutionException { try { db.createCollection(COLLECTION_NAME, null).get(); for (int i = 0; i < 10; i++) { @@ -397,9 +399,8 @@ public void query() throws InterruptedException, ExecutionException { } db.query("for i in db_test return i._id", null, null, String.class) .whenComplete((cursor, ex) -> { - assertThat(cursor, is(notNullValue())); for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat(cursor.hasNext()).isEqualTo(true); } }) .get(); @@ -409,7 +410,7 @@ public void query() throws InterruptedException, ExecutionException { } @Test - public void queryForEach() throws InterruptedException, ExecutionException { + void queryForEach() throws InterruptedException, ExecutionException { try { db.createCollection(COLLECTION_NAME, null).get(); for (int i = 0; i < 10; i++) { @@ -417,10 +418,9 @@ public void queryForEach() throws InterruptedException, ExecutionException { } db.query("for i in db_test return i._id", null, null, String.class) .whenComplete((cursor, ex) -> { - assertThat(cursor, is(notNullValue())); final AtomicInteger i = new AtomicInteger(0); cursor.forEachRemaining(e -> i.incrementAndGet()); - assertThat(i.get(), is(10)); + assertThat(i.get()).isEqualTo(10); }) .get(); } finally { @@ -429,7 +429,7 @@ public void queryForEach() throws InterruptedException, ExecutionException { } @Test - public void queryStream() throws InterruptedException, ExecutionException { + void queryStream() throws InterruptedException, ExecutionException { try { db.createCollection(COLLECTION_NAME, null).get(); for (int i = 0; i < 10; i++) { @@ -437,10 +437,9 @@ public void queryStream() throws InterruptedException, ExecutionException { } db.query("for i in db_test return i._id", null, null, String.class) .whenComplete((cursor, ex) -> { - assertThat(cursor, is(notNullValue())); final AtomicInteger i = new AtomicInteger(0); cursor.forEachRemaining(e -> i.incrementAndGet()); - assertThat(i.get(), is(10)); + assertThat(i.get()).isEqualTo(10); }) .get(); } finally { @@ -449,20 +448,20 @@ public void queryStream() throws InterruptedException, ExecutionException { } @Test - public void queryWithTimeout() throws ExecutionException, InterruptedException { + void queryWithTimeout() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 6)); try { db.query("RETURN SLEEP(1)", null, new AqlQueryOptions().maxRuntime(0.1), String.class).get().next(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); - assertThat(((ArangoDBException) e.getCause()).getResponseCode(), is(410)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); + assertThat(((ArangoDBException) e.getCause()).getResponseCode()).isEqualTo(410); } } @Test - public void queryWithCount() throws InterruptedException, ExecutionException { + void queryWithCount() throws InterruptedException, ExecutionException { try { db.createCollection(COLLECTION_NAME, null).get(); for (int i = 0; i < 10; i++) { @@ -471,11 +470,10 @@ public void queryWithCount() throws InterruptedException, ExecutionException { db.query("for i in db_test Limit 6 return i._id", null, new AqlQueryOptions().count(true), String.class) .whenComplete((cursor, ex) -> { - assertThat(cursor, is(notNullValue())); for (int i = 0; i < 6; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat(cursor.hasNext()).isEqualTo(true); } - assertThat(cursor.getCount(), is(6)); + assertThat(cursor.getCount()).isEqualTo(6); }) .get(); } finally { @@ -484,7 +482,7 @@ public void queryWithCount() throws InterruptedException, ExecutionException { } @Test - public void queryWithLimitAndFullCount() throws InterruptedException, ExecutionException { + void queryWithLimitAndFullCount() throws InterruptedException, ExecutionException { try { db.createCollection(COLLECTION_NAME, null).get(); for (int i = 0; i < 10; i++) { @@ -493,12 +491,11 @@ public void queryWithLimitAndFullCount() throws InterruptedException, ExecutionE db.query("for i in db_test Limit 5 return i._id", null, new AqlQueryOptions().fullCount(true), String.class) .whenComplete((cursor, ex) -> { - assertThat(cursor, is(notNullValue())); for (int i = 0; i < 5; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat(cursor.hasNext()).isEqualTo(true); } - assertThat(cursor.getStats(), is(notNullValue())); - assertThat(cursor.getStats().getFullCount(), is(10L)); + assertThat(cursor.getStats()).isNotNull(); + assertThat(cursor.getStats().getFullCount()).isEqualTo(10L); }) .get(); } finally { @@ -507,7 +504,7 @@ public void queryWithLimitAndFullCount() throws InterruptedException, ExecutionE } @Test - public void queryWithBatchSize() throws InterruptedException, ExecutionException { + void queryWithBatchSize() throws InterruptedException, ExecutionException { try { db.createCollection(COLLECTION_NAME, null).get(); for (int i = 0; i < 10; i++) { @@ -515,9 +512,8 @@ public void queryWithBatchSize() throws InterruptedException, ExecutionException } final ArangoCursorAsync cursor = db.query("for i in db_test return i._id", null, new AqlQueryOptions().batchSize(5).count(true), String.class).get(); - assertThat(cursor, is(notNullValue())); for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat(cursor.hasNext()).isTrue(); } } finally { db.collection(COLLECTION_NAME).drop().get(); @@ -525,7 +521,7 @@ public void queryWithBatchSize() throws InterruptedException, ExecutionException } @Test - public void queryStreamWithBatchSize() throws InterruptedException, ExecutionException { + void queryStreamWithBatchSize() throws InterruptedException, ExecutionException { try { db.createCollection(COLLECTION_NAME, null).get(); for (int i = 0; i < 10; i++) { @@ -533,10 +529,9 @@ public void queryStreamWithBatchSize() throws InterruptedException, ExecutionExc } final ArangoCursorAsync cursor = db.query("for i in db_test return i._id", null, new AqlQueryOptions().batchSize(5).count(true), String.class).get(); - assertThat(cursor, is(notNullValue())); final AtomicInteger i = new AtomicInteger(0); cursor.streamRemaining().forEach(e -> i.incrementAndGet()); - assertThat(i.get(), is(10)); + assertThat(i.get()).isEqualTo(10); } finally { db.collection(COLLECTION_NAME).drop().get(); } @@ -546,8 +541,8 @@ public void queryStreamWithBatchSize() throws InterruptedException, ExecutionExc * ignored. takes to long */ @Test - @Ignore - public void queryWithTTL() throws InterruptedException, ExecutionException { + @Disabled + void queryWithTTL() throws InterruptedException, ExecutionException { // set TTL to 1 seconds and get the second batch after 2 seconds! final int ttl = 1; final int wait = 2; @@ -558,37 +553,36 @@ public void queryWithTTL() throws InterruptedException, ExecutionException { } final ArangoCursorAsync cursor = db.query("for i in db_test return i._id", null, new AqlQueryOptions().batchSize(5).ttl(ttl), String.class).get(); - assertThat(cursor, is(notNullValue())); for (int i = 0; i < 10; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat(cursor.hasNext()).isTrue(); if (i == 1) { Thread.sleep(wait * 1000); } } fail(); } catch (final ArangoDBException ex) { - assertThat(ex.getResponseCode(), is(404)); - assertThat(ex.getErrorNum(), is(1600)); + assertThat(ex.getResponseCode()).isEqualTo(404); + assertThat(ex.getErrorNum()).isEqualTo(1600); } finally { db.collection(COLLECTION_NAME).drop().get(); } } @Test - public void changeQueryCache() throws InterruptedException, ExecutionException { + void changeQueryCache() throws InterruptedException, ExecutionException { try { QueryCachePropertiesEntity properties = db.getQueryCacheProperties().get(); - assertThat(properties, is(notNullValue())); - assertThat(properties.getMode(), is(CacheMode.off)); - assertThat(properties.getMaxResults(), greaterThan(0L)); + assertThat(properties).isNotNull(); + assertThat(properties.getMode()).isEqualTo(CacheMode.off); + assertThat(properties.getMaxResults()).isPositive(); properties.setMode(CacheMode.on); properties = db.setQueryCacheProperties(properties).get(); - assertThat(properties, is(notNullValue())); - assertThat(properties.getMode(), is(CacheMode.on)); + assertThat(properties).isNotNull(); + assertThat(properties.getMode()).isEqualTo(CacheMode.on); properties = db.getQueryCacheProperties().get(); - assertThat(properties.getMode(), is(CacheMode.on)); + assertThat(properties.getMode()).isEqualTo(CacheMode.on); } finally { final QueryCachePropertiesEntity properties = new QueryCachePropertiesEntity(); properties.setMode(CacheMode.off); @@ -597,7 +591,7 @@ public void changeQueryCache() throws InterruptedException, ExecutionException { } @Test - public void queryWithCache() throws InterruptedException, ExecutionException { + void queryWithCache() throws InterruptedException, ExecutionException { assumeTrue(isSingleServer()); try { db.createCollection(COLLECTION_NAME, null).get(); @@ -614,16 +608,14 @@ public void queryWithCache() throws InterruptedException, ExecutionException { new AqlQueryOptions().cache(true), String.class) .get(); - assertThat(cursor, is(notNullValue())); - assertThat(cursor.isCached(), is(false)); + assertThat(cursor.isCached()).isFalse(); final ArangoCursorAsync cachedCursor = db .query("FOR t IN db_test FILTER t.age >= 10 SORT t.age RETURN t._id", null, new AqlQueryOptions().cache(true), String.class) .get(); - assertThat(cachedCursor, is(notNullValue())); - assertThat(cachedCursor.isCached(), is(true)); + assertThat(cachedCursor.isCached()).isTrue(); } finally { db.collection(COLLECTION_NAME).drop().get(); @@ -634,7 +626,7 @@ public void queryWithCache() throws InterruptedException, ExecutionException { } @Test - public void queryCursor() throws InterruptedException, ExecutionException { + void queryCursor() throws InterruptedException, ExecutionException { try { db.createCollection(COLLECTION_NAME, null).get(); final int numbDocs = 10; @@ -645,16 +637,14 @@ public void queryCursor() throws InterruptedException, ExecutionException { final int batchSize = 5; final ArangoCursorAsync cursor = db.query("for i in db_test return i._id", null, new AqlQueryOptions().batchSize(batchSize).count(true), String.class).get(); - assertThat(cursor, is(notNullValue())); - assertThat(cursor.getCount(), is(numbDocs)); + assertThat(cursor.getCount()).isEqualTo(numbDocs); final ArangoCursorAsync cursor2 = db.cursor(cursor.getId(), String.class).get(); - assertThat(cursor2, is(notNullValue())); - assertThat(cursor2.getCount(), is(numbDocs)); - assertThat(cursor2.hasNext(), is(true)); + assertThat(cursor2.getCount()).isEqualTo(numbDocs); + assertThat(cursor2.hasNext()).isTrue(); for (int i = 0; i < batchSize; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat(cursor.hasNext()).isTrue(); } } finally { db.collection(COLLECTION_NAME).drop().get(); @@ -662,21 +652,21 @@ public void queryCursor() throws InterruptedException, ExecutionException { } @Test - public void changeQueryTrackingProperties() throws InterruptedException, ExecutionException { + void changeQueryTrackingProperties() throws InterruptedException, ExecutionException { try { QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties().get(); - assertThat(properties, is(notNullValue())); - assertThat(properties.getEnabled(), is(true)); - assertThat(properties.getTrackSlowQueries(), is(true)); - assertThat(properties.getMaxQueryStringLength(), greaterThan(0L)); - assertThat(properties.getMaxSlowQueries(), greaterThan(0L)); - assertThat(properties.getSlowQueryThreshold(), greaterThan(0L)); + assertThat(properties).isNotNull(); + assertThat(properties.getEnabled()).isTrue(); + assertThat(properties.getTrackSlowQueries()).isTrue(); + assertThat(properties.getMaxQueryStringLength()).isPositive(); + assertThat(properties.getMaxSlowQueries()).isPositive(); + assertThat(properties.getSlowQueryThreshold()).isPositive(); properties.setEnabled(false); properties = db.setQueryTrackingProperties(properties).get(); - assertThat(properties, is(notNullValue())); - assertThat(properties.getEnabled(), is(false)); + assertThat(properties).isNotNull(); + assertThat(properties.getEnabled()).isFalse(); properties = db.getQueryTrackingProperties().get(); - assertThat(properties.getEnabled(), is(false)); + assertThat(properties.getEnabled()).isFalse(); } finally { final QueryTrackingPropertiesEntity properties = new QueryTrackingPropertiesEntity(); properties.setEnabled(true); @@ -685,7 +675,7 @@ public void changeQueryTrackingProperties() throws InterruptedException, Executi } @Test - public void queryWithBindVars() throws InterruptedException, ExecutionException { + void queryWithBindVars() throws InterruptedException, ExecutionException { try { db.createCollection(COLLECTION_NAME, null).get(); for (int i = 0; i < 10; i++) { @@ -698,9 +688,8 @@ public void queryWithBindVars() throws InterruptedException, ExecutionException bindVars.put("age", 25); db.query("FOR t IN @@coll FILTER t.age >= @age SORT t.age RETURN t._id", bindVars, null, String.class) .whenComplete((cursor, ex) -> { - assertThat(cursor, is(notNullValue())); for (int i = 0; i < 5; i++, cursor.next()) { - assertThat(cursor.hasNext(), is(true)); + assertThat(cursor.hasNext()).isEqualTo(true); } }) .get(); @@ -710,18 +699,17 @@ public void queryWithBindVars() throws InterruptedException, ExecutionException } @Test - public void queryWithWarning() throws InterruptedException, ExecutionException { + void queryWithWarning() throws InterruptedException, ExecutionException { arangoDB.db().query("return 1/0", null, null, String.class) .whenComplete((cursor, ex) -> { - assertThat(cursor, is(notNullValue())); - assertThat(cursor.getWarnings(), is(notNullValue())); - assertThat(cursor.getWarnings(), is(not(empty()))); + assertThat(cursor.getWarnings()).isNotNull(); + assertThat(cursor.getWarnings()).isNotEmpty(); }) .get(); } @Test - public void queryClose() throws IOException, InterruptedException, ExecutionException { + void queryClose() throws IOException, InterruptedException, ExecutionException { final ArangoCursorAsync cursor = arangoDB.db() .query("for i in 1..2 return i", null, new AqlQueryOptions().batchSize(1), String.class).get(); cursor.close(); @@ -731,68 +719,68 @@ public void queryClose() throws IOException, InterruptedException, ExecutionExce } fail(); } catch (final ArangoDBException e) { - assertThat(count, is(1)); + assertThat(count).isEqualTo(1); } } @Test - public void explainQuery() throws InterruptedException, ExecutionException { + void explainQuery() throws InterruptedException, ExecutionException { arangoDB.db().explainQuery("for i in 1..1 return i", null, null) .whenComplete((explain, ex) -> { - assertThat(explain, is(notNullValue())); - assertThat(explain.getPlan(), is(notNullValue())); - assertThat(explain.getPlans(), is(nullValue())); + assertThat(explain).isNotNull(); + assertThat(explain.getPlan()).isNotNull(); + assertThat(explain.getPlans()).isNull(); final ExecutionPlan plan = explain.getPlan(); - assertThat(plan.getCollections().size(), is(0)); - assertThat(plan.getEstimatedCost(), greaterThan(0)); - assertThat(plan.getEstimatedNrItems(), greaterThan(0)); - assertThat(plan.getVariables().size(), is(2)); - assertThat(plan.getNodes().size(), is(greaterThan(0))); + assertThat(plan.getCollections().size()).isEqualTo(0); + assertThat(plan.getEstimatedCost()).isGreaterThan(0); + assertThat(plan.getEstimatedNrItems()).isGreaterThan(0); + assertThat(plan.getVariables().size()).isEqualTo(2); + assertThat(plan.getNodes().size()).isGreaterThan(0); }) .get(); } @Test - public void parseQuery() throws InterruptedException, ExecutionException { + void parseQuery() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); arangoDB.db().parseQuery("for i in _apps return i") .whenComplete((parse, ex) -> { - assertThat(parse, is(notNullValue())); - assertThat(parse.getBindVars(), is(empty())); - assertThat(parse.getCollections().size(), is(1)); - assertThat(parse.getCollections().iterator().next(), is("_apps")); - assertThat(parse.getAst().size(), is(1)); + assertThat(parse).isNotNull(); + assertThat(parse.getBindVars()).isEmpty(); + assertThat(parse.getCollections().size()).isEqualTo(1); + assertThat(parse.getCollections().iterator().next()).isEqualTo("_apps"); + assertThat(parse.getAst().size()).isEqualTo(1); final AstNode root = parse.getAst().iterator().next(); - assertThat(root.getType(), is("root")); - assertThat(root.getName(), is(nullValue())); - assertThat(root.getSubNodes(), is(notNullValue())); - assertThat(root.getSubNodes().size(), is(2)); + assertThat(root.getType()).isEqualTo("root"); + assertThat(root.getName()).isNull(); + assertThat(root.getSubNodes()).isNotNull(); + assertThat(root.getSubNodes().size()).isEqualTo(2); final Iterator iterator = root.getSubNodes().iterator(); final AstNode for_ = iterator.next(); - assertThat(for_.getType(), is("for")); - assertThat(for_.getSubNodes(), is(notNullValue())); - assertThat(for_.getSubNodes().size(), is(3)); + assertThat(for_.getType()).isEqualTo("for"); + assertThat(for_.getSubNodes()).isNotNull(); + assertThat(for_.getSubNodes().size()).isEqualTo(3); final Iterator iterator2 = for_.getSubNodes().iterator(); final AstNode first = iterator2.next(); - assertThat(first.getType(), is("variable")); - assertThat(first.getName(), is("i")); + assertThat(first.getType()).isEqualTo("variable"); + assertThat(first.getName()).isEqualTo("i"); final AstNode second = iterator2.next(); - assertThat(second.getType(), is("collection")); - assertThat(second.getName(), is("_apps")); + assertThat(second.getType()).isEqualTo("collection"); + assertThat(second.getName()).isEqualTo("_apps"); final AstNode return_ = iterator.next(); - assertThat(return_.getType(), is("return")); - assertThat(return_.getSubNodes(), is(notNullValue())); - assertThat(return_.getSubNodes().size(), is(1)); - assertThat(return_.getSubNodes().iterator().next().getType(), is("reference")); - assertThat(return_.getSubNodes().iterator().next().getName(), is("i")); + assertThat(return_.getType()).isEqualTo("return"); + assertThat(return_.getSubNodes()).isNotNull(); + assertThat(return_.getSubNodes().size()).isEqualTo(1); + assertThat(return_.getSubNodes().iterator().next().getType()).isEqualTo("reference"); + assertThat(return_.getSubNodes().iterator().next().getName()).isEqualTo("i"); }) .get(); } @Test - @Ignore - public void getAndClearSlowQueries() throws InterruptedException, ExecutionException { + @Disabled + void getAndClearSlowQueries() throws InterruptedException, ExecutionException { final QueryTrackingPropertiesEntity properties = db.getQueryTrackingProperties().get(); final Long slowQueryThreshold = properties.getSlowQueryThreshold(); try { @@ -801,13 +789,13 @@ public void getAndClearSlowQueries() throws InterruptedException, ExecutionExcep db.query("return sleep(1.1)", null, null, Void.class); final Collection slowQueries = db.getSlowQueries().get(); - assertThat(slowQueries, is(notNullValue())); - assertThat(slowQueries.size(), is(1)); + assertThat(slowQueries).isNotNull(); + assertThat(slowQueries).hasSize(1); final QueryEntity queryEntity = slowQueries.iterator().next(); - assertThat(queryEntity.getQuery(), is("return sleep(1.1)")); + assertThat(queryEntity.getQuery()).isEqualTo("return sleep(1.1)"); db.clearSlowQueries().get(); - assertThat(db.getSlowQueries().get().size(), is(0)); + assertThat(db.getSlowQueries().get().size()).isZero(); } finally { properties.setSlowQueryThreshold(slowQueryThreshold); db.setQueryTrackingProperties(properties); @@ -815,34 +803,34 @@ public void getAndClearSlowQueries() throws InterruptedException, ExecutionExcep } @Test - public void createGetDeleteAqlFunction() throws InterruptedException, ExecutionException { + void createGetDeleteAqlFunction() throws InterruptedException, ExecutionException { final Collection aqlFunctionsInitial = db.getAqlFunctions(null).get(); - assertThat(aqlFunctionsInitial, is(empty())); + assertThat(aqlFunctionsInitial).isEmpty(); try { db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit", "function (celsius) { return celsius * 1.8 + 32; }", null).get(); final Collection aqlFunctions = db.getAqlFunctions(null).get(); - assertThat(aqlFunctions.size(), is(greaterThan(aqlFunctionsInitial.size()))); + assertThat(aqlFunctions).hasSizeGreaterThan(aqlFunctionsInitial.size()); } finally { final Integer deleteCount = db.deleteAqlFunction("myfunctions::temperature::celsiustofahrenheit", null) .get(); // compatibility with ArangoDB < 3.4 if (isAtLeastVersion(3, 4)) { - assertThat(deleteCount, is(1)); + assertThat(deleteCount).isEqualTo(1); } else { - assertThat(deleteCount, is(nullValue())); + assertThat(deleteCount).isNull(); } final Collection aqlFunctions = db.getAqlFunctions(null).get(); - assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size())); + assertThat(aqlFunctions).hasSameSizeAs(aqlFunctionsInitial); } } @Test - public void createGetDeleteAqlFunctionWithNamespace() throws InterruptedException, ExecutionException { + void createGetDeleteAqlFunctionWithNamespace() throws InterruptedException, ExecutionException { final Collection aqlFunctionsInitial = db.getAqlFunctions(null).get(); - assertThat(aqlFunctionsInitial, is(empty())); + assertThat(aqlFunctionsInitial).isEmpty(); try { db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit1", "function (celsius) { return celsius * 1.8 + 32; }", null).get(); @@ -853,17 +841,17 @@ public void createGetDeleteAqlFunctionWithNamespace() throws InterruptedExceptio db.deleteAqlFunction("myfunctions::temperature", new AqlFunctionDeleteOptions().group(true)).get(); final Collection aqlFunctions = db.getAqlFunctions(null).get(); - assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size())); + assertThat(aqlFunctions).hasSameSizeAs(aqlFunctionsInitial); } } @Test - public void createGraph() throws InterruptedException, ExecutionException { + void createGraph() throws InterruptedException, ExecutionException { try { db.createGraph(GRAPH_NAME, null, null) .whenComplete((result, ex) -> { - assertThat(result, is(notNullValue())); - assertThat(result.getName(), is(GRAPH_NAME)); + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo(GRAPH_NAME); }) .get(); } finally { @@ -872,13 +860,13 @@ public void createGraph() throws InterruptedException, ExecutionException { } @Test - public void getGraphs() throws InterruptedException, ExecutionException { + void getGraphs() throws InterruptedException, ExecutionException { try { db.createGraph(GRAPH_NAME, null, null).get(); db.getGraphs() .whenComplete((graphs, ex) -> { - assertThat(graphs, is(notNullValue())); - assertThat(graphs.size(), is(1)); + assertThat(graphs).isNotNull(); + assertThat(graphs.size()).isEqualTo(1); }) .get(); } finally { @@ -887,39 +875,39 @@ public void getGraphs() throws InterruptedException, ExecutionException { } @Test - public void transactionString() throws InterruptedException, ExecutionException { + void transactionString() throws InterruptedException, ExecutionException { final TransactionOptions options = new TransactionOptions().params("test"); db.transaction("function (params) {return params;}", String.class, options) - .whenComplete((result, ex) -> assertThat(result, is("test"))) + .whenComplete((result, ex) -> assertThat(result).isEqualTo("test")) .get(); } @Test - public void transactionNumber() throws InterruptedException, ExecutionException { + void transactionNumber() throws InterruptedException, ExecutionException { final TransactionOptions options = new TransactionOptions().params(5); db.transaction("function (params) {return params;}", Integer.class, options) - .whenComplete((result, ex) -> assertThat(result, is(5))) + .whenComplete((result, ex) -> assertThat(result).isEqualTo(5)) .get(); } @Test - public void transactionVPack() throws VPackException, InterruptedException, ExecutionException { + void transactionVPack() throws VPackException, InterruptedException, ExecutionException { final TransactionOptions options = new TransactionOptions().params(new VPackBuilder().add("test").slice()); db.transaction("function (params) {return params;}", VPackSlice.class, options) .whenComplete((result, ex) -> { - assertThat(result.isString(), is(true)); - assertThat(result.getAsString(), is("test")); + assertThat(result.isString()).isEqualTo(true); + assertThat(result.getAsString()).isEqualTo("test"); }) .get(); } @Test - public void transactionEmpty() throws InterruptedException, ExecutionException { + void transactionEmpty() throws InterruptedException, ExecutionException { db.transaction("function () {}", null, null).get(); } @Test - public void transactionallowImplicit() throws InterruptedException, ExecutionException { + void transactionallowImplicit() throws InterruptedException, ExecutionException { try { db.createCollection("someCollection", null).get(); db.createCollection("someOtherCollection", null).get(); @@ -933,7 +921,7 @@ public void transactionallowImplicit() throws InterruptedException, ExecutionExc db.transaction(action, VPackSlice.class, options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } finally { db.collection("someCollection").drop().get(); @@ -942,32 +930,32 @@ public void transactionallowImplicit() throws InterruptedException, ExecutionExc } @Test - public void transactionPojoReturn() throws ExecutionException, InterruptedException { + void transactionPojoReturn() throws ExecutionException, InterruptedException { final String action = "function() { return {'value':'hello world'}; }"; db.transaction(action, TransactionTestEntity.class, new TransactionOptions()) .whenComplete((res, ex) -> { - assertThat(res, is(notNullValue())); - assertThat(res.value, is("hello world")); + assertThat(res).isNotNull(); + assertThat(res.value).isEqualTo("hello world"); }) .get(); } @Test - public void getInfo() throws InterruptedException, ExecutionException { + void getInfo() throws InterruptedException, ExecutionException { final CompletableFuture f = db.getInfo(); - assertThat(f, is(notNullValue())); + assertThat(f).isNotNull(); f.whenComplete((info, ex) -> { - assertThat(info, is(notNullValue())); - assertThat(info.getId(), is(notNullValue())); - assertThat(info.getName(), is(TEST_DB)); - assertThat(info.getPath(), is(notNullValue())); - assertThat(info.getIsSystem(), is(false)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(TEST_DB.get()); + assertThat(info.getPath()).isNotNull(); + assertThat(info.getIsSystem()).isFalse(); try { if (isAtLeastVersion(3, 6) && isCluster()) { - assertThat(info.getSharding(), notNullValue()); - assertThat(info.getWriteConcern(), notNullValue()); - assertThat(info.getReplicationFactor(), notNullValue()); + assertThat(info.getSharding()).isNotNull(); + assertThat(info.getWriteConcern()).isNotNull(); + assertThat(info.getReplicationFactor()).isNotNull(); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); @@ -979,7 +967,7 @@ public void getInfo() throws InterruptedException, ExecutionException { } @Test - public void executeTraversal() throws InterruptedException, ExecutionException { + void executeTraversal() throws InterruptedException, ExecutionException { try { db.createCollection("person", null).get(); db.createCollection("knows", new CollectionCreateOptions().type(CollectionType.EDGES)).get(); @@ -1000,28 +988,28 @@ public void executeTraversal() throws InterruptedException, ExecutionException { .direction(Direction.outbound); db.executeTraversal(BaseDocument.class, BaseEdgeDocument.class, options) .whenComplete((traversal, ex) -> { - assertThat(traversal, is(notNullValue())); + assertThat(traversal).isNotNull(); final Collection vertices = traversal.getVertices(); - assertThat(vertices, is(notNullValue())); - assertThat(vertices.size(), is(4)); + assertThat(vertices).isNotNull(); + assertThat(vertices.size()).isEqualTo(4); final Iterator verticesIterator = vertices.iterator(); final Collection v = Arrays.asList("Alice", "Bob", "Charlie", "Dave"); - for (; verticesIterator.hasNext(); ) { - assertThat(v.contains(verticesIterator.next().getKey()), is(true)); + while (verticesIterator.hasNext()) { + assertThat(v.contains(verticesIterator.next().getKey())).isEqualTo(true); } final Collection> paths = traversal.getPaths(); - assertThat(paths, is(notNullValue())); - assertThat(paths.size(), is(4)); + assertThat(paths).isNotNull(); + assertThat(paths.size()).isEqualTo(4); - assertThat(paths.iterator().hasNext(), is(true)); + assertThat(paths.iterator().hasNext()).isEqualTo(true); final PathEntity first = paths.iterator().next(); - assertThat(first, is(notNullValue())); - assertThat(first.getEdges().size(), is(0)); - assertThat(first.getVertices().size(), is(1)); - assertThat(first.getVertices().iterator().next().getKey(), is("Alice")); + assertThat(first).isNotNull(); + assertThat(first.getEdges().size()).isEqualTo(0); + assertThat(first.getVertices().size()).isEqualTo(1); + assertThat(first.getVertices().iterator().next().getKey()).isEqualTo("Alice"); }) .get(); } finally { @@ -1031,7 +1019,7 @@ public void executeTraversal() throws InterruptedException, ExecutionException { } @Test - public void getDocument() throws InterruptedException, ExecutionException { + void getDocument() throws InterruptedException, ExecutionException { String collectionName = COLLECTION_NAME + "getDocument"; db.createCollection(collectionName).get(); final BaseDocument value = new BaseDocument(); @@ -1039,45 +1027,46 @@ public void getDocument() throws InterruptedException, ExecutionException { db.collection(collectionName).insertDocument(value).get(); db.getDocument(collectionName + "/123", BaseDocument.class) .whenComplete((document, ex) -> { - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is("123")); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo("123"); }) .get(); db.collection(collectionName).drop().get(); } @Test - public void shouldIncludeExceptionMessage() throws InterruptedException, ExecutionException { + void shouldIncludeExceptionMessage() throws InterruptedException, ExecutionException { final String exceptionMessage = "My error context"; final String action = "function (params) {" + "throw '" + exceptionMessage + "';" + "}"; try { db.transaction(action, VPackSlice.class, null).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); ArangoDBException cause = ((ArangoDBException) e.getCause()); - assertThat(cause.getErrorNum(), is(1650)); + assertThat(cause.getErrorNum()).isEqualTo(1650); if (isAtLeastVersion(3, 4)) { - assertThat(cause.getErrorMessage(), is(exceptionMessage)); + assertThat(cause.getErrorMessage()).isEqualTo(exceptionMessage); } } } - @Test(expected = ArangoDBException.class) - public void getDocumentWrongId() throws InterruptedException, ExecutionException { - db.getDocument("123", BaseDocument.class).get(); + @Test + void getDocumentWrongId() { + Throwable thrown = catchThrowable(() -> db.getDocument("123", BaseDocument.class).get()); + assertThat(thrown).isInstanceOf(ArangoDBException.class); } @Test - public void reloadRouting() throws InterruptedException, ExecutionException { + void reloadRouting() throws InterruptedException, ExecutionException { db.reloadRouting().get(); } @SuppressWarnings({"WeakerAccess", "unused"}) - protected static class TransactionTestEntity { + static class TransactionTestEntity { private String value; - public TransactionTestEntity() { + TransactionTestEntity() { super(); } } diff --git a/src/test/java/com/arangodb/async/ArangoEdgeCollectionTest.java b/src/test/java/com/arangodb/async/ArangoEdgeCollectionTest.java index 87a4034bd..4424451e9 100644 --- a/src/test/java/com/arangodb/async/ArangoEdgeCollectionTest.java +++ b/src/test/java/com/arangodb/async/ArangoEdgeCollectionTest.java @@ -23,29 +23,30 @@ import com.arangodb.ArangoDBException; import com.arangodb.entity.*; import com.arangodb.model.*; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.ExecutionException; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Mark Vollmary */ -public class ArangoEdgeCollectionTest extends BaseTest { +class ArangoEdgeCollectionTest extends BaseTest { private static final String GRAPH_NAME = "db_collection_test"; private static final String EDGE_COLLECTION_NAME = "db_edge_collection_test"; private static final String VERTEX_COLLECTION_NAME = "db_vertex_collection_test"; - @BeforeClass - public static void setup() throws InterruptedException, ExecutionException { + @BeforeAll + static void setup() throws InterruptedException, ExecutionException { if (!db.collection(VERTEX_COLLECTION_NAME).exists().get()) { db.createCollection(VERTEX_COLLECTION_NAME, null).get(); } @@ -58,8 +59,8 @@ public static void setup() throws InterruptedException, ExecutionException { db.createGraph(GRAPH_NAME, edgeDefinitions, null).get(); } - @After - public void teardown() throws InterruptedException, ExecutionException { + @AfterEach + void teardown() throws InterruptedException, ExecutionException { for (final String collection : new String[]{VERTEX_COLLECTION_NAME, EDGE_COLLECTION_NAME}) { db.collection(collection).truncate().get(); } @@ -78,39 +79,39 @@ private BaseEdgeDocument createEdgeValue() throws InterruptedException, Executio } @Test - public void insertEdge() throws InterruptedException, ExecutionException { + void insertEdge() throws InterruptedException, ExecutionException { final BaseEdgeDocument value = createEdgeValue(); final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); - assertThat(edge, is(notNullValue())); + assertThat(edge).isNotNull(); final BaseEdgeDocument document = db.collection(EDGE_COLLECTION_NAME) .getDocument(edge.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(edge.getKey()); } @Test - public void getEdge() throws InterruptedException, ExecutionException { + void getEdge() throws InterruptedException, ExecutionException { final BaseEdgeDocument value = createEdgeValue(); final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .getEdge(edge.getKey(), BaseDocument.class, null).get(); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(edge.getKey()); } @Test - public void getEdgeIfMatch() throws InterruptedException, ExecutionException { + void getEdgeIfMatch() throws InterruptedException, ExecutionException { final BaseEdgeDocument value = createEdgeValue(); final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch(edge.getRev()); final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .getEdge(edge.getKey(), BaseDocument.class, options).get(); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(edge.getKey()); } @Test - public void getEdgeIfMatchFail() throws InterruptedException, ExecutionException { + void getEdgeIfMatchFail() throws InterruptedException, ExecutionException { final BaseEdgeDocument value = createEdgeValue(); final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch("no").catchException(false); @@ -119,23 +120,23 @@ public void getEdgeIfMatchFail() throws InterruptedException, ExecutionException .getEdge(edge.getKey(), BaseEdgeDocument.class, options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void getEdgeIfNoneMatch() throws InterruptedException, ExecutionException { + void getEdgeIfNoneMatch() throws InterruptedException, ExecutionException { final BaseEdgeDocument value = createEdgeValue(); final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch("no"); final BaseDocument document = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .getEdge(edge.getKey(), BaseDocument.class, options).get(); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(edge.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(edge.getKey()); } @Test - public void getEdgeIfNoneMatchFail() throws InterruptedException, ExecutionException { + void getEdgeIfNoneMatchFail() throws InterruptedException, ExecutionException { final BaseEdgeDocument value = createEdgeValue(); final EdgeEntity edge = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(value, null).get(); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch(edge.getRev()).catchException(false); @@ -144,12 +145,12 @@ public void getEdgeIfNoneMatchFail() throws InterruptedException, ExecutionExcep .getEdge(edge.getKey(), BaseEdgeDocument.class, options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void replaceEdge() throws InterruptedException, ExecutionException { + void replaceEdge() throws InterruptedException, ExecutionException { final BaseEdgeDocument doc = createEdgeValue(); doc.addAttribute("a", "test"); final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) @@ -158,22 +159,22 @@ public void replaceEdge() throws InterruptedException, ExecutionException { doc.addAttribute("b", "test"); final EdgeUpdateEntity replaceResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .replaceEdge(createResult.getKey(), doc, null).get(); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } @Test - public void replaceEdgeIfMatch() throws InterruptedException, ExecutionException { + void replaceEdgeIfMatch() throws InterruptedException, ExecutionException { final BaseEdgeDocument doc = createEdgeValue(); doc.addAttribute("a", "test"); final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) @@ -183,22 +184,22 @@ public void replaceEdgeIfMatch() throws InterruptedException, ExecutionException final EdgeReplaceOptions options = new EdgeReplaceOptions().ifMatch(createResult.getRev()); final EdgeUpdateEntity replaceResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .replaceEdge(createResult.getKey(), doc, options).get(); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } @Test - public void replaceEdgeIfMatchFail() throws InterruptedException, ExecutionException { + void replaceEdgeIfMatchFail() throws InterruptedException, ExecutionException { final BaseEdgeDocument doc = createEdgeValue(); doc.addAttribute("a", "test"); final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) @@ -211,12 +212,12 @@ public void replaceEdgeIfMatchFail() throws InterruptedException, ExecutionExcep .get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void updateEdge() throws InterruptedException, ExecutionException { + void updateEdge() throws InterruptedException, ExecutionException { final BaseEdgeDocument doc = createEdgeValue(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -227,24 +228,24 @@ public void updateEdge() throws InterruptedException, ExecutionException { doc.updateAttribute("c", null); final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .updateEdge(createResult.getKey(), doc, null).get(); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); } @Test - public void updateEdgeIfMatch() throws InterruptedException, ExecutionException { + void updateEdgeIfMatch() throws InterruptedException, ExecutionException { final BaseEdgeDocument doc = createEdgeValue(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -256,24 +257,24 @@ public void updateEdgeIfMatch() throws InterruptedException, ExecutionException final EdgeUpdateOptions options = new EdgeUpdateOptions().ifMatch(createResult.getRev()); final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .updateEdge(createResult.getKey(), doc, options).get(); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); } @Test - public void updateEdgeIfMatchFail() throws InterruptedException, ExecutionException { + void updateEdgeIfMatchFail() throws InterruptedException, ExecutionException { final BaseEdgeDocument doc = createEdgeValue(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -288,12 +289,12 @@ public void updateEdgeIfMatchFail() throws InterruptedException, ExecutionExcept .get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void updateEdgeKeepNullTrue() throws InterruptedException, ExecutionException { + void updateEdgeKeepNullTrue() throws InterruptedException, ExecutionException { final BaseEdgeDocument doc = createEdgeValue(); doc.addAttribute("a", "test"); final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) @@ -302,20 +303,20 @@ public void updateEdgeKeepNullTrue() throws InterruptedException, ExecutionExcep final EdgeUpdateOptions options = new EdgeUpdateOptions().keepNull(true); final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .updateEdge(createResult.getKey(), doc, options).get(); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet().size(), is(1)); - assertThat(readResult.getProperties().keySet(), hasItem("a")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getProperties().keySet()).hasSize(1); + assertThat(readResult.getProperties()).containsKey("a"); } @Test - public void updateEdgeKeepNullFalse() throws InterruptedException, ExecutionException { + void updateEdgeKeepNullFalse() throws InterruptedException, ExecutionException { final BaseEdgeDocument doc = createEdgeValue(); doc.addAttribute("a", "test"); final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) @@ -324,21 +325,21 @@ public void updateEdgeKeepNullFalse() throws InterruptedException, ExecutionExce final EdgeUpdateOptions options = new EdgeUpdateOptions().keepNull(false); final EdgeUpdateEntity updateResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .updateEdge(createResult.getKey(), doc, options).get(); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseEdgeDocument readResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME) .getEdge(createResult.getKey(), BaseEdgeDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getRevision(), is(notNullValue())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getRevision()).isNotNull(); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); } @Test - public void deleteEdge() throws InterruptedException, ExecutionException { + void deleteEdge() throws InterruptedException, ExecutionException { final BaseEdgeDocument doc = createEdgeValue(); final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) .get(); @@ -348,12 +349,12 @@ public void deleteEdge() throws InterruptedException, ExecutionException { .getEdge(createResult.getKey(), BaseEdgeDocument.class, new GraphDocumentReadOptions().catchException(false)).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void deleteEdgeIfMatch() throws InterruptedException, ExecutionException { + void deleteEdgeIfMatch() throws InterruptedException, ExecutionException { final BaseEdgeDocument doc = createEdgeValue(); final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) .get(); @@ -364,12 +365,12 @@ public void deleteEdgeIfMatch() throws InterruptedException, ExecutionException .getEdge(createResult.getKey(), BaseEdgeDocument.class, new GraphDocumentReadOptions().catchException(false)).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void deleteEdgeIfMatchFail() throws InterruptedException, ExecutionException { + void deleteEdgeIfMatchFail() throws InterruptedException, ExecutionException { final BaseEdgeDocument doc = createEdgeValue(); final EdgeEntity createResult = db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).insertEdge(doc, null) .get(); @@ -378,7 +379,7 @@ public void deleteEdgeIfMatchFail() throws InterruptedException, ExecutionExcept db.graph(GRAPH_NAME).edgeCollection(EDGE_COLLECTION_NAME).deleteEdge(createResult.getKey(), options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } } diff --git a/src/test/java/com/arangodb/async/ArangoGraphTest.java b/src/test/java/com/arangodb/async/ArangoGraphTest.java index 7551b2931..19b91a03a 100644 --- a/src/test/java/com/arangodb/async/ArangoGraphTest.java +++ b/src/test/java/com/arangodb/async/ArangoGraphTest.java @@ -26,9 +26,9 @@ import com.arangodb.entity.ServerRole; import com.arangodb.model.GraphCreateOptions; import com.arangodb.model.VertexCollectionCreateOptions; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collection; @@ -36,15 +36,13 @@ import java.util.Iterator; import java.util.concurrent.ExecutionException; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Mark Vollmary */ -public class ArangoGraphTest extends BaseTest { +class ArangoGraphTest extends BaseTest { private static final String GRAPH_NAME = "db_collection_test"; private static final String EDGE_COL_1 = "db_edge1_collection_test"; @@ -57,8 +55,8 @@ public class ArangoGraphTest extends BaseTest { private static final Integer REPLICATION_FACTOR = 2; private static final Integer NUMBER_OF_SHARDS = 2; - @BeforeClass - public static void setup() throws InterruptedException, ExecutionException { + @BeforeAll + static void setup() throws InterruptedException, ExecutionException { if (db.graph(GRAPH_NAME).exists().get()) { db.graph(GRAPH_NAME).drop().get(); } @@ -73,8 +71,8 @@ public static void setup() throws InterruptedException, ExecutionException { db.createGraph(GRAPH_NAME, edgeDefinitions, options).get(); } - @After - public void teardown() throws InterruptedException, ExecutionException { + @AfterEach + void teardown() throws InterruptedException, ExecutionException { for (final String collection : new String[]{EDGE_COL_1, EDGE_COL_2, VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, VERTEX_COL_4}) { final ArangoCollectionAsync c = db.collection(collection); @@ -85,85 +83,85 @@ public void teardown() throws InterruptedException, ExecutionException { } @Test - public void create() throws InterruptedException, ExecutionException { + void create() throws InterruptedException, ExecutionException { try { final GraphEntity result = db.graph(GRAPH_NAME + "_1").create(null).get(); - assertThat(result, is(notNullValue())); - assertThat(result.getName(), is(GRAPH_NAME + "_1")); + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo(GRAPH_NAME + "_1"); } finally { db.graph(GRAPH_NAME + "_1").drop().get(); } } @Test - public void createWithReplicationAndMinReplicationFactor() throws ExecutionException, InterruptedException { + void createWithReplicationAndMinReplicationFactor() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isCluster()); final Collection edgeDefinitions = new ArrayList<>(); final GraphEntity graph = db.createGraph(GRAPH_NAME + "_1", edgeDefinitions, new GraphCreateOptions().isSmart(true).replicationFactor(2).minReplicationFactor(2)).get(); - assertThat(graph, is(notNullValue())); - assertThat(graph.getName(), is(GRAPH_NAME + "_1")); - assertThat(graph.getMinReplicationFactor(), is(2)); - assertThat(graph.getReplicationFactor(), is(2)); + assertThat(graph).isNotNull(); + assertThat(graph.getName()).isEqualTo(GRAPH_NAME + "_1"); + assertThat(graph.getMinReplicationFactor()).isEqualTo(2); + assertThat(graph.getReplicationFactor()).isEqualTo(2); db.graph(GRAPH_NAME + "_1").drop(); } @Test - public void getGraphs() throws InterruptedException, ExecutionException { + void getGraphs() throws InterruptedException, ExecutionException { final Collection graphs = db.getGraphs().get(); - assertThat(graphs, is(notNullValue())); - assertThat(graphs.size(), greaterThanOrEqualTo(1)); + assertThat(graphs).isNotNull(); + assertThat(graphs).isNotEmpty(); } @Test - public void getInfo() throws InterruptedException, ExecutionException { + void getInfo() throws InterruptedException, ExecutionException { final GraphEntity info = db.graph(GRAPH_NAME).getInfo().get(); - assertThat(info, is(notNullValue())); - assertThat(info.getName(), is(GRAPH_NAME)); - assertThat(info.getEdgeDefinitions().size(), is(2)); + assertThat(info).isNotNull(); + assertThat(info.getName()).isEqualTo(GRAPH_NAME); + assertThat(info.getEdgeDefinitions()).hasSize(2); final Iterator iterator = info.getEdgeDefinitions().iterator(); final EdgeDefinition e1 = iterator.next(); - assertThat(e1.getCollection(), is(EDGE_COL_1)); - assertThat(e1.getFrom(), hasItem(VERTEX_COL_1)); - assertThat(e1.getTo(), hasItem(VERTEX_COL_2)); + assertThat(e1.getCollection()).isEqualTo(EDGE_COL_1); + assertThat(e1.getFrom()).contains(VERTEX_COL_1); + assertThat(e1.getTo()).contains(VERTEX_COL_2); final EdgeDefinition e2 = iterator.next(); - assertThat(e2.getCollection(), is(EDGE_COL_2)); - assertThat(e2.getFrom(), hasItem(VERTEX_COL_2)); - assertThat(e2.getTo(), hasItems(VERTEX_COL_1, VERTEX_COL_3)); - assertThat(info.getOrphanCollections(), is(empty())); + assertThat(e2.getCollection()).isEqualTo(EDGE_COL_2); + assertThat(e2.getFrom()).contains(VERTEX_COL_2); + assertThat(e2.getTo()).contains(VERTEX_COL_1, VERTEX_COL_3); + assertThat(info.getOrphanCollections()).isEmpty(); if (isCluster()) { for (final String collection : new String[]{VERTEX_COL_1, VERTEX_COL_2}) { final CollectionPropertiesEntity properties = db.collection(collection).getProperties().get(); - assertThat(properties.getReplicationFactor(), is(REPLICATION_FACTOR)); - assertThat(properties.getNumberOfShards(), is(NUMBER_OF_SHARDS)); + assertThat(properties.getReplicationFactor()).isEqualTo(REPLICATION_FACTOR); + assertThat(properties.getNumberOfShards()).isEqualTo(NUMBER_OF_SHARDS); } for (final String collection : new String[]{EDGE_COL_1, EDGE_COL_2}) { final CollectionPropertiesEntity properties = db.collection(collection).getProperties().get(); - assertThat(properties.getReplicationFactor(), is(REPLICATION_FACTOR)); + assertThat(properties.getReplicationFactor()).isEqualTo(REPLICATION_FACTOR); } } } @Test - public void getVertexCollections() throws InterruptedException, ExecutionException { + void getVertexCollections() throws InterruptedException, ExecutionException { final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections().get(); - assertThat(vertexCollections, is(notNullValue())); - assertThat(vertexCollections.size(), is(3)); - assertThat(vertexCollections, hasItems(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3)); + assertThat(vertexCollections).isNotNull(); + assertThat(vertexCollections).hasSize(3); + assertThat(vertexCollections).contains(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3); } @Test - public void addVertexCollection() throws InterruptedException, ExecutionException { + void addVertexCollection() throws InterruptedException, ExecutionException { final GraphEntity graph = db.graph(GRAPH_NAME).addVertexCollection(VERTEX_COL_4).get(); - assertThat(graph, is(notNullValue())); + assertThat(graph).isNotNull(); final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections().get(); - assertThat(vertexCollections, hasItems(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, VERTEX_COL_4)); + assertThat(vertexCollections).contains(VERTEX_COL_1, VERTEX_COL_2, VERTEX_COL_3, VERTEX_COL_4); setup(); } @Test - public void addSatelliteVertexCollection() throws ExecutionException, InterruptedException { + void addSatelliteVertexCollection() throws ExecutionException, InterruptedException { assumeTrue(isCluster()); assumeTrue(isEnterprise()); assumeTrue(isAtLeastVersion(3, 9)); @@ -175,52 +173,52 @@ public void addSatelliteVertexCollection() throws ExecutionException, Interrupte g.addVertexCollection(v1Name, new VertexCollectionCreateOptions().satellites(v1Name)).get(); Collection vertexCollections = g.getVertexCollections().get(); - assertThat(vertexCollections, hasItems(v1Name)); - assertThat(db.collection(v1Name).getProperties().get().getSatellite(), is(true)); + assertThat(vertexCollections).contains(v1Name); + assertThat(db.collection(v1Name).getProperties().get().getSatellite()).isTrue(); // revert g.drop().get(); } @Test - public void getEdgeCollections() throws InterruptedException, ExecutionException { + void getEdgeCollections() throws InterruptedException, ExecutionException { final Collection edgeCollections = db.graph(GRAPH_NAME).getEdgeDefinitions().get(); - assertThat(edgeCollections, is(notNullValue())); - assertThat(edgeCollections.size(), is(2)); - assertThat(edgeCollections, hasItems(EDGE_COL_1, EDGE_COL_2)); + assertThat(edgeCollections).isNotNull(); + assertThat(edgeCollections).hasSize(2); + assertThat(edgeCollections).contains(EDGE_COL_1, EDGE_COL_2); } @Test - public void addEdgeDefinition() throws InterruptedException, ExecutionException { + void addEdgeDefinition() throws InterruptedException, ExecutionException { final GraphEntity graph = db.graph(GRAPH_NAME) .addEdgeDefinition(new EdgeDefinition().collection(EDGE_COL_3).from(VERTEX_COL_1).to(VERTEX_COL_2)) .get(); - assertThat(graph, is(notNullValue())); + assertThat(graph).isNotNull(); final Collection edgeDefinitions = graph.getEdgeDefinitions(); - assertThat(edgeDefinitions.size(), is(3)); + assertThat(edgeDefinitions).hasSize(3); int count = 0; for (final EdgeDefinition e : edgeDefinitions) { if (e.getCollection().equals(EDGE_COL_3)) { count++; } } - assertThat(count, is(1)); + assertThat(count).isEqualTo(1); for (final EdgeDefinition e : edgeDefinitions) { if (e.getCollection().equals(EDGE_COL_3)) { - assertThat(e.getFrom(), hasItem(VERTEX_COL_1)); - assertThat(e.getTo(), hasItem(VERTEX_COL_2)); + assertThat(e.getFrom()).contains(VERTEX_COL_1); + assertThat(e.getTo()).contains(VERTEX_COL_2); } } if (isCluster()) { final CollectionPropertiesEntity properties = db.collection(EDGE_COL_3).getProperties().get(); - assertThat(properties.getReplicationFactor(), is(REPLICATION_FACTOR)); - assertThat(properties.getNumberOfShards(), is(NUMBER_OF_SHARDS)); + assertThat(properties.getReplicationFactor()).isEqualTo(REPLICATION_FACTOR); + assertThat(properties.getNumberOfShards()).isEqualTo(NUMBER_OF_SHARDS); } setup(); } @Test - public void addSatelliteEdgeDefinition() throws ExecutionException, InterruptedException { + void addSatelliteEdgeDefinition() throws ExecutionException, InterruptedException { assumeTrue(isCluster()); assumeTrue(isEnterprise()); assumeTrue(isAtLeastVersion(3, 9)); @@ -234,54 +232,54 @@ public void addSatelliteEdgeDefinition() throws ExecutionException, InterruptedE g.createGraph(Collections.emptyList(), new GraphCreateOptions().isSmart(true).smartGraphAttribute("test")).get(); g.addEdgeDefinition(ed).get(); final GraphEntity ge = g.getInfo().get(); - assertThat(ge, is(notNullValue())); + assertThat(ge).isNotNull(); final Collection edgeDefinitions = ge.getEdgeDefinitions(); - assertThat(edgeDefinitions.size(), is(1)); + assertThat(edgeDefinitions).hasSize(1); EdgeDefinition e = edgeDefinitions.iterator().next(); - assertThat(e.getCollection(), is(eName)); - assertThat(e.getFrom(), hasItem(v1Name)); - assertThat(e.getTo(), hasItem(v2Name)); + assertThat(e.getCollection()).isEqualTo(eName); + assertThat(e.getFrom()).contains(v1Name); + assertThat(e.getTo()).contains(v2Name); - assertThat(db.collection(v1Name).getProperties().get().getSatellite(), is(true)); + assertThat(db.collection(v1Name).getProperties().get().getSatellite()).isTrue(); // revert g.drop().get(); } @Test - public void replaceEdgeDefinition() throws InterruptedException, ExecutionException { + void replaceEdgeDefinition() throws InterruptedException, ExecutionException { final GraphEntity graph = db.graph(GRAPH_NAME) .replaceEdgeDefinition(new EdgeDefinition().collection(EDGE_COL_1).from(VERTEX_COL_3).to(VERTEX_COL_4)) .get(); final Collection edgeDefinitions = graph.getEdgeDefinitions(); - assertThat(edgeDefinitions.size(), is(2)); + assertThat(edgeDefinitions).hasSize(2); int count = 0; for (final EdgeDefinition e : edgeDefinitions) { if (e.getCollection().equals(EDGE_COL_1)) { count++; } } - assertThat(count, is(1)); + assertThat(count).isEqualTo(1); for (final EdgeDefinition e : edgeDefinitions) { if (e.getCollection().equals(EDGE_COL_1)) { - assertThat(e.getFrom(), hasItem(VERTEX_COL_3)); - assertThat(e.getTo(), hasItem(VERTEX_COL_4)); + assertThat(e.getFrom()).contains(VERTEX_COL_3); + assertThat(e.getTo()).contains(VERTEX_COL_4); } } setup(); } @Test - public void removeEdgeDefinition() throws InterruptedException, ExecutionException { + void removeEdgeDefinition() throws InterruptedException, ExecutionException { final GraphEntity graph = db.graph(GRAPH_NAME).removeEdgeDefinition(EDGE_COL_1).get(); final Collection edgeDefinitions = graph.getEdgeDefinitions(); - assertThat(edgeDefinitions.size(), is(1)); - assertThat(edgeDefinitions.iterator().next().getCollection(), is(EDGE_COL_2)); + assertThat(edgeDefinitions).hasSize(1); + assertThat(edgeDefinitions.iterator().next().getCollection()).isEqualTo(EDGE_COL_2); setup(); } @Test - public void smartGraph() throws InterruptedException, ExecutionException { + void smartGraph() throws InterruptedException, ExecutionException { assumeTrue(isCluster()); assumeTrue(isEnterprise()); for (final String collection : new String[]{EDGE_COL_1, EDGE_COL_2, VERTEX_COL_1, VERTEX_COL_2, @@ -298,17 +296,17 @@ public void smartGraph() throws InterruptedException, ExecutionException { new GraphCreateOptions().isSmart(true).smartGraphAttribute("test").replicationFactor(REPLICATION_FACTOR) .numberOfShards(NUMBER_OF_SHARDS)) .get(); - assertThat(graph, is(notNullValue())); - assertThat(graph.getIsSmart(), is(true)); - assertThat(graph.getSmartGraphAttribute(), is("test")); - assertThat(graph.getNumberOfShards(), is(2)); + assertThat(graph).isNotNull(); + assertThat(graph.getIsSmart()).isTrue(); + assertThat(graph.getSmartGraphAttribute()).isEqualTo("test"); + assertThat(graph.getNumberOfShards()).isEqualTo(2); if (db.graph(GRAPH_NAME + "_smart").exists().get()) { db.graph(GRAPH_NAME + "_smart").drop().get(); } } @Test - public void hybridSmartGraph() throws ExecutionException, InterruptedException { + void hybridSmartGraph() throws ExecutionException, InterruptedException { assumeTrue(isEnterprise()); assumeTrue(isCluster()); assumeTrue((isAtLeastVersion(3, 9))); @@ -324,18 +322,18 @@ public void hybridSmartGraph() throws ExecutionException, InterruptedException { .satellites(eName, v1Name) .isSmart(true).smartGraphAttribute("test").replicationFactor(2).numberOfShards(2)).get(); - assertThat(g, is(notNullValue())); - assertThat(g.getIsSmart(), is(true)); - assertThat(g.getSmartGraphAttribute(), is("test")); - assertThat(g.getNumberOfShards(), is(2)); + assertThat(g).isNotNull(); + assertThat(g.getIsSmart()).isTrue(); + assertThat(g.getSmartGraphAttribute()).isEqualTo("test"); + assertThat(g.getNumberOfShards()).isEqualTo(2); - assertThat(db.collection(eName).getProperties().get().getSatellite(), is(true)); - assertThat(db.collection(v1Name).getProperties().get().getSatellite(), is(true)); - assertThat(db.collection(v2Name).getProperties().get().getReplicationFactor(), is(2)); + assertThat(db.collection(eName).getProperties().get().getSatellite()).isTrue(); + assertThat(db.collection(v1Name).getProperties().get().getSatellite()).isTrue(); + assertThat(db.collection(v2Name).getProperties().get().getReplicationFactor()).isEqualTo(2); } @Test - public void hybridDisjointSmartGraph() throws ExecutionException, InterruptedException { + void hybridDisjointSmartGraph() throws ExecutionException, InterruptedException { assumeTrue(isEnterprise()); assumeTrue(isCluster()); assumeTrue((isAtLeastVersion(3, 9))); @@ -351,41 +349,41 @@ public void hybridDisjointSmartGraph() throws ExecutionException, InterruptedExc .satellites(v1Name) .isSmart(true).isDisjoint(true).smartGraphAttribute("test").replicationFactor(2).numberOfShards(2)).get(); - assertThat(g, is(notNullValue())); - assertThat(g.getIsSmart(), is(true)); - assertThat(g.getIsDisjoint(), is(true)); - assertThat(g.getSmartGraphAttribute(), is("test")); - assertThat(g.getNumberOfShards(), is(2)); + assertThat(g).isNotNull(); + assertThat(g.getIsSmart()).isTrue(); + assertThat(g.getIsDisjoint()).isTrue(); + assertThat(g.getSmartGraphAttribute()).isEqualTo("test"); + assertThat(g.getNumberOfShards()).isEqualTo(2); - assertThat(db.collection(v1Name).getProperties().get().getSatellite(), is(true)); - assertThat(db.collection(v2Name).getProperties().get().getReplicationFactor(), is(2)); + assertThat(db.collection(v1Name).getProperties().get().getSatellite()).isTrue(); + assertThat(db.collection(v2Name).getProperties().get().getReplicationFactor()).isEqualTo(2); } @Test - public void drop() throws InterruptedException, ExecutionException { + void drop() throws InterruptedException, ExecutionException { final String edgeCollection = "edge_drop"; final String vertexCollection = "vertex_drop"; final String graph = GRAPH_NAME + "_drop"; final GraphEntity result = db.graph(graph).create(Collections .singleton(new EdgeDefinition().collection(edgeCollection).from(vertexCollection).to(vertexCollection))) .get(); - assertThat(result, is(notNullValue())); + assertThat(result).isNotNull(); db.graph(graph).drop().get(); - assertThat(db.collection(edgeCollection).exists().get(), is(true)); - assertThat(db.collection(vertexCollection).exists().get(), is(true)); + assertThat(db.collection(edgeCollection).exists().get()).isTrue(); + assertThat(db.collection(vertexCollection).exists().get()).isTrue(); } @Test - public void dropPlusDropCollections() throws InterruptedException, ExecutionException { + void dropPlusDropCollections() throws InterruptedException, ExecutionException { final String edgeCollection = "edge_dropC"; final String vertexCollection = "vertex_dropC"; final String graph = GRAPH_NAME + "_dropC"; final GraphEntity result = db.graph(graph).create(Collections .singleton(new EdgeDefinition().collection(edgeCollection).from(vertexCollection).to(vertexCollection))) .get(); - assertThat(result, is(notNullValue())); + assertThat(result).isNotNull(); db.graph(graph).drop(true).get(); - assertThat(db.collection(edgeCollection).exists().get(), is(false)); - assertThat(db.collection(vertexCollection).exists().get(), is(false)); + assertThat(db.collection(edgeCollection).exists().get()).isFalse(); + assertThat(db.collection(vertexCollection).exists().get()).isFalse(); } } diff --git a/src/test/java/com/arangodb/async/ArangoRouteTest.java b/src/test/java/com/arangodb/async/ArangoRouteTest.java index ecb026d7e..d01b3ad11 100644 --- a/src/test/java/com/arangodb/async/ArangoRouteTest.java +++ b/src/test/java/com/arangodb/async/ArangoRouteTest.java @@ -23,29 +23,30 @@ import com.arangodb.ArangoDBException; import com.arangodb.entity.BaseDocument; import com.arangodb.internal.ArangoRequestParam; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.util.concurrent.ExecutionException; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Mark Vollmary */ -public class ArangoRouteTest extends BaseTest { +class ArangoRouteTest extends BaseTest { /* @Test - public void get() throws InterruptedException, ExecutionException { + void get() throws InterruptedException, ExecutionException { final Response res = db.route("/_api/version").get().get(); - assertThat(res.getBody().get("version").isString(), is(true)); + assertThat(res.getBody().get("version").isString()).isEqualTo(true); }*/ /* @Test - public void withHeader() throws InterruptedException, ExecutionException { + void withHeader() throws InterruptedException, ExecutionException { final ArangoCollectionAsync collection = db.collection("route-test-col"); try { collection.create(); @@ -55,7 +56,7 @@ public void withHeader() throws InterruptedException, ExecutionException { .get().get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause() instanceof ArangoDBException, is(true)); + assertThat(e.getCause() instanceof ArangoDBException).isEqualTo(true); } finally { collection.drop(); } @@ -63,7 +64,7 @@ public void withHeader() throws InterruptedException, ExecutionException { */ @Test - public void withParentHeader() throws InterruptedException, ExecutionException { + void withParentHeader() throws InterruptedException, ExecutionException { final ArangoCollectionAsync collection = db.collection("route-test-col"); try { collection.create().get(); @@ -73,7 +74,7 @@ public void withParentHeader() throws InterruptedException, ExecutionException { .route(doc.getId()).get().get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } collection.drop().get(); } diff --git a/src/test/java/com/arangodb/async/ArangoSearchTest.java b/src/test/java/com/arangodb/async/ArangoSearchTest.java index fd9ad387d..47c183b54 100644 --- a/src/test/java/com/arangodb/async/ArangoSearchTest.java +++ b/src/test/java/com/arangodb/async/ArangoSearchTest.java @@ -28,96 +28,95 @@ import com.arangodb.model.arangosearch.AnalyzerDeleteOptions; import com.arangodb.model.arangosearch.ArangoSearchCreateOptions; import com.arangodb.model.arangosearch.ArangoSearchPropertiesOptions; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.*; import java.util.concurrent.ExecutionException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Mark Vollmary */ -public class ArangoSearchTest extends BaseTest { +class ArangoSearchTest extends BaseTest { private static final String VIEW_NAME = "view_test"; - @BeforeClass - public static void setup() throws InterruptedException, ExecutionException { + @BeforeAll + static void setup() throws InterruptedException, ExecutionException { if (!isAtLeastVersion(arangoDB, 3, 4)) return; db.createArangoSearch(VIEW_NAME, new ArangoSearchCreateOptions()).get(); } @Test - public void exists() throws InterruptedException, ExecutionException { + void exists() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); - assertThat(db.arangoSearch(VIEW_NAME).exists().get(), is(true)); + assertThat(db.arangoSearch(VIEW_NAME).exists().get()).isTrue(); } @Test - public void getInfo() throws InterruptedException, ExecutionException { + void getInfo() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); final ViewEntity info = db.arangoSearch(VIEW_NAME).getInfo().get(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(VIEW_NAME)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(VIEW_NAME); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); } @Test - public void drop() throws InterruptedException, ExecutionException { + void drop() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); final String name = VIEW_NAME + "_droptest"; db.createArangoSearch(name, new ArangoSearchCreateOptions()).get(); final ArangoViewAsync view = db.arangoSearch(name); view.drop().get(); - assertThat(view.exists().get(), is(false)); + assertThat(view.exists().get()).isFalse(); } @Test - public void rename() throws InterruptedException, ExecutionException { + void rename() throws InterruptedException, ExecutionException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 4)); final String name = VIEW_NAME + "_renametest"; final String newName = name + "_new"; db.createArangoSearch(name, new ArangoSearchCreateOptions()).get(); db.arangoSearch(name).rename(newName).get(); - assertThat(db.arangoSearch(name).exists().get(), is(false)); - assertThat(db.arangoSearch(newName).exists().get(), is(true)); + assertThat(db.arangoSearch(name).exists().get()).isFalse(); + assertThat(db.arangoSearch(newName).exists().get()).isTrue(); } @Test - public void create() throws InterruptedException, ExecutionException { + void create() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); final String name = VIEW_NAME + "_createtest"; final ViewEntity info = db.arangoSearch(name).create().get(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(name)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(name).exists().get(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(name); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); + assertThat(db.arangoSearch(name).exists().get()).isTrue(); } @Test - public void createWithOptions() throws InterruptedException, ExecutionException { + void createWithOptions() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); final String name = VIEW_NAME + "_createtest_withotpions"; final ViewEntity info = db.arangoSearch(name).create(new ArangoSearchCreateOptions()).get(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(name)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(name).exists().get(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(name); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); + assertThat(db.arangoSearch(name).exists().get()).isTrue(); } @Test - public void createWithPrimarySort() throws ExecutionException, InterruptedException { + void createWithPrimarySort() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); final String name = "createWithPrimarySort"; final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); @@ -128,54 +127,54 @@ public void createWithPrimarySort() throws ExecutionException, InterruptedExcept options.consolidationIntervalMsec(666666L); final ViewEntity info = db.arangoSearch(name).create(options).get(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(name)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(name).exists().get(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(name); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); + assertThat(db.arangoSearch(name).exists().get()).isTrue(); } @Test - public void createWithCommitIntervalMsec() throws ExecutionException, InterruptedException { + void createWithCommitIntervalMsec() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); final String name = "createWithCommitIntervalMsec"; final ArangoSearchCreateOptions options = new ArangoSearchCreateOptions(); options.commitIntervalMsec(666666L); final ViewEntity info = db.arangoSearch(name).create(options).get(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(name)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(db.arangoSearch(name).exists().get(), is(true)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(name); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); + assertThat(db.arangoSearch(name).exists().get()).isTrue(); // check commit interval msec property final ArangoSearchAsync view = db.arangoSearch(name); final ArangoSearchPropertiesEntity properties = view.getProperties().get(); - assertThat(properties.getCommitIntervalMsec(), is(666666L)); + assertThat(properties.getCommitIntervalMsec()).isEqualTo(666666L); } @Test - public void getProperties() throws InterruptedException, ExecutionException { + void getProperties() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); final String name = VIEW_NAME + "_getpropertiestest"; final ArangoSearchAsync view = db.arangoSearch(name); view.create(new ArangoSearchCreateOptions()).get(); final ArangoSearchPropertiesEntity properties = view.getProperties().get(); - assertThat(properties, is(not(nullValue()))); - assertThat(properties.getId(), is(not(nullValue()))); - assertThat(properties.getName(), is(name)); - assertThat(properties.getType(), is(ViewType.ARANGO_SEARCH)); - assertThat(properties.getConsolidationIntervalMsec(), is(not(nullValue()))); - assertThat(properties.getCleanupIntervalStep(), is(not(nullValue()))); + assertThat(properties).isNotNull(); + assertThat(properties.getId()).isNotNull(); + assertThat(properties.getName()).isEqualTo(name); + assertThat(properties.getType()).isEqualTo(ViewType.ARANGO_SEARCH); + assertThat(properties.getConsolidationIntervalMsec()).isNotNull(); + assertThat(properties.getCleanupIntervalStep()).isNotNull(); final ConsolidationPolicy consolidate = properties.getConsolidationPolicy(); - assertThat(consolidate, is(is(not(nullValue())))); + assertThat(consolidate).isNotNull(); final Collection links = properties.getLinks(); - assertThat(links.isEmpty(), is(true)); + assertThat(links).isEmpty(); } @Test - public void updateProperties() throws InterruptedException, ExecutionException { + void updateProperties() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); db.createCollection("view_update_prop_test_collection").get(); final String name = VIEW_NAME + "_updatepropertiestest"; @@ -189,26 +188,26 @@ public void updateProperties() throws InterruptedException, ExecutionException { CollectionLink.on("view_update_prop_test_collection").fields(FieldLink.on("value").analyzers("identity") .trackListPositions(true).includeAllFields(true).storeValues(StoreValuesType.ID))); final ArangoSearchPropertiesEntity properties = view.updateProperties(options).get(); - assertThat(properties, is(not(nullValue()))); - assertThat(properties.getCleanupIntervalStep(), is(15L)); - assertThat(properties.getConsolidationIntervalMsec(), is(65000L)); + assertThat(properties).isNotNull(); + assertThat(properties.getCleanupIntervalStep()).isEqualTo(15L); + assertThat(properties.getConsolidationIntervalMsec()).isEqualTo(65000L); final ConsolidationPolicy consolidate = properties.getConsolidationPolicy(); - assertThat(consolidate, is(not(nullValue()))); - assertThat(consolidate.getType(), is(ConsolidationType.BYTES_ACCUM)); - assertThat(consolidate.getThreshold(), is(1.)); - assertThat(properties.getLinks().size(), is(1)); + assertThat(consolidate).isNotNull(); + assertThat(consolidate.getType()).isEqualTo(ConsolidationType.BYTES_ACCUM); + assertThat(consolidate.getThreshold()).isEqualTo(1.); + assertThat(properties.getLinks()).hasSize(1); final CollectionLink link = properties.getLinks().iterator().next(); - assertThat(link.getName(), is("view_update_prop_test_collection")); - assertThat(link.getFields().size(), is(1)); + assertThat(link.getName()).isEqualTo("view_update_prop_test_collection"); + assertThat(link.getFields()).hasSize(1); final FieldLink next = link.getFields().iterator().next(); - assertThat(next.getName(), is("value")); - assertThat(next.getIncludeAllFields(), is(true)); - assertThat(next.getTrackListPositions(), is(true)); - assertThat(next.getStoreValues(), is(StoreValuesType.ID)); + assertThat(next.getName()).isEqualTo("value"); + assertThat(next.getIncludeAllFields()).isTrue(); + assertThat(next.getTrackListPositions()).isTrue(); + assertThat(next.getStoreValues()).isEqualTo(StoreValuesType.ID); } @Test - public void replaceProperties() throws InterruptedException, ExecutionException { + void replaceProperties() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); db.createCollection("view_replace_prop_test_collection").get(); final String name = VIEW_NAME + "_replacepropertiestest"; @@ -218,12 +217,12 @@ public void replaceProperties() throws InterruptedException, ExecutionException options.link( CollectionLink.on("view_replace_prop_test_collection").fields(FieldLink.on("value").analyzers("identity"))); final ArangoSearchPropertiesEntity properties = view.replaceProperties(options).get(); - assertThat(properties, is(not(nullValue()))); - assertThat(properties.getLinks().size(), is(1)); + assertThat(properties).isNotNull(); + assertThat(properties.getLinks()).hasSize(1); final CollectionLink link = properties.getLinks().iterator().next(); - assertThat(link.getName(), is("view_replace_prop_test_collection")); - assertThat(link.getFields().size(), is(1)); - assertThat(link.getFields().iterator().next().getName(), is("value")); + assertThat(link.getName()).isEqualTo("view_replace_prop_test_collection"); + assertThat(link.getFields()).hasSize(1); + assertThat(link.getFields().iterator().next().getName()).isEqualTo("value"); } private void createGetAndDeleteTypedAnalyzer(SearchAnalyzer analyzer) throws ExecutionException, InterruptedException { @@ -233,17 +232,17 @@ private void createGetAndDeleteTypedAnalyzer(SearchAnalyzer analyzer) throws Exe // createAnalyzer SearchAnalyzer createdAnalyzer = db.createSearchAnalyzer(analyzer).get(); - assertThat(createdAnalyzer, is(analyzer)); + assertThat(createdAnalyzer).isEqualTo(analyzer); // getAnalyzer SearchAnalyzer gotAnalyzer = db.getSearchAnalyzer(analyzer.getName()).get(); - assertThat(gotAnalyzer, is(analyzer)); + assertThat(gotAnalyzer).isEqualTo(analyzer); // getAnalyzers @SuppressWarnings("OptionalGetWithoutIsPresent") SearchAnalyzer foundAnalyzer = db.getSearchAnalyzers().get().stream().filter(it -> it.getName().equals(fullyQualifiedName)) .findFirst().get(); - assertThat(foundAnalyzer, is(analyzer)); + assertThat(foundAnalyzer).isEqualTo(analyzer); // deleteAnalyzer AnalyzerDeleteOptions deleteOptions = new AnalyzerDeleteOptions(); @@ -255,9 +254,9 @@ private void createGetAndDeleteTypedAnalyzer(SearchAnalyzer analyzer) throws Exe db.getAnalyzer(analyzer.getName()).get(); fail("deleted analyzer should not be found!"); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); - assertThat(((ArangoDBException) e.getCause()).getResponseCode(), is(404)); - assertThat(((ArangoDBException) e.getCause()).getErrorNum(), is(1202)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); + assertThat(((ArangoDBException) e.getCause()).getResponseCode()).isEqualTo(404); + assertThat(((ArangoDBException) e.getCause()).getErrorNum()).isEqualTo(1202); } } @@ -269,16 +268,16 @@ private void createGetAndDeleteAnalyzer(AnalyzerEntity options) throws Execution // createAnalyzer AnalyzerEntity createdAnalyzer = db.createAnalyzer(options).get(); - assertThat(createdAnalyzer.getName(), is(fullyQualifiedName)); - assertThat(createdAnalyzer.getType(), is(options.getType())); - assertThat(createdAnalyzer.getFeatures(), is(options.getFeatures())); + assertThat(createdAnalyzer.getName()).isEqualTo(fullyQualifiedName); + assertThat(createdAnalyzer.getType()).isEqualTo(options.getType()); + assertThat(createdAnalyzer.getFeatures()).isEqualTo(options.getFeatures()); compareProperties(createdAnalyzer.getProperties(), options.getProperties()); // getAnalyzer AnalyzerEntity gotAnalyzer = db.getAnalyzer(options.getName()).get(); - assertThat(gotAnalyzer.getName(), is(fullyQualifiedName)); - assertThat(gotAnalyzer.getType(), is(options.getType())); - assertThat(gotAnalyzer.getFeatures(), is(options.getFeatures())); + assertThat(gotAnalyzer.getName()).isEqualTo(fullyQualifiedName); + assertThat(gotAnalyzer.getType()).isEqualTo(options.getType()); + assertThat(gotAnalyzer.getFeatures()).isEqualTo(options.getFeatures()); compareProperties(gotAnalyzer.getProperties(), options.getProperties()); // getAnalyzers @@ -286,9 +285,9 @@ private void createGetAndDeleteAnalyzer(AnalyzerEntity options) throws Execution AnalyzerEntity foundAnalyzer = db.getAnalyzers().get().stream().filter(it -> it.getName().equals(fullyQualifiedName)) .findFirst().get(); - assertThat(foundAnalyzer.getName(), is(fullyQualifiedName)); - assertThat(foundAnalyzer.getType(), is(options.getType())); - assertThat(foundAnalyzer.getFeatures(), is(options.getFeatures())); + assertThat(foundAnalyzer.getName()).isEqualTo(fullyQualifiedName); + assertThat(foundAnalyzer.getType()).isEqualTo(options.getType()); + assertThat(foundAnalyzer.getFeatures()).isEqualTo(options.getFeatures()); compareProperties(foundAnalyzer.getProperties(), options.getProperties()); AnalyzerDeleteOptions deleteOptions = new AnalyzerDeleteOptions(); @@ -301,8 +300,8 @@ private void createGetAndDeleteAnalyzer(AnalyzerEntity options) throws Execution db.getAnalyzer(options.getName()).get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); - assertThat(((ArangoDBException) e.getCause()).getResponseCode(), is(404)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); + assertThat(((ArangoDBException) e.getCause()).getResponseCode()).isEqualTo(404); } } @@ -310,21 +309,21 @@ private void compareProperties(Map actualProperties, Map { Object actualValue = actualProperties.get(key); if (expectedValue instanceof Map) { - assertThat(actualValue, notNullValue()); - assertThat(actualValue, instanceOf(Map.class)); + assertThat(actualValue).isNotNull(); + assertThat(actualValue).isInstanceOf(Map.class); compareProperties((Map) actualValue, (Map) expectedValue); } else if (expectedValue instanceof Number) { - assertThat(Double.valueOf(actualValue.toString()), is(Double.valueOf(expectedValue.toString()))); + assertThat(Double.valueOf(actualValue.toString())).isEqualTo(Double.valueOf(expectedValue.toString())); } else { - assertThat(actualValue, is(expectedValue)); + assertThat(actualValue).isEqualTo(expectedValue); } }); } @Test - public void identityAnalyzer() throws ExecutionException, InterruptedException { + void identityAnalyzer() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -341,10 +340,10 @@ public void identityAnalyzer() throws ExecutionException, InterruptedException { } @Test - public void identityAnalyzerTyped() throws ExecutionException, InterruptedException { + void identityAnalyzerTyped() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -359,9 +358,9 @@ public void identityAnalyzerTyped() throws ExecutionException, InterruptedExcept } @Test - public void delimiterAnalyzer() throws ExecutionException, InterruptedException { + void delimiterAnalyzer() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -378,10 +377,10 @@ public void delimiterAnalyzer() throws ExecutionException, InterruptedException } @Test - public void delimiterAnalyzerTyped() throws ExecutionException, InterruptedException { + void delimiterAnalyzerTyped() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -400,9 +399,9 @@ public void delimiterAnalyzerTyped() throws ExecutionException, InterruptedExcep } @Test - public void stemAnalyzer() throws ExecutionException, InterruptedException { + void stemAnalyzer() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -419,10 +418,10 @@ public void stemAnalyzer() throws ExecutionException, InterruptedException { } @Test - public void stemAnalyzerTyped() throws ExecutionException, InterruptedException { + void stemAnalyzerTyped() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -441,9 +440,9 @@ public void stemAnalyzerTyped() throws ExecutionException, InterruptedException } @Test - public void normAnalyzer() throws ExecutionException, InterruptedException { + void normAnalyzer() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -465,10 +464,10 @@ public void normAnalyzer() throws ExecutionException, InterruptedException { } @Test - public void normAnalyzerTyped() throws ExecutionException, InterruptedException { + void normAnalyzerTyped() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -489,10 +488,10 @@ public void normAnalyzerTyped() throws ExecutionException, InterruptedException } @Test - public void ngramAnalyzer() throws ExecutionException, InterruptedException { + void ngramAnalyzer() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -514,10 +513,10 @@ public void ngramAnalyzer() throws ExecutionException, InterruptedException { } @Test - public void ngramAnalyzerTyped() throws ExecutionException, InterruptedException { + void ngramAnalyzerTyped() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -539,10 +538,10 @@ public void ngramAnalyzerTyped() throws ExecutionException, InterruptedException } @Test - public void textAnalyzer() throws ExecutionException, InterruptedException { + void textAnalyzer() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); @@ -566,10 +565,10 @@ public void textAnalyzer() throws ExecutionException, InterruptedException { } @Test - public void textAnalyzerTyped() throws ExecutionException, InterruptedException { + void textAnalyzerTyped() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); - String name = "test-" + UUID.randomUUID().toString(); + String name = "test-" + UUID.randomUUID(); Set features = new HashSet<>(); features.add(AnalyzerFeature.frequency); diff --git a/src/test/java/com/arangodb/async/ArangoVertexCollectionTest.java b/src/test/java/com/arangodb/async/ArangoVertexCollectionTest.java index a04635dc1..cdaa860c8 100644 --- a/src/test/java/com/arangodb/async/ArangoVertexCollectionTest.java +++ b/src/test/java/com/arangodb/async/ArangoVertexCollectionTest.java @@ -25,27 +25,28 @@ import com.arangodb.entity.VertexEntity; import com.arangodb.entity.VertexUpdateEntity; import com.arangodb.model.*; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + import java.util.Collection; import java.util.concurrent.ExecutionException; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Mark Vollmary */ -public class ArangoVertexCollectionTest extends BaseTest { +class ArangoVertexCollectionTest extends BaseTest { private static final String GRAPH_NAME = "db_collection_test"; private static final String COLLECTION_NAME = "db_vertex_collection_test"; - @BeforeClass - public static void setup() throws InterruptedException, ExecutionException { + @BeforeAll + static void setup() throws InterruptedException, ExecutionException { if (!db.collection(COLLECTION_NAME).exists().get()) { db.createCollection(COLLECTION_NAME, null).get(); } @@ -53,52 +54,52 @@ public static void setup() throws InterruptedException, ExecutionException { db.createGraph(GRAPH_NAME, null, options).get(); } - @After - public void teardown() throws InterruptedException, ExecutionException { + @AfterEach + void teardown() throws InterruptedException, ExecutionException { db.collection(COLLECTION_NAME).truncate().get(); } @Test - public void dropVertexCollection() throws InterruptedException, ExecutionException { + void dropVertexCollection() throws InterruptedException, ExecutionException { db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).drop().get(); final Collection vertexCollections = db.graph(GRAPH_NAME).getVertexCollections().get(); - assertThat(vertexCollections, not(hasItem(COLLECTION_NAME))); + assertThat(vertexCollections).doesNotContain(COLLECTION_NAME); } @Test - public void insertVertex() throws InterruptedException, ExecutionException { + void insertVertex() throws InterruptedException, ExecutionException { final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .insertVertex(new BaseDocument(), null).get(); - assertThat(vertex, is(notNullValue())); + assertThat(vertex).isNotNull(); final BaseDocument document = db.collection(COLLECTION_NAME) .getDocument(vertex.getKey(), BaseDocument.class, null).get(); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(vertex.getKey()); } @Test - public void getVertex() throws InterruptedException, ExecutionException { + void getVertex() throws InterruptedException, ExecutionException { final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .insertVertex(new BaseDocument(), null).get(); final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .getVertex(vertex.getKey(), BaseDocument.class, null).get(); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(vertex.getKey()); } @Test - public void getVertexIfMatch() throws InterruptedException, ExecutionException { + void getVertexIfMatch() throws InterruptedException, ExecutionException { final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .insertVertex(new BaseDocument(), null).get(); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch(vertex.getRev()); final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .getVertex(vertex.getKey(), BaseDocument.class, options).get(); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(vertex.getKey()); } @Test - public void getVertexIfMatchFail() throws InterruptedException, ExecutionException { + void getVertexIfMatchFail() throws InterruptedException, ExecutionException { final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .insertVertex(new BaseDocument(), null).get(); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifMatch("no").catchException(false); @@ -107,23 +108,23 @@ public void getVertexIfMatchFail() throws InterruptedException, ExecutionExcepti .getVertex(vertex.getKey(), BaseDocument.class, options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void getVertexIfNoneMatch() throws InterruptedException, ExecutionException { + void getVertexIfNoneMatch() throws InterruptedException, ExecutionException { final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .insertVertex(new BaseDocument(), null).get(); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch("no"); final BaseDocument document = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .getVertex(vertex.getKey(), BaseDocument.class, options).get(); - assertThat(document, is(notNullValue())); - assertThat(document.getKey(), is(vertex.getKey())); + assertThat(document).isNotNull(); + assertThat(document.getKey()).isEqualTo(vertex.getKey()); } @Test - public void getVertexIfNoneMatchFail() throws InterruptedException, ExecutionException { + void getVertexIfNoneMatchFail() throws InterruptedException, ExecutionException { final VertexEntity vertex = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .insertVertex(new BaseDocument(), null).get(); final GraphDocumentReadOptions options = new GraphDocumentReadOptions().ifNoneMatch(vertex.getRev()).catchException(false); @@ -132,12 +133,12 @@ public void getVertexIfNoneMatchFail() throws InterruptedException, ExecutionExc .getVertex(vertex.getKey(), BaseDocument.class, options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void replaceVertex() throws InterruptedException, ExecutionException { + void replaceVertex() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) @@ -146,22 +147,22 @@ public void replaceVertex() throws InterruptedException, ExecutionException { doc.addAttribute("b", "test"); final VertexUpdateEntity replaceResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .replaceVertex(createResult.getKey(), doc, null).get(); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } @Test - public void replaceVertexIfMatch() throws InterruptedException, ExecutionException { + void replaceVertexIfMatch() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) @@ -171,22 +172,22 @@ public void replaceVertexIfMatch() throws InterruptedException, ExecutionExcepti final VertexReplaceOptions options = new VertexReplaceOptions().ifMatch(createResult.getRev()); final VertexUpdateEntity replaceResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .replaceVertex(createResult.getKey(), doc, options).get(); - assertThat(replaceResult, is(notNullValue())); - assertThat(replaceResult.getId(), is(createResult.getId())); - assertThat(replaceResult.getRev(), is(not(replaceResult.getOldRev()))); - assertThat(replaceResult.getOldRev(), is(createResult.getRev())); + assertThat(replaceResult).isNotNull(); + assertThat(replaceResult.getId()).isEqualTo(createResult.getId()); + assertThat(replaceResult.getRev()).isNotEqualTo(replaceResult.getOldRev()); + assertThat(replaceResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getRevision(), is(replaceResult.getRev())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getRevision()).isEqualTo(replaceResult.getRev()); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); } @Test - public void replaceVertexIfMatchFail() throws InterruptedException, ExecutionException { + void replaceVertexIfMatchFail() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) @@ -199,12 +200,12 @@ public void replaceVertexIfMatchFail() throws InterruptedException, ExecutionExc .get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void updateVertex() throws InterruptedException, ExecutionException { + void updateVertex() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -215,24 +216,24 @@ public void updateVertex() throws InterruptedException, ExecutionException { doc.updateAttribute("c", null); final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .updateVertex(createResult.getKey(), doc, null).get(); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); } @Test - public void updateVertexIfMatch() throws InterruptedException, ExecutionException { + void updateVertexIfMatch() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -244,24 +245,24 @@ public void updateVertexIfMatch() throws InterruptedException, ExecutionExceptio final VertexUpdateOptions options = new VertexUpdateOptions().ifMatch(createResult.getRev()); final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .updateVertex(createResult.getKey(), doc, options).get(); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getAttribute("a"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("a")), is("test1")); - assertThat(readResult.getAttribute("b"), is(notNullValue())); - assertThat(String.valueOf(readResult.getAttribute("b")), is("test")); - assertThat(readResult.getRevision(), is(updateResult.getRev())); - assertThat(readResult.getProperties().keySet(), hasItem("c")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getAttribute("a")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("a"))).isEqualTo("test1"); + assertThat(readResult.getAttribute("b")).isNotNull(); + assertThat(String.valueOf(readResult.getAttribute("b"))).isEqualTo("test"); + assertThat(readResult.getRevision()).isEqualTo(updateResult.getRev()); + assertThat(readResult.getProperties()).containsKey("c"); } @Test - public void updateVertexIfMatchFail() throws InterruptedException, ExecutionException { + void updateVertexIfMatchFail() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); doc.addAttribute("c", "test"); @@ -276,12 +277,12 @@ public void updateVertexIfMatchFail() throws InterruptedException, ExecutionExce .get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void updateVertexKeepNullTrue() throws InterruptedException, ExecutionException { + void updateVertexKeepNullTrue() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) @@ -290,20 +291,20 @@ public void updateVertexKeepNullTrue() throws InterruptedException, ExecutionExc final VertexUpdateOptions options = new VertexUpdateOptions().keepNull(true); final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .updateVertex(createResult.getKey(), doc, options).get(); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getProperties().keySet().size(), is(1)); - assertThat(readResult.getProperties().keySet(), hasItem("a")); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getProperties().keySet()).hasSize(1); + assertThat(readResult.getProperties()).containsKey("a"); } @Test - public void updateVertexKeepNullFalse() throws InterruptedException, ExecutionException { + void updateVertexKeepNullFalse() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); doc.addAttribute("a", "test"); final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) @@ -312,21 +313,21 @@ public void updateVertexKeepNullFalse() throws InterruptedException, ExecutionEx final VertexUpdateOptions options = new VertexUpdateOptions().keepNull(false); final VertexUpdateEntity updateResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .updateVertex(createResult.getKey(), doc, options).get(); - assertThat(updateResult, is(notNullValue())); - assertThat(updateResult.getId(), is(createResult.getId())); - assertThat(updateResult.getRev(), is(not(updateResult.getOldRev()))); - assertThat(updateResult.getOldRev(), is(createResult.getRev())); + assertThat(updateResult).isNotNull(); + assertThat(updateResult.getId()).isEqualTo(createResult.getId()); + assertThat(updateResult.getRev()).isNotEqualTo(updateResult.getOldRev()); + assertThat(updateResult.getOldRev()).isEqualTo(createResult.getRev()); final BaseDocument readResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME) .getVertex(createResult.getKey(), BaseDocument.class, null).get(); - assertThat(readResult.getKey(), is(createResult.getKey())); - assertThat(readResult.getId(), is(createResult.getId())); - assertThat(readResult.getRevision(), is(notNullValue())); - assertThat(readResult.getProperties().keySet(), not(hasItem("a"))); + assertThat(readResult.getKey()).isEqualTo(createResult.getKey()); + assertThat(readResult.getId()).isEqualTo(createResult.getId()); + assertThat(readResult.getRevision()).isNotNull(); + assertThat(readResult.getProperties().keySet()).doesNotContain("a"); } @Test - public void deleteVertex() throws InterruptedException, ExecutionException { + void deleteVertex() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) .get(); @@ -336,12 +337,12 @@ public void deleteVertex() throws InterruptedException, ExecutionException { .getVertex(createResult.getKey(), BaseDocument.class, new GraphDocumentReadOptions().catchException(false)).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void deleteVertexIfMatch() throws InterruptedException, ExecutionException { + void deleteVertexIfMatch() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) .get(); @@ -352,12 +353,12 @@ public void deleteVertexIfMatch() throws InterruptedException, ExecutionExceptio .getVertex(createResult.getKey(), BaseDocument.class, new GraphDocumentReadOptions().catchException(false)).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void deleteVertexIfMatchFail() throws InterruptedException, ExecutionException { + void deleteVertexIfMatchFail() throws InterruptedException, ExecutionException { final BaseDocument doc = new BaseDocument(); final VertexEntity createResult = db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).insertVertex(doc, null) .get(); @@ -366,7 +367,7 @@ public void deleteVertexIfMatchFail() throws InterruptedException, ExecutionExce db.graph(GRAPH_NAME).vertexCollection(COLLECTION_NAME).deleteVertex(createResult.getKey(), options).get(); fail(); } catch (final ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } } diff --git a/src/test/java/com/arangodb/async/ArangoViewTest.java b/src/test/java/com/arangodb/async/ArangoViewTest.java index 334a05830..8bc81b238 100644 --- a/src/test/java/com/arangodb/async/ArangoViewTest.java +++ b/src/test/java/com/arangodb/async/ArangoViewTest.java @@ -22,66 +22,65 @@ import com.arangodb.entity.ViewEntity; import com.arangodb.entity.ViewType; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.concurrent.ExecutionException; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Mark Vollmary */ -public class ArangoViewTest extends BaseTest { +class ArangoViewTest extends BaseTest { private static final String VIEW_NAME = "view_test"; - @BeforeClass - public static void setup() throws InterruptedException, ExecutionException { + @BeforeAll + static void setup() throws InterruptedException, ExecutionException { if (!isAtLeastVersion(arangoDB, 3, 4)) return; db.createView(VIEW_NAME, ViewType.ARANGO_SEARCH).get(); } @Test - public void exists() throws InterruptedException, ExecutionException { + void exists() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); - assertThat(db.view(VIEW_NAME).exists().get(), is(true)); + assertThat(db.view(VIEW_NAME).exists().get()).isTrue(); } @Test - public void getInfo() throws InterruptedException, ExecutionException { + void getInfo() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); final ViewEntity info = db.view(VIEW_NAME).getInfo().get(); - assertThat(info, is(not(nullValue()))); - assertThat(info.getId(), is(not(nullValue()))); - assertThat(info.getName(), is(VIEW_NAME)); - assertThat(info.getType(), is(ViewType.ARANGO_SEARCH)); + assertThat(info).isNotNull(); + assertThat(info.getId()).isNotNull(); + assertThat(info.getName()).isEqualTo(VIEW_NAME); + assertThat(info.getType()).isEqualTo(ViewType.ARANGO_SEARCH); } @Test - public void drop() throws InterruptedException, ExecutionException { + void drop() throws InterruptedException, ExecutionException { assumeTrue(isAtLeastVersion(3, 4)); final String name = VIEW_NAME + "_droptest"; db.createView(name, ViewType.ARANGO_SEARCH).get(); final ArangoViewAsync view = db.view(name); view.drop().get(); - assertThat(view.exists().get(), is(false)); + assertThat(view.exists().get()).isFalse(); } @Test - public void rename() throws InterruptedException, ExecutionException { + void rename() throws InterruptedException, ExecutionException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 4)); final String name = VIEW_NAME + "_renametest"; final String newName = name + "_new"; db.createView(name, ViewType.ARANGO_SEARCH).get(); db.view(name).rename(newName).get(); - assertThat(db.view(name).exists().get(), is(false)); - assertThat(db.view(newName).exists().get(), is(true)); + assertThat(db.view(name).exists().get()).isFalse(); + assertThat(db.view(newName).exists().get()).isTrue(); } } diff --git a/src/test/java/com/arangodb/async/BaseTest.java b/src/test/java/com/arangodb/async/BaseTest.java index 819ef79cb..db4f312aa 100644 --- a/src/test/java/com/arangodb/async/BaseTest.java +++ b/src/test/java/com/arangodb/async/BaseTest.java @@ -24,8 +24,9 @@ import com.arangodb.DbName; import com.arangodb.entity.License; import com.arangodb.entity.ServerRole; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import java.util.UUID; import java.util.concurrent.ExecutionException; @@ -40,10 +41,10 @@ public abstract class BaseTest { static ArangoDBAsync arangoDB; static ArangoDatabaseAsync db; - @BeforeClass - public static void init() throws InterruptedException, ExecutionException { + @BeforeAll + static void init() throws InterruptedException, ExecutionException { if (arangoDB == null) { - arangoDB = new ArangoDBAsync.Builder().build(); + arangoDB = new ArangoDBAsync.Builder().serializer(new ArangoJack()).build(); } if (arangoDB.db(TEST_DB).exists().get()) { @@ -54,8 +55,8 @@ public static void init() throws InterruptedException, ExecutionException { BaseTest.db = arangoDB.db(TEST_DB); } - @AfterClass - public static void shutdown() throws InterruptedException, ExecutionException { + @AfterAll + static void shutdown() throws InterruptedException, ExecutionException { arangoDB.db(TEST_DB).drop().get(); arangoDB.shutdown(); arangoDB = null; @@ -69,6 +70,7 @@ protected static boolean isAtLeastVersion(final ArangoDBAsync arangoDB, final in throws InterruptedException, ExecutionException { return com.arangodb.util.TestUtils.isAtLeastVersion(arangoDB.getVersion().get().getVersion(), major, minor, patch); } + protected static boolean isAtLeastVersion(final ArangoDBAsync arangoDB, final int major, final int minor) throws InterruptedException, ExecutionException { return isAtLeastVersion(arangoDB, major, minor, 0); diff --git a/src/test/java/com/arangodb/async/CommunicationTest.java b/src/test/java/com/arangodb/async/CommunicationTest.java index 11477a130..744aa0087 100644 --- a/src/test/java/com/arangodb/async/CommunicationTest.java +++ b/src/test/java/com/arangodb/async/CommunicationTest.java @@ -20,27 +20,29 @@ package com.arangodb.async; -import org.junit.Ignore; -import org.junit.Test; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import java.util.concurrent.CompletableFuture; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Mark Vollmary */ -public class CommunicationTest { +class CommunicationTest { @Test - @Ignore - public void disconnect() { - final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().build(); + @Disabled + void disconnect() { + final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().serializer(new ArangoJack()).build(); final CompletableFuture> result = arangoDB.db().query("return sleep(1)", null, null, null); arangoDB.shutdown(); - assertThat(result.isCompletedExceptionally(), is(true)); + assertThat(result.isCompletedExceptionally()).isEqualTo(true); } } diff --git a/src/test/java/com/arangodb/async/ConcurrencyTest.java b/src/test/java/com/arangodb/async/ConcurrencyTest.java index c6c9c45ec..46c6bd552 100644 --- a/src/test/java/com/arangodb/async/ConcurrencyTest.java +++ b/src/test/java/com/arangodb/async/ConcurrencyTest.java @@ -23,9 +23,11 @@ import com.arangodb.async.internal.ArangoExecutorAsync; import com.arangodb.entity.ArangoDBVersion; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -33,27 +35,29 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Michele Rastelli */ -public class ConcurrencyTest { +class ConcurrencyTest { private ArangoDBAsync arangoDB; - @Before - public void initialize() { - arangoDB = new ArangoDBAsync.Builder().build(); + @BeforeEach + void initialize() { + arangoDB = new ArangoDBAsync.Builder().serializer(new ArangoJack()).build(); } /** * FIXME: make the user executor configurable in com.arangodb.internal.ArangoExecutorAsync::execute * (eg. this test passes using a CachedThreadPool) */ - @Ignore - @Test(timeout = 2000) - public void executorLimit() { + @Disabled + @Test + @Timeout(2) + void executorLimit() { List> futures = IntStream.range(0, 20) .mapToObj(i -> arangoDB.getVersion() .whenComplete((dbVersion, ex) -> { @@ -80,9 +84,10 @@ public void executorLimit() { /** * outgoing requests should be queued in the {@link ArangoExecutorAsync} outgoingExecutor */ - @Ignore - @Test(timeout = 1000) - public void outgoingRequestsParallelismTest() { + @Disabled + @Test + @Timeout(1) + void outgoingRequestsParallelismTest() { for (int i = 0; i < 50_000; i++) { arangoDB.getVersion(); } diff --git a/src/test/java/com/arangodb/async/ConcurrencyTests.java b/src/test/java/com/arangodb/async/ConcurrencyTests.java index 746ef2923..edbad7c81 100644 --- a/src/test/java/com/arangodb/async/ConcurrencyTests.java +++ b/src/test/java/com/arangodb/async/ConcurrencyTests.java @@ -1,6 +1,9 @@ package com.arangodb.async; -import org.junit.Test; + + +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -8,11 +11,11 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -public class ConcurrencyTests { +class ConcurrencyTests { @Test - public void concurrentPendingRequests() throws ExecutionException, InterruptedException { - ArangoDBAsync adb = new ArangoDBAsync.Builder().build(); + void concurrentPendingRequests() throws ExecutionException, InterruptedException { + ArangoDBAsync adb = new ArangoDBAsync.Builder().serializer(new ArangoJack()).build(); List>> reqs = IntStream.range(0, 10) .mapToObj(__ -> adb.db().query("RETURN SLEEP(1)", Void.class)) .collect(Collectors.toList()); diff --git a/src/test/java/com/arangodb/async/JwtAuthTest.java b/src/test/java/com/arangodb/async/JwtAuthTest.java index 25f6d1a06..c9d0f40d1 100644 --- a/src/test/java/com/arangodb/async/JwtAuthTest.java +++ b/src/test/java/com/arangodb/async/JwtAuthTest.java @@ -2,56 +2,58 @@ import com.arangodb.ArangoDB; import com.arangodb.ArangoDBException; +import com.arangodb.DbName; +import com.arangodb.mapping.ArangoJack; import com.arangodb.util.ArangoSerialization; import com.arangodb.velocystream.Request; import com.arangodb.velocystream.RequestType; import com.arangodb.velocystream.Response; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; -public class JwtAuthTest { +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; + +class JwtAuthTest { private static String jwt; private ArangoDBAsync arangoDB; - @BeforeClass - public static void init() { - ArangoDB arangoDB = new ArangoDB.Builder().build(); + @BeforeAll + static void init() { + ArangoDB arangoDB = new ArangoDB.Builder().serializer(new ArangoJack()).build(); jwt = getJwt(arangoDB); arangoDB.shutdown(); } - @After - public void after() { + @AfterEach + void after() { if (arangoDB != null) arangoDB.shutdown(); } @Test - public void notAuthenticated() throws InterruptedException { + void notAuthenticated() throws InterruptedException { arangoDB = getBuilder().build(); try { arangoDB.getVersion().get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), is(instanceOf(ArangoDBException.class))); - assertThat(((ArangoDBException) e.getCause()).getResponseCode(), is(401)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); + assertThat(((ArangoDBException) e.getCause()).getResponseCode()).isEqualTo(401); } arangoDB.shutdown(); } @Test - public void authenticated() throws ExecutionException, InterruptedException { + void authenticated() throws ExecutionException, InterruptedException { arangoDB = getBuilder() .jwt(jwt) .build(); @@ -60,7 +62,7 @@ public void authenticated() throws ExecutionException, InterruptedException { } @Test - public void updateJwt() throws ExecutionException, InterruptedException { + void updateJwt() throws ExecutionException, InterruptedException { arangoDB = getBuilder() .jwt(jwt) .build(); @@ -70,8 +72,8 @@ public void updateJwt() throws ExecutionException, InterruptedException { arangoDB.getVersion().get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), is(instanceOf(ArangoDBException.class))); - assertThat(((ArangoDBException) e.getCause()).getResponseCode(), is(401)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); + assertThat(((ArangoDBException) e.getCause()).getResponseCode()).isEqualTo(401); } arangoDB.updateJwt(jwt); @@ -81,6 +83,7 @@ public void updateJwt() throws ExecutionException, InterruptedException { private ArangoDBAsync.Builder getBuilder() { return new ArangoDBAsync.Builder() + .serializer(new ArangoJack()) .jwt(null) // unset credentials from properties file .user(null) // unset credentials from properties file .password(null); // unset credentials from properties file @@ -92,7 +95,7 @@ private static String getJwt(ArangoDB arangoDB) { reqBody.put("username", "root"); reqBody.put("password", "test"); - Request req = new Request("_system", RequestType.POST, "/_open/auth"); + Request req = new Request(DbName.SYSTEM, RequestType.POST, "/_open/auth"); req.setBody(serde.serialize(reqBody)); Response resp = arangoDB.execute(req); diff --git a/src/test/java/com/arangodb/async/StreamTransactionConflictsTest.java b/src/test/java/com/arangodb/async/StreamTransactionConflictsTest.java index 1a3384ac3..659781ae2 100644 --- a/src/test/java/com/arangodb/async/StreamTransactionConflictsTest.java +++ b/src/test/java/com/arangodb/async/StreamTransactionConflictsTest.java @@ -26,21 +26,20 @@ import com.arangodb.entity.StreamTransactionEntity; import com.arangodb.model.DocumentCreateOptions; import com.arangodb.model.StreamTransactionOptions; -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.UUID; import java.util.concurrent.ExecutionException; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Michele Rastelli */ -public class StreamTransactionConflictsTest extends BaseTest { +class StreamTransactionConflictsTest extends BaseTest { private static final String COLLECTION_NAME = "db_concurrent_stream_transactions_test"; @@ -51,14 +50,14 @@ public StreamTransactionConflictsTest() throws ExecutionException, InterruptedEx db.createCollection(COLLECTION_NAME, null).get(); } - @After - public void teardown() throws ExecutionException, InterruptedException { + @AfterEach + void teardown() throws ExecutionException, InterruptedException { if (db.collection(COLLECTION_NAME).exists().get()) db.collection(COLLECTION_NAME).drop().get(); } @Test - public void conflictOnInsertDocumentWithNotYetCommittedTx() throws ExecutionException, InterruptedException { + void conflictOnInsertDocumentWithNotYetCommittedTx() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -80,7 +79,7 @@ public void conflictOnInsertDocumentWithNotYetCommittedTx() throws ExecutionExce new DocumentCreateOptions().streamTransactionId(tx2.getId())).get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), Matchers.instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } db.abortStreamTransaction(tx1.getId()).get(); @@ -88,7 +87,7 @@ public void conflictOnInsertDocumentWithNotYetCommittedTx() throws ExecutionExce } @Test - public void conflictOnInsertDocumentWithAlreadyCommittedTx() throws ExecutionException, InterruptedException { + void conflictOnInsertDocumentWithAlreadyCommittedTx() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -113,7 +112,7 @@ public void conflictOnInsertDocumentWithAlreadyCommittedTx() throws ExecutionExc new DocumentCreateOptions().streamTransactionId(tx2.getId())).get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), Matchers.instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } db.abortStreamTransaction(tx2.getId()).get(); diff --git a/src/test/java/com/arangodb/async/StreamTransactionGraphTest.java b/src/test/java/com/arangodb/async/StreamTransactionGraphTest.java index cf5fc53b6..cb62b8f8f 100644 --- a/src/test/java/com/arangodb/async/StreamTransactionGraphTest.java +++ b/src/test/java/com/arangodb/async/StreamTransactionGraphTest.java @@ -38,22 +38,20 @@ import com.arangodb.model.VertexDeleteOptions; import com.arangodb.model.VertexReplaceOptions; import com.arangodb.model.VertexUpdateOptions; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.concurrent.ExecutionException; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + /** * @author Michele Rastelli */ -public class StreamTransactionGraphTest extends BaseTest { +class StreamTransactionGraphTest extends BaseTest { private static final String GRAPH_NAME = "graph_stream_transaction_graph_test"; private static final String EDGE_COLLECTION = "edge_collection_stream_transaction_graph_test"; @@ -61,9 +59,9 @@ public class StreamTransactionGraphTest extends BaseTest { private static final String VERTEX_COLLECTION_2 = "vertex_collection_2_stream_transaction_graph_test"; private final ArangoGraphAsync graph; - private ArangoVertexCollectionAsync vertexCollection1; - private ArangoVertexCollectionAsync vertexCollection2; - private ArangoEdgeCollectionAsync edgeCollection; + private final ArangoVertexCollectionAsync vertexCollection1; + private final ArangoVertexCollectionAsync vertexCollection2; + private final ArangoEdgeCollectionAsync edgeCollection; public StreamTransactionGraphTest() throws ExecutionException, InterruptedException { @@ -79,8 +77,8 @@ public StreamTransactionGraphTest() throws ExecutionException, InterruptedExcept edgeCollection = graph.edgeCollection(EDGE_COLLECTION); } - @After - public void teardown() throws ExecutionException, InterruptedException { + @AfterEach + void teardown() throws ExecutionException, InterruptedException { if (graph.exists().get()) graph.drop().get(); if (db.collection(EDGE_COLLECTION).exists().get()) @@ -101,7 +99,7 @@ private BaseEdgeDocument createEdgeValue(String streamTransactionId) throws Exec } @Test - public void getVertex() throws ExecutionException, InterruptedException { + void getVertex() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -116,14 +114,14 @@ public void getVertex() throws ExecutionException, InterruptedException { // assert that the vertex is not found from within the tx assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get(), is(nullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNull(); db.abortStreamTransaction(tx.getId()).get(); } @Test - public void createVertex() throws ExecutionException, InterruptedException { + void createVertex() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -137,20 +135,20 @@ public void createVertex() throws ExecutionException, InterruptedException { VertexEntity createdVertex = vertexCollection1.insertVertex(new BaseDocument(), new VertexCreateOptions().streamTransactionId(tx.getId())).get(); // assert that the vertex is not found from outside the tx - assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null).get(), is(nullValue())); + assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null).get()).isNull(); // assert that the vertex is found from within the tx assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get(), is(notNullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNotNull(); db.commitStreamTransaction(tx.getId()).get(); // assert that the vertex is found after commit - assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null).get(), is(notNullValue())); + assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null).get()).isNotNull(); } @Test - public void replaceVertex() throws ExecutionException, InterruptedException { + void replaceVertex() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -173,21 +171,21 @@ public void replaceVertex() throws ExecutionException, InterruptedException { // assert that the vertex has not been replaced from outside the tx assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null).get() - .getProperties().get("test"), is("foo")); + .getProperties()).containsEntry("test", "foo"); // assert that the vertex has been replaced from within the tx assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties().get("test"), is("bar")); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties()).containsEntry("test", "bar"); db.commitStreamTransaction(tx.getId()).get(); // assert that the vertex has been replaced after commit assertThat(vertexCollection1.getVertex(createdVertex.getKey(), BaseDocument.class, null).get() - .getProperties().get("test"), is("bar")); + .getProperties()).containsEntry("test", "bar"); } @Test - public void updateVertex() throws ExecutionException, InterruptedException { + void updateVertex() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -209,21 +207,21 @@ public void updateVertex() throws ExecutionException, InterruptedException { // assert that the vertex has not been updated from outside the tx assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null).get() - .getProperties().get("test"), is("foo")); + .getProperties()).containsEntry("test", "foo"); // assert that the vertex has been updated from within the tx assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties().get("test"), is("bar")); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties()).containsEntry("test", "bar"); db.commitStreamTransaction(tx.getId()).get(); // assert that the vertex has been updated after commit assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null).get() - .getProperties().get("test"), is("bar")); + .getProperties()).containsEntry("test", "bar"); } @Test - public void deleteVertex() throws ExecutionException, InterruptedException { + void deleteVertex() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -239,22 +237,21 @@ public void deleteVertex() throws ExecutionException, InterruptedException { vertexCollection1.deleteVertex(createdDoc.getKey(), new VertexDeleteOptions().streamTransactionId(tx.getId())).get(); // assert that the vertex has not been deleted from outside the tx - assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null).get(), is(notNullValue())); + assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null).get()).isNotNull(); // assert that the vertex has been deleted from within the tx assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get(), is(nullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNull(); db.commitStreamTransaction(tx.getId()).get(); // assert that the vertex has been deleted after commit - assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null).get(), - is(nullValue())); + assertThat(vertexCollection1.getVertex(createdDoc.getKey(), BaseDocument.class, null).get()).isNull(); } @Test - public void getEdge() throws ExecutionException, InterruptedException { + void getEdge() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -264,19 +261,19 @@ public void getEdge() throws ExecutionException, InterruptedException { .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - // insert a edge from outside the tx + // insert an edge from outside the tx EdgeEntity createdEdge = edgeCollection.insertEdge(createEdgeValue(null)).get(); // assert that the edge is not found from within the tx assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get(), is(nullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNull(); db.abortStreamTransaction(tx.getId()).get(); } @Test - public void createEdge() throws ExecutionException, InterruptedException { + void createEdge() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -286,24 +283,24 @@ public void createEdge() throws ExecutionException, InterruptedException { .readCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION) .writeCollections(VERTEX_COLLECTION_1, VERTEX_COLLECTION_2, EDGE_COLLECTION)).get(); - // insert a edge from within the tx + // insert an edge from within the tx EdgeEntity createdEdge = edgeCollection.insertEdge(createEdgeValue(tx.getId()), new EdgeCreateOptions().streamTransactionId(tx.getId())).get(); // assert that the edge is not found from outside the tx - assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null).get(), is(nullValue())); + assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null).get()).isNull(); // assert that the edge is found from within the tx assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get(), is(notNullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNotNull(); db.commitStreamTransaction(tx.getId()).get(); // assert that the edge is found after commit - assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null).get(), is(notNullValue())); + assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null).get()).isNotNull(); } @Test - public void replaceEdge() throws ExecutionException, InterruptedException { + void replaceEdge() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -326,21 +323,21 @@ public void replaceEdge() throws ExecutionException, InterruptedException { // assert that the edge has not been replaced from outside the tx assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null).get() - .getProperties().get("test"), is("foo")); + .getProperties()).containsEntry("test", "foo"); // assert that the edge has been replaced from within the tx assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties().get("test"), is("bar")); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties()).containsEntry("test", "bar"); db.commitStreamTransaction(tx.getId()).get(); // assert that the edge has been replaced after commit assertThat(edgeCollection.getEdge(createdEdge.getKey(), BaseEdgeDocument.class, null).get() - .getProperties().get("test"), is("bar")); + .getProperties()).containsEntry("test", "bar"); } @Test - public void updateEdge() throws ExecutionException, InterruptedException { + void updateEdge() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -363,21 +360,21 @@ public void updateEdge() throws ExecutionException, InterruptedException { // assert that the edge has not been updated from outside the tx assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null).get() - .getProperties().get("test"), is("foo")); + .getProperties()).containsEntry("test", "foo"); // assert that the edge has been updated from within the tx assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties().get("test"), is("bar")); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get().getProperties()).containsEntry("test", "bar"); db.commitStreamTransaction(tx.getId()).get(); // assert that the edge has been updated after commit assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null).get() - .getProperties().get("test"), is("bar")); + .getProperties()).containsEntry("test", "bar"); } @Test - public void deleteEdge() throws ExecutionException, InterruptedException { + void deleteEdge() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -393,17 +390,16 @@ public void deleteEdge() throws ExecutionException, InterruptedException { edgeCollection.deleteEdge(createdDoc.getKey(), new EdgeDeleteOptions().streamTransactionId(tx.getId())).get(); // assert that the edge has not been deleted from outside the tx - assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null).get(), is(notNullValue())); + assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null).get()).isNotNull(); // assert that the edge has been deleted from within the tx assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, - new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get(), is(nullValue())); + new GraphDocumentReadOptions().streamTransactionId(tx.getId())).get()).isNull(); db.commitStreamTransaction(tx.getId()).get(); // assert that the edge has been deleted after commit - assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null).get(), - is(nullValue())); + assertThat(edgeCollection.getEdge(createdDoc.getKey(), BaseEdgeDocument.class, null).get()).isNull(); } } diff --git a/src/test/java/com/arangodb/async/StreamTransactionTest.java b/src/test/java/com/arangodb/async/StreamTransactionTest.java index 158df293b..9925a110e 100644 --- a/src/test/java/com/arangodb/async/StreamTransactionTest.java +++ b/src/test/java/com/arangodb/async/StreamTransactionTest.java @@ -25,8 +25,8 @@ import com.arangodb.model.DocumentCreateOptions; import com.arangodb.model.DocumentReadOptions; import com.arangodb.model.StreamTransactionOptions; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; @@ -34,16 +34,14 @@ import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Michele Rastelli */ -public class StreamTransactionTest extends BaseTest { +class StreamTransactionTest extends BaseTest { private static final String COLLECTION_NAME = "db_stream_transaction_test"; @@ -54,26 +52,26 @@ public StreamTransactionTest() throws ExecutionException, InterruptedException { db.createCollection(COLLECTION_NAME, null).get(); } - @After - public void teardown() throws ExecutionException, InterruptedException { + @AfterEach + void teardown() throws ExecutionException, InterruptedException { if (db.collection(COLLECTION_NAME).exists().get()) db.collection(COLLECTION_NAME).drop().get(); } @Test - public void beginStreamTransaction() throws ExecutionException, InterruptedException { + void beginStreamTransaction() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); StreamTransactionEntity tx = db.beginStreamTransaction(null).get(); - assertThat(tx.getId(), is(notNullValue())); - assertThat(tx.getStatus(), is(StreamTransactionStatus.running)); + assertThat(tx.getId()).isNotNull(); + assertThat(tx.getStatus()).isEqualTo(StreamTransactionStatus.running); db.abortStreamTransaction(tx.getId()).get(); } @Test - public void beginStreamTransactionWithNonExistingCollectionsShouldThrow() throws ExecutionException, InterruptedException { + void beginStreamTransactionWithNonExistingCollectionsShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -82,12 +80,12 @@ public void beginStreamTransactionWithNonExistingCollectionsShouldThrow() throws db.beginStreamTransaction(new StreamTransactionOptions().writeCollections("notExistingCollection")).get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void abortStreamTransaction() throws ExecutionException, InterruptedException { + void abortStreamTransaction() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -95,13 +93,13 @@ public void abortStreamTransaction() throws ExecutionException, InterruptedExcep StreamTransactionEntity begunTx = db.beginStreamTransaction(null).get(); StreamTransactionEntity abortedTx = db.abortStreamTransaction(begunTx.getId()).get(); - assertThat(abortedTx.getId(), is(notNullValue())); - assertThat(abortedTx.getId(), is(begunTx.getId())); - assertThat(abortedTx.getStatus(), is(StreamTransactionStatus.aborted)); + assertThat(abortedTx.getId()).isNotNull(); + assertThat(abortedTx.getId()).isEqualTo(begunTx.getId()); + assertThat(abortedTx.getStatus()).isEqualTo(StreamTransactionStatus.aborted); } @Test - public void abortStreamTransactionTwice() throws ExecutionException, InterruptedException { + void abortStreamTransactionTwice() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -112,7 +110,7 @@ public void abortStreamTransactionTwice() throws ExecutionException, Interrupted } @Test - public void abortStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() throws ExecutionException, InterruptedException { + void abortStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -121,12 +119,12 @@ public void abortStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() th db.abortStreamTransaction("000000").get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void abortStreamTransactionWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { + void abortStreamTransactionWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -135,12 +133,12 @@ public void abortStreamTransactionWithInvalidTransactionIdShouldThrow() throws E db.abortStreamTransaction("invalidTransactionId").get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void abortCommittedStreamTransactionShouldThrow() throws ExecutionException, InterruptedException { + void abortCommittedStreamTransactionShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -152,12 +150,12 @@ public void abortCommittedStreamTransactionShouldThrow() throws ExecutionExcepti db.abortStreamTransaction(createdTx.getId()).get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void getStreamTransaction() throws ExecutionException, InterruptedException { + void getStreamTransaction() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -165,15 +163,15 @@ public void getStreamTransaction() throws ExecutionException, InterruptedExcepti StreamTransactionEntity createdTx = db.beginStreamTransaction(null).get(); StreamTransactionEntity gotTx = db.getStreamTransaction(createdTx.getId()).get(); - assertThat(gotTx.getId(), is(notNullValue())); - assertThat(gotTx.getId(), is(createdTx.getId())); - assertThat(gotTx.getStatus(), is(StreamTransactionStatus.running)); + assertThat(gotTx.getId()).isNotNull(); + assertThat(gotTx.getId()).isEqualTo(createdTx.getId()); + assertThat(gotTx.getStatus()).isEqualTo(StreamTransactionStatus.running); db.abortStreamTransaction(createdTx.getId()).get(); } @Test - public void getStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() throws ExecutionException, InterruptedException { + void getStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -182,12 +180,12 @@ public void getStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() thro db.getStreamTransaction("000000").get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void getStreamTransactionWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { + void getStreamTransactionWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -196,12 +194,12 @@ public void getStreamTransactionWithInvalidTransactionIdShouldThrow() throws Exe db.getStreamTransaction("invalidTransactionId").get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void commitStreamTransaction() throws ExecutionException, InterruptedException { + void commitStreamTransaction() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -209,13 +207,13 @@ public void commitStreamTransaction() throws ExecutionException, InterruptedExce StreamTransactionEntity createdTx = db.beginStreamTransaction(null).get(); StreamTransactionEntity committedTx = db.commitStreamTransaction(createdTx.getId()).get(); - assertThat(committedTx.getId(), is(notNullValue())); - assertThat(committedTx.getId(), is(createdTx.getId())); - assertThat(committedTx.getStatus(), is(StreamTransactionStatus.committed)); + assertThat(committedTx.getId()).isNotNull(); + assertThat(committedTx.getId()).isEqualTo(createdTx.getId()); + assertThat(committedTx.getStatus()).isEqualTo(StreamTransactionStatus.committed); } @Test - public void commitStreamTransactionTwice() throws ExecutionException, InterruptedException { + void commitStreamTransactionTwice() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -226,7 +224,7 @@ public void commitStreamTransactionTwice() throws ExecutionException, Interrupte } @Test - public void commitStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() throws ExecutionException, InterruptedException { + void commitStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -235,12 +233,12 @@ public void commitStreamTransactionWhenTransactionIdDoesNotExistsShouldThrow() t db.commitStreamTransaction("000000").get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void commitStreamTransactionWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { + void commitStreamTransactionWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -249,12 +247,12 @@ public void commitStreamTransactionWithInvalidTransactionIdShouldThrow() throws db.commitStreamTransaction("invalidTransactionId").get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void commitAbortedStreamTransactionShouldThrow() throws ExecutionException, InterruptedException { + void commitAbortedStreamTransactionShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -266,12 +264,12 @@ public void commitAbortedStreamTransactionShouldThrow() throws ExecutionExceptio db.commitStreamTransaction(createdTx.getId()).get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void getDocument() throws ExecutionException, InterruptedException { + void getDocument() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -285,13 +283,13 @@ public void getDocument() throws ExecutionException, InterruptedException { // assert that the document is not found from within the tx assertThat(db.collection(COLLECTION_NAME).getDocument(externalDoc.getKey(), BaseDocument.class, - new DocumentReadOptions().streamTransactionId(tx.getId())).get(), is(nullValue())); + new DocumentReadOptions().streamTransactionId(tx.getId())).get()).isNull(); db.abortStreamTransaction(tx.getId()).get(); } @Test - public void getDocumentWithNonExistingTransactionIdShouldThrow() throws ExecutionException, InterruptedException { + void getDocumentWithNonExistingTransactionIdShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -302,12 +300,12 @@ public void getDocumentWithNonExistingTransactionIdShouldThrow() throws Executio .get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void insertDocumentWithNonExistingTransactionIdShouldThrow() throws ExecutionException, InterruptedException { + void insertDocumentWithNonExistingTransactionIdShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -317,12 +315,12 @@ public void insertDocumentWithNonExistingTransactionIdShouldThrow() throws Execu .insertDocument(new BaseDocument(), new DocumentCreateOptions().streamTransactionId("123456")).get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void getDocumentWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { + void getDocumentWithInvalidTransactionIdShouldThrow() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -333,12 +331,12 @@ public void getDocumentWithInvalidTransactionIdShouldThrow() throws ExecutionExc .get(); fail(); } catch (ExecutionException e) { - assertThat(e.getCause(), instanceOf(ArangoDBException.class)); + assertThat(e.getCause()).isInstanceOf(ArangoDBException.class); } } @Test - public void getStreamTransactions() throws ExecutionException, InterruptedException { + void getStreamTransactions() throws ExecutionException, InterruptedException { assumeTrue(isSingleServer()); assumeTrue(isAtLeastVersion(3, 5)); assumeTrue(isStorageEngine(ArangoDBEngine.StorageEngineName.rocksdb)); @@ -350,9 +348,9 @@ public void getStreamTransactions() throws ExecutionException, InterruptedExcept Set gotTxs = db.getStreamTransactions().get().stream(). filter(it -> createdIds.contains(it.getId())).collect(Collectors.toSet()); - assertThat(gotTxs.size(), is(createdIds.size())); + assertThat(gotTxs).hasSameSizeAs(createdIds); assertThat(gotTxs.stream() - .allMatch(it -> it.getStatus() == StreamTransactionStatus.running), is(true)); + .allMatch(it -> it.getStatus() == StreamTransactionStatus.running)).isTrue(); db.abortStreamTransaction(tx1.getId()).get(); db.abortStreamTransaction(tx2.getId()).get(); diff --git a/src/test/java/com/arangodb/async/debug/ConsolidationIntervalMsec.java b/src/test/java/com/arangodb/async/debug/ConsolidationIntervalMsecTest.java similarity index 65% rename from src/test/java/com/arangodb/async/debug/ConsolidationIntervalMsec.java rename to src/test/java/com/arangodb/async/debug/ConsolidationIntervalMsecTest.java index d921a4029..14f5b7ab3 100644 --- a/src/test/java/com/arangodb/async/debug/ConsolidationIntervalMsec.java +++ b/src/test/java/com/arangodb/async/debug/ConsolidationIntervalMsecTest.java @@ -20,36 +20,37 @@ package com.arangodb.async.debug; +import com.arangodb.DbName; import com.arangodb.async.ArangoDBAsync; import com.arangodb.async.ArangoDatabaseAsync; import com.arangodb.async.BaseTest; -import com.arangodb.DbName; import com.arangodb.entity.ViewEntity; import com.arangodb.entity.ViewType; import com.arangodb.entity.arangosearch.ArangoSearchPropertiesEntity; import com.arangodb.entity.arangosearch.CollectionLink; import com.arangodb.entity.arangosearch.FieldLink; +import com.arangodb.mapping.ArangoJack; import com.arangodb.model.arangosearch.ArangoSearchCreateOptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.ExecutionException; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Michele Rastelli *

* https://github.com/arangodb/arangodb-java-driver-async/issues/15 */ -public class ConsolidationIntervalMsec extends BaseTest { +class ConsolidationIntervalMsecTest extends BaseTest { @Test - public void consolidationIntervalMsec() throws ExecutionException, InterruptedException { + void consolidationIntervalMsec() throws ExecutionException, InterruptedException { assumeTrue(isAtLeastVersion(3, 4)); ArangoDBAsync arango = new ArangoDBAsync.Builder() + .serializer(new ArangoJack()) .user("root") .password("test") .build(); @@ -63,20 +64,20 @@ public void consolidationIntervalMsec() throws ExecutionException, InterruptedEx db.collection("Thing").create().join(); ViewEntity result = db.createArangoSearch("ThingsSearchView", new ArangoSearchCreateOptions() - .consolidationIntervalMsec(60000L) //<== This line breaks it - .link(CollectionLink.on("Thing") - .fields(FieldLink.on("name") - .analyzers("identity")))) + .consolidationIntervalMsec(60000L) //<== This line breaks it + .link(CollectionLink.on("Thing") + .fields(FieldLink.on("name") + .analyzers("identity")))) .join(); - assertThat(result.getName(), is("ThingsSearchView")); - assertThat(result.getType(), is(ViewType.ARANGO_SEARCH)); + assertThat(result.getName()).isEqualTo("ThingsSearchView"); + assertThat(result.getType()).isEqualTo(ViewType.ARANGO_SEARCH); ArangoSearchPropertiesEntity props = db.arangoSearch("ThingsSearchView").getProperties().join(); - assertThat(props.getName(), is("ThingsSearchView")); - assertThat(props.getConsolidationIntervalMsec(), is(60000L)); - assertThat(props.getLinks().iterator().hasNext(), is(true)); - assertThat(props.getLinks().iterator().next().getName(), is("Thing")); + assertThat(props.getName()).isEqualTo("ThingsSearchView"); + assertThat(props.getConsolidationIntervalMsec()).isEqualTo(60000L); + assertThat(props.getLinks().iterator().hasNext()).isTrue(); + assertThat(props.getLinks().iterator().next().getName()).isEqualTo("Thing"); } } diff --git a/src/test/java/com/arangodb/async/example/ExampleBase.java b/src/test/java/com/arangodb/async/example/ExampleBase.java index abf1ffaaa..9ae6e510a 100644 --- a/src/test/java/com/arangodb/async/example/ExampleBase.java +++ b/src/test/java/com/arangodb/async/example/ExampleBase.java @@ -20,11 +20,13 @@ package com.arangodb.async.example; +import com.arangodb.DbName; import com.arangodb.async.ArangoCollectionAsync; import com.arangodb.async.ArangoDBAsync; import com.arangodb.async.ArangoDatabaseAsync; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import java.util.concurrent.ExecutionException; @@ -34,14 +36,14 @@ public class ExampleBase { protected static final String COLLECTION_NAME = "json_example_collection"; - private static final String DB_NAME = "json_example_db"; + private static final DbName DB_NAME = DbName.of("json_example_db"); protected static ArangoDatabaseAsync db; protected static ArangoCollectionAsync collection; private static ArangoDBAsync arangoDB; - @BeforeClass - public static void setUp() throws InterruptedException, ExecutionException { - arangoDB = new ArangoDBAsync.Builder().build(); + @BeforeAll + static void setUp() throws InterruptedException, ExecutionException { + arangoDB = new ArangoDBAsync.Builder().serializer(new ArangoJack()).build(); if (arangoDB.db(DB_NAME).exists().get()) { arangoDB.db(DB_NAME).drop().get(); } @@ -51,8 +53,8 @@ public static void setUp() throws InterruptedException, ExecutionException { collection = db.collection(COLLECTION_NAME); } - @AfterClass - public static void tearDown() throws InterruptedException, ExecutionException { + @AfterAll + static void tearDown() throws InterruptedException, ExecutionException { db.drop().get(); arangoDB.shutdown(); } diff --git a/src/test/java/com/arangodb/async/example/document/AqlQueryWithSpecialReturnTypesExample.java b/src/test/java/com/arangodb/async/example/document/AqlQueryWithSpecialReturnTypesExample.java deleted file mode 100644 index 1bc7c7c62..000000000 --- a/src/test/java/com/arangodb/async/example/document/AqlQueryWithSpecialReturnTypesExample.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * 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 - * - * 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. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.async.example.document; - -import com.arangodb.async.example.ExampleBase; -import com.arangodb.entity.BaseDocument; -import com.arangodb.util.MapBuilder; -import com.arangodb.velocypack.VPackSlice; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import static org.hamcrest.Matchers.*; -import static org.hamcrest.MatcherAssert.assertThat; - -/** - * @author Mark Vollmary - */ -public class AqlQueryWithSpecialReturnTypesExample extends ExampleBase { - - @BeforeClass - public static void before() throws InterruptedException, ExecutionException { - createExamples(); - } - - private static void createExamples() throws InterruptedException, ExecutionException { - for (int i = 0; i < 100; i++) { - final BaseDocument value = new BaseDocument(); - value.addAttribute("name", "TestUser" + i); - value.addAttribute("gender", (i % 2) == 0 ? Gender.MALE : Gender.FEMALE); - value.addAttribute("age", i + 10); - db.collection(COLLECTION_NAME).insertDocument(value).get(); - } - } - - @Test - public void aqlWithLimitQueryAsVPackObject() throws InterruptedException, ExecutionException { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - db.query(query, bindVars, null, VPackSlice.class) - .whenComplete((cursor, ex) -> { - assertThat(cursor, is(notNullValue())); - cursor.forEachRemaining(vpack -> { - assertThat(vpack.get("name").getAsString(), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(vpack.get("gender").getAsString(), is(Gender.FEMALE.name())); - assertThat(vpack.get("age").getAsInt(), isOneOf(21, 23, 25, 27, 29)); - }); - }) - .get(); - } - - @Test - public void aqlWithLimitQueryAsVPackArray() throws InterruptedException, ExecutionException { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - db.query(query, bindVars, null, VPackSlice.class) - .whenComplete((cursor, ex) -> { - assertThat(cursor, is(notNullValue())); - cursor.forEachRemaining(vpack -> { - assertThat(vpack.get(0).getAsString(), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(vpack.get(1).getAsString(), is(Gender.FEMALE.name())); - assertThat(vpack.get(2).getAsInt(), isOneOf(21, 23, 25, 27, 29)); - }); - }) - .get(); - } - - @Test - public void aqlWithLimitQueryAsMap() throws InterruptedException, ExecutionException { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - db.query(query, bindVars, null, Map.class) - .whenComplete((cursor, ex) -> { - assertThat(cursor, is(notNullValue())); - cursor.forEachRemaining(map -> { - assertThat(map.get("name"), is(notNullValue())); - assertThat(String.valueOf(map.get("name")), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(map.get("gender"), is(notNullValue())); - assertThat(String.valueOf(map.get("gender")), is(Gender.FEMALE.name())); - assertThat(map.get("age"), is(notNullValue())); - assertThat(Long.valueOf(map.get("age").toString()), isOneOf(21L, 23L, 25L, 27L, 29L)); - }); - }) - .get(); - } - - @Test - public void aqlWithLimitQueryAsList() throws InterruptedException, ExecutionException { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - db.query(query, bindVars, null, List.class) - .whenComplete((cursor, ex) -> { - assertThat(cursor, is(notNullValue())); - cursor.forEachRemaining(list -> { - assertThat(list.get(0), is(notNullValue())); - assertThat(String.valueOf(list.get(0)), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(list.get(1), is(notNullValue())); - assertThat(Gender.valueOf(String.valueOf(list.get(1))), is(Gender.FEMALE)); - assertThat(list.get(2), is(notNullValue())); - assertThat(Long.valueOf(String.valueOf(list.get(2))), isOneOf(21L, 23L, 25L, 27L, 29L)); - }); - }) - .get(); - } - - public enum Gender { - MALE, FEMALE - } -} diff --git a/src/test/java/com/arangodb/async/example/document/AqlQueryWithSpecialReturnTypesExampleTest.java b/src/test/java/com/arangodb/async/example/document/AqlQueryWithSpecialReturnTypesExampleTest.java new file mode 100644 index 000000000..a5ab9ab14 --- /dev/null +++ b/src/test/java/com/arangodb/async/example/document/AqlQueryWithSpecialReturnTypesExampleTest.java @@ -0,0 +1,122 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * 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 + * + * 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. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.async.example.document; + +import com.arangodb.async.example.ExampleBase; +import com.arangodb.entity.BaseDocument; +import com.arangodb.util.MapBuilder; +import com.arangodb.velocypack.VPackSlice; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; + +import static org.assertj.core.api.Assertions.assertThat; + + +/** + * @author Mark Vollmary + */ +class AqlQueryWithSpecialReturnTypesExampleTest extends ExampleBase { + + @BeforeAll + static void before() throws InterruptedException, ExecutionException { + createExamples(); + } + + private static void createExamples() throws InterruptedException, ExecutionException { + for (int i = 0; i < 100; i++) { + final BaseDocument value = new BaseDocument(); + value.addAttribute("name", "TestUser" + i); + value.addAttribute("gender", (i % 2) == 0 ? Gender.MALE : Gender.FEMALE); + value.addAttribute("age", i + 10); + db.collection(COLLECTION_NAME).insertDocument(value).get(); + } + } + + @Test + void aqlWithLimitQueryAsVPackObject() throws InterruptedException, ExecutionException { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + db.query(query, bindVars, null, VPackSlice.class) + .whenComplete((cursor, ex) -> cursor.forEachRemaining(vpack -> { + assertThat(vpack.get("name").getAsString()).isIn("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19"); + assertThat(vpack.get("gender").getAsString()).isEqualTo(Gender.FEMALE.name()); + assertThat(vpack.get("age").getAsInt()).isIn(21, 23, 25, 27, 29); + })) + .get(); + } + + @Test + void aqlWithLimitQueryAsVPackArray() throws InterruptedException, ExecutionException { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + db.query(query, bindVars, null, VPackSlice.class) + .whenComplete((cursor, ex) -> cursor.forEachRemaining(vpack -> { + assertThat(vpack.get(0).getAsString()).isIn("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19"); + assertThat(vpack.get(1).getAsString()).isEqualTo(Gender.FEMALE.name()); + assertThat(vpack.get(2).getAsInt()).isIn(21, 23, 25, 27, 29); + })) + .get(); + } + + @Test + void aqlWithLimitQueryAsMap() throws InterruptedException, ExecutionException { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + db.query(query, bindVars, null, Map.class) + .whenComplete((cursor, ex) -> cursor.forEachRemaining(map -> { + assertThat(map.get("name")).isNotNull(); + assertThat(String.valueOf(map.get("name"))).isIn("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19"); + assertThat(map.get("gender")).isNotNull(); + assertThat(String.valueOf(map.get("gender"))).isEqualTo(Gender.FEMALE.name()); + assertThat(map.get("age")).isNotNull(); + assertThat(Long.valueOf(map.get("age").toString())).isIn(21L, 23L, 25L, 27L, 29L); + })) + .get(); + } + + @Test + void aqlWithLimitQueryAsList() throws InterruptedException, ExecutionException { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + db.query(query, bindVars, null, List.class) + .whenComplete((cursor, ex) -> cursor.forEachRemaining(list -> { + assertThat(list.get(0)).isNotNull(); + assertThat(String.valueOf(list.get(0))).isIn("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19"); + assertThat(list.get(1)).isNotNull(); + assertThat(Gender.valueOf(String.valueOf(list.get(1)))).isEqualTo(Gender.FEMALE); + assertThat(list.get(2)).isNotNull(); + assertThat(Long.valueOf(String.valueOf(list.get(2)))).isIn(21L, 23L, 25L, 27L, 29L); + })) + .get(); + } + + public enum Gender { + MALE, FEMALE + } +} diff --git a/src/test/java/com/arangodb/async/example/document/GetDocumentExample.java b/src/test/java/com/arangodb/async/example/document/GetDocumentExampleTest.java similarity index 60% rename from src/test/java/com/arangodb/async/example/document/GetDocumentExample.java rename to src/test/java/com/arangodb/async/example/document/GetDocumentExampleTest.java index c71be2c8d..0e7ae4c72 100644 --- a/src/test/java/com/arangodb/async/example/document/GetDocumentExample.java +++ b/src/test/java/com/arangodb/async/example/document/GetDocumentExampleTest.java @@ -24,24 +24,24 @@ import com.arangodb.entity.BaseDocument; import com.arangodb.entity.DocumentCreateEntity; import com.arangodb.velocypack.VPackSlice; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + import java.util.concurrent.ExecutionException; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Mark Vollmary */ -public class GetDocumentExample extends ExampleBase { +class GetDocumentExampleTest extends ExampleBase { private static String key = null; - @BeforeClass - public static void before() throws InterruptedException, ExecutionException { + @BeforeAll + static void before() throws InterruptedException, ExecutionException { final BaseDocument value = new BaseDocument(); value.addAttribute("foo", "bar"); final DocumentCreateEntity doc = collection.insertDocument(value).get(); @@ -49,44 +49,44 @@ public static void before() throws InterruptedException, ExecutionException { } @Test - public void getAsBean() throws InterruptedException, ExecutionException { + void getAsBean() throws InterruptedException, ExecutionException { collection.getDocument(key, TestEntity.class) .whenComplete((doc, ex) -> { - assertThat(doc, is(notNullValue())); - assertThat(doc.getFoo(), is("bar")); + assertThat(doc).isNotNull(); + assertThat(doc.getFoo()).isEqualTo("bar"); }) .get(); } @Test - public void getAsBaseDocument() throws InterruptedException, ExecutionException { + void getAsBaseDocument() throws InterruptedException, ExecutionException { collection.getDocument(key, BaseDocument.class) .whenComplete((doc, ex) -> { - assertThat(doc, is(notNullValue())); - assertThat(doc.getAttribute("foo"), is(notNullValue())); - assertThat(String.valueOf(doc.getAttribute("foo")), is("bar")); + assertThat(doc).isNotNull(); + assertThat(doc.getAttribute("foo")).isNotNull(); + assertThat(String.valueOf(doc.getAttribute("foo"))).isEqualTo("bar"); }) .get(); } @Test - public void getAsVPack() throws InterruptedException, ExecutionException { + void getAsVPack() throws InterruptedException, ExecutionException { collection.getDocument(key, VPackSlice.class) .whenComplete((doc, ex) -> { - assertThat(doc, is(notNullValue())); - assertThat(doc.get("foo").isString(), is(true)); - assertThat(doc.get("foo").getAsString(), is("bar")); + assertThat(doc).isNotNull(); + assertThat(doc.get("foo").isString()).isEqualTo(true); + assertThat(doc.get("foo").getAsString()).isEqualTo("bar"); }) .get(); } @Test - public void getAsJson() throws InterruptedException, ExecutionException { + void getAsJson() throws InterruptedException, ExecutionException { collection.getDocument(key, String.class) .whenComplete((doc, ex) -> { - assertThat(doc, is(notNullValue())); - assertThat(doc.contains("foo"), is(true)); - assertThat(doc.contains("bar"), is(true)); + assertThat(doc).isNotNull(); + assertThat(doc.contains("foo")).isEqualTo(true); + assertThat(doc.contains("bar")).isEqualTo(true); }) .get(); } diff --git a/src/test/java/com/arangodb/async/example/document/ImportDocumentExample.java b/src/test/java/com/arangodb/async/example/document/ImportDocumentExampleTest.java similarity index 94% rename from src/test/java/com/arangodb/async/example/document/ImportDocumentExample.java rename to src/test/java/com/arangodb/async/example/document/ImportDocumentExampleTest.java index bb33be74b..d2df0678c 100644 --- a/src/test/java/com/arangodb/async/example/document/ImportDocumentExample.java +++ b/src/test/java/com/arangodb/async/example/document/ImportDocumentExampleTest.java @@ -23,7 +23,8 @@ import com.arangodb.async.example.ExampleBase; import com.arangodb.entity.DocumentImportEntity; import com.arangodb.model.DocumentImportOptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.util.List; import java.util.UUID; @@ -34,17 +35,17 @@ import java.util.stream.IntStream; import java.util.stream.Stream; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Michele Rastelli */ -public class ImportDocumentExample extends ExampleBase { +class ImportDocumentExampleTest extends ExampleBase { private static final int MAX_PENDING_REQUESTS = 10; @Test - public void importDocument() { + void importDocument() { AtomicLong pendingReqsCount = new AtomicLong(); Stream> chunks = IntStream.range(0, 100) diff --git a/src/test/java/com/arangodb/async/example/document/InsertDocumentExample.java b/src/test/java/com/arangodb/async/example/document/InsertDocumentExampleTest.java similarity index 74% rename from src/test/java/com/arangodb/async/example/document/InsertDocumentExample.java rename to src/test/java/com/arangodb/async/example/document/InsertDocumentExampleTest.java index 6d36e4684..abaedab49 100644 --- a/src/test/java/com/arangodb/async/example/document/InsertDocumentExample.java +++ b/src/test/java/com/arangodb/async/example/document/InsertDocumentExampleTest.java @@ -24,48 +24,48 @@ import com.arangodb.entity.BaseDocument; import com.arangodb.velocypack.VPackBuilder; import com.arangodb.velocypack.ValueType; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.util.concurrent.ExecutionException; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Mark Vollmary */ -public class InsertDocumentExample extends ExampleBase { +class InsertDocumentExampleTest extends ExampleBase { @Test - public void insertBean() throws ExecutionException, InterruptedException { + void insertBean() throws ExecutionException, InterruptedException { collection.insertDocument(new TestEntity("bar")) - .whenComplete((doc, ex) -> assertThat(doc.getKey(), is(notNullValue()))) + .whenComplete((doc, ex) -> assertThat(doc.getKey()).isNotNull()) .get(); } @Test - public void insertBaseDocument() throws ExecutionException, InterruptedException { + void insertBaseDocument() throws ExecutionException, InterruptedException { final BaseDocument value = new BaseDocument(); value.addAttribute("foo", "bar"); collection.insertDocument(value) - .whenComplete((doc, ex) -> assertThat(doc.getKey(), is(notNullValue()))) + .whenComplete((doc, ex) -> assertThat(doc.getKey()).isNotNull()) .get(); } @Test - public void insertVPack() throws ExecutionException, InterruptedException { + void insertVPack() throws ExecutionException, InterruptedException { final VPackBuilder builder = new VPackBuilder(); builder.add(ValueType.OBJECT).add("foo", "bar").close(); collection.insertDocument(builder.slice()) - .whenComplete((doc, ex) -> assertThat(doc.getKey(), is(notNullValue()))) + .whenComplete((doc, ex) -> assertThat(doc.getKey()).isNotNull()) .get(); } @Test - public void insertJson() throws ExecutionException, InterruptedException { + void insertJson() throws ExecutionException, InterruptedException { collection.insertDocument("{\"foo\":\"bar\"}") - .whenComplete((doc, ex) -> assertThat(doc.getKey(), is(notNullValue()))) + .whenComplete((doc, ex) -> assertThat(doc.getKey()).isNotNull()) .get(); } diff --git a/src/test/java/com/arangodb/async/example/document/TestEntity.java b/src/test/java/com/arangodb/async/example/document/TestEntity.java index 2e1330b97..d33126814 100644 --- a/src/test/java/com/arangodb/async/example/document/TestEntity.java +++ b/src/test/java/com/arangodb/async/example/document/TestEntity.java @@ -41,7 +41,7 @@ public String getFoo() { return foo; } - public void setFoo(final String foo) { + void setFoo(final String foo) { this.foo = foo; } diff --git a/src/test/java/com/arangodb/async/example/graph/AQLActorsAndMoviesExample.java b/src/test/java/com/arangodb/async/example/graph/AQLActorsAndMoviesExampleTest.java similarity index 82% rename from src/test/java/com/arangodb/async/example/graph/AQLActorsAndMoviesExample.java rename to src/test/java/com/arangodb/async/example/graph/AQLActorsAndMoviesExampleTest.java index 9aefb8bea..d0e293a62 100644 --- a/src/test/java/com/arangodb/async/example/graph/AQLActorsAndMoviesExample.java +++ b/src/test/java/com/arangodb/async/example/graph/AQLActorsAndMoviesExampleTest.java @@ -20,6 +20,7 @@ package com.arangodb.async.example.graph; +import com.arangodb.DbName; import com.arangodb.async.ArangoCollectionAsync; import com.arangodb.async.ArangoCursorAsync; import com.arangodb.async.ArangoDBAsync; @@ -28,16 +29,17 @@ import com.arangodb.entity.BaseEdgeDocument; import com.arangodb.entity.CollectionType; import com.arangodb.entity.DocumentCreateEntity; +import com.arangodb.mapping.ArangoJack; import com.arangodb.model.CollectionCreateOptions; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Mark Vollmary @@ -45,15 +47,15 @@ * Actors and Movies Database */ @SuppressWarnings("JavaDoc") -public class AQLActorsAndMoviesExample { +class AQLActorsAndMoviesExampleTest { - private static final String TEST_DB = "actors_movies_test_db"; + private static final DbName TEST_DB = DbName.of("actors_movies_test_db"); private static ArangoDBAsync arangoDB; private static ArangoDatabaseAsync db; - @BeforeClass - public static void setUp() throws InterruptedException, ExecutionException { - arangoDB = new ArangoDBAsync.Builder().build(); + @BeforeAll + static void setUp() throws InterruptedException, ExecutionException { + arangoDB = new ArangoDBAsync.Builder().serializer(new ArangoJack()).build(); if (arangoDB.db(TEST_DB).exists().get()) { arangoDB.db(TEST_DB).drop().get(); } @@ -62,8 +64,8 @@ public static void setUp() throws InterruptedException, ExecutionException { createData(); } - @AfterClass - public static void tearDown() throws InterruptedException, ExecutionException { + @AfterAll + static void tearDown() throws InterruptedException, ExecutionException { db.drop().get(); arangoDB.shutdown(); } @@ -312,12 +314,11 @@ private static void createData() throws InterruptedException, ExecutionException * Example Queries on an Actors and Movies Database */ @Test - public void allActorsActsInMovie1or2() throws InterruptedException, ExecutionException { + void allActorsActsInMovie1or2() throws InterruptedException, ExecutionException { final CompletableFuture> f = db.query( "WITH actors, movies FOR x IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN x._id", null, null, String.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining(), - hasItems("actors/Keanu", "actors/Hugo", "actors/Emil", "actors/Carrie", "actors/Laurence"))).get(); + f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains("actors/Keanu", "actors/Hugo", "actors/Emil", "actors/Carrie", "actors/Laurence")).get(); } /** @@ -328,12 +329,13 @@ public void allActorsActsInMovie1or2() throws InterruptedException, ExecutionExc * Example Queries on an Actors and Movies Database */ @Test - public void allActorsActsInMovie1or2UnionDistinct() throws InterruptedException, ExecutionException { + void allActorsActsInMovie1or2UnionDistinct() throws InterruptedException, ExecutionException { final CompletableFuture> f = db.query( "WITH actors, movies FOR x IN UNION_DISTINCT ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", null, null, String.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining(), hasItems("actors/Emil", "actors/Hugo", "actors/Carrie", - "actors/Laurence", "actors/Keanu", "actors/Al", "actors/Charlize"))).get(); + f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains( + "actors/Emil", "actors/Hugo", "actors/Carrie", + "actors/Laurence", "actors/Keanu", "actors/Al", "actors/Charlize")).get(); } /** @@ -344,11 +346,11 @@ public void allActorsActsInMovie1or2UnionDistinct() throws InterruptedException, * Example Queries on an Actors and Movies Database */ @Test - public void allActorsActsInMovie1and2() throws InterruptedException, ExecutionException { + void allActorsActsInMovie1and2() throws InterruptedException, ExecutionException { final CompletableFuture> f = db.query( "WITH actors, movies FOR x IN INTERSECTION ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", null, null, String.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining(), hasItems("actors/Keanu"))).get(); + f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains("actors/Keanu")).get(); } /** @@ -359,12 +361,11 @@ public void allActorsActsInMovie1and2() throws InterruptedException, ExecutionEx * Example Queries on an Actors and Movies Database */ @Test - public void allMoviesBetweenActor1andActor2() throws InterruptedException, ExecutionException { + void allMoviesBetweenActor1andActor2() throws InterruptedException, ExecutionException { final CompletableFuture> f = db.query( "WITH actors, movies FOR x IN INTERSECTION ((FOR y IN ANY 'actors/Hugo' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'actors/Keanu' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", null, null, String.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining(), - hasItems("movies/TheMatrixRevolutions", "movies/TheMatrixReloaded", "movies/TheMatrix"))).get(); + f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains("movies/TheMatrixRevolutions", "movies/TheMatrixReloaded", "movies/TheMatrix")).get(); } /** @@ -375,14 +376,14 @@ public void allMoviesBetweenActor1andActor2() throws InterruptedException, Execu * Example Queries on an Actors and Movies Database */ @Test - public void allActorsWhoActedIn3orMoreMovies() throws InterruptedException, ExecutionException { + void allActorsWhoActedIn3orMoreMovies() throws InterruptedException, ExecutionException { final CompletableFuture> f = db.query( "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter FILTER counter >= 3 RETURN {actor: actor, movies: counter}", null, null, Actor.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining(), - hasItems(new Actor("actors/Carrie", 3), new Actor("actors/CubaG", 4), new Actor("actors/Hugo", 3), - new Actor("actors/Keanu", 4), new Actor("actors/Laurence", 3), new Actor("actors/MegR", 5), - new Actor("actors/TomC", 3), new Actor("actors/TomH", 3)))).get(); + f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains( + new Actor("actors/Carrie", 3), new Actor("actors/CubaG", 4), new Actor("actors/Hugo", 3), + new Actor("actors/Keanu", 4), new Actor("actors/Laurence", 3), new Actor("actors/MegR", 5), + new Actor("actors/TomC", 3), new Actor("actors/TomH", 3))).get(); } /** @@ -393,12 +394,11 @@ public void allActorsWhoActedIn3orMoreMovies() throws InterruptedException, Exec * Example Queries on an Actors and Movies Database */ @Test - public void allMoviesWhereExactly6ActorsActedIn() throws InterruptedException, ExecutionException { + void allMoviesWhereExactly6ActorsActedIn() throws InterruptedException, ExecutionException { final CompletableFuture> f = db.query( "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter FILTER counter == 6 RETURN movie", null, null, String.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining(), - hasItems("movies/SleeplessInSeattle", "movies/TopGun", "movies/YouveGotMail"))).get(); + f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains("movies/SleeplessInSeattle", "movies/TopGun", "movies/YouveGotMail")).get(); } /** @@ -409,19 +409,19 @@ public void allMoviesWhereExactly6ActorsActedIn() throws InterruptedException, E * Example Queries on an Actors and Movies Database */ @Test - public void theNumberOfActorsByMovie() throws InterruptedException, ExecutionException { + void theNumberOfActorsByMovie() throws InterruptedException, ExecutionException { final CompletableFuture> f = db.query( "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter RETURN {movie: movie, actors: counter}", null, null, Movie.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining(), - hasItems(new Movie("movies/AFewGoodMen", 11), new Movie("movies/AsGoodAsItGets", 4), - new Movie("movies/JerryMaguire", 9), new Movie("movies/JoeVersustheVolcano", 3), - new Movie("movies/SleeplessInSeattle", 6), new Movie("movies/SnowFallingonCedars", 4), - new Movie("movies/StandByMe", 7), new Movie("movies/TheDevilsAdvocate", 3), - new Movie("movies/TheMatrix", 5), new Movie("movies/TheMatrixReloaded", 4), - new Movie("movies/TheMatrixRevolutions", 4), new Movie("movies/TopGun", 6), - new Movie("movies/WhatDreamsMayCome", 5), new Movie("movies/WhenHarryMetSally", 4), - new Movie("movies/YouveGotMail", 6)))).get(); + f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains( + new Movie("movies/AFewGoodMen", 11), new Movie("movies/AsGoodAsItGets", 4), + new Movie("movies/JerryMaguire", 9), new Movie("movies/JoeVersustheVolcano", 3), + new Movie("movies/SleeplessInSeattle", 6), new Movie("movies/SnowFallingonCedars", 4), + new Movie("movies/StandByMe", 7), new Movie("movies/TheDevilsAdvocate", 3), + new Movie("movies/TheMatrix", 5), new Movie("movies/TheMatrixReloaded", 4), + new Movie("movies/TheMatrixRevolutions", 4), new Movie("movies/TopGun", 6), + new Movie("movies/WhatDreamsMayCome", 5), new Movie("movies/WhenHarryMetSally", 4), + new Movie("movies/YouveGotMail", 6))).get(); } /** @@ -432,30 +432,30 @@ public void theNumberOfActorsByMovie() throws InterruptedException, ExecutionExc * Example Queries on an Actors and Movies Database */ @Test - public void theNumberOfMoviesByActor() throws InterruptedException, ExecutionException { + void theNumberOfMoviesByActor() throws InterruptedException, ExecutionException { final CompletableFuture> f = db.query( "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", null, null, Actor.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining(), - hasItems(new Actor("actors/Al", 1), new Actor("actors/AnnabellaS", 1), new Actor("actors/AnthonyE", 1), - new Actor("actors/BillPull", 1), new Actor("actors/BillyC", 1), new Actor("actors/BonnieH", 1), - new Actor("actors/BrunoK", 1), new Actor("actors/Carrie", 3), new Actor("actors/CarrieF", 1), - new Actor("actors/Charlize", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CoreyF", 1), - new Actor("actors/CubaG", 4), new Actor("actors/DaveC", 1), new Actor("actors/DemiM", 1), - new Actor("actors/Emil", 1), new Actor("actors/EthanH", 1), new Actor("actors/GregK", 2), - new Actor("actors/HelenH", 1), new Actor("actors/Hugo", 3), new Actor("actors/JackN", 2), - new Actor("actors/JamesC", 1), new Actor("actors/JamesM", 1), new Actor("actors/JayM", 1), - new Actor("actors/JerryO", 2), new Actor("actors/JohnC", 1), new Actor("actors/JonathanL", 1), - new Actor("actors/JTW", 1), new Actor("actors/Keanu", 4), new Actor("actors/KellyM", 1), - new Actor("actors/KellyP", 1), new Actor("actors/KevinB", 1), new Actor("actors/KevinP", 1), - new Actor("actors/KieferS", 2), new Actor("actors/Laurence", 3), new Actor("actors/MarshallB", 1), - new Actor("actors/MaxS", 2), new Actor("actors/MegR", 5), new Actor("actors/Nathan", 1), - new Actor("actors/NoahW", 1), new Actor("actors/ParkerP", 1), new Actor("actors/ReginaK", 1), - new Actor("actors/ReneeZ", 1), new Actor("actors/RickY", 1), new Actor("actors/RitaW", 1), - new Actor("actors/RiverP", 1), new Actor("actors/Robin", 1), new Actor("actors/RosieO", 1), - new Actor("actors/SteveZ", 1), new Actor("actors/TomC", 3), new Actor("actors/TomH", 3), - new Actor("actors/TomS", 1), new Actor("actors/ValK", 1), new Actor("actors/VictorG", 1), - new Actor("actors/WernerH", 1), new Actor("actors/WilW", 1)))).get(); + f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains( + new Actor("actors/Al", 1), new Actor("actors/AnnabellaS", 1), new Actor("actors/AnthonyE", 1), + new Actor("actors/BillPull", 1), new Actor("actors/BillyC", 1), new Actor("actors/BonnieH", 1), + new Actor("actors/BrunoK", 1), new Actor("actors/Carrie", 3), new Actor("actors/CarrieF", 1), + new Actor("actors/Charlize", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CoreyF", 1), + new Actor("actors/CubaG", 4), new Actor("actors/DaveC", 1), new Actor("actors/DemiM", 1), + new Actor("actors/Emil", 1), new Actor("actors/EthanH", 1), new Actor("actors/GregK", 2), + new Actor("actors/HelenH", 1), new Actor("actors/Hugo", 3), new Actor("actors/JackN", 2), + new Actor("actors/JamesC", 1), new Actor("actors/JamesM", 1), new Actor("actors/JayM", 1), + new Actor("actors/JerryO", 2), new Actor("actors/JohnC", 1), new Actor("actors/JonathanL", 1), + new Actor("actors/JTW", 1), new Actor("actors/Keanu", 4), new Actor("actors/KellyM", 1), + new Actor("actors/KellyP", 1), new Actor("actors/KevinB", 1), new Actor("actors/KevinP", 1), + new Actor("actors/KieferS", 2), new Actor("actors/Laurence", 3), new Actor("actors/MarshallB", 1), + new Actor("actors/MaxS", 2), new Actor("actors/MegR", 5), new Actor("actors/Nathan", 1), + new Actor("actors/NoahW", 1), new Actor("actors/ParkerP", 1), new Actor("actors/ReginaK", 1), + new Actor("actors/ReneeZ", 1), new Actor("actors/RickY", 1), new Actor("actors/RitaW", 1), + new Actor("actors/RiverP", 1), new Actor("actors/Robin", 1), new Actor("actors/RosieO", 1), + new Actor("actors/SteveZ", 1), new Actor("actors/TomC", 3), new Actor("actors/TomH", 3), + new Actor("actors/TomS", 1), new Actor("actors/ValK", 1), new Actor("actors/VictorG", 1), + new Actor("actors/WernerH", 1), new Actor("actors/WilW", 1))).get(); } /** @@ -466,17 +466,17 @@ public void theNumberOfMoviesByActor() throws InterruptedException, ExecutionExc * Example Queries on an Actors and Movies Database */ @Test - public void theNumberOfMoviesActedInBetween2005and2010byActor() throws InterruptedException, ExecutionException { + void theNumberOfMoviesActedInBetween2005and2010byActor() throws InterruptedException, ExecutionException { final CompletableFuture> f = db.query( "FOR x IN actsIn FILTER x.year >= 1990 && x.year <= 1995 COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", null, null, Actor.class); - f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining(), - hasItems(new Actor("actors/BillPull", 1), new Actor("actors/ChristopherG", 1), - new Actor("actors/CubaG", 1), new Actor("actors/DemiM", 1), new Actor("actors/JackN", 1), - new Actor("actors/JamesM", 1), new Actor("actors/JTW", 1), new Actor("actors/KevinB", 1), - new Actor("actors/KieferS", 1), new Actor("actors/MegR", 2), new Actor("actors/Nathan", 1), - new Actor("actors/NoahW", 1), new Actor("actors/RitaW", 1), new Actor("actors/RosieO", 1), - new Actor("actors/TomC", 1), new Actor("actors/TomH", 2), new Actor("actors/VictorG", 1)))).get(); + f.whenComplete((cursor, ex) -> assertThat(cursor.asListRemaining()).contains( + new Actor("actors/BillPull", 1), new Actor("actors/ChristopherG", 1), + new Actor("actors/CubaG", 1), new Actor("actors/DemiM", 1), new Actor("actors/JackN", 1), + new Actor("actors/JamesM", 1), new Actor("actors/JTW", 1), new Actor("actors/KevinB", 1), + new Actor("actors/KieferS", 1), new Actor("actors/MegR", 2), new Actor("actors/Nathan", 1), + new Actor("actors/NoahW", 1), new Actor("actors/RitaW", 1), new Actor("actors/RosieO", 1), + new Actor("actors/TomC", 1), new Actor("actors/TomH", 2), new Actor("actors/VictorG", 1))).get(); } @SuppressWarnings("WeakerAccess") diff --git a/src/test/java/com/arangodb/async/example/graph/BaseGraphTest.java b/src/test/java/com/arangodb/async/example/graph/BaseGraphTest.java index ac5621891..5496496f5 100644 --- a/src/test/java/com/arangodb/async/example/graph/BaseGraphTest.java +++ b/src/test/java/com/arangodb/async/example/graph/BaseGraphTest.java @@ -20,12 +20,14 @@ package com.arangodb.async.example.graph; +import com.arangodb.DbName; import com.arangodb.async.ArangoDBAsync; import com.arangodb.async.ArangoDatabaseAsync; import com.arangodb.entity.EdgeDefinition; import com.arangodb.entity.VertexEntity; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import java.util.ArrayList; import java.util.Collection; @@ -36,17 +38,17 @@ */ public abstract class BaseGraphTest { - private static final String TEST_DB = "java_driver_graph_test_db"; + private static final DbName TEST_DB = DbName.of("java_driver_graph_test_db"); private static final String GRAPH_NAME = "traversalGraph"; private static final String EDGE_COLLECTION_NAME = "edges"; - private static final String VERTEXT_COLLECTION_NAME = "circles"; + private static final String VERTEX_COLLECTION_NAME = "circles"; static ArangoDatabaseAsync db; private static ArangoDBAsync arangoDB; - @BeforeClass - public static void init() throws InterruptedException, ExecutionException { + @BeforeAll + static void init() throws InterruptedException, ExecutionException { if (arangoDB == null) { - arangoDB = new ArangoDBAsync.Builder().build(); + arangoDB = new ArangoDBAsync.Builder().serializer(new ArangoJack()).build(); } if (arangoDB.db(TEST_DB).exists().get()) { arangoDB.db(TEST_DB).drop().get(); @@ -56,14 +58,14 @@ public static void init() throws InterruptedException, ExecutionException { final Collection edgeDefinitions = new ArrayList<>(); final EdgeDefinition edgeDefinition = new EdgeDefinition().collection(EDGE_COLLECTION_NAME) - .from(VERTEXT_COLLECTION_NAME).to(VERTEXT_COLLECTION_NAME); + .from(VERTEX_COLLECTION_NAME).to(VERTEX_COLLECTION_NAME); edgeDefinitions.add(edgeDefinition); db.createGraph(GRAPH_NAME, edgeDefinitions, null).get(); addExampleElements(); } - @AfterClass - public static void shutdown() throws InterruptedException, ExecutionException { + @AfterAll + static void shutdown() throws InterruptedException, ExecutionException { arangoDB.db(TEST_DB).drop().get(); arangoDB.shutdown(); arangoDB = null; @@ -106,7 +108,7 @@ private static void saveEdge(final CircleEdge edge) private static VertexEntity createVertex(final Circle vertex) throws InterruptedException, ExecutionException { - return db.graph(GRAPH_NAME).vertexCollection(VERTEXT_COLLECTION_NAME).insertVertex(vertex).get(); + return db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME).insertVertex(vertex).get(); } } diff --git a/src/test/java/com/arangodb/async/example/graph/Circle.java b/src/test/java/com/arangodb/async/example/graph/Circle.java index b37714386..ef4ca66da 100644 --- a/src/test/java/com/arangodb/async/example/graph/Circle.java +++ b/src/test/java/com/arangodb/async/example/graph/Circle.java @@ -27,7 +27,7 @@ * @author a-brandt */ @SuppressWarnings({"WeakerAccess", "unused"}) -public class Circle { +class Circle { @DocumentField(Type.ID) private String id; @@ -49,7 +49,7 @@ public String getId() { return id; } - public void setId(String id) { + void setId(String id) { this.id = id; } @@ -57,7 +57,7 @@ public String getKey() { return key; } - public void setKey(String key) { + void setKey(String key) { this.key = key; } @@ -65,7 +65,7 @@ public String getRevision() { return revision; } - public void setRevision(String revision) { + void setRevision(String revision) { this.revision = revision; } @@ -73,7 +73,7 @@ public String getLabel() { return label; } - public void setLabel(String label) { + void setLabel(String label) { this.label = label; } diff --git a/src/test/java/com/arangodb/async/example/graph/CircleEdge.java b/src/test/java/com/arangodb/async/example/graph/CircleEdge.java index 970809116..718762ec2 100644 --- a/src/test/java/com/arangodb/async/example/graph/CircleEdge.java +++ b/src/test/java/com/arangodb/async/example/graph/CircleEdge.java @@ -27,7 +27,7 @@ * @author a-brandt */ @SuppressWarnings({"WeakerAccess", "unused"}) -public class CircleEdge { +class CircleEdge { @DocumentField(Type.ID) private String id; @@ -61,7 +61,7 @@ public String getId() { return id; } - public void setId(String id) { + void setId(String id) { this.id = id; } @@ -69,7 +69,7 @@ public String getKey() { return key; } - public void setKey(String key) { + void setKey(String key) { this.key = key; } @@ -77,7 +77,7 @@ public String getRevision() { return revision; } - public void setRevision(String revision) { + void setRevision(String revision) { this.revision = revision; } @@ -85,7 +85,7 @@ public String getFrom() { return from; } - public void setFrom(String from) { + void setFrom(String from) { this.from = from; } @@ -93,7 +93,7 @@ public String getTo() { return to; } - public void setTo(String to) { + void setTo(String to) { this.to = to; } @@ -101,7 +101,7 @@ public Boolean getTheFalse() { return theFalse; } - public void setTheFalse(Boolean theFalse) { + void setTheFalse(Boolean theFalse) { this.theFalse = theFalse; } @@ -109,7 +109,7 @@ public Boolean getTheTruth() { return theTruth; } - public void setTheTruth(Boolean theTruth) { + void setTheTruth(Boolean theTruth) { this.theTruth = theTruth; } @@ -117,7 +117,7 @@ public String getLabel() { return label; } - public void setLabel(String label) { + void setLabel(String label) { this.label = label; } diff --git a/src/test/java/com/arangodb/async/example/graph/GraphTraversalsInAQLExample.java b/src/test/java/com/arangodb/async/example/graph/GraphTraversalsInAQLExampleTest.java similarity index 71% rename from src/test/java/com/arangodb/async/example/graph/GraphTraversalsInAQLExample.java rename to src/test/java/com/arangodb/async/example/graph/GraphTraversalsInAQLExampleTest.java index 51d9702ec..f6b46cbd2 100644 --- a/src/test/java/com/arangodb/async/example/graph/GraphTraversalsInAQLExample.java +++ b/src/test/java/com/arangodb/async/example/graph/GraphTraversalsInAQLExampleTest.java @@ -21,14 +21,14 @@ package com.arangodb.async.example.graph; import com.arangodb.async.ArangoCursorAsync; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.util.Collection; import java.util.concurrent.ExecutionException; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Graph traversals in AQL @@ -36,84 +36,84 @@ * @author a-brandt * @see Graph traversals in AQL */ -public class GraphTraversalsInAQLExample extends BaseGraphTest { +class GraphTraversalsInAQLExampleTest extends BaseGraphTest { @Test - public void queryAllVertices() throws InterruptedException, ExecutionException { + void queryAllVertices() throws InterruptedException, ExecutionException { String queryString = "FOR v IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' RETURN v._key"; ArangoCursorAsync cursor = db.query(queryString, null, null, String.class).get(); Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(10)); + assertThat(result).hasSize(10); queryString = "WITH circles FOR v IN 1..3 OUTBOUND 'circles/A' edges RETURN v._key"; cursor = db.query(queryString, null, null, String.class).get(); result = cursor.asListRemaining(); - assertThat(result.size(), is(10)); + assertThat(result).hasSize(10); } @Test - public void queryDepthTwo() throws InterruptedException, ExecutionException { + void queryDepthTwo() throws InterruptedException, ExecutionException { String queryString = "FOR v IN 2..2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; ArangoCursorAsync cursor = db.query(queryString, null, null, String.class).get(); Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(4)); - assertThat(result, hasItems("C", "E", "H", "J")); + assertThat(result).hasSize(4); + assertThat(result).contains("C", "E", "H", "J"); queryString = "FOR v IN 2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; cursor = db.query(queryString, null, null, String.class).get(); result = cursor.asListRemaining(); - assertThat(result.size(), is(4)); - assertThat(result, hasItems("C", "E", "H", "J")); + assertThat(result).hasSize(4); + assertThat(result).contains("C", "E", "H", "J"); } @Test - public void queryWithFilter() throws InterruptedException, ExecutionException { + void queryWithFilter() throws InterruptedException, ExecutionException { String queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' RETURN v._key"; ArangoCursorAsync cursor = db.query(queryString, null, null, String.class).get(); Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(5)); - assertThat(result, hasItems("B", "C", "D", "E", "F")); + assertThat(result).hasSize(5); + assertThat(result).contains("B", "C", "D", "E", "F"); queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.edges[0].label != 'right_foo' RETURN v._key"; cursor = db.query(queryString, null, null, String.class).get(); result = cursor.asListRemaining(); - assertThat(result.size(), is(5)); - assertThat(result, hasItems("B", "C", "D", "E", "F")); + assertThat(result).hasSize(5); + assertThat(result).contains("B", "C", "D", "E", "F"); queryString = "FOR v,e,p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' FILTER p.edges[1].label != 'left_blub' return v._key"; cursor = db.query(queryString, null, null, String.class).get(); result = cursor.asListRemaining(); - assertThat(result.size(), is(3)); - assertThat(result, hasItems("B", "C", "D")); + assertThat(result).hasSize(3); + assertThat(result).contains("B", "C", "D"); queryString = "FOR v,e,p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' AND p.edges[1].label != 'left_blub' return v._key"; cursor = db.query(queryString, null, null, String.class).get(); result = cursor.asListRemaining(); - assertThat(result.size(), is(3)); - assertThat(result, hasItems("B", "C", "D")); + assertThat(result).hasSize(3); + assertThat(result).contains("B", "C", "D"); } @Test - public void queryOutboundInbound() throws InterruptedException, ExecutionException { + void queryOutboundInbound() throws InterruptedException, ExecutionException { String queryString = "FOR v IN 1..3 OUTBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; ArangoCursorAsync cursor = db.query(queryString, null, null, String.class).get(); Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(1)); - assertThat(result, hasItems("F")); + assertThat(result).hasSize(1); + assertThat(result).contains("F"); queryString = "FOR v IN 1..3 INBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; cursor = db.query(queryString, null, null, String.class).get(); result = cursor.asListRemaining(); - assertThat(result.size(), is(2)); - assertThat(result, hasItems("B", "A")); + assertThat(result).hasSize(2); + assertThat(result).contains("B", "A"); queryString = "FOR v IN 1..3 ANY 'circles/E' GRAPH 'traversalGraph' return v._key"; cursor = db.query(queryString, null, null, String.class).get(); result = cursor.asListRemaining(); - assertThat(result.size(), is(6)); - assertThat(result, hasItems("F", "B", "C", "D", "A", "G")); + assertThat(result).hasSize(6); + assertThat(result).contains("F", "B", "C", "D", "A", "G"); } } diff --git a/src/test/java/com/arangodb/async/example/graph/ShortestPathInAQLExample.java b/src/test/java/com/arangodb/async/example/graph/ShortestPathInAQLExampleTest.java similarity index 74% rename from src/test/java/com/arangodb/async/example/graph/ShortestPathInAQLExample.java rename to src/test/java/com/arangodb/async/example/graph/ShortestPathInAQLExampleTest.java index 0f0e89b86..4d1edf9b4 100644 --- a/src/test/java/com/arangodb/async/example/graph/ShortestPathInAQLExample.java +++ b/src/test/java/com/arangodb/async/example/graph/ShortestPathInAQLExampleTest.java @@ -21,16 +21,16 @@ package com.arangodb.async.example.graph; import com.arangodb.async.ArangoCursorAsync; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutionException; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * Shortest Path in AQL @@ -38,39 +38,39 @@ * @author a-brandt * @see Shortest Path in AQL */ -public class ShortestPathInAQLExample extends BaseGraphTest { +class ShortestPathInAQLExampleTest extends BaseGraphTest { @Test - public void queryShortestPathFromAToD() throws InterruptedException, ExecutionException { + void queryShortestPathFromAToD() throws InterruptedException, ExecutionException { String queryString = "FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' GRAPH 'traversalGraph' RETURN {'vertex': v._key, 'edge': e._key}"; ArangoCursorAsync cursor = db.query(queryString, null, null, Pair.class).get(); final Collection collection = toVertexCollection(cursor); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); + assertThat(collection).hasSize(4); + assertThat(collection).contains("A", "B", "C", "D"); queryString = "WITH circles FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' edges RETURN {'vertex': v._key, 'edge': e._key}"; db.query(queryString, null, null, Pair.class).get(); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); + assertThat(collection).hasSize(4); + assertThat(collection).contains("A", "B", "C", "D"); } @Test - public void queryShortestPathByFilter() throws InterruptedException, ExecutionException { + void queryShortestPathByFilter() throws InterruptedException, ExecutionException { String queryString = "FOR a IN circles FILTER a._key == 'A' FOR d IN circles FILTER d._key == 'D' FOR v, e IN OUTBOUND SHORTEST_PATH a TO d GRAPH 'traversalGraph' RETURN {'vertex':v._key, 'edge':e._key}"; ArangoCursorAsync cursor = db.query(queryString, null, null, Pair.class).get(); final Collection collection = toVertexCollection(cursor); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); + assertThat(collection).hasSize(4); + assertThat(collection).contains("A", "B", "C", "D"); queryString = "FOR a IN circles FILTER a._key == 'A' FOR d IN circles FILTER d._key == 'D' FOR v, e IN OUTBOUND SHORTEST_PATH a TO d edges RETURN {'vertex': v._key, 'edge': e._key}"; db.query(queryString, null, null, Pair.class).get(); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); + assertThat(collection).hasSize(4); + assertThat(collection).contains("A", "B", "C", "D"); } private Collection toVertexCollection(final ArangoCursorAsync cursor) { final List result = new ArrayList<>(); - for (; cursor.hasNext(); ) { + while (cursor.hasNext()) { final Pair pair = cursor.next(); result.add(pair.getVertex()); } @@ -87,7 +87,7 @@ public String getVertex() { return vertex; } - public void setVertex(final String vertex) { + void setVertex(final String vertex) { this.vertex = vertex; } @@ -95,7 +95,7 @@ public String getEdge() { return edge; } - public void setEdge(final String edge) { + void setEdge(final String edge) { this.edge = edge; } diff --git a/src/test/java/com/arangodb/async/example/ssl/SslExample.java b/src/test/java/com/arangodb/async/example/ssl/SslExampleTest.java similarity index 80% rename from src/test/java/com/arangodb/async/example/ssl/SslExample.java rename to src/test/java/com/arangodb/async/example/ssl/SslExampleTest.java index e7b3b2148..68d19f0d6 100644 --- a/src/test/java/com/arangodb/async/example/ssl/SslExample.java +++ b/src/test/java/com/arangodb/async/example/ssl/SslExampleTest.java @@ -22,22 +22,24 @@ import com.arangodb.async.ArangoDBAsync; import com.arangodb.entity.ArangoDBVersion; -import org.junit.Ignore; -import org.junit.Test; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import java.security.KeyStore; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Mark Vollmary */ -public class SslExample { +@EnabledIfSystemProperty(named = "SslTest", matches = "true") +class SslExampleTest { /*- * a SSL trust store @@ -52,8 +54,7 @@ public class SslExample { private static final String SSL_TRUSTSTORE_PASSWORD = "12345678"; @Test - @Ignore - public void connect() throws Exception { + void connect() throws Exception { final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray()); @@ -67,10 +68,10 @@ public void connect() throws Exception { sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder() - .loadProperties(SslExample.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) - .sslContext(sc).build(); + .loadProperties(SslExampleTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) + .sslContext(sc).serializer(new ArangoJack()).build(); final ArangoDBVersion version = arangoDB.getVersion().get(); - assertThat(version, is(notNullValue())); + assertThat(version).isNotNull(); } } diff --git a/src/test/java/com/arangodb/async/example/velocypack/VPackExample.java b/src/test/java/com/arangodb/async/example/velocypack/VPackExampleTest.java similarity index 73% rename from src/test/java/com/arangodb/async/example/velocypack/VPackExample.java rename to src/test/java/com/arangodb/async/example/velocypack/VPackExampleTest.java index 12e57cad9..a2a91781b 100644 --- a/src/test/java/com/arangodb/async/example/velocypack/VPackExample.java +++ b/src/test/java/com/arangodb/async/example/velocypack/VPackExampleTest.java @@ -24,21 +24,22 @@ import com.arangodb.velocypack.VPackSlice; import com.arangodb.velocypack.ValueType; import com.arangodb.velocypack.exception.VPackException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.util.Iterator; import java.util.Map.Entry; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Mark Vollmary */ -public class VPackExample { +class VPackExampleTest { @Test - public void buildObject() throws VPackException { + void buildObject() throws VPackException { final VPackBuilder builder = new VPackBuilder(); builder.add(ValueType.OBJECT);// object start builder.add("foo", 1); // add field "foo" with value 1 @@ -46,26 +47,26 @@ public void buildObject() throws VPackException { builder.close();// object end final VPackSlice slice = builder.slice(); // create slice - assertThat(slice.isObject(), is(true)); - assertThat(slice.size(), is(2)); // number of fields + assertThat(slice.isObject()).isTrue(); + assertThat(slice.size()).isEqualTo(2); // number of fields final VPackSlice foo = slice.get("foo"); // get field "foo" - assertThat(foo.isInteger(), is(true)); - assertThat(foo.getAsInt(), is(1)); + assertThat(foo.isInteger()).isTrue(); + assertThat(foo.getAsInt()).isEqualTo(1); final VPackSlice bar = slice.get("bar"); // get field "bar" - assertThat(bar.isInteger(), is(true)); - assertThat(bar.getAsInt(), is(2)); + assertThat(bar.isInteger()).isTrue(); + assertThat(bar.getAsInt()).isEqualTo(2); // iterate over the fields for (final Iterator> iterator = slice.objectIterator(); iterator.hasNext(); ) { final Entry field = iterator.next(); - assertThat(field.getValue().isInteger(), is(true)); + assertThat(field.getValue().isInteger()).isTrue(); } } @Test - public void buildArray() throws VPackException { + void buildArray() throws VPackException { final VPackBuilder builder = new VPackBuilder(); builder.add(ValueType.ARRAY); // array start builder.add(1);// add value 1 @@ -74,25 +75,25 @@ public void buildArray() throws VPackException { builder.close(); // array end final VPackSlice slice = builder.slice();// create slice - assertThat(slice.isArray(), is(true)); - assertThat(slice.size(), is(3));// number of values + assertThat(slice.isArray()).isTrue(); + assertThat(slice.size()).isEqualTo(3);// number of values // iterate over values for (int i = 0; i < slice.size(); i++) { final VPackSlice value = slice.get(i); - assertThat(value.isInteger(), is(true)); - assertThat(value.getAsInt(), is(i + 1)); + assertThat(value.isInteger()).isTrue(); + assertThat(value.getAsInt()).isEqualTo(i + 1); } // iterate over values with Iterator for (final Iterator iterator = slice.arrayIterator(); iterator.hasNext(); ) { final VPackSlice value = iterator.next(); - assertThat(value.isInteger(), is(true)); + assertThat(value.isInteger()).isTrue(); } } @Test - public void buildObjectInObject() throws VPackException { + void buildObjectInObject() throws VPackException { final VPackBuilder builder = new VPackBuilder(); builder.add(ValueType.OBJECT);// object start builder.add("foo", ValueType.OBJECT); // add object in field "foo" @@ -101,13 +102,13 @@ public void buildObjectInObject() throws VPackException { builder.close();// object end final VPackSlice slice = builder.slice(); // create slice - assertThat(slice.isObject(), is(true)); + assertThat(slice.isObject()).isTrue(); final VPackSlice foo = slice.get("foo"); - assertThat(foo.isObject(), is(true)); + assertThat(foo.isObject()).isTrue(); final VPackSlice bar = foo.get("bar"); // get field "bar" from "foo" - assertThat(bar.isInteger(), is(true)); + assertThat(bar.isInteger()).isTrue(); } } diff --git a/src/test/java/com/arangodb/async/serde/CustomSerdeTest.java b/src/test/java/com/arangodb/async/serde/CustomSerdeTest.java index 19d49a063..90022a845 100644 --- a/src/test/java/com/arangodb/async/serde/CustomSerdeTest.java +++ b/src/test/java/com/arangodb/async/serde/CustomSerdeTest.java @@ -21,15 +21,17 @@ package com.arangodb.async.serde; +import com.arangodb.DbName; import com.arangodb.async.ArangoCollectionAsync; import com.arangodb.async.ArangoDBAsync; import com.arangodb.async.ArangoDatabaseAsync; import com.arangodb.entity.BaseDocument; import com.arangodb.mapping.ArangoJack; import com.arangodb.model.DocumentCreateOptions; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.math.BigInteger; import java.util.Collections; @@ -39,22 +41,21 @@ import static com.fasterxml.jackson.databind.DeserializationFeature.USE_BIG_INTEGER_FOR_INTS; import static com.fasterxml.jackson.databind.SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Michele Rastelli */ -public class CustomSerdeTest { +class CustomSerdeTest { private static final String COLLECTION_NAME = "collection"; private ArangoDatabaseAsync db; private ArangoCollectionAsync collection; - @Before - public void init() throws ExecutionException, InterruptedException { + @BeforeEach + void init() throws ExecutionException, InterruptedException { ArangoJack arangoJack = new ArangoJack(); arangoJack.configure((mapper) -> { mapper.configure(WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true); @@ -62,7 +63,7 @@ public void init() throws ExecutionException, InterruptedException { }); ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().serializer(arangoJack).build(); - String TEST_DB = "custom-serde-test"; + DbName TEST_DB = DbName.of("custom-serde-test"); db = arangoDB.db(TEST_DB); if (!db.exists().get()) { db.create().get(); @@ -74,14 +75,14 @@ public void init() throws ExecutionException, InterruptedException { } } - @After - public void shutdown() throws ExecutionException, InterruptedException { + @AfterEach + void shutdown() throws ExecutionException, InterruptedException { db.drop().get(); } @Test - public void aqlSerialization() throws ExecutionException, InterruptedException { - String key = "test-" + UUID.randomUUID().toString(); + void aqlSerialization() throws ExecutionException, InterruptedException { + String key = "test-" + UUID.randomUUID(); BaseDocument doc = new BaseDocument(key); doc.addAttribute("arr", Collections.singletonList("hello")); @@ -95,17 +96,17 @@ public void aqlSerialization() throws ExecutionException, InterruptedException { "INSERT @doc INTO @@collection RETURN NEW", params, BaseDocument.class - ).get().first(); + ).get().next(); - assertThat(result.getAttribute("arr"), instanceOf(String.class)); - assertThat(result.getAttribute("arr"), is("hello")); - assertThat(result.getAttribute("int"), instanceOf(BigInteger.class)); - assertThat(result.getAttribute("int"), is(BigInteger.valueOf(10))); + assertThat(result.getAttribute("arr")).isInstanceOf(String.class); + assertThat(result.getAttribute("arr")).isEqualTo("hello"); + assertThat(result.getAttribute("int")).isInstanceOf(BigInteger.class); + assertThat(result.getAttribute("int")).isEqualTo(BigInteger.valueOf(10)); } @Test - public void aqlDeserialization() throws ExecutionException, InterruptedException { - String key = "test-" + UUID.randomUUID().toString(); + void aqlDeserialization() throws ExecutionException, InterruptedException { + String key = "test-" + UUID.randomUUID(); BaseDocument doc = new BaseDocument(key); doc.addAttribute("arr", Collections.singletonList("hello")); @@ -117,17 +118,17 @@ public void aqlDeserialization() throws ExecutionException, InterruptedException "RETURN DOCUMENT(@docId)", Collections.singletonMap("docId", COLLECTION_NAME + "/" + key), BaseDocument.class - ).get().first(); + ).get().next(); - assertThat(result.getAttribute("arr"), instanceOf(String.class)); - assertThat(result.getAttribute("arr"), is("hello")); - assertThat(result.getAttribute("int"), instanceOf(BigInteger.class)); - assertThat(result.getAttribute("int"), is(BigInteger.valueOf(10))); + assertThat(result.getAttribute("arr")).isInstanceOf(String.class); + assertThat(result.getAttribute("arr")).isEqualTo("hello"); + assertThat(result.getAttribute("int")).isInstanceOf(BigInteger.class); + assertThat(result.getAttribute("int")).isEqualTo(BigInteger.valueOf(10)); } @Test - public void insertDocument() throws ExecutionException, InterruptedException { - String key = "test-" + UUID.randomUUID().toString(); + void insertDocument() throws ExecutionException, InterruptedException { + String key = "test-" + UUID.randomUUID(); BaseDocument doc = new BaseDocument(key); doc.addAttribute("arr", Collections.singletonList("hello")); @@ -138,15 +139,15 @@ public void insertDocument() throws ExecutionException, InterruptedException { new DocumentCreateOptions().returnNew(true) ).get().getNew(); - assertThat(result.getAttribute("arr"), instanceOf(String.class)); - assertThat(result.getAttribute("arr"), is("hello")); - assertThat(result.getAttribute("int"), instanceOf(BigInteger.class)); - assertThat(result.getAttribute("int"), is(BigInteger.valueOf(10))); + assertThat(result.getAttribute("arr")).isInstanceOf(String.class); + assertThat(result.getAttribute("arr")).isEqualTo("hello"); + assertThat(result.getAttribute("int")).isInstanceOf(BigInteger.class); + assertThat(result.getAttribute("int")).isEqualTo(BigInteger.valueOf(10)); } @Test - public void getDocument() throws ExecutionException, InterruptedException { - String key = "test-" + UUID.randomUUID().toString(); + void getDocument() throws ExecutionException, InterruptedException { + String key = "test-" + UUID.randomUUID(); BaseDocument doc = new BaseDocument(key); doc.addAttribute("arr", Collections.singletonList("hello")); @@ -159,10 +160,10 @@ public void getDocument() throws ExecutionException, InterruptedException { BaseDocument.class, null).get(); - assertThat(result.getAttribute("arr"), instanceOf(String.class)); - assertThat(result.getAttribute("arr"), is("hello")); - assertThat(result.getAttribute("int"), instanceOf(BigInteger.class)); - assertThat(result.getAttribute("int"), is(BigInteger.valueOf(10))); + assertThat(result.getAttribute("arr")).isInstanceOf(String.class); + assertThat(result.getAttribute("arr")).isEqualTo("hello"); + assertThat(result.getAttribute("int")).isInstanceOf(BigInteger.class); + assertThat(result.getAttribute("int")).isEqualTo(BigInteger.valueOf(10)); } } diff --git a/src/test/java/com/arangodb/example/ExampleBase.java b/src/test/java/com/arangodb/example/ExampleBase.java index a1fc11363..c378c789c 100644 --- a/src/test/java/com/arangodb/example/ExampleBase.java +++ b/src/test/java/com/arangodb/example/ExampleBase.java @@ -23,8 +23,9 @@ import com.arangodb.ArangoCollection; import com.arangodb.ArangoDB; import com.arangodb.ArangoDatabase; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; /** * @author Mark Vollmary @@ -38,9 +39,9 @@ public class ExampleBase { protected static ArangoDatabase db; protected static ArangoCollection collection; - @BeforeClass - public static void setUp() { - arangoDB = new ArangoDB.Builder().build(); + @BeforeAll + static void setUp() { + arangoDB = new ArangoDB.Builder().serializer(new ArangoJack()).build(); if (arangoDB.db(DB_NAME).exists()) arangoDB.db(DB_NAME).drop(); arangoDB.createDatabase(DB_NAME); @@ -49,8 +50,8 @@ public static void setUp() { collection = db.collection(COLLECTION_NAME); } - @AfterClass - public static void tearDown() { + @AfterAll + static void tearDown() { db.drop(); arangoDB.shutdown(); } diff --git a/src/test/java/com/arangodb/example/FirstProject.java b/src/test/java/com/arangodb/example/FirstProject.java index 158367ba0..db14e3741 100644 --- a/src/test/java/com/arangodb/example/FirstProject.java +++ b/src/test/java/com/arangodb/example/FirstProject.java @@ -6,6 +6,7 @@ import com.arangodb.ArangoDBException; import com.arangodb.entity.BaseDocument; import com.arangodb.entity.CollectionEntity; +import com.arangodb.mapping.ArangoJack; import com.arangodb.util.MapBuilder; import com.arangodb.velocypack.VPackSlice; @@ -14,7 +15,7 @@ public class FirstProject { public static void main(final String[] args) { - final ArangoDB arangoDB = new ArangoDB.Builder().user("root").build(); + final ArangoDB arangoDB = new ArangoDB.Builder().user("root").serializer(new ArangoJack()).build(); // create database final String dbName = "mydb"; diff --git a/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java b/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExampleTest.java similarity index 57% rename from src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java rename to src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExampleTest.java index 5f6b62302..1a46d3a15 100644 --- a/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExample.java +++ b/src/test/java/com/arangodb/example/document/AqlQueryWithSpecialReturnTypesExampleTest.java @@ -1,132 +1,132 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * 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 - * - * 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. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.example.document; - -import com.arangodb.ArangoCursor; -import com.arangodb.entity.BaseDocument; -import com.arangodb.example.ExampleBase; -import com.arangodb.util.MapBuilder; -import com.arangodb.velocypack.VPackSlice; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.List; -import java.util.Map; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - -/** - * @author Mark Vollmary - */ -public class AqlQueryWithSpecialReturnTypesExample extends ExampleBase { - - @BeforeClass - public static void before() { - createExamples(); - } - - public enum Gender { - MALE, FEMALE - } - - private static void createExamples() { - for (int i = 0; i < 100; i++) { - final BaseDocument value = new BaseDocument(); - value.addAttribute("name", "TestUser" + i); - value.addAttribute("gender", (i % 2) == 0 ? Gender.MALE : Gender.FEMALE); - value.addAttribute("age", i + 10); - db.collection(COLLECTION_NAME).insertDocument(value); - } - } - - @Test - public void aqlWithLimitQueryAsVPackObject() { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - final ArangoCursor cursor = db.query(query, bindVars, null, VPackSlice.class); - assertThat(cursor, is(notNullValue())); - for (; cursor.hasNext(); ) { - final VPackSlice vpack = cursor.next(); - assertThat(vpack.get("name").getAsString(), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(vpack.get("gender").getAsString(), is(Gender.FEMALE.name())); - assertThat(vpack.get("age").getAsInt(), isOneOf(21, 23, 25, 27, 29)); - } - } - - @Test - public void aqlWithLimitQueryAsVPackArray() { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - final ArangoCursor cursor = db.query(query, bindVars, null, VPackSlice.class); - assertThat(cursor, is(notNullValue())); - for (; cursor.hasNext(); ) { - final VPackSlice vpack = cursor.next(); - assertThat(vpack.get(0).getAsString(), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(vpack.get(1).getAsString(), is(Gender.FEMALE.name())); - assertThat(vpack.get(2).getAsInt(), isOneOf(21, 23, 25, 27, 29)); - } - } - - @Test - @SuppressWarnings("rawtypes") - public void aqlWithLimitQueryAsMap() { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - final ArangoCursor cursor = db.query(query, bindVars, null, Map.class); - assertThat(cursor, is(notNullValue())); - for (; cursor.hasNext(); ) { - final Map map = cursor.next(); - assertThat(map.get("name"), is(notNullValue())); - assertThat(String.valueOf(map.get("name")), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(map.get("gender"), is(notNullValue())); - assertThat(String.valueOf(map.get("gender")), is(Gender.FEMALE.name())); - assertThat(map.get("age"), is(notNullValue())); - assertThat(Long.valueOf(map.get("age").toString()), isOneOf(21L, 23L, 25L, 27L, 29L)); - } - } - - @Test - @SuppressWarnings("rawtypes") - public void aqlWithLimitQueryAsList() { - final String query = "FOR t IN " + COLLECTION_NAME - + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; - final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); - final ArangoCursor cursor = db.query(query, bindVars, null, List.class); - assertThat(cursor, is(notNullValue())); - for (; cursor.hasNext(); ) { - final List list = cursor.next(); - assertThat(list.get(0), is(notNullValue())); - assertThat(String.valueOf(list.get(0)), - isOneOf("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19")); - assertThat(list.get(1), is(notNullValue())); - assertThat(Gender.valueOf(String.valueOf(list.get(1))), is(Gender.FEMALE)); - assertThat(list.get(2), is(notNullValue())); - assertThat(Long.valueOf(String.valueOf(list.get(2))), isOneOf(21L, 23L, 25L, 27L, 29L)); - } - } -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * 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 + * + * 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. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example.document; + +import com.arangodb.ArangoCursor; +import com.arangodb.entity.BaseDocument; +import com.arangodb.example.ExampleBase; +import com.arangodb.util.MapBuilder; +import com.arangodb.velocypack.VPackSlice; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + + +/** + * @author Mark Vollmary + */ +class AqlQueryWithSpecialReturnTypesExampleTest extends ExampleBase { + + @BeforeAll + static void before() { + createExamples(); + } + + enum Gender { + MALE, FEMALE + } + + private static void createExamples() { + for (int i = 0; i < 100; i++) { + final BaseDocument value = new BaseDocument(); + value.addAttribute("name", "TestUser" + i); + value.addAttribute("gender", (i % 2) == 0 ? Gender.MALE : Gender.FEMALE); + value.addAttribute("age", i + 10); + db.collection(COLLECTION_NAME).insertDocument(value); + } + } + + @Test + void aqlWithLimitQueryAsVPackObject() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, VPackSlice.class); + assertThat((Object) cursor).isNotNull(); + while (cursor.hasNext()) { + final VPackSlice vpack = cursor.next(); + assertThat(vpack.get("name").getAsString()) + .isIn("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19"); + assertThat(vpack.get("gender").getAsString()).isEqualTo(Gender.FEMALE.name()); + assertThat(vpack.get("age").getAsInt()).isIn(21, 23, 25, 27, 29); + } + } + + @Test + void aqlWithLimitQueryAsVPackArray() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, VPackSlice.class); + assertThat((Object) cursor).isNotNull(); + while (cursor.hasNext()) { + final VPackSlice vpack = cursor.next(); + assertThat(vpack.get(0).getAsString()) + .isIn("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19"); + assertThat(vpack.get(1).getAsString()).isEqualTo(Gender.FEMALE.name()); + assertThat(vpack.get(2).getAsInt()).isIn(21, 23, 25, 27, 29); + } + } + + @Test + @SuppressWarnings("rawtypes") + void aqlWithLimitQueryAsMap() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN t"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, Map.class); + assertThat((Object) cursor).isNotNull(); + while (cursor.hasNext()) { + final Map map = cursor.next(); + assertThat(map.get("name")).isNotNull(); + assertThat(String.valueOf(map.get("name"))) + .isIn("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19"); + assertThat(map.get("gender")).isNotNull(); + assertThat(String.valueOf(map.get("gender"))).isEqualTo(Gender.FEMALE.name()); + assertThat(map.get("age")).isNotNull(); + assertThat(Long.valueOf(map.get("age").toString())).isIn(21L, 23L, 25L, 27L, 29L); + } + } + + @Test + @SuppressWarnings("rawtypes") + void aqlWithLimitQueryAsList() { + final String query = "FOR t IN " + COLLECTION_NAME + + " FILTER t.age >= 20 && t.age < 30 && t.gender == @gender RETURN [t.name, t.gender, t.age]"; + final Map bindVars = new MapBuilder().put("gender", Gender.FEMALE).get(); + final ArangoCursor cursor = db.query(query, bindVars, null, List.class); + assertThat((Object) cursor).isNotNull(); + while (cursor.hasNext()) { + final List list = cursor.next(); + assertThat(list.get(0)).isNotNull(); + assertThat(String.valueOf(list.get(0))) + .isIn("TestUser11", "TestUser13", "TestUser15", "TestUser17", "TestUser19"); + assertThat(list.get(1)).isNotNull(); + assertThat(Gender.valueOf(String.valueOf(list.get(1)))).isEqualTo(Gender.FEMALE); + assertThat(list.get(2)).isNotNull(); + assertThat(Long.valueOf(String.valueOf(list.get(2)))).isIn(21L, 23L, 25L, 27L, 29L); + } + } +} diff --git a/src/test/java/com/arangodb/example/document/GetDocumentExample.java b/src/test/java/com/arangodb/example/document/GetDocumentExampleTest.java similarity index 59% rename from src/test/java/com/arangodb/example/document/GetDocumentExample.java rename to src/test/java/com/arangodb/example/document/GetDocumentExampleTest.java index da9f09fb2..10df2972e 100644 --- a/src/test/java/com/arangodb/example/document/GetDocumentExample.java +++ b/src/test/java/com/arangodb/example/document/GetDocumentExampleTest.java @@ -24,24 +24,23 @@ import com.arangodb.entity.DocumentCreateEntity; import com.arangodb.example.ExampleBase; import com.arangodb.velocypack.VPackSlice; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.Map; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Mark Vollmary */ -public class GetDocumentExample extends ExampleBase { +class GetDocumentExampleTest extends ExampleBase { private static String key = null; - @BeforeClass - public static void before() { + @BeforeAll + static void before() { final BaseDocument value = new BaseDocument(); value.addAttribute("foo", "bar"); final DocumentCreateEntity doc = collection.insertDocument(value); @@ -49,43 +48,43 @@ public static void before() { } @Test - public void getAsBean() { + void getAsBean() { final TestEntity doc = collection.getDocument(key, TestEntity.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getFoo(), is("bar")); + assertThat(doc).isNotNull(); + assertThat(doc.getFoo()).isEqualTo("bar"); } @Test - public void getAsBaseDocument() { + void getAsBaseDocument() { final BaseDocument doc = collection.getDocument(key, BaseDocument.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.getAttribute("foo"), is(notNullValue())); - assertThat(String.valueOf(doc.getAttribute("foo")), is("bar")); + assertThat(doc).isNotNull(); + assertThat(doc.getAttribute("foo")).isNotNull(); + assertThat(String.valueOf(doc.getAttribute("foo"))).isEqualTo("bar"); } @SuppressWarnings("unchecked") @Test - public void getAsMap() { + void getAsMap() { final Map doc = collection.getDocument(key, Map.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.get("foo"), is(notNullValue())); - assertThat(String.valueOf(doc.get("foo")), is("bar")); + assertThat(doc).isNotNull(); + assertThat(doc.get("foo")).isNotNull(); + assertThat(String.valueOf(doc.get("foo"))).isEqualTo("bar"); } @Test - public void getAsVPack() { + void getAsVPack() { final VPackSlice doc = collection.getDocument(key, VPackSlice.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.get("foo").isString(), is(true)); - assertThat(doc.get("foo").getAsString(), is("bar")); + assertThat(doc).isNotNull(); + assertThat(doc.get("foo").isString()).isTrue(); + assertThat(doc.get("foo").getAsString()).isEqualTo("bar"); } @Test - public void getAsJson() { + void getAsJson() { final String doc = collection.getDocument(key, String.class); - assertThat(doc, is(notNullValue())); - assertThat(doc.contains("foo"), is(true)); - assertThat(doc.contains("bar"), is(true)); + assertThat(doc).isNotNull(); + assertThat(doc).contains("foo"); + assertThat(doc).contains("bar"); } } diff --git a/src/test/java/com/arangodb/example/document/InsertDocumentExample.java b/src/test/java/com/arangodb/example/document/InsertDocumentExample.java deleted file mode 100644 index 4f475fedc..000000000 --- a/src/test/java/com/arangodb/example/document/InsertDocumentExample.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * 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 - * - * 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. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.example.document; - -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.DocumentCreateEntity; -import com.arangodb.example.ExampleBase; -import com.arangodb.velocypack.VPackBuilder; -import com.arangodb.velocypack.VPackSlice; -import com.arangodb.velocypack.ValueType; -import org.junit.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; - -/** - * @author Mark Vollmary - */ -public class InsertDocumentExample extends ExampleBase { - - @Test - public void insertBean() { - final DocumentCreateEntity doc = collection.insertDocument(new TestEntity("bar")); - assertThat(doc.getKey(), is(notNullValue())); - } - - @Test - public void insertBaseDocument() { - final BaseDocument value = new BaseDocument(); - value.addAttribute("foo", "bar"); - final DocumentCreateEntity doc = collection.insertDocument(value); - assertThat(doc.getKey(), is(notNullValue())); - } - - @Test - public void insertVPack() { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT).add("foo", "bar").close(); - final DocumentCreateEntity doc = collection.insertDocument(builder.slice()); - assertThat(doc.getKey(), is(notNullValue())); - } - - @Test - public void insertJson() { - final DocumentCreateEntity doc = collection.insertDocument("{\"foo\":\"bar\"}"); - assertThat(doc.getKey(), is(notNullValue())); - } - -} diff --git a/src/test/java/com/arangodb/example/document/InsertDocumentExampleTest.java b/src/test/java/com/arangodb/example/document/InsertDocumentExampleTest.java new file mode 100644 index 000000000..016d7f2c3 --- /dev/null +++ b/src/test/java/com/arangodb/example/document/InsertDocumentExampleTest.java @@ -0,0 +1,67 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * 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 + * + * 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. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example.document; + +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.DocumentCreateEntity; +import com.arangodb.example.ExampleBase; +import com.arangodb.velocypack.VPackBuilder; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.ValueType; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + + +/** + * @author Mark Vollmary + */ +class InsertDocumentExampleTest extends ExampleBase { + + @Test + void insertBean() { + final DocumentCreateEntity doc = collection.insertDocument(new TestEntity("bar")); + assertThat(doc.getKey()).isNotNull(); + } + + @Test + void insertBaseDocument() { + final BaseDocument value = new BaseDocument(); + value.addAttribute("foo", "bar"); + final DocumentCreateEntity doc = collection.insertDocument(value); + assertThat(doc.getKey()).isNotNull(); + } + + @Test + void insertVPack() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT).add("foo", "bar").close(); + final DocumentCreateEntity doc = collection.insertDocument(builder.slice()); + assertThat(doc.getKey()).isNotNull(); + } + + @Test + void insertJson() { + final DocumentCreateEntity doc = collection.insertDocument("{\"foo\":\"bar\"}"); + assertThat(doc.getKey()).isNotNull(); + } + +} diff --git a/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java b/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExampleTest.java similarity index 89% rename from src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java rename to src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExampleTest.java index 959af9478..f5283c5aa 100644 --- a/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExample.java +++ b/src/test/java/com/arangodb/example/graph/AQLActorsAndMoviesExampleTest.java @@ -1,559 +1,555 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * 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 - * - * 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. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.example.graph; - -import com.arangodb.ArangoCollection; -import com.arangodb.ArangoCursor; -import com.arangodb.ArangoDB; -import com.arangodb.ArangoDatabase; -import com.arangodb.entity.BaseDocument; -import com.arangodb.entity.BaseEdgeDocument; -import com.arangodb.entity.CollectionType; -import com.arangodb.entity.DocumentCreateEntity; -import com.arangodb.model.CollectionCreateOptions; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItems; - -/** - * @author Mark Vollmary - * @see AQL Example Queries on an - * Actors and Movies Database - */ -public class AQLActorsAndMoviesExample { - - private static final String TEST_DB = "actors_movies_test_db"; - private static ArangoDB arangoDB; - private static ArangoDatabase db; - - @BeforeClass - public static void setUp() { - arangoDB = new ArangoDB.Builder().build(); - if (arangoDB.db(TEST_DB).exists()) - arangoDB.db(TEST_DB).drop(); - arangoDB.createDatabase(TEST_DB); - db = arangoDB.db(TEST_DB); - createData(); - } - - @AfterClass - public static void tearDown() { - db.drop(); - arangoDB.shutdown(); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allActorsActsInMovie1or2() { - final ArangoCursor cursor = db.query( - "WITH actors, movies FOR x IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN x._id", - null, null, String.class); - assertThat(cursor.asListRemaining(), - hasItems("actors/Keanu", "actors/Hugo", "actors/Emil", "actors/Carrie", "actors/Laurence")); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allActorsActsInMovie1or2UnionDistinct() { - final ArangoCursor cursor = db.query( - "WITH actors, movies FOR x IN UNION_DISTINCT ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", - null, null, String.class); - assertThat(cursor.asListRemaining(), hasItems("actors/Emil", "actors/Hugo", "actors/Carrie", "actors/Laurence", - "actors/Keanu", "actors/Al", "actors/Charlize")); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allActorsActsInMovie1and2() { - final ArangoCursor cursor = db.query( - "WITH actors, movies FOR x IN INTERSECTION ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", - null, null, String.class); - assertThat(cursor.asListRemaining(), hasItems("actors/Keanu")); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allMoviesBetweenActor1andActor2() { - final ArangoCursor cursor = db.query( - "WITH actors, movies FOR x IN INTERSECTION ((FOR y IN ANY 'actors/Hugo' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'actors/Keanu' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", - null, null, String.class); - assertThat(cursor.asListRemaining(), - hasItems("movies/TheMatrixRevolutions", "movies/TheMatrixReloaded", "movies/TheMatrix")); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allActorsWhoActedIn3orMoreMovies() { - final ArangoCursor cursor = db.query( - "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter FILTER counter >= 3 RETURN {actor: actor, movies: counter}", - null, null, Actor.class); - assertThat(cursor.asListRemaining(), - hasItems(new Actor("actors/Carrie", 3), new Actor("actors/CubaG", 4), new Actor("actors/Hugo", 3), - new Actor("actors/Keanu", 4), new Actor("actors/Laurence", 3), new Actor("actors/MegR", 5), - new Actor("actors/TomC", 3), new Actor("actors/TomH", 3))); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void allMoviesWhereExactly6ActorsActedIn() { - final ArangoCursor cursor = db.query( - "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter FILTER counter == 6 RETURN movie", null, - null, String.class); - assertThat(cursor.asListRemaining(), - hasItems("movies/SleeplessInSeattle", "movies/TopGun", "movies/YouveGotMail")); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void theNumberOfActorsByMovie() { - final ArangoCursor cursor = db.query( - "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter RETURN {movie: movie, actors: counter}", - null, null, Movie.class); - assertThat(cursor.asListRemaining(), - hasItems(new Movie("movies/AFewGoodMen", 11), new Movie("movies/AsGoodAsItGets", 4), - new Movie("movies/JerryMaguire", 9), new Movie("movies/JoeVersustheVolcano", 3), - new Movie("movies/SleeplessInSeattle", 6), new Movie("movies/SnowFallingonCedars", 4), - new Movie("movies/StandByMe", 7), new Movie("movies/TheDevilsAdvocate", 3), - new Movie("movies/TheMatrix", 5), new Movie("movies/TheMatrixReloaded", 4), - new Movie("movies/TheMatrixRevolutions", 4), new Movie("movies/TopGun", 6), - new Movie("movies/WhatDreamsMayCome", 5), new Movie("movies/WhenHarryMetSally", 4), - new Movie("movies/YouveGotMail", 6))); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void theNumberOfMoviesByActor() { - final ArangoCursor cursor = db.query( - "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", - null, null, Actor.class); - assertThat(cursor.asListRemaining(), - hasItems(new Actor("actors/Al", 1), new Actor("actors/AnnabellaS", 1), new Actor("actors/AnthonyE", 1), - new Actor("actors/BillPull", 1), new Actor("actors/BillyC", 1), new Actor("actors/BonnieH", 1), - new Actor("actors/BrunoK", 1), new Actor("actors/Carrie", 3), new Actor("actors/CarrieF", 1), - new Actor("actors/Charlize", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CoreyF", 1), - new Actor("actors/CubaG", 4), new Actor("actors/DaveC", 1), new Actor("actors/DemiM", 1), - new Actor("actors/Emil", 1), new Actor("actors/EthanH", 1), new Actor("actors/GregK", 2), - new Actor("actors/HelenH", 1), new Actor("actors/Hugo", 3), new Actor("actors/JackN", 2), - new Actor("actors/JamesC", 1), new Actor("actors/JamesM", 1), new Actor("actors/JayM", 1), - new Actor("actors/JerryO", 2), new Actor("actors/JohnC", 1), new Actor("actors/JonathanL", 1), - new Actor("actors/JTW", 1), new Actor("actors/Keanu", 4), new Actor("actors/KellyM", 1), - new Actor("actors/KellyP", 1), new Actor("actors/KevinB", 1), new Actor("actors/KevinP", 1), - new Actor("actors/KieferS", 2), new Actor("actors/Laurence", 3), new Actor("actors/MarshallB", 1), - new Actor("actors/MaxS", 2), new Actor("actors/MegR", 5), new Actor("actors/Nathan", 1), - new Actor("actors/NoahW", 1), new Actor("actors/ParkerP", 1), new Actor("actors/ReginaK", 1), - new Actor("actors/ReneeZ", 1), new Actor("actors/RickY", 1), new Actor("actors/RitaW", 1), - new Actor("actors/RiverP", 1), new Actor("actors/Robin", 1), new Actor("actors/RosieO", 1), - new Actor("actors/SteveZ", 1), new Actor("actors/TomC", 3), new Actor("actors/TomH", 3), - new Actor("actors/TomS", 1), new Actor("actors/ValK", 1), new Actor("actors/VictorG", 1), - new Actor("actors/WernerH", 1), new Actor("actors/WilW", 1))); - } - - /** - * @see AQL - * Example Queries on an Actors and Movies Database - */ - @Test - public void theNumberOfMoviesActedInBetween2005and2010byActor() { - final ArangoCursor cursor = db.query( - "FOR x IN actsIn FILTER x.year >= 1990 && x.year <= 1995 COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", - null, null, Actor.class); - assertThat(cursor.asListRemaining(), - hasItems(new Actor("actors/BillPull", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CubaG", 1), - new Actor("actors/DemiM", 1), new Actor("actors/JackN", 1), new Actor("actors/JamesM", 1), - new Actor("actors/JTW", 1), new Actor("actors/KevinB", 1), new Actor("actors/KieferS", 1), - new Actor("actors/MegR", 2), new Actor("actors/Nathan", 1), new Actor("actors/NoahW", 1), - new Actor("actors/RitaW", 1), new Actor("actors/RosieO", 1), new Actor("actors/TomC", 1), - new Actor("actors/TomH", 2), new Actor("actors/VictorG", 1))); - } - - @SuppressWarnings("WeakerAccess") - public static class Actor { - private String actor; - private Integer movies; - - public Actor() { - super(); - } - - public Actor(final String actor, final Integer movies) { - super(); - this.actor = actor; - this.movies = movies; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((actor == null) ? 0 : actor.hashCode()); - result = prime * result + ((movies == null) ? 0 : movies.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Actor other = (Actor) obj; - if (actor == null) { - if (other.actor != null) { - return false; - } - } else if (!actor.equals(other.actor)) { - return false; - } - if (movies == null) { - return other.movies == null; - } else return movies.equals(other.movies); - } - - } - - @SuppressWarnings("WeakerAccess") - public static class Movie { - private String movie; - private Integer actors; - - public Movie() { - super(); - } - - public Movie(final String movie, final Integer actors) { - super(); - this.movie = movie; - this.actors = actors; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((actors == null) ? 0 : actors.hashCode()); - result = prime * result + ((movie == null) ? 0 : movie.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Movie other = (Movie) obj; - if (actors == null) { - if (other.actors != null) { - return false; - } - } else if (!actors.equals(other.actors)) { - return false; - } - if (movie == null) { - return other.movie == null; - } else return movie.equals(other.movie); - } - - } - - private static DocumentCreateEntity saveMovie( - final ArangoCollection movies, - final String key, - final String title, - final int released, - final String tagline) { - final BaseDocument value = new BaseDocument(); - value.setKey(key); - value.addAttribute("title", title); - value.addAttribute("released", released); - value.addAttribute("tagline", tagline); - return movies.insertDocument(value); - } - - private static DocumentCreateEntity saveActor( - final ArangoCollection actors, - final String key, - final String name, - final int born) { - final BaseDocument value = new BaseDocument(); - value.setKey(key); - value.addAttribute("name", name); - value.addAttribute("born", born); - return actors.insertDocument(value); - } - - private static void saveActsIn( - final ArangoCollection actsIn, - final String actor, - final String movie, - final String[] roles, - final int year) { - final BaseEdgeDocument value = new BaseEdgeDocument(); - value.setFrom(actor); - value.setTo(movie); - value.addAttribute("roles", roles); - value.addAttribute("year", year); - actsIn.insertDocument(value); - } - - private static void createData() { - db.createCollection("actors"); - final ArangoCollection actors = db.collection("actors"); - db.createCollection("movies"); - final ArangoCollection movies = db.collection("movies"); - db.createCollection("actsIn", new CollectionCreateOptions().type(CollectionType.EDGES)); - final ArangoCollection actsIn = db.collection("actsIn"); - - final String theMatrix = saveMovie(movies, "TheMatrix", "The Matrix", 1999, "Welcome to the Real World") - .getId(); - final String keanu = saveActor(actors, "Keanu", "Keanu Reeves", 1964).getId(); - final String carrie = saveActor(actors, "Carrie", "Carrie-Anne Moss", 1967).getId(); - final String laurence = saveActor(actors, "Laurence", "Laurence Fishburne", 1961).getId(); - final String hugo = saveActor(actors, "Hugo", "Hugo Weaving", 1960).getId(); - final String emil = saveActor(actors, "Emil", "Emil Eifrem", 1978).getId(); - - saveActsIn(actsIn, keanu, theMatrix, new String[]{"Neo"}, 1999); - saveActsIn(actsIn, carrie, theMatrix, new String[]{"Trinity"}, 1999); - saveActsIn(actsIn, laurence, theMatrix, new String[]{"Morpheus"}, 1999); - saveActsIn(actsIn, hugo, theMatrix, new String[]{"Agent Smith"}, 1999); - saveActsIn(actsIn, emil, theMatrix, new String[]{"Emil"}, 1999); - - final String theMatrixReloaded = saveMovie(movies, "TheMatrixReloaded", "The Matrix Reloaded", 2003, - "Free your mind").getId(); - saveActsIn(actsIn, keanu, theMatrixReloaded, new String[]{"Neo"}, 2003); - saveActsIn(actsIn, carrie, theMatrixReloaded, new String[]{"Trinity"}, 2003); - saveActsIn(actsIn, laurence, theMatrixReloaded, new String[]{"Morpheus"}, 2003); - saveActsIn(actsIn, hugo, theMatrixReloaded, new String[]{"Agent Smith"}, 2003); - - final String theMatrixRevolutions = saveMovie(movies, "TheMatrixRevolutions", "The Matrix Revolutions", 2003, - "Everything that has a beginning has an end").getId(); - saveActsIn(actsIn, keanu, theMatrixRevolutions, new String[]{"Neo"}, 2003); - saveActsIn(actsIn, carrie, theMatrixRevolutions, new String[]{"Trinity"}, 2003); - saveActsIn(actsIn, laurence, theMatrixRevolutions, new String[]{"Morpheus"}, 2003); - saveActsIn(actsIn, hugo, theMatrixRevolutions, new String[]{"Agent Smith"}, 2003); - - final String theDevilsAdvocate = saveMovie(movies, "TheDevilsAdvocate", "The Devil's Advocate", 1997, - "Evil has its winning ways").getId(); - final String charlize = saveActor(actors, "Charlize", "Charlize Theron", 1975).getId(); - final String al = saveActor(actors, "Al", "Al Pacino", 1940).getId(); - saveActsIn(actsIn, keanu, theDevilsAdvocate, new String[]{"Kevin Lomax"}, 1997); - saveActsIn(actsIn, charlize, theDevilsAdvocate, new String[]{"Mary Ann Lomax"}, 1997); - saveActsIn(actsIn, al, theDevilsAdvocate, new String[]{"John Milton"}, 1997); - - final String AFewGoodMen = saveMovie(movies, "AFewGoodMen", "A Few Good Men", 1992, - "In the heart of the nation's capital, in a courthouse of the U.S. government, one man will stop at nothing to keep his honor, and one will stop at nothing to find the truth.") - .getId(); - final String tomC = saveActor(actors, "TomC", "Tom Cruise", 1962).getId(); - final String jackN = saveActor(actors, "JackN", "Jack Nicholson", 1937).getId(); - final String demiM = saveActor(actors, "DemiM", "Demi Moore", 1962).getId(); - final String kevinB = saveActor(actors, "KevinB", "Kevin Bacon", 1958).getId(); - final String kieferS = saveActor(actors, "KieferS", "Kiefer Sutherland", 1966).getId(); - final String noahW = saveActor(actors, "NoahW", "Noah Wyle", 1971).getId(); - final String cubaG = saveActor(actors, "CubaG", "Cuba Gooding Jr.", 1968).getId(); - final String kevinP = saveActor(actors, "KevinP", "Kevin Pollak", 1957).getId(); - final String jTW = saveActor(actors, "JTW", "J.T. Walsh", 1943).getId(); - final String jamesM = saveActor(actors, "JamesM", "James Marshall", 1967).getId(); - final String christopherG = saveActor(actors, "ChristopherG", "Christopher Guest", 1948).getId(); - saveActsIn(actsIn, tomC, AFewGoodMen, new String[]{"Lt. Daniel Kaffee"}, 1992); - saveActsIn(actsIn, jackN, AFewGoodMen, new String[]{"Col. Nathan R. Jessup"}, 1992); - saveActsIn(actsIn, demiM, AFewGoodMen, new String[]{"Lt. Cdr. JoAnne Galloway"}, 1992); - saveActsIn(actsIn, kevinB, AFewGoodMen, new String[]{"Capt. Jack Ross"}, 1992); - saveActsIn(actsIn, kieferS, AFewGoodMen, new String[]{"Lt. Jonathan Kendrick"}, 1992); - saveActsIn(actsIn, noahW, AFewGoodMen, new String[]{"Cpl. Jeffrey Barnes"}, 1992); - saveActsIn(actsIn, cubaG, AFewGoodMen, new String[]{"Cpl. Carl Hammaker"}, 1992); - saveActsIn(actsIn, kevinP, AFewGoodMen, new String[]{"Lt. Sam Weinberg"}, 1992); - saveActsIn(actsIn, jTW, AFewGoodMen, new String[]{"Lt. Col. Matthew Andrew Markinson"}, 1992); - saveActsIn(actsIn, jamesM, AFewGoodMen, new String[]{"Pfc. Louden Downey"}, 1992); - saveActsIn(actsIn, christopherG, AFewGoodMen, new String[]{"Dr. Stone"}, 1992); - - final String topGun = saveMovie(movies, "TopGun", "Top Gun", 1986, "I feel the need, the need for speed.") - .getId(); - final String kellyM = saveActor(actors, "KellyM", "Kelly McGillis", 1957).getId(); - final String valK = saveActor(actors, "ValK", "Val Kilmer", 1959).getId(); - final String anthonyE = saveActor(actors, "AnthonyE", "Anthony Edwards", 1962).getId(); - final String tomS = saveActor(actors, "TomS", "Tom Skerritt", 1933).getId(); - final String megR = saveActor(actors, "MegR", "Meg Ryan", 1961).getId(); - saveActsIn(actsIn, tomC, topGun, new String[]{"Maverick"}, 1986); - saveActsIn(actsIn, kellyM, topGun, new String[]{"Charlie"}, 1986); - saveActsIn(actsIn, valK, topGun, new String[]{"Iceman"}, 1986); - saveActsIn(actsIn, anthonyE, topGun, new String[]{"Goose"}, 1986); - saveActsIn(actsIn, tomS, topGun, new String[]{"Viper"}, 1986); - saveActsIn(actsIn, megR, topGun, new String[]{"Carole"}, 1986); - - final String jerryMaguire = saveMovie(movies, "JerryMaguire", "Jerry Maguire", 2000, - "The rest of his life begins now.").getId(); - final String reneeZ = saveActor(actors, "ReneeZ", "Renee Zellweger", 1969).getId(); - final String kellyP = saveActor(actors, "KellyP", "Kelly Preston", 1962).getId(); - final String jerryO = saveActor(actors, "JerryO", "Jerry O'Connell", 1974).getId(); - final String jayM = saveActor(actors, "JayM", "Jay Mohr", 1970).getId(); - final String bonnieH = saveActor(actors, "BonnieH", "Bonnie Hunt", 1961).getId(); - final String reginaK = saveActor(actors, "ReginaK", "Regina King", 1971).getId(); - final String jonathanL = saveActor(actors, "JonathanL", "Jonathan Lipnicki", 1996).getId(); - saveActsIn(actsIn, tomC, jerryMaguire, new String[]{"Jerry Maguire"}, 2000); - saveActsIn(actsIn, cubaG, jerryMaguire, new String[]{"Rod Tidwell"}, 2000); - saveActsIn(actsIn, reneeZ, jerryMaguire, new String[]{"Dorothy Boyd"}, 2000); - saveActsIn(actsIn, kellyP, jerryMaguire, new String[]{"Avery Bishop"}, 2000); - saveActsIn(actsIn, jerryO, jerryMaguire, new String[]{"Frank Cushman"}, 2000); - saveActsIn(actsIn, jayM, jerryMaguire, new String[]{"Bob Sugar"}, 2000); - saveActsIn(actsIn, bonnieH, jerryMaguire, new String[]{"Laurel Boyd"}, 2000); - saveActsIn(actsIn, reginaK, jerryMaguire, new String[]{"Marcee Tidwell"}, 2000); - saveActsIn(actsIn, jonathanL, jerryMaguire, new String[]{"Ray Boyd"}, 2000); - - final String standByMe = saveMovie(movies, "StandByMe", "Stand By Me", 1986, - "For some, it's the last real taste of innocence, and the first real taste of life. But for everyone, it's the time that memories are made of.") - .getId(); - final String riverP = saveActor(actors, "RiverP", "River Phoenix", 1970).getId(); - final String coreyF = saveActor(actors, "CoreyF", "Corey Feldman", 1971).getId(); - final String wilW = saveActor(actors, "WilW", "Wil Wheaton", 1972).getId(); - final String johnC = saveActor(actors, "JohnC", "John Cusack", 1966).getId(); - final String marshallB = saveActor(actors, "MarshallB", "Marshall Bell", 1942).getId(); - saveActsIn(actsIn, wilW, standByMe, new String[]{"Gordie Lachance"}, 1986); - saveActsIn(actsIn, riverP, standByMe, new String[]{"Chris Chambers"}, 1986); - saveActsIn(actsIn, jerryO, standByMe, new String[]{"Vern Tessio"}, 1986); - saveActsIn(actsIn, coreyF, standByMe, new String[]{"Teddy Duchamp"}, 1986); - saveActsIn(actsIn, johnC, standByMe, new String[]{"Denny Lachance"}, 1986); - saveActsIn(actsIn, kieferS, standByMe, new String[]{"Ace Merrill"}, 1986); - saveActsIn(actsIn, marshallB, standByMe, new String[]{"Mr. Lachance"}, 1986); - - final String asGoodAsItGets = saveMovie(movies, "AsGoodAsItGets", "As Good as It Gets", 1997, - "A comedy from the heart that goes for the throat.").getId(); - final String helenH = saveActor(actors, "HelenH", "Helen Hunt", 1963).getId(); - final String gregK = saveActor(actors, "GregK", "Greg Kinnear", 1963).getId(); - saveActsIn(actsIn, jackN, asGoodAsItGets, new String[]{"Melvin Udall"}, 1997); - saveActsIn(actsIn, helenH, asGoodAsItGets, new String[]{"Carol Connelly"}, 1997); - saveActsIn(actsIn, gregK, asGoodAsItGets, new String[]{"Simon Bishop"}, 1997); - saveActsIn(actsIn, cubaG, asGoodAsItGets, new String[]{"Frank Sachs"}, 1997); - - final String whatDreamsMayCome = saveMovie(movies, "WhatDreamsMayCome", "What Dreams May Come", 1998, - "After life there is more. The end is just the beginning.").getId(); - final String annabellaS = saveActor(actors, "AnnabellaS", "Annabella Sciorra", 1960).getId(); - final String maxS = saveActor(actors, "MaxS", "Max von Sydow", 1929).getId(); - final String wernerH = saveActor(actors, "WernerH", "Werner Herzog", 1942).getId(); - final String robin = saveActor(actors, "Robin", "Robin Williams", 1951).getId(); - saveActsIn(actsIn, robin, whatDreamsMayCome, new String[]{"Chris Nielsen"}, 1998); - saveActsIn(actsIn, cubaG, whatDreamsMayCome, new String[]{"Albert Lewis"}, 1998); - saveActsIn(actsIn, annabellaS, whatDreamsMayCome, new String[]{"Annie Collins-Nielsen"}, 1998); - saveActsIn(actsIn, maxS, whatDreamsMayCome, new String[]{"The Tracker"}, 1998); - saveActsIn(actsIn, wernerH, whatDreamsMayCome, new String[]{"The Face"}, 1998); - - final String snowFallingonCedars = saveMovie(movies, "SnowFallingonCedars", "Snow Falling on Cedars", 1999, - "First loves last. Forever.").getId(); - final String ethanH = saveActor(actors, "EthanH", "Ethan Hawke", 1970).getId(); - final String rickY = saveActor(actors, "RickY", "Rick Yune", 1971).getId(); - final String jamesC = saveActor(actors, "JamesC", "James Cromwell", 1940).getId(); - saveActsIn(actsIn, ethanH, snowFallingonCedars, new String[]{"Ishmael Chambers"}, 1999); - saveActsIn(actsIn, rickY, snowFallingonCedars, new String[]{"Kazuo Miyamoto"}, 1999); - saveActsIn(actsIn, maxS, snowFallingonCedars, new String[]{"Nels Gudmundsson"}, 1999); - saveActsIn(actsIn, jamesC, snowFallingonCedars, new String[]{"Judge Fielding"}, 1999); - - final String youveGotMail = saveMovie(movies, "YouveGotMail", "You've Got Mail", 1998, - "At odds in life... in love on-line.").getId(); - final String parkerP = saveActor(actors, "ParkerP", "Parker Posey", 1968).getId(); - final String daveC = saveActor(actors, "DaveC", "Dave Chappelle", 1973).getId(); - final String steveZ = saveActor(actors, "SteveZ", "Steve Zahn", 1967).getId(); - final String tomH = saveActor(actors, "TomH", "Tom Hanks", 1956).getId(); - saveActsIn(actsIn, tomH, youveGotMail, new String[]{"Joe Fox"}, 1998); - saveActsIn(actsIn, megR, youveGotMail, new String[]{"Kathleen Kelly"}, 1998); - saveActsIn(actsIn, gregK, youveGotMail, new String[]{"Frank Navasky"}, 1998); - saveActsIn(actsIn, parkerP, youveGotMail, new String[]{"Patricia Eden"}, 1998); - saveActsIn(actsIn, daveC, youveGotMail, new String[]{"Kevin Jackson"}, 1998); - saveActsIn(actsIn, steveZ, youveGotMail, new String[]{"George Pappas"}, 1998); - - final String sleeplessInSeattle = saveMovie(movies, "SleeplessInSeattle", "Sleepless in Seattle", 1993, - "What if someone you never met, someone you never saw, someone you never knew was the only someone for you?") - .getId(); - final String ritaW = saveActor(actors, "RitaW", "Rita Wilson", 1956).getId(); - final String billPull = saveActor(actors, "BillPull", "Bill Pullman", 1953).getId(); - final String victorG = saveActor(actors, "VictorG", "Victor Garber", 1949).getId(); - final String rosieO = saveActor(actors, "RosieO", "Rosie O'Donnell", 1962).getId(); - saveActsIn(actsIn, tomH, sleeplessInSeattle, new String[]{"Sam Baldwin"}, 1993); - saveActsIn(actsIn, megR, sleeplessInSeattle, new String[]{"Annie Reed"}, 1993); - saveActsIn(actsIn, ritaW, sleeplessInSeattle, new String[]{"Suzy"}, 1993); - saveActsIn(actsIn, billPull, sleeplessInSeattle, new String[]{"Walter"}, 1993); - saveActsIn(actsIn, victorG, sleeplessInSeattle, new String[]{"Greg"}, 1993); - saveActsIn(actsIn, rosieO, sleeplessInSeattle, new String[]{"Becky"}, 1993); - - final String joeVersustheVolcano = saveMovie(movies, "JoeVersustheVolcano", "Joe Versus the Volcano", 1990, - "A story of love, lava and burning desire.").getId(); - final String nathan = saveActor(actors, "Nathan", "Nathan Lane", 1956).getId(); - saveActsIn(actsIn, tomH, joeVersustheVolcano, new String[]{"Joe Banks"}, 1990); - saveActsIn(actsIn, megR, joeVersustheVolcano, - new String[]{"DeDe', 'Angelica Graynamore', 'Patricia Graynamore"}, 1990); - saveActsIn(actsIn, nathan, joeVersustheVolcano, new String[]{"Baw"}, 1990); - - final String whenHarryMetSally = saveMovie(movies, "WhenHarryMetSally", "When Harry Met Sally", 1998, - "At odds in life... in love on-line.").getId(); - final String billyC = saveActor(actors, "BillyC", "Billy Crystal", 1948).getId(); - final String carrieF = saveActor(actors, "CarrieF", "Carrie Fisher", 1956).getId(); - final String brunoK = saveActor(actors, "BrunoK", "Bruno Kirby", 1949).getId(); - saveActsIn(actsIn, billyC, whenHarryMetSally, new String[]{"Harry Burns"}, 1998); - saveActsIn(actsIn, megR, whenHarryMetSally, new String[]{"Sally Albright"}, 1998); - saveActsIn(actsIn, carrieF, whenHarryMetSally, new String[]{"Marie"}, 1998); - saveActsIn(actsIn, brunoK, whenHarryMetSally, new String[]{"Jess"}, 1998); - } - -} +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * 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 + * + * 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. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example.graph; + +import com.arangodb.*; +import com.arangodb.entity.BaseDocument; +import com.arangodb.entity.BaseEdgeDocument; +import com.arangodb.entity.CollectionType; +import com.arangodb.entity.DocumentCreateEntity; +import com.arangodb.mapping.ArangoJack; +import com.arangodb.model.CollectionCreateOptions; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + + +/** + * @author Mark Vollmary + * @see AQL Example Queries on an + * Actors and Movies Database + */ +class AQLActorsAndMoviesExampleTest { + + private static final DbName TEST_DB = DbName.of("actors_movies_test_db"); + private static ArangoDB arangoDB; + private static ArangoDatabase db; + + @BeforeAll + static void setUp() { + arangoDB = new ArangoDB.Builder().serializer(new ArangoJack()).build(); + if (arangoDB.db(TEST_DB).exists()) + arangoDB.db(TEST_DB).drop(); + arangoDB.createDatabase(TEST_DB); + db = arangoDB.db(TEST_DB); + createData(); + } + + @AfterAll + static void tearDown() { + db.drop(); + arangoDB.shutdown(); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + void allActorsActsInMovie1or2() { + final ArangoCursor cursor = db.query( + "WITH actors, movies FOR x IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN x._id", + null, null, String.class); + assertThat(cursor.asListRemaining()) + .contains("actors/Keanu", "actors/Hugo", "actors/Emil", "actors/Carrie", "actors/Laurence"); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + void allActorsActsInMovie1or2UnionDistinct() { + final ArangoCursor cursor = db.query( + "WITH actors, movies FOR x IN UNION_DISTINCT ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", + null, null, String.class); + assertThat(cursor.asListRemaining()).contains("actors/Emil", "actors/Hugo", "actors/Carrie", "actors/Laurence", + "actors/Keanu", "actors/Al", "actors/Charlize"); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + void allActorsActsInMovie1and2() { + final ArangoCursor cursor = db.query( + "WITH actors, movies FOR x IN INTERSECTION ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", + null, null, String.class); + assertThat(cursor.asListRemaining()).contains("actors/Keanu"); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + void allMoviesBetweenActor1andActor2() { + final ArangoCursor cursor = db.query( + "WITH actors, movies FOR x IN INTERSECTION ((FOR y IN ANY 'actors/Hugo' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'actors/Keanu' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x", + null, null, String.class); + assertThat(cursor.asListRemaining()) + .contains("movies/TheMatrixRevolutions", "movies/TheMatrixReloaded", "movies/TheMatrix"); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + void allActorsWhoActedIn3orMoreMovies() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter FILTER counter >= 3 RETURN {actor: actor, movies: counter}", + null, null, Actor.class); + assertThat(cursor.asListRemaining()) + .contains(new Actor("actors/Carrie", 3), new Actor("actors/CubaG", 4), new Actor("actors/Hugo", 3), + new Actor("actors/Keanu", 4), new Actor("actors/Laurence", 3), new Actor("actors/MegR", 5), + new Actor("actors/TomC", 3), new Actor("actors/TomH", 3)); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + void allMoviesWhereExactly6ActorsActedIn() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter FILTER counter == 6 RETURN movie", null, + null, String.class); + assertThat(cursor.asListRemaining()) + .contains("movies/SleeplessInSeattle", "movies/TopGun", "movies/YouveGotMail"); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + void theNumberOfActorsByMovie() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter RETURN {movie: movie, actors: counter}", + null, null, Movie.class); + assertThat(cursor.asListRemaining()) + .contains(new Movie("movies/AFewGoodMen", 11), new Movie("movies/AsGoodAsItGets", 4), + new Movie("movies/JerryMaguire", 9), new Movie("movies/JoeVersustheVolcano", 3), + new Movie("movies/SleeplessInSeattle", 6), new Movie("movies/SnowFallingonCedars", 4), + new Movie("movies/StandByMe", 7), new Movie("movies/TheDevilsAdvocate", 3), + new Movie("movies/TheMatrix", 5), new Movie("movies/TheMatrixReloaded", 4), + new Movie("movies/TheMatrixRevolutions", 4), new Movie("movies/TopGun", 6), + new Movie("movies/WhatDreamsMayCome", 5), new Movie("movies/WhenHarryMetSally", 4), + new Movie("movies/YouveGotMail", 6)); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + void theNumberOfMoviesByActor() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", + null, null, Actor.class); + assertThat(cursor.asListRemaining()) + .contains(new Actor("actors/Al", 1), new Actor("actors/AnnabellaS", 1), new Actor("actors/AnthonyE", 1), + new Actor("actors/BillPull", 1), new Actor("actors/BillyC", 1), new Actor("actors/BonnieH", 1), + new Actor("actors/BrunoK", 1), new Actor("actors/Carrie", 3), new Actor("actors/CarrieF", 1), + new Actor("actors/Charlize", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CoreyF", 1), + new Actor("actors/CubaG", 4), new Actor("actors/DaveC", 1), new Actor("actors/DemiM", 1), + new Actor("actors/Emil", 1), new Actor("actors/EthanH", 1), new Actor("actors/GregK", 2), + new Actor("actors/HelenH", 1), new Actor("actors/Hugo", 3), new Actor("actors/JackN", 2), + new Actor("actors/JamesC", 1), new Actor("actors/JamesM", 1), new Actor("actors/JayM", 1), + new Actor("actors/JerryO", 2), new Actor("actors/JohnC", 1), new Actor("actors/JonathanL", 1), + new Actor("actors/JTW", 1), new Actor("actors/Keanu", 4), new Actor("actors/KellyM", 1), + new Actor("actors/KellyP", 1), new Actor("actors/KevinB", 1), new Actor("actors/KevinP", 1), + new Actor("actors/KieferS", 2), new Actor("actors/Laurence", 3), new Actor("actors/MarshallB", 1), + new Actor("actors/MaxS", 2), new Actor("actors/MegR", 5), new Actor("actors/Nathan", 1), + new Actor("actors/NoahW", 1), new Actor("actors/ParkerP", 1), new Actor("actors/ReginaK", 1), + new Actor("actors/ReneeZ", 1), new Actor("actors/RickY", 1), new Actor("actors/RitaW", 1), + new Actor("actors/RiverP", 1), new Actor("actors/Robin", 1), new Actor("actors/RosieO", 1), + new Actor("actors/SteveZ", 1), new Actor("actors/TomC", 3), new Actor("actors/TomH", 3), + new Actor("actors/TomS", 1), new Actor("actors/ValK", 1), new Actor("actors/VictorG", 1), + new Actor("actors/WernerH", 1), new Actor("actors/WilW", 1)); + } + + /** + * @see AQL + * Example Queries on an Actors and Movies Database + */ + @Test + void theNumberOfMoviesActedInBetween2005and2010byActor() { + final ArangoCursor cursor = db.query( + "FOR x IN actsIn FILTER x.year >= 1990 && x.year <= 1995 COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}", + null, null, Actor.class); + assertThat(cursor.asListRemaining()) + .contains(new Actor("actors/BillPull", 1), new Actor("actors/ChristopherG", 1), new Actor("actors/CubaG", 1), + new Actor("actors/DemiM", 1), new Actor("actors/JackN", 1), new Actor("actors/JamesM", 1), + new Actor("actors/JTW", 1), new Actor("actors/KevinB", 1), new Actor("actors/KieferS", 1), + new Actor("actors/MegR", 2), new Actor("actors/Nathan", 1), new Actor("actors/NoahW", 1), + new Actor("actors/RitaW", 1), new Actor("actors/RosieO", 1), new Actor("actors/TomC", 1), + new Actor("actors/TomH", 2), new Actor("actors/VictorG", 1)); + } + + public static class Actor { + private String actor; + private Integer movies; + + public Actor() { + super(); + } + + Actor(final String actor, final Integer movies) { + super(); + this.actor = actor; + this.movies = movies; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actor == null) ? 0 : actor.hashCode()); + result = prime * result + ((movies == null) ? 0 : movies.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Actor other = (Actor) obj; + if (actor == null) { + if (other.actor != null) { + return false; + } + } else if (!actor.equals(other.actor)) { + return false; + } + if (movies == null) { + return other.movies == null; + } else return movies.equals(other.movies); + } + + } + + public static class Movie { + private String movie; + private Integer actors; + + public Movie() { + super(); + } + + Movie(final String movie, final Integer actors) { + super(); + this.movie = movie; + this.actors = actors; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actors == null) ? 0 : actors.hashCode()); + result = prime * result + ((movie == null) ? 0 : movie.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Movie other = (Movie) obj; + if (actors == null) { + if (other.actors != null) { + return false; + } + } else if (!actors.equals(other.actors)) { + return false; + } + if (movie == null) { + return other.movie == null; + } else return movie.equals(other.movie); + } + + } + + private static DocumentCreateEntity saveMovie( + final ArangoCollection movies, + final String key, + final String title, + final int released, + final String tagline) { + final BaseDocument value = new BaseDocument(); + value.setKey(key); + value.addAttribute("title", title); + value.addAttribute("released", released); + value.addAttribute("tagline", tagline); + return movies.insertDocument(value); + } + + private static DocumentCreateEntity saveActor( + final ArangoCollection actors, + final String key, + final String name, + final int born) { + final BaseDocument value = new BaseDocument(); + value.setKey(key); + value.addAttribute("name", name); + value.addAttribute("born", born); + return actors.insertDocument(value); + } + + private static void saveActsIn( + final ArangoCollection actsIn, + final String actor, + final String movie, + final String[] roles, + final int year) { + final BaseEdgeDocument value = new BaseEdgeDocument(); + value.setFrom(actor); + value.setTo(movie); + value.addAttribute("roles", roles); + value.addAttribute("year", year); + actsIn.insertDocument(value); + } + + private static void createData() { + db.createCollection("actors"); + final ArangoCollection actors = db.collection("actors"); + db.createCollection("movies"); + final ArangoCollection movies = db.collection("movies"); + db.createCollection("actsIn", new CollectionCreateOptions().type(CollectionType.EDGES)); + final ArangoCollection actsIn = db.collection("actsIn"); + + final String theMatrix = saveMovie(movies, "TheMatrix", "The Matrix", 1999, "Welcome to the Real World") + .getId(); + final String keanu = saveActor(actors, "Keanu", "Keanu Reeves", 1964).getId(); + final String carrie = saveActor(actors, "Carrie", "Carrie-Anne Moss", 1967).getId(); + final String laurence = saveActor(actors, "Laurence", "Laurence Fishburne", 1961).getId(); + final String hugo = saveActor(actors, "Hugo", "Hugo Weaving", 1960).getId(); + final String emil = saveActor(actors, "Emil", "Emil Eifrem", 1978).getId(); + + saveActsIn(actsIn, keanu, theMatrix, new String[]{"Neo"}, 1999); + saveActsIn(actsIn, carrie, theMatrix, new String[]{"Trinity"}, 1999); + saveActsIn(actsIn, laurence, theMatrix, new String[]{"Morpheus"}, 1999); + saveActsIn(actsIn, hugo, theMatrix, new String[]{"Agent Smith"}, 1999); + saveActsIn(actsIn, emil, theMatrix, new String[]{"Emil"}, 1999); + + final String theMatrixReloaded = saveMovie(movies, "TheMatrixReloaded", "The Matrix Reloaded", 2003, + "Free your mind").getId(); + saveActsIn(actsIn, keanu, theMatrixReloaded, new String[]{"Neo"}, 2003); + saveActsIn(actsIn, carrie, theMatrixReloaded, new String[]{"Trinity"}, 2003); + saveActsIn(actsIn, laurence, theMatrixReloaded, new String[]{"Morpheus"}, 2003); + saveActsIn(actsIn, hugo, theMatrixReloaded, new String[]{"Agent Smith"}, 2003); + + final String theMatrixRevolutions = saveMovie(movies, "TheMatrixRevolutions", "The Matrix Revolutions", 2003, + "Everything that has a beginning has an end").getId(); + saveActsIn(actsIn, keanu, theMatrixRevolutions, new String[]{"Neo"}, 2003); + saveActsIn(actsIn, carrie, theMatrixRevolutions, new String[]{"Trinity"}, 2003); + saveActsIn(actsIn, laurence, theMatrixRevolutions, new String[]{"Morpheus"}, 2003); + saveActsIn(actsIn, hugo, theMatrixRevolutions, new String[]{"Agent Smith"}, 2003); + + final String theDevilsAdvocate = saveMovie(movies, "TheDevilsAdvocate", "The Devil's Advocate", 1997, + "Evil has its winning ways").getId(); + final String charlize = saveActor(actors, "Charlize", "Charlize Theron", 1975).getId(); + final String al = saveActor(actors, "Al", "Al Pacino", 1940).getId(); + saveActsIn(actsIn, keanu, theDevilsAdvocate, new String[]{"Kevin Lomax"}, 1997); + saveActsIn(actsIn, charlize, theDevilsAdvocate, new String[]{"Mary Ann Lomax"}, 1997); + saveActsIn(actsIn, al, theDevilsAdvocate, new String[]{"John Milton"}, 1997); + + final String AFewGoodMen = saveMovie(movies, "AFewGoodMen", "A Few Good Men", 1992, + "In the heart of the nation's capital, in a courthouse of the U.S. government, one man will stop at nothing to keep his honor, and one will stop at nothing to find the truth.") + .getId(); + final String tomC = saveActor(actors, "TomC", "Tom Cruise", 1962).getId(); + final String jackN = saveActor(actors, "JackN", "Jack Nicholson", 1937).getId(); + final String demiM = saveActor(actors, "DemiM", "Demi Moore", 1962).getId(); + final String kevinB = saveActor(actors, "KevinB", "Kevin Bacon", 1958).getId(); + final String kieferS = saveActor(actors, "KieferS", "Kiefer Sutherland", 1966).getId(); + final String noahW = saveActor(actors, "NoahW", "Noah Wyle", 1971).getId(); + final String cubaG = saveActor(actors, "CubaG", "Cuba Gooding Jr.", 1968).getId(); + final String kevinP = saveActor(actors, "KevinP", "Kevin Pollak", 1957).getId(); + final String jTW = saveActor(actors, "JTW", "J.T. Walsh", 1943).getId(); + final String jamesM = saveActor(actors, "JamesM", "James Marshall", 1967).getId(); + final String christopherG = saveActor(actors, "ChristopherG", "Christopher Guest", 1948).getId(); + saveActsIn(actsIn, tomC, AFewGoodMen, new String[]{"Lt. Daniel Kaffee"}, 1992); + saveActsIn(actsIn, jackN, AFewGoodMen, new String[]{"Col. Nathan R. Jessup"}, 1992); + saveActsIn(actsIn, demiM, AFewGoodMen, new String[]{"Lt. Cdr. JoAnne Galloway"}, 1992); + saveActsIn(actsIn, kevinB, AFewGoodMen, new String[]{"Capt. Jack Ross"}, 1992); + saveActsIn(actsIn, kieferS, AFewGoodMen, new String[]{"Lt. Jonathan Kendrick"}, 1992); + saveActsIn(actsIn, noahW, AFewGoodMen, new String[]{"Cpl. Jeffrey Barnes"}, 1992); + saveActsIn(actsIn, cubaG, AFewGoodMen, new String[]{"Cpl. Carl Hammaker"}, 1992); + saveActsIn(actsIn, kevinP, AFewGoodMen, new String[]{"Lt. Sam Weinberg"}, 1992); + saveActsIn(actsIn, jTW, AFewGoodMen, new String[]{"Lt. Col. Matthew Andrew Markinson"}, 1992); + saveActsIn(actsIn, jamesM, AFewGoodMen, new String[]{"Pfc. Louden Downey"}, 1992); + saveActsIn(actsIn, christopherG, AFewGoodMen, new String[]{"Dr. Stone"}, 1992); + + final String topGun = saveMovie(movies, "TopGun", "Top Gun", 1986, "I feel the need, the need for speed.") + .getId(); + final String kellyM = saveActor(actors, "KellyM", "Kelly McGillis", 1957).getId(); + final String valK = saveActor(actors, "ValK", "Val Kilmer", 1959).getId(); + final String anthonyE = saveActor(actors, "AnthonyE", "Anthony Edwards", 1962).getId(); + final String tomS = saveActor(actors, "TomS", "Tom Skerritt", 1933).getId(); + final String megR = saveActor(actors, "MegR", "Meg Ryan", 1961).getId(); + saveActsIn(actsIn, tomC, topGun, new String[]{"Maverick"}, 1986); + saveActsIn(actsIn, kellyM, topGun, new String[]{"Charlie"}, 1986); + saveActsIn(actsIn, valK, topGun, new String[]{"Iceman"}, 1986); + saveActsIn(actsIn, anthonyE, topGun, new String[]{"Goose"}, 1986); + saveActsIn(actsIn, tomS, topGun, new String[]{"Viper"}, 1986); + saveActsIn(actsIn, megR, topGun, new String[]{"Carole"}, 1986); + + final String jerryMaguire = saveMovie(movies, "JerryMaguire", "Jerry Maguire", 2000, + "The rest of his life begins now.").getId(); + final String reneeZ = saveActor(actors, "ReneeZ", "Renee Zellweger", 1969).getId(); + final String kellyP = saveActor(actors, "KellyP", "Kelly Preston", 1962).getId(); + final String jerryO = saveActor(actors, "JerryO", "Jerry O'Connell", 1974).getId(); + final String jayM = saveActor(actors, "JayM", "Jay Mohr", 1970).getId(); + final String bonnieH = saveActor(actors, "BonnieH", "Bonnie Hunt", 1961).getId(); + final String reginaK = saveActor(actors, "ReginaK", "Regina King", 1971).getId(); + final String jonathanL = saveActor(actors, "JonathanL", "Jonathan Lipnicki", 1996).getId(); + saveActsIn(actsIn, tomC, jerryMaguire, new String[]{"Jerry Maguire"}, 2000); + saveActsIn(actsIn, cubaG, jerryMaguire, new String[]{"Rod Tidwell"}, 2000); + saveActsIn(actsIn, reneeZ, jerryMaguire, new String[]{"Dorothy Boyd"}, 2000); + saveActsIn(actsIn, kellyP, jerryMaguire, new String[]{"Avery Bishop"}, 2000); + saveActsIn(actsIn, jerryO, jerryMaguire, new String[]{"Frank Cushman"}, 2000); + saveActsIn(actsIn, jayM, jerryMaguire, new String[]{"Bob Sugar"}, 2000); + saveActsIn(actsIn, bonnieH, jerryMaguire, new String[]{"Laurel Boyd"}, 2000); + saveActsIn(actsIn, reginaK, jerryMaguire, new String[]{"Marcee Tidwell"}, 2000); + saveActsIn(actsIn, jonathanL, jerryMaguire, new String[]{"Ray Boyd"}, 2000); + + final String standByMe = saveMovie(movies, "StandByMe", "Stand By Me", 1986, + "For some, it's the last real taste of innocence, and the first real taste of life. But for everyone, it's the time that memories are made of.") + .getId(); + final String riverP = saveActor(actors, "RiverP", "River Phoenix", 1970).getId(); + final String coreyF = saveActor(actors, "CoreyF", "Corey Feldman", 1971).getId(); + final String wilW = saveActor(actors, "WilW", "Wil Wheaton", 1972).getId(); + final String johnC = saveActor(actors, "JohnC", "John Cusack", 1966).getId(); + final String marshallB = saveActor(actors, "MarshallB", "Marshall Bell", 1942).getId(); + saveActsIn(actsIn, wilW, standByMe, new String[]{"Gordie Lachance"}, 1986); + saveActsIn(actsIn, riverP, standByMe, new String[]{"Chris Chambers"}, 1986); + saveActsIn(actsIn, jerryO, standByMe, new String[]{"Vern Tessio"}, 1986); + saveActsIn(actsIn, coreyF, standByMe, new String[]{"Teddy Duchamp"}, 1986); + saveActsIn(actsIn, johnC, standByMe, new String[]{"Denny Lachance"}, 1986); + saveActsIn(actsIn, kieferS, standByMe, new String[]{"Ace Merrill"}, 1986); + saveActsIn(actsIn, marshallB, standByMe, new String[]{"Mr. Lachance"}, 1986); + + final String asGoodAsItGets = saveMovie(movies, "AsGoodAsItGets", "As Good as It Gets", 1997, + "A comedy from the heart that goes for the throat.").getId(); + final String helenH = saveActor(actors, "HelenH", "Helen Hunt", 1963).getId(); + final String gregK = saveActor(actors, "GregK", "Greg Kinnear", 1963).getId(); + saveActsIn(actsIn, jackN, asGoodAsItGets, new String[]{"Melvin Udall"}, 1997); + saveActsIn(actsIn, helenH, asGoodAsItGets, new String[]{"Carol Connelly"}, 1997); + saveActsIn(actsIn, gregK, asGoodAsItGets, new String[]{"Simon Bishop"}, 1997); + saveActsIn(actsIn, cubaG, asGoodAsItGets, new String[]{"Frank Sachs"}, 1997); + + final String whatDreamsMayCome = saveMovie(movies, "WhatDreamsMayCome", "What Dreams May Come", 1998, + "After life there is more. The end is just the beginning.").getId(); + final String annabellaS = saveActor(actors, "AnnabellaS", "Annabella Sciorra", 1960).getId(); + final String maxS = saveActor(actors, "MaxS", "Max von Sydow", 1929).getId(); + final String wernerH = saveActor(actors, "WernerH", "Werner Herzog", 1942).getId(); + final String robin = saveActor(actors, "Robin", "Robin Williams", 1951).getId(); + saveActsIn(actsIn, robin, whatDreamsMayCome, new String[]{"Chris Nielsen"}, 1998); + saveActsIn(actsIn, cubaG, whatDreamsMayCome, new String[]{"Albert Lewis"}, 1998); + saveActsIn(actsIn, annabellaS, whatDreamsMayCome, new String[]{"Annie Collins-Nielsen"}, 1998); + saveActsIn(actsIn, maxS, whatDreamsMayCome, new String[]{"The Tracker"}, 1998); + saveActsIn(actsIn, wernerH, whatDreamsMayCome, new String[]{"The Face"}, 1998); + + final String snowFallingonCedars = saveMovie(movies, "SnowFallingonCedars", "Snow Falling on Cedars", 1999, + "First loves last. Forever.").getId(); + final String ethanH = saveActor(actors, "EthanH", "Ethan Hawke", 1970).getId(); + final String rickY = saveActor(actors, "RickY", "Rick Yune", 1971).getId(); + final String jamesC = saveActor(actors, "JamesC", "James Cromwell", 1940).getId(); + saveActsIn(actsIn, ethanH, snowFallingonCedars, new String[]{"Ishmael Chambers"}, 1999); + saveActsIn(actsIn, rickY, snowFallingonCedars, new String[]{"Kazuo Miyamoto"}, 1999); + saveActsIn(actsIn, maxS, snowFallingonCedars, new String[]{"Nels Gudmundsson"}, 1999); + saveActsIn(actsIn, jamesC, snowFallingonCedars, new String[]{"Judge Fielding"}, 1999); + + final String youveGotMail = saveMovie(movies, "YouveGotMail", "You've Got Mail", 1998, + "At odds in life... in love on-line.").getId(); + final String parkerP = saveActor(actors, "ParkerP", "Parker Posey", 1968).getId(); + final String daveC = saveActor(actors, "DaveC", "Dave Chappelle", 1973).getId(); + final String steveZ = saveActor(actors, "SteveZ", "Steve Zahn", 1967).getId(); + final String tomH = saveActor(actors, "TomH", "Tom Hanks", 1956).getId(); + saveActsIn(actsIn, tomH, youveGotMail, new String[]{"Joe Fox"}, 1998); + saveActsIn(actsIn, megR, youveGotMail, new String[]{"Kathleen Kelly"}, 1998); + saveActsIn(actsIn, gregK, youveGotMail, new String[]{"Frank Navasky"}, 1998); + saveActsIn(actsIn, parkerP, youveGotMail, new String[]{"Patricia Eden"}, 1998); + saveActsIn(actsIn, daveC, youveGotMail, new String[]{"Kevin Jackson"}, 1998); + saveActsIn(actsIn, steveZ, youveGotMail, new String[]{"George Pappas"}, 1998); + + final String sleeplessInSeattle = saveMovie(movies, "SleeplessInSeattle", "Sleepless in Seattle", 1993, + "What if someone you never met, someone you never saw, someone you never knew was the only someone for you?") + .getId(); + final String ritaW = saveActor(actors, "RitaW", "Rita Wilson", 1956).getId(); + final String billPull = saveActor(actors, "BillPull", "Bill Pullman", 1953).getId(); + final String victorG = saveActor(actors, "VictorG", "Victor Garber", 1949).getId(); + final String rosieO = saveActor(actors, "RosieO", "Rosie O'Donnell", 1962).getId(); + saveActsIn(actsIn, tomH, sleeplessInSeattle, new String[]{"Sam Baldwin"}, 1993); + saveActsIn(actsIn, megR, sleeplessInSeattle, new String[]{"Annie Reed"}, 1993); + saveActsIn(actsIn, ritaW, sleeplessInSeattle, new String[]{"Suzy"}, 1993); + saveActsIn(actsIn, billPull, sleeplessInSeattle, new String[]{"Walter"}, 1993); + saveActsIn(actsIn, victorG, sleeplessInSeattle, new String[]{"Greg"}, 1993); + saveActsIn(actsIn, rosieO, sleeplessInSeattle, new String[]{"Becky"}, 1993); + + final String joeVersustheVolcano = saveMovie(movies, "JoeVersustheVolcano", "Joe Versus the Volcano", 1990, + "A story of love, lava and burning desire.").getId(); + final String nathan = saveActor(actors, "Nathan", "Nathan Lane", 1956).getId(); + saveActsIn(actsIn, tomH, joeVersustheVolcano, new String[]{"Joe Banks"}, 1990); + saveActsIn(actsIn, megR, joeVersustheVolcano, + new String[]{"DeDe', 'Angelica Graynamore', 'Patricia Graynamore"}, 1990); + saveActsIn(actsIn, nathan, joeVersustheVolcano, new String[]{"Baw"}, 1990); + + final String whenHarryMetSally = saveMovie(movies, "WhenHarryMetSally", "When Harry Met Sally", 1998, + "At odds in life... in love on-line.").getId(); + final String billyC = saveActor(actors, "BillyC", "Billy Crystal", 1948).getId(); + final String carrieF = saveActor(actors, "CarrieF", "Carrie Fisher", 1956).getId(); + final String brunoK = saveActor(actors, "BrunoK", "Bruno Kirby", 1949).getId(); + saveActsIn(actsIn, billyC, whenHarryMetSally, new String[]{"Harry Burns"}, 1998); + saveActsIn(actsIn, megR, whenHarryMetSally, new String[]{"Sally Albright"}, 1998); + saveActsIn(actsIn, carrieF, whenHarryMetSally, new String[]{"Marie"}, 1998); + saveActsIn(actsIn, brunoK, whenHarryMetSally, new String[]{"Jess"}, 1998); + } + +} diff --git a/src/test/java/com/arangodb/example/graph/BaseGraphTest.java b/src/test/java/com/arangodb/example/graph/BaseGraphTest.java index ff25732c8..f74c4ed42 100644 --- a/src/test/java/com/arangodb/example/graph/BaseGraphTest.java +++ b/src/test/java/com/arangodb/example/graph/BaseGraphTest.java @@ -23,10 +23,12 @@ import com.arangodb.ArangoDB; import com.arangodb.ArangoDBException; import com.arangodb.ArangoDatabase; +import com.arangodb.DbName; import com.arangodb.entity.EdgeDefinition; import com.arangodb.entity.VertexEntity; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import java.util.ArrayList; import java.util.Collection; @@ -34,19 +36,19 @@ /** * @author Mark Vollmary */ -public abstract class BaseGraphTest { +abstract class BaseGraphTest { - private static final String TEST_DB = "java_driver_graph_test_db"; + private static final DbName TEST_DB = DbName.of("java_driver_graph_test_db"); private static ArangoDB arangoDB; static ArangoDatabase db; private static final String GRAPH_NAME = "traversalGraph"; private static final String EDGE_COLLECTION_NAME = "edges"; - private static final String VERTEXT_COLLECTION_NAME = "circles"; + private static final String VERTEX_COLLECTION_NAME = "circles"; - @BeforeClass - public static void init() { + @BeforeAll + static void init() { if (arangoDB == null) { - arangoDB = new ArangoDB.Builder().build(); + arangoDB = new ArangoDB.Builder().serializer(new ArangoJack()).build(); } if (arangoDB.db(TEST_DB).exists()) arangoDB.db(TEST_DB).drop(); @@ -55,15 +57,15 @@ public static void init() { final Collection edgeDefinitions = new ArrayList<>(); final EdgeDefinition edgeDefinition = new EdgeDefinition().collection(EDGE_COLLECTION_NAME) - .from(VERTEXT_COLLECTION_NAME).to(VERTEXT_COLLECTION_NAME); + .from(VERTEX_COLLECTION_NAME).to(VERTEX_COLLECTION_NAME); edgeDefinitions.add(edgeDefinition); if (!db.graph(GRAPH_NAME).exists()) db.createGraph(GRAPH_NAME, edgeDefinitions, null); addExampleElements(); } - @AfterClass - public static void shutdown() { + @AfterAll + static void shutdown() { arangoDB.db(TEST_DB).drop(); arangoDB.shutdown(); arangoDB = null; @@ -104,7 +106,7 @@ private static void saveEdge(final CircleEdge edge) throws ArangoDBException { } private static VertexEntity createVertex(final Circle vertex) throws ArangoDBException { - return db.graph(GRAPH_NAME).vertexCollection(VERTEXT_COLLECTION_NAME).insertVertex(vertex); + return db.graph(GRAPH_NAME).vertexCollection(VERTEX_COLLECTION_NAME).insertVertex(vertex); } } diff --git a/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java b/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java deleted file mode 100644 index 1738cb345..000000000 --- a/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * 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 - * - * 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. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.example.graph; - -import com.arangodb.ArangoCursor; -import com.arangodb.ArangoDBException; -import org.junit.Test; - -import java.util.Collection; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.is; - - -/** - * Graph traversals in AQL - * - * @author a-brandt - * @see Graph traversals in AQL - */ -public class GraphTraversalsInAQLExample extends BaseGraphTest { - - @Test - public void queryAllVertices() throws ArangoDBException { - String queryString = "FOR v IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' RETURN v._key"; - ArangoCursor cursor = db.query(queryString, null, null, String.class); - Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(10)); - - queryString = "WITH circles FOR v IN 1..3 OUTBOUND 'circles/A' edges RETURN v._key"; - cursor = db.query(queryString, null, null, String.class); - result = cursor.asListRemaining(); - assertThat(result.size(), is(10)); - } - - @Test - public void queryDepthTwo() throws ArangoDBException { - String queryString = "FOR v IN 2..2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; - ArangoCursor cursor = db.query(queryString, null, null, String.class); - Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(4)); - assertThat(result, hasItems("C", "E", "H", "J")); - - queryString = "FOR v IN 2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; - cursor = db.query(queryString, null, null, String.class); - result = cursor.asListRemaining(); - assertThat(result.size(), is(4)); - assertThat(result, hasItems("C", "E", "H", "J")); - } - - @Test - public void queryWithFilter() throws ArangoDBException { - String queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' RETURN v._key"; - ArangoCursor cursor = db.query(queryString, null, null, String.class); - Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(5)); - assertThat(result, hasItems("B", "C", "D", "E", "F")); - - queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.edges[0].label != 'right_foo' RETURN v._key"; - cursor = db.query(queryString, null, null, String.class); - result = cursor.asListRemaining(); - assertThat(result.size(), is(5)); - assertThat(result, hasItems("B", "C", "D", "E", "F")); - - queryString = "FOR v,e,p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' FILTER p.edges[1].label != 'left_blub' return v._key"; - cursor = db.query(queryString, null, null, String.class); - - result = cursor.asListRemaining(); - assertThat(result.size(), is(3)); - assertThat(result, hasItems("B", "C", "D")); - - queryString = "FOR v,e,p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' AND p.edges[1].label != 'left_blub' return v._key"; - cursor = db.query(queryString, null, null, String.class); - result = cursor.asListRemaining(); - assertThat(result.size(), is(3)); - assertThat(result, hasItems("B", "C", "D")); - } - - @Test - public void queryOutboundInbound() throws ArangoDBException { - String queryString = "FOR v IN 1..3 OUTBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; - ArangoCursor cursor = db.query(queryString, null, null, String.class); - Collection result = cursor.asListRemaining(); - assertThat(result.size(), is(1)); - assertThat(result, hasItems("F")); - - queryString = "FOR v IN 1..3 INBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; - cursor = db.query(queryString, null, null, String.class); - result = cursor.asListRemaining(); - assertThat(result.size(), is(2)); - assertThat(result, hasItems("B", "A")); - - queryString = "FOR v IN 1..3 ANY 'circles/E' GRAPH 'traversalGraph' return v._key"; - cursor = db.query(queryString, null, null, String.class); - - result = cursor.asListRemaining(); - assertThat(result.size(), is(6)); - assertThat(result, hasItems("F", "B", "C", "D", "A", "G")); - } - -} diff --git a/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExampleTest.java b/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExampleTest.java new file mode 100644 index 000000000..35330c490 --- /dev/null +++ b/src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExampleTest.java @@ -0,0 +1,109 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * 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 + * + * 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. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example.graph; + +import com.arangodb.ArangoCursor; +import com.arangodb.ArangoDBException; +import org.junit.jupiter.api.Test; + +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + + +/** + * Graph traversals in AQL + * + * @author a-brandt + * @see Graph traversals in AQL + */ +class GraphTraversalsInAQLExampleTest extends BaseGraphTest { + + @Test + void queryAllVertices() throws ArangoDBException { + String queryString = "FOR v IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' RETURN v._key"; + ArangoCursor cursor = db.query(queryString, null, null, String.class); + Collection result = cursor.asListRemaining(); + assertThat(result).hasSize(10); + + queryString = "WITH circles FOR v IN 1..3 OUTBOUND 'circles/A' edges RETURN v._key"; + cursor = db.query(queryString, null, null, String.class); + result = cursor.asListRemaining(); + assertThat(result).hasSize(10); + } + + @Test + void queryDepthTwo() throws ArangoDBException { + String queryString = "FOR v IN 2..2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; + ArangoCursor cursor = db.query(queryString, null, null, String.class); + Collection result = cursor.asListRemaining(); + assertThat(result).containsExactlyInAnyOrder("C", "E", "H", "J"); + + queryString = "FOR v IN 2 OUTBOUND 'circles/A' GRAPH 'traversalGraph' return v._key"; + cursor = db.query(queryString, null, null, String.class); + result = cursor.asListRemaining(); + assertThat(result).containsExactlyInAnyOrder("C", "E", "H", "J"); + } + + @Test + void queryWithFilter() throws ArangoDBException { + String queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' RETURN v._key"; + ArangoCursor cursor = db.query(queryString, null, null, String.class); + Collection result = cursor.asListRemaining(); + assertThat(result).containsExactlyInAnyOrder("B", "C", "D", "E", "F"); + + queryString = "FOR v, e, p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.edges[0].label != 'right_foo' RETURN v._key"; + cursor = db.query(queryString, null, null, String.class); + result = cursor.asListRemaining(); + assertThat(result).containsExactlyInAnyOrder("B", "C", "D", "E", "F"); + + queryString = "FOR v,e,p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' FILTER p.edges[1].label != 'left_blub' return v._key"; + cursor = db.query(queryString, null, null, String.class); + + result = cursor.asListRemaining(); + assertThat(result).containsExactlyInAnyOrder("B", "C", "D"); + + queryString = "FOR v,e,p IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' FILTER p.vertices[1]._key != 'G' AND p.edges[1].label != 'left_blub' return v._key"; + cursor = db.query(queryString, null, null, String.class); + result = cursor.asListRemaining(); + assertThat(result).containsExactlyInAnyOrder("B", "C", "D"); + } + + @Test + void queryOutboundInbound() throws ArangoDBException { + String queryString = "FOR v IN 1..3 OUTBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; + ArangoCursor cursor = db.query(queryString, null, null, String.class); + Collection result = cursor.asListRemaining(); + assertThat(result).containsExactlyInAnyOrder("F"); + + queryString = "FOR v IN 1..3 INBOUND 'circles/E' GRAPH 'traversalGraph' return v._key"; + cursor = db.query(queryString, null, null, String.class); + result = cursor.asListRemaining(); + assertThat(result).containsExactlyInAnyOrder("B", "A"); + + queryString = "FOR v IN 1..3 ANY 'circles/E' GRAPH 'traversalGraph' return v._key"; + cursor = db.query(queryString, null, null, String.class); + + result = cursor.asListRemaining(); + assertThat(result).containsExactlyInAnyOrder("F", "B", "C", "D", "A", "G"); + } + +} diff --git a/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java b/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java deleted file mode 100644 index 613fa8892..000000000 --- a/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * 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 - * - * 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. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.example.graph; - -import com.arangodb.ArangoCursor; -import com.arangodb.ArangoDBException; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.is; - - -/** - * Shortest Path in AQL - * - * @author a-brandt - * @see Shortest Path in AQL - */ -public class ShortestPathInAQLExample extends BaseGraphTest { - - @SuppressWarnings({"WeakerAccess", "unused"}) - public static class Pair { - - private String vertex; - private String edge; - - public String getVertex() { - return vertex; - } - - public void setVertex(final String vertex) { - this.vertex = vertex; - } - - public String getEdge() { - return edge; - } - - public void setEdge(final String edge) { - this.edge = edge; - } - - } - - @Test - public void queryShortestPathFromAToD() throws ArangoDBException { - String queryString = "FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' GRAPH 'traversalGraph' RETURN {'vertex': v._key, 'edge': e._key}"; - ArangoCursor cursor = db.query(queryString, null, null, Pair.class); - final Collection collection = toVertexCollection(cursor); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); - - queryString = "WITH circles FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' edges RETURN {'vertex': v._key, 'edge': e._key}"; - db.query(queryString, null, null, Pair.class); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); - } - - @Test - public void queryShortestPathByFilter() throws ArangoDBException { - String queryString = "FOR a IN circles FILTER a._key == 'A' FOR d IN circles FILTER d._key == 'D' FOR v, e IN OUTBOUND SHORTEST_PATH a TO d GRAPH 'traversalGraph' RETURN {'vertex':v._key, 'edge':e._key}"; - ArangoCursor cursor = db.query(queryString, null, null, Pair.class); - final Collection collection = toVertexCollection(cursor); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); - - queryString = "FOR a IN circles FILTER a._key == 'A' FOR d IN circles FILTER d._key == 'D' FOR v, e IN OUTBOUND SHORTEST_PATH a TO d edges RETURN {'vertex': v._key, 'edge': e._key}"; - db.query(queryString, null, null, Pair.class); - assertThat(collection.size(), is(4)); - assertThat(collection, hasItems("A", "B", "C", "D")); - } - - private Collection toVertexCollection(final ArangoCursor cursor) { - final List result = new ArrayList<>(); - for (; cursor.hasNext(); ) { - final Pair pair = cursor.next(); - result.add(pair.getVertex()); - } - return result; - } - -} diff --git a/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExampleTest.java b/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExampleTest.java new file mode 100644 index 000000000..7eb87fcb3 --- /dev/null +++ b/src/test/java/com/arangodb/example/graph/ShortestPathInAQLExampleTest.java @@ -0,0 +1,102 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * 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 + * + * 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. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example.graph; + +import com.arangodb.ArangoCursor; +import com.arangodb.ArangoDBException; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Shortest Path in AQL + * + * @author a-brandt + * @see Shortest Path in AQL + */ +class ShortestPathInAQLExampleTest extends BaseGraphTest { + + @SuppressWarnings({"WeakerAccess", "unused"}) + public static class Pair { + + private String vertex; + private String edge; + + String getVertex() { + return vertex; + } + + void setVertex(final String vertex) { + this.vertex = vertex; + } + + String getEdge() { + return edge; + } + + void setEdge(final String edge) { + this.edge = edge; + } + + } + + @Test + void queryShortestPathFromAToD() throws ArangoDBException { + String queryString = "FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' GRAPH 'traversalGraph' RETURN {'vertex': v._key, 'edge': e._key}"; + ArangoCursor cursor = db.query(queryString, null, null, Pair.class); + final Collection collection = toVertexCollection(cursor); + assertThat(collection.size()).isEqualTo(4); + assertThat(collection).containsExactlyInAnyOrder("A", "B", "C", "D"); + + queryString = "WITH circles FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' edges RETURN {'vertex': v._key, 'edge': e._key}"; + db.query(queryString, null, null, Pair.class); + assertThat(collection.size()).isEqualTo(4); + assertThat(collection).containsExactlyInAnyOrder("A", "B", "C", "D"); + } + + @Test + void queryShortestPathByFilter() throws ArangoDBException { + String queryString = "FOR a IN circles FILTER a._key == 'A' FOR d IN circles FILTER d._key == 'D' FOR v, e IN OUTBOUND SHORTEST_PATH a TO d GRAPH 'traversalGraph' RETURN {'vertex':v._key, 'edge':e._key}"; + ArangoCursor cursor = db.query(queryString, null, null, Pair.class); + final Collection collection = toVertexCollection(cursor); + assertThat(collection.size()).isEqualTo(4); + assertThat(collection).containsExactlyInAnyOrder("A", "B", "C", "D"); + + queryString = "FOR a IN circles FILTER a._key == 'A' FOR d IN circles FILTER d._key == 'D' FOR v, e IN OUTBOUND SHORTEST_PATH a TO d edges RETURN {'vertex': v._key, 'edge': e._key}"; + db.query(queryString, null, null, Pair.class); + assertThat(collection.size()).isEqualTo(4); + assertThat(collection).containsExactlyInAnyOrder("A", "B", "C", "D"); + } + + private Collection toVertexCollection(final ArangoCursor cursor) { + final List result = new ArrayList<>(); + while (cursor.hasNext()) { + final Pair pair = cursor.next(); + result.add(pair.getVertex()); + } + return result; + } + +} diff --git a/src/test/java/com/arangodb/example/ssl/SslExample.java b/src/test/java/com/arangodb/example/ssl/SslExample.java deleted file mode 100644 index 7512f30ff..000000000 --- a/src/test/java/com/arangodb/example/ssl/SslExample.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * 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 - * - * 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. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.example.ssl; - -import com.arangodb.ArangoDB; -import com.arangodb.Protocol; -import com.arangodb.entity.ArangoDBVersion; -import org.apache.http.conn.ssl.NoopHostnameVerifier; -import org.junit.Ignore; -import org.junit.Test; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; -import java.security.KeyStore; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; - -/** - * @author Mark Vollmary - */ -public class SslExample { - - /*- - * a SSL trust store - * - * create the trust store for the self signed certificate: - * keytool -import -alias "my arangodb server cert" -file server.pem -keystore example.truststore - * - * Documentation: - * https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/conn/ssl/SSLSocketFactory.html - */ - private static final String SSL_TRUSTSTORE = "/example.truststore"; - private static final String SSL_TRUSTSTORE_PASSWORD = "12345678"; - - @Test - @Ignore - public void connect() throws Exception { - final ArangoDB arangoDB = new ArangoDB.Builder() - .host("localhost", 8529) - .password("test") - .useSsl(true) - .sslContext(createSslContext()) - .useProtocol(Protocol.HTTP_JSON) - .build(); - final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); - System.out.println(version.getVersion()); - } - - @Test - @Ignore - public void noopHostnameVerifier() throws Exception { - final ArangoDB arangoDB = new ArangoDB.Builder() - .host("127.0.0.1", 8529) - .password("test") - .useSsl(true) - .sslContext(createSslContext()) - .hostnameVerifier(NoopHostnameVerifier.INSTANCE) - .useProtocol(Protocol.HTTP_JSON) - .build(); - final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); - System.out.println(version.getVersion()); - } - - private SSLContext createSslContext() throws Exception { - final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray()); - - final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - kmf.init(ks, SSL_TRUSTSTORE_PASSWORD.toCharArray()); - - final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(ks); - - final SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sc; - } - -} diff --git a/src/test/java/com/arangodb/async/ArangoSslTest.java b/src/test/java/com/arangodb/example/ssl/SslExampleTest.java similarity index 52% rename from src/test/java/com/arangodb/async/ArangoSslTest.java rename to src/test/java/com/arangodb/example/ssl/SslExampleTest.java index a520b3fe1..a21384bdd 100644 --- a/src/test/java/com/arangodb/async/ArangoSslTest.java +++ b/src/test/java/com/arangodb/example/ssl/SslExampleTest.java @@ -18,34 +18,35 @@ * Copyright holder is ArangoDB GmbH, Cologne, Germany */ -package com.arangodb.async; +package com.arangodb.example.ssl; -import com.arangodb.ArangoDBException; +import com.arangodb.ArangoDB; +import com.arangodb.Protocol; import com.arangodb.entity.ArangoDBVersion; -import org.junit.Ignore; -import org.junit.Test; +import com.arangodb.mapping.ArangoJack; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.TrustManagerFactory; import java.security.KeyStore; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Vollmary + * @author Michele Rastelli */ -public class ArangoSslTest { +@EnabledIfSystemProperty(named = "SslTest", matches = "true") +class SslExampleTest { /*- * a SSL trust store * * create the trust store for the self signed certificate: - * keytool -import -alias "my arangodb server cert" -file UnitTests/server.pem -keystore example.truststore + * keytool -import -alias "my arangodb server cert" -file server.pem -keystore example.truststore * * Documentation: * https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/conn/ssl/SSLSocketFactory.html @@ -54,8 +55,37 @@ public class ArangoSslTest { private static final String SSL_TRUSTSTORE_PASSWORD = "12345678"; @Test - @Ignore - public void connect() throws Exception { + void connect() throws Exception { + final ArangoDB arangoDB = new ArangoDB.Builder() + .serializer(new ArangoJack()) + .host("localhost", 8529) + .password("test") + .useSsl(true) + .sslContext(createSslContext()) + .useProtocol(Protocol.HTTP_JSON) + .build(); + final ArangoDBVersion version = arangoDB.getVersion(); + assertThat(version).isNotNull(); + System.out.println(version.getVersion()); + } + + @Test + void noopHostnameVerifier() throws Exception { + final ArangoDB arangoDB = new ArangoDB.Builder() + .serializer(new ArangoJack()) + .host("127.0.0.1", 8529) + .password("test") + .useSsl(true) + .sslContext(createSslContext()) + .hostnameVerifier(NoopHostnameVerifier.INSTANCE) + .useProtocol(Protocol.HTTP_JSON) + .build(); + final ArangoDBVersion version = arangoDB.getVersion(); + assertThat(version).isNotNull(); + System.out.println(version.getVersion()); + } + + private SSLContext createSslContext() throws Exception { final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray()); @@ -68,25 +98,7 @@ public void connect() throws Exception { final SSLContext sc = SSLContext.getInstance("TLS"); sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder() - .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) - .sslContext(sc).build(); - final ArangoDBVersion version = arangoDB.getVersion().get(); - assertThat(version, is(notNullValue())); - } - - @Test - @Ignore - public void connectWithoutValidSslContext() throws Exception { - try { - final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder() - .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true) - .build(); - arangoDB.getVersion().get(); - fail("this should fail"); - } catch (final ArangoDBException ex) { - assertThat(ex.getCause() instanceof SSLHandshakeException, is(true)); - } + return sc; } } diff --git a/src/test/java/com/arangodb/example/velocypack/VPackExample.java b/src/test/java/com/arangodb/example/velocypack/VPackExample.java deleted file mode 100644 index 3cda187f1..000000000 --- a/src/test/java/com/arangodb/example/velocypack/VPackExample.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * 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 - * - * 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. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.example.velocypack; - -import com.arangodb.velocypack.VPackBuilder; -import com.arangodb.velocypack.VPackSlice; -import com.arangodb.velocypack.ValueType; -import com.arangodb.velocypack.exception.VPackException; -import org.junit.Test; - -import java.util.Iterator; -import java.util.Map.Entry; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - -/** - * @author Mark Vollmary - */ -public class VPackExample { - - @Test - public void buildObject() throws VPackException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT);// object start - builder.add("foo", 1); // add field "foo" with value 1 - builder.add("bar", 2); // add field "bar" with value 2 - builder.close();// object end - - final VPackSlice slice = builder.slice(); // create slice - assertThat(slice.isObject(), is(true)); - assertThat(slice.size(), is(2)); // number of fields - - final VPackSlice foo = slice.get("foo"); // get field "foo" - assertThat(foo.isInteger(), is(true)); - assertThat(foo.getAsInt(), is(1)); - - final VPackSlice bar = slice.get("bar"); // get field "bar" - assertThat(bar.isInteger(), is(true)); - assertThat(bar.getAsInt(), is(2)); - - // iterate over the fields - for (final Iterator> iterator = slice.objectIterator(); iterator.hasNext(); ) { - final Entry field = iterator.next(); - assertThat(field.getValue().isInteger(), is(true)); - } - } - - @Test - public void buildArray() throws VPackException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.ARRAY); // array start - builder.add(1);// add value 1 - builder.add(2);// add value 2 - builder.add(3);// add value 3 - builder.close(); // array end - - final VPackSlice slice = builder.slice();// create slice - assertThat(slice.isArray(), is(true)); - assertThat(slice.size(), is(3));// number of values - - // iterate over values - for (int i = 0; i < slice.size(); i++) { - final VPackSlice value = slice.get(i); - assertThat(value.isInteger(), is(true)); - assertThat(value.getAsInt(), is(i + 1)); - } - - // iterate over values with Iterator - for (final Iterator iterator = slice.arrayIterator(); iterator.hasNext(); ) { - final VPackSlice value = iterator.next(); - assertThat(value.isInteger(), is(true)); - } - } - - @Test - public void buildObjectInObject() throws VPackException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT);// object start - builder.add("foo", ValueType.OBJECT); // add object in field "foo" - builder.add("bar", 2); // add field "bar" with value 2 to object "foo" - builder.close();// object "foo" end - builder.close();// object end - - final VPackSlice slice = builder.slice(); // create slice - assertThat(slice.isObject(), is(true)); - - final VPackSlice foo = slice.get("foo"); - assertThat(foo.isObject(), is(true)); - - final VPackSlice bar = foo.get("bar"); // get field "bar" from "foo" - assertThat(bar.isInteger(), is(true)); - } - -} diff --git a/src/test/java/com/arangodb/example/velocypack/VPackExampleTest.java b/src/test/java/com/arangodb/example/velocypack/VPackExampleTest.java new file mode 100644 index 000000000..dd1d1e421 --- /dev/null +++ b/src/test/java/com/arangodb/example/velocypack/VPackExampleTest.java @@ -0,0 +1,113 @@ +/* + * DISCLAIMER + * + * Copyright 2016 ArangoDB GmbH, Cologne, Germany + * + * 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 + * + * 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. + * + * Copyright holder is ArangoDB GmbH, Cologne, Germany + */ + +package com.arangodb.example.velocypack; + +import com.arangodb.velocypack.VPackBuilder; +import com.arangodb.velocypack.VPackSlice; +import com.arangodb.velocypack.ValueType; +import com.arangodb.velocypack.exception.VPackException; +import org.junit.jupiter.api.Test; + +import java.util.Iterator; +import java.util.Map.Entry; + +import static org.assertj.core.api.Assertions.assertThat; + + +/** + * @author Mark Vollmary + */ +class VPackExampleTest { + + @Test + void buildObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT);// object start + builder.add("foo", 1); // add field "foo" with value 1 + builder.add("bar", 2); // add field "bar" with value 2 + builder.close();// object end + + final VPackSlice slice = builder.slice(); // create slice + assertThat(slice.isObject()).isTrue(); + assertThat(slice.size()).isEqualTo(2); // number of fields + + final VPackSlice foo = slice.get("foo"); // get field "foo" + assertThat(foo.isInteger()).isTrue(); + assertThat(foo.getAsInt()).isEqualTo(1); + + final VPackSlice bar = slice.get("bar"); // get field "bar" + assertThat(bar.isInteger()).isTrue(); + assertThat(bar.getAsInt()).isEqualTo(2); + + // iterate over the fields + for (final Iterator> iterator = slice.objectIterator(); iterator.hasNext(); ) { + final Entry field = iterator.next(); + assertThat(field.getValue().isInteger()).isTrue(); + } + } + + @Test + void buildArray() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); // array start + builder.add(1);// add value 1 + builder.add(2);// add value 2 + builder.add(3);// add value 3 + builder.close(); // array end + + final VPackSlice slice = builder.slice();// create slice + assertThat(slice.isArray()).isTrue(); + assertThat(slice.size()).isEqualTo(3);// number of values + + // iterate over values + for (int i = 0; i < slice.size(); i++) { + final VPackSlice value = slice.get(i); + assertThat(value.isInteger()).isTrue(); + assertThat(value.getAsInt()).isEqualTo(i + 1); + } + + // iterate over values with Iterator + for (final Iterator iterator = slice.arrayIterator(); iterator.hasNext(); ) { + final VPackSlice value = iterator.next(); + assertThat(value.isInteger()).isTrue(); + } + } + + @Test + void buildObjectInObject() throws VPackException { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT);// object start + builder.add("foo", ValueType.OBJECT); // add object in field "foo" + builder.add("bar", 2); // add field "bar" with value 2 to object "foo" + builder.close();// object "foo" end + builder.close();// object end + + final VPackSlice slice = builder.slice(); // create slice + assertThat(slice.isObject()).isTrue(); + + final VPackSlice foo = slice.get("foo"); + assertThat(foo.isObject()).isTrue(); + + final VPackSlice bar = foo.get("bar"); // get field "bar" from "foo" + assertThat(bar.isInteger()).isTrue(); + } + +} diff --git a/src/test/java/com/arangodb/internal/DocumentCacheTest.java b/src/test/java/com/arangodb/internal/DocumentCacheTest.java index 46bc001c4..16a2e90a2 100644 --- a/src/test/java/com/arangodb/internal/DocumentCacheTest.java +++ b/src/test/java/com/arangodb/internal/DocumentCacheTest.java @@ -22,29 +22,27 @@ import com.arangodb.entity.BaseDocument; import com.arangodb.entity.DocumentField; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Vollmary */ -public class DocumentCacheTest { +class DocumentCacheTest { @Test - public void setValues() { + void setValues() { final DocumentCache cache = new DocumentCache(); final BaseDocument doc = new BaseDocument(); - assertThat(doc.getId(), is(nullValue())); - assertThat(doc.getKey(), is(nullValue())); - assertThat(doc.getRevision(), is(nullValue())); + assertThat(doc.getId()).isNull(); + assertThat(doc.getKey()).isNull(); + assertThat(doc.getRevision()).isNull(); final Map values = new HashMap<>(); values.put(DocumentField.Type.ID, "testId"); @@ -52,13 +50,13 @@ public void setValues() { values.put(DocumentField.Type.REV, "testRev"); cache.setValues(doc, values); - assertThat(doc.getId(), is("testId")); - assertThat(doc.getKey(), is("testKey")); - assertThat(doc.getRevision(), is("testRev")); + assertThat(doc.getId()).isEqualTo("testId"); + assertThat(doc.getKey()).isEqualTo("testKey"); + assertThat(doc.getRevision()).isEqualTo("testRev"); } @Test - public void setValuesMap() { + void setValuesMap() { final DocumentCache cache = new DocumentCache(); final Map map = new HashMap<>(); @@ -68,6 +66,6 @@ public void setValuesMap() { values.put(DocumentField.Type.REV, "testRev"); cache.setValues(map, values); - assertThat(map.isEmpty(), is(true)); + assertThat(map.isEmpty()).isTrue(); } } diff --git a/src/test/java/com/arangodb/internal/HostHandlerTest.java b/src/test/java/com/arangodb/internal/HostHandlerTest.java index b25585e50..56b09ca5d 100644 --- a/src/test/java/com/arangodb/internal/HostHandlerTest.java +++ b/src/test/java/com/arangodb/internal/HostHandlerTest.java @@ -24,20 +24,17 @@ import com.arangodb.ArangoDBMultipleException; import com.arangodb.internal.net.*; import com.arangodb.util.ArangoSerialization; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import java.io.IOException; import java.util.List; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Mark Vollmary */ -public class HostHandlerTest { +class HostHandlerTest { private static final ConnectionPool mockCP = new ConnectionPool() { @Override @@ -56,7 +53,7 @@ public void setJwt(String jwt) { } @Override - public void close() throws IOException { + public void close() { } }; @@ -102,90 +99,93 @@ public void init(ArangoExecutorSync executor, ArangoSerialization arangoSerializ }; @Test - public void fallbackHostHandlerSingleHost() { + void fallbackHostHandlerSingleHost() { final HostHandler handler = new FallbackHostHandler(SINGLE_HOST); - assertThat(handler.get(null, null), is(HOST_0)); + assertThat(handler.get(null, null)).isEqualTo(HOST_0); handler.fail(new RuntimeException()); - assertThat(handler.get(null, null), is(HOST_0)); + assertThat(handler.get(null, null)).isEqualTo(HOST_0); } @Test - public void fallbackHostHandlerMultipleHosts() { + void fallbackHostHandlerMultipleHosts() { final HostHandler handler = new FallbackHostHandler(MULTIPLE_HOSTS); for (int i = 0; i < 3; i++) { - assertThat(handler.get(null, null), is(HOST_0)); + assertThat(handler.get(null, null)).isEqualTo(HOST_0); handler.fail(new RuntimeException("HOST_0 failed")); - assertThat(handler.get(null, null), is(HOST_1)); + assertThat(handler.get(null, null)).isEqualTo(HOST_1); handler.fail(new RuntimeException("HOST_1 failed")); - assertThat(handler.get(null, null), is(HOST_2)); + assertThat(handler.get(null, null)).isEqualTo(HOST_2); handler.fail(new RuntimeException("HOST_2 failed")); if (i < 2) { - assertThat(handler.get(null, null), is(HOST_0)); + assertThat(handler.get(null, null)).isEqualTo(HOST_0); } else { try { handler.get(null, null); fail(); } catch (ArangoDBException e) { - assertThat(e.getCause(), is(notNullValue())); - assertThat(e.getCause(), is(instanceOf(ArangoDBMultipleException.class))); + assertThat(e.getCause()).isNotNull(); + assertThat(e.getCause()).isInstanceOf(ArangoDBMultipleException.class); List exceptions = ((ArangoDBMultipleException) e.getCause()).getExceptions(); - assertThat(exceptions.get(0), is(instanceOf(RuntimeException.class))); - assertThat(exceptions.get(0).getMessage(), is("HOST_0 failed")); - assertThat(exceptions.get(1), is(instanceOf(RuntimeException.class))); - assertThat(exceptions.get(1).getMessage(), is("HOST_1 failed")); - assertThat(exceptions.get(2), is(instanceOf(RuntimeException.class))); - assertThat(exceptions.get(2).getMessage(), is("HOST_2 failed")); + assertThat(exceptions.get(0)).isInstanceOf(RuntimeException.class); + assertThat(exceptions.get(0).getMessage()).isEqualTo("HOST_0 failed"); + assertThat(exceptions.get(1)).isInstanceOf(RuntimeException.class); + assertThat(exceptions.get(1).getMessage()).isEqualTo("HOST_1 failed"); + assertThat(exceptions.get(2)).isInstanceOf(RuntimeException.class); + assertThat(exceptions.get(2).getMessage()).isEqualTo("HOST_2 failed"); } } } } @Test - public void randomHostHandlerSingleHost() { + void randomHostHandlerSingleHost() { final HostHandler handler = new RandomHostHandler(SINGLE_HOST, new FallbackHostHandler(SINGLE_HOST)); - assertThat(handler.get(null, null), is(HOST_0)); + assertThat(handler.get(null, null)).isEqualTo(HOST_0); handler.fail(new RuntimeException()); - assertThat(handler.get(null, null), is(HOST_0)); + assertThat(handler.get(null, null)).isEqualTo(HOST_0); } @Test - public void randomHostHandlerMultipeHosts() { + void randomHostHandlerMultipleHosts() { final HostHandler handler = new RandomHostHandler(MULTIPLE_HOSTS, new FallbackHostHandler(MULTIPLE_HOSTS)); final Host pick0 = handler.get(null, null); - assertThat(pick0, anyOf(is(HOST_0), is(HOST_1), is(HOST_2))); + assertThat(pick0).isIn(HOST_0, HOST_1, HOST_2); handler.fail(new RuntimeException()); final Host pick1 = handler.get(null, null); - assertThat(pick1, anyOf(is(HOST_0), is(HOST_1), is(HOST_2))); + assertThat(pick1).isIn(HOST_0, HOST_1, HOST_2); handler.success(); final Host pick3 = handler.get(null, null); - assertThat(pick3, anyOf(is(HOST_0), is(HOST_1), is(HOST_2))); - assertThat(pick3, is(pick1)); + assertThat(pick3) + .isIn(HOST_0, HOST_1, HOST_2) + .isEqualTo(pick1); } @Test - public void roundRobinHostHandlerSingleHost() { + void roundRobinHostHandlerSingleHost() { final HostHandler handler = new RoundRobinHostHandler(SINGLE_HOST); - assertThat(handler.get(null, null), is(HOST_0)); + assertThat(handler.get(null, null)).isEqualTo(HOST_0); handler.fail(new RuntimeException()); - assertThat(handler.get(null, null), is(HOST_0)); + assertThat(handler.get(null, null)).isEqualTo(HOST_0); } @Test - public void roundRobinHostHandlerMultipleHosts() { + void roundRobinHostHandlerMultipleHosts() { final HostHandler handler = new RoundRobinHostHandler(MULTIPLE_HOSTS); final Host pick0 = handler.get(null, null); - assertThat(pick0, anyOf(is(HOST_0), is(HOST_1), is(HOST_2))); + assertThat(pick0).isIn(HOST_0, HOST_1, HOST_2); final Host pick1 = handler.get(null, null); - assertThat(pick1, anyOf(is(HOST_0), is(HOST_1), is(HOST_2))); - assertThat(pick1, is(not(pick0))); + assertThat(pick1) + .isIn(HOST_0, HOST_1, HOST_2) + .isNotEqualTo(pick0); final Host pick2 = handler.get(null, null); - assertThat(pick2, anyOf(is(HOST_0), is(HOST_1), is(HOST_2))); - assertThat(pick2, not(anyOf(is(pick0), is(pick1)))); + assertThat(pick2) + .isIn(HOST_0, HOST_1, HOST_2) + .isNotIn(pick0, pick1); final Host pick4 = handler.get(null, null); - assertThat(pick4, is(pick0)); + assertThat(pick4).isEqualTo(pick0); } } diff --git a/src/test/java/com/arangodb/internal/QueueTimeMetricsImplTest.java b/src/test/java/com/arangodb/internal/QueueTimeMetricsImplTest.java index 0d86b737b..7c4ca4c8a 100644 --- a/src/test/java/com/arangodb/internal/QueueTimeMetricsImplTest.java +++ b/src/test/java/com/arangodb/internal/QueueTimeMetricsImplTest.java @@ -1,36 +1,37 @@ package com.arangodb.internal; import com.arangodb.model.QueueTimeSample; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Random; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; -public class QueueTimeMetricsImplTest { + +class QueueTimeMetricsImplTest { private final static int QSIZE = 1024; private final Random rnd = new Random(); private final QueueTimeMetricsImpl q = new QueueTimeMetricsImpl(QSIZE); @Test - public void halfSizeTest() { + void halfSizeTest() { testQueue(QSIZE / 2); } @Test - public void fullSizeTest() { + void fullSizeTest() { testQueue(QSIZE); } @Test - public void emptySizeTest() { + void emptySizeTest() { testQueue(0); } @Test - public void overSizeTest() { + void overSizeTest() { testQueue((int) (QSIZE * 1.2)); testQueue((int) (QSIZE * 3000.4)); } @@ -41,14 +42,14 @@ private void testQueue(int size) { q.add(new QueueTimeSample(i, rnd.nextDouble())); } QueueTimeSample[] values = q.getValues(); - assertThat(values.length, is(Math.min(size, QSIZE))); - assertThat(q.getAvg(), is(closeTo(getAvg(values), 1.0E-12))); - assertThat(q.getAvg(), is(greaterThanOrEqualTo(0.0))); + assertThat(values).hasSize(Math.min(size, QSIZE)); + assertThat(q.getAvg()).isEqualTo(getAvg(values), within(1.0E-12)); + assertThat(q.getAvg()).isGreaterThanOrEqualTo(0.0); for (int i = 0; i < values.length; i++) { - assertThat(values[i], is(notNullValue())); + assertThat(values[i]).isNotNull(); if (i > 0) { - assertThat(values[i].timestamp, greaterThan(values[i - 1].timestamp)); + assertThat(values[i].timestamp).isGreaterThan(values[i - 1].timestamp); } } } diff --git a/src/test/java/com/arangodb/internal/http/HttpRetryTest.java b/src/test/java/com/arangodb/internal/http/HttpRetryTest.java deleted file mode 100644 index 384ae92f5..000000000 --- a/src/test/java/com/arangodb/internal/http/HttpRetryTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * DISCLAIMER - * - * Copyright 2016 ArangoDB GmbH, Cologne, Germany - * - * 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 - * - * 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. - * - * Copyright holder is ArangoDB GmbH, Cologne, Germany - */ - -package com.arangodb.internal.http; - - -import com.arangodb.ArangoDB; -import com.arangodb.ArangoDBException; -import com.arangodb.Protocol; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.protocol.HttpContext; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.IOException; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.fail; - -/** - * @author Michele Rastelli - */ -public class HttpRetryTest { - - private final static int RETRIES = 2; - - private static class TestRetryHandler implements HttpRequestRetryHandler { - private int retriesCounter = 0; - - @Override - public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { - return ++retriesCounter < RETRIES; - } - - } - - /** - * remove host from src/test/resources/arangodb.properties to run this test - */ - @Test - @Ignore - public void retry() { - TestRetryHandler retryHandler = new TestRetryHandler(); - ArangoDB arangoDB = new ArangoDB.Builder() - .host("wrongHost", 8529) - .useProtocol(Protocol.HTTP_JSON) - .httpRequestRetryHandler(retryHandler) - .build(); - - try { - arangoDB.getVersion(); - fail("it should throw I/O exception"); - } catch (ArangoDBException e) { - assertThat(retryHandler.retriesCounter, is(RETRIES)); - } - - } - -} diff --git a/src/test/java/com/arangodb/internal/velocypack/VPackSerializersTest.java b/src/test/java/com/arangodb/internal/velocypack/VPackSerializersTest.java index c709b6969..5c3880ba6 100644 --- a/src/test/java/com/arangodb/internal/velocypack/VPackSerializersTest.java +++ b/src/test/java/com/arangodb/internal/velocypack/VPackSerializersTest.java @@ -27,55 +27,53 @@ import com.arangodb.model.arangosearch.ArangoSearchCreateOptions; import com.arangodb.velocypack.VPack; import com.arangodb.velocypack.VPackSlice; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; +import static org.assertj.core.api.Assertions.assertThat; -public class VPackSerializersTest { +class VPackSerializersTest { private VPack vpack; - @Before - public void init() { + @BeforeEach + void init() { vpack = new VPack.Builder() .registerSerializer(ArangoSearchProperties.class, VPackSerializers.ARANGO_SEARCH_PROPERTIES) .build(); } @Test - public void serializeArangoSearchProperties() { + void serializeArangoSearchProperties() { final ArangoSearchCreateOptions opts = new ArangoSearchCreateOptions() .storedValues(new StoredValue(Collections.singletonList("dummy"), ArangoSearchCompression.lz4)); final VPackSlice slice = vpack.serialize(opts); - assertThat(slice.isObject(), is(true)); - assertThat(slice.get("type").isString(), is(true)); - assertThat(slice.get("type").getAsString(), is(ViewType.ARANGO_SEARCH.name())); - assertThat(slice.get("storedValues"), notNullValue()); - assertThat(slice.get("storedValues").isArray(), is(true)); - assertThat(slice.get("storedValues").size(), is(1)); - assertThat(slice.get("storedValues").get(0).isObject(), is(true)); - assertThat(slice.get("storedValues").get(0).get("fields").isArray(), is(true)); - assertThat(slice.get("storedValues").get(0).get("fields").size(), is(1)); - assertThat(slice.get("storedValues").get(0).get("fields").get(0).isString(), is(true)); - assertThat(slice.get("storedValues").get(0).get("fields").get(0).getAsString(), is("dummy")); - assertThat(slice.get("storedValues").get(0).get("compression").isString(), is(true)); - assertThat(slice.get("storedValues").get(0).get("compression").getAsString(), is(ArangoSearchCompression.lz4.name())); + assertThat(slice.isObject()).isTrue(); + assertThat(slice.get("type").isString()).isTrue(); + assertThat(slice.get("type").getAsString()).isEqualTo(ViewType.ARANGO_SEARCH.name()); + assertThat(slice.get("storedValues")).isNotNull(); + assertThat(slice.get("storedValues").isArray()).isTrue(); + assertThat(slice.get("storedValues").size()).isEqualTo(1); + assertThat(slice.get("storedValues").get(0).isObject()).isTrue(); + assertThat(slice.get("storedValues").get(0).get("fields").isArray()).isTrue(); + assertThat(slice.get("storedValues").get(0).get("fields").size()).isEqualTo(1); + assertThat(slice.get("storedValues").get(0).get("fields").get(0).isString()).isTrue(); + assertThat(slice.get("storedValues").get(0).get("fields").get(0).getAsString()).isEqualTo("dummy"); + assertThat(slice.get("storedValues").get(0).get("compression").isString()).isTrue(); + assertThat(slice.get("storedValues").get(0).get("compression").getAsString()).isEqualTo(ArangoSearchCompression.lz4.name()); } @Test - public void serializeArangoSearchPropertiesWithDefaultCompression() { + void serializeArangoSearchPropertiesWithDefaultCompression() { final ArangoSearchCreateOptions opts = new ArangoSearchCreateOptions() .storedValues(new StoredValue(Collections.singletonList("dummy"))); final VPackSlice slice = vpack.serialize(opts); - assertThat(slice.get("storedValues").get(0).get("compression").isNone(), is(true)); + assertThat(slice.get("storedValues").get(0).get("compression").isNone()).isTrue(); } } diff --git a/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java b/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java index 87e8e5db9..0778c58ed 100644 --- a/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java +++ b/src/test/java/com/arangodb/internal/velocystream/CommunicationTest.java @@ -23,35 +23,33 @@ import com.arangodb.ArangoDB; import com.arangodb.ArangoDatabase; import com.arangodb.entity.ArangoDBVersion; -import org.junit.Test; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.Test; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Vollmary */ -public class CommunicationTest { +class CommunicationTest { private static final String FAST = "fast"; private static final String SLOW = "slow"; @Test - public void chunkSizeSmall() { - final ArangoDB arangoDB = new ArangoDB.Builder().chunksize(20).build(); + void chunkSizeSmall() { + final ArangoDB arangoDB = new ArangoDB.Builder().chunksize(20).serializer(new ArangoJack()).build(); final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); + assertThat(version).isNotNull(); } @Test - public void multiThread() throws Exception { - final ArangoDB arangoDB = new ArangoDB.Builder().build(); + void multiThread() throws Exception { + final ArangoDB arangoDB = new ArangoDB.Builder().serializer(new ArangoJack()).build(); arangoDB.getUsers(); // authentication and active-failover connection redirect to master final Collection result = new ConcurrentLinkedQueue<>(); @@ -69,15 +67,15 @@ public void multiThread() throws Exception { slow.join(); fast.join(); - assertThat(result.size(), is(2)); + assertThat(result.size()).isEqualTo(2); final Iterator iterator = result.iterator(); - assertThat(iterator.next(), is(FAST)); - assertThat(iterator.next(), is(SLOW)); + assertThat(iterator.next()).isEqualTo(FAST); + assertThat(iterator.next()).isEqualTo(SLOW); } @Test - public void multiThreadSameDatabases() throws Exception { - final ArangoDB arangoDB = new ArangoDB.Builder().build(); + void multiThreadSameDatabases() throws Exception { + final ArangoDB arangoDB = new ArangoDB.Builder().serializer(new ArangoJack()).build(); arangoDB.getUsers(); // authentication and active-failover connection redirect to master final ArangoDatabase db = arangoDB.db(); @@ -95,20 +93,20 @@ public void multiThreadSameDatabases() throws Exception { t1.start(); t2.join(); t1.join(); - assertThat(result.size(), is(2)); + assertThat(result.size()).isEqualTo(2); } @Test - public void minOneConnection() { - final ArangoDB arangoDB = new ArangoDB.Builder().maxConnections(0).build(); + void minOneConnection() { + final ArangoDB arangoDB = new ArangoDB.Builder().maxConnections(0).serializer(new ArangoJack()).build(); final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); + assertThat(version).isNotNull(); } @Test - public void defaultMaxConnection() { - final ArangoDB arangoDB = new ArangoDB.Builder().maxConnections(null).build(); + void defaultMaxConnection() { + final ArangoDB arangoDB = new ArangoDB.Builder().maxConnections(null).serializer(new ArangoJack()).build(); final ArangoDBVersion version = arangoDB.getVersion(); - assertThat(version, is(notNullValue())); + assertThat(version).isNotNull(); } } diff --git a/src/test/java/com/arangodb/mapping/VPackSerializeDeserializeTest.java b/src/test/java/com/arangodb/mapping/VPackSerializeDeserializeTest.java index 19fb30671..eed9a8052 100644 --- a/src/test/java/com/arangodb/mapping/VPackSerializeDeserializeTest.java +++ b/src/test/java/com/arangodb/mapping/VPackSerializeDeserializeTest.java @@ -24,14 +24,13 @@ import com.arangodb.velocypack.*; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DateFormat; @@ -39,3297 +38,3265 @@ import java.util.*; import java.util.Map.Entry; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Vollmary - * */ -public class VPackSerializeDeserializeTest { - - private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");// ISO 8601 - - static { - DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); - } - - private final ObjectMapper mapper = ArangoJack.createDefaultMapper(); - - public static class TestEntityBoolean { - private boolean a = true; - private boolean b = false; - private Boolean c = Boolean.TRUE; - private Boolean d = Boolean.FALSE; - - public boolean isA() { - return a; - } - - public void setA(final boolean a) { - this.a = a; - } - - public boolean isB() { - return b; - } - - public void setB(final boolean b) { - this.b = b; - } - - public Boolean getC() { - return c; - } - - public void setC(final Boolean c) { - this.c = c; - } - - public Boolean getD() { - return d; - } - - public void setD(final Boolean d) { - this.d = d; - } - } - - @Test - public void fromBoolean() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityBoolean())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice a = vpack.get("a"); - assertThat(a.isBoolean(), is(true)); - assertThat(a.getAsBoolean(), is(true)); - } - { - final VPackSlice b = vpack.get("b"); - assertThat(b.isBoolean(), is(true)); - assertThat(b.getAsBoolean(), is(false)); - } - { - final VPackSlice c = vpack.get("c"); - assertThat(c.isBoolean(), is(true)); - assertThat(c.getAsBoolean(), is(true)); - } - { - final VPackSlice d = vpack.get("d"); - assertThat(d.isBoolean(), is(true)); - assertThat(d.getAsBoolean(), is(false)); - } - } - - @Test - public void toBoolean() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("a", false); - builder.add("b", true); - builder.add("c", Boolean.FALSE); - builder.add("d", Boolean.TRUE); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityBoolean entity = mapper.readValue(vpack.getBuffer(), TestEntityBoolean.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.a, is(false)); - assertThat(entity.b, is(true)); - assertThat(entity.c, is(Boolean.FALSE)); - assertThat(entity.d, is(Boolean.TRUE)); - } - - public static class TestEntityString { - private String s = "test"; - private Character c1 = 't'; - private char c2 = 't'; - - public String getS() { - return s; - } - - public void setS(final String s) { - this.s = s; - } - - public Character getC1() { - return c1; - } - - public void setC1(final Character c1) { - this.c1 = c1; - } - - public char getC2() { - return c2; - } - - public void setC2(final char c2) { - this.c2 = c2; - } - } - - @Test - public void fromStrings() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityString())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice s = vpack.get("s"); - assertThat(s.isString(), is(true)); - assertThat(s.getAsString(), is("test")); - } - { - final VPackSlice c1 = vpack.get("c1"); - assertThat(c1.isString(), is(true)); - assertThat(c1.getAsChar(), is('t')); - } - { - final VPackSlice c2 = vpack.get("c2"); - assertThat(c2.isString(), is(true)); - assertThat(c2.getAsChar(), is('t')); - } - } - - @Test - public void toStrings() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("s", "abc"); - builder.add("c1", 'd'); - builder.add("c2", 'd'); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityString entity = mapper.readValue(vpack.getBuffer(), TestEntityString.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.s, is("abc")); - assertThat(entity.c1, is(new Character('d'))); - assertThat(entity.c1, is(new Character('d'))); - } - - public static class TestEntityInteger { - private int i1 = 1; - private Integer i2 = 1; - - public int getI1() { - return i1; - } - - public void setI1(final int i1) { - this.i1 = i1; - } - - public Integer getI2() { - return i2; - } - - public void setI2(final Integer i2) { - this.i2 = i2; - } - } - - @Test - public void fromInteger() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityInteger())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice i1 = vpack.get("i1"); - assertThat(i1.isInteger(), is(true)); - assertThat(i1.getAsInt(), is(1)); - } - { - final VPackSlice i2 = vpack.get("i2"); - assertThat(i2.isInteger(), is(true)); - assertThat(i2.getAsInt(), is(1)); - } - } - - @Test - public void fromNegativeInteger() throws JsonProcessingException { - final TestEntityInteger entity = new TestEntityInteger(); - entity.i1 = -50; - entity.i2 = -50; - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice i1 = vpack.get("i1"); - assertThat(i1.isInteger(), is(true)); - assertThat(i1.getAsInt(), is(-50)); - } - { - final VPackSlice i2 = vpack.get("i2"); - assertThat(i2.isInteger(), is(true)); - assertThat(i2.getAsInt(), is(-50)); - } - } - - @Test - public void toInteger() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("i1", 2); - builder.add("i2", 3); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityInteger entity = mapper.readValue(vpack.getBuffer(), TestEntityInteger.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.i1, is(2)); - assertThat(entity.i2, is(new Integer(3))); - } - - @Test - public void toNegativeInteger() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("i1", -50); - builder.add("i2", -50); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityInteger entity = mapper.readValue(vpack.getBuffer(), TestEntityInteger.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.i1, is(-50)); - assertThat(entity.i2, is(new Integer(-50))); - } - - public static class TestEntityLong { - private long l1 = 1; - private Long l2 = 1L; - - public long getL1() { - return l1; - } - - public void setL1(final long l1) { - this.l1 = l1; - } - - public Long getL2() { - return l2; - } - - public void setL2(final Long l2) { - this.l2 = l2; - } - } - - @Test - public void fromLong() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityLong())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice l1 = vpack.get("l1"); - assertThat(l1.isInteger(), is(true)); - assertThat(l1.getAsLong(), is(1L)); - } - { - final VPackSlice l2 = vpack.get("l2"); - assertThat(l2.isInteger(), is(true)); - assertThat(l2.getAsLong(), is(1L)); - } - } - - @Test - public void fromNegativeLong() throws JsonProcessingException { - final TestEntityLong entity = new TestEntityLong(); - entity.l1 = -100L; - entity.l2 = new Long(-300); - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice l1 = vpack.get("l1"); - assertThat(l1.isInteger(), is(true)); - assertThat(l1.getAsLong(), is(-100L)); - } - { - final VPackSlice l2 = vpack.get("l2"); - assertThat(l2.isInteger(), is(true)); - assertThat(l2.getAsLong(), is(-300L)); - } - } - - @Test - public void toLong() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("l1", 2); - builder.add("l2", 3); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityLong entity = mapper.readValue(vpack.getBuffer(), TestEntityLong.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.l1, is(2L)); - assertThat(entity.l2, is(new Long(3))); - } - - @Test - public void toNegativeLong() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("l1", -100L); - builder.add("l2", -300L); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityLong entity = mapper.readValue(vpack.getBuffer(), TestEntityLong.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.l1, is(-100L)); - assertThat(entity.l2, is(new Long(-300))); - } - - @Test - public void negativeLong() throws JsonProcessingException { - final TestEntityLong entity = new TestEntityLong(); - entity.l1 = -100L; - entity.l2 = new Long(-300); - final VPack vp = new VPack.Builder().build(); - final TestEntityLong out = vp.deserialize(vp.serialize(entity), TestEntityLong.class); - assertThat(out.l1, is(entity.l1)); - assertThat(out.l2, is(entity.l2)); - } - - @Test - public void intToLong() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("l1", 100); - builder.add("l2", 300); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityLong entity = mapper.readValue(vpack.getBuffer(), TestEntityLong.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.l1, is(100L)); - assertThat(entity.l2, is(new Long(300))); - } - - @Test - public void negativeIntToLong() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("l1", -100); - builder.add("l2", -300); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityLong entity = mapper.readValue(vpack.getBuffer(), TestEntityLong.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.l1, is(-100L)); - assertThat(entity.l2, is(new Long(-300))); - } - - @Test - public void negativeLongToInt() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("i1", -100L); - builder.add("i2", -300L); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityInteger entity = mapper.readValue(vpack.getBuffer(), TestEntityInteger.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.i1, is(-100)); - assertThat(entity.i2, is(new Integer(-300))); - } - - @Test - public void negativeLongToShort() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("s1", -100L); - builder.add("s2", -300L); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityShort entity = mapper.readValue(vpack.getBuffer(), TestEntityShort.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.s1, is((short) -100)); - assertThat(entity.s2, is(new Short((short) -300))); - } - - @Test - public void negativeShortToLong() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("l1", (short) -100); - builder.add("l2", (short) -300); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityLong entity = mapper.readValue(vpack.getBuffer(), TestEntityLong.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.l1, is(-100L)); - assertThat(entity.l2, is(new Long(-300))); - } - - public static class TestEntityFloat { - private float f1 = 1; - private Float f2 = 1F; - - public float getF1() { - return f1; - } - - public void setF1(final float f1) { - this.f1 = f1; - } - - public Float getF2() { - return f2; - } - - public void setF2(final Float f2) { - this.f2 = f2; - } - } - - @Test - public void fromFloat() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityFloat())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice f1 = vpack.get("f1"); - assertThat(f1.isDouble(), is(true)); - assertThat(f1.getAsFloat(), is(1.0F)); - } - { - final VPackSlice f2 = vpack.get("f2"); - assertThat(f2.isDouble(), is(true)); - assertThat(f2.getAsFloat(), is(1.0F)); - } - } - - @Test - public void toFloat() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("f1", 2F); - builder.add("f2", 3F); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityFloat entity = mapper.readValue(vpack.getBuffer(), TestEntityFloat.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.f1, is(2F)); - assertThat(entity.f2, is(new Float(3))); - } - - public static class TestEntityShort { - private short s1 = 1; - private Short s2 = 1; - - public short getS1() { - return s1; - } - - public void setS1(final short s1) { - this.s1 = s1; - } - - public Short getS2() { - return s2; - } - - public void setS2(final Short s2) { - this.s2 = s2; - } - } - - @Test - public void fromShort() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityShort())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice s1 = vpack.get("s1"); - assertThat(s1.isInteger(), is(true)); - assertThat(s1.getAsShort(), is((short) 1)); - } - { - final VPackSlice s2 = vpack.get("s2"); - assertThat(s2.isInteger(), is(true)); - assertThat(s2.getAsShort(), is((short) 1)); - } - } - - @Test - public void toShort() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("s1", 2); - builder.add("s2", 3); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityShort entity = mapper.readValue(vpack.getBuffer(), TestEntityShort.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.s1, is((short) 2)); - assertThat(entity.s2, is(new Short((short) 3))); - } - - public static class TestEntityByte { - private byte b1 = 1; // short integer path - private Byte b2 = 100; // integer path - - public byte getB1() { - return b1; - } - - public void setB1(final byte b1) { - this.b1 = b1; - } - - public Byte getB2() { - return b2; - } - - public void setB2(final Byte b2) { - this.b2 = b2; - } - } - - @Test - public void fromByte() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityByte())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice b1 = vpack.get("b1"); - assertThat(b1.isInteger(), is(true)); - assertThat(b1.getAsByte(), is((byte) 1)); - } - { - final VPackSlice b2 = vpack.get("b2"); - assertThat(b2.isInteger(), is(true)); - assertThat(b2.getAsByte(), is((byte) 100)); - } - } - - @Test - public void toByte() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("b1", 30); // integer path - builder.add("b2", 4); // short integer path - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityByte entity = mapper.readValue(vpack.getBuffer(), TestEntityByte.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.b1, is((byte) 30)); - assertThat(entity.b2, is(new Byte((byte) 4))); - } - - public static class TestEntityDouble { - private Double d1 = 1.5; - private double d2 = 1.5; - - public Double getD1() { - return d1; - } - - public void setD1(final Double d1) { - this.d1 = d1; - } - - public double getD2() { - return d2; - } - - public void setD2(final double d2) { - this.d2 = d2; - } - } - - @Test - public void fromDouble() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityDouble())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice d1 = vpack.get("d1"); - assertThat(d1.isDouble(), is(true)); - assertThat(d1.getAsDouble(), is(1.5)); - } - { - final VPackSlice d2 = vpack.get("d2"); - assertThat(d2.isDouble(), is(true)); - assertThat(d2.getAsDouble(), is(1.5)); - } - } - - @Test - public void toDouble() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("d1", 2.25); - builder.add("d2", 3.75); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityDouble entity = mapper.readValue(vpack.getBuffer(), TestEntityDouble.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.d1, is(2.25)); - assertThat(entity.d2, is(3.75)); - } - - public static class TestEntityBigNumber { - private static BigInteger BI = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE); - private static BigDecimal BD = BigDecimal.valueOf(Double.MAX_VALUE).add(BigDecimal.ONE); - - private BigInteger bi = BI; - private BigDecimal bd = BD; - - public BigInteger getBi() { - return bi; - } - - public void setBi(final BigInteger bi) { - this.bi = bi; - } - - public BigDecimal getBd() { - return bd; - } - - public void setBd(final BigDecimal bd) { - this.bd = bd; - } - } - - @Test - public void fromBigNumbers() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityBigNumber())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice bi = vpack.get("bi"); - assertThat(bi.isString(), is(true)); - assertThat(bi.getAsBigInteger(), is(TestEntityBigNumber.BI)); - } - { - final VPackSlice bd = vpack.get("bd"); - assertThat(bd.isString(), is(true)); - assertThat(bd.getAsBigDecimal(), is(TestEntityBigNumber.BD)); - } - } - - @Test - public void toBigNumbers() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("bi", BigInteger.valueOf(2)); - builder.add("bd", BigDecimal.valueOf(3.75)); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityBigNumber entity = mapper.readValue(vpack.getBuffer(), TestEntityBigNumber.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.bi, is(BigInteger.valueOf(2))); - assertThat(entity.bd, is(BigDecimal.valueOf(3.75))); - } - - @Test - public void bigDecimal() { - final BigDecimal fromDouble = BigDecimal.valueOf(-710.01); - final BigDecimal fromString = new BigDecimal("-710.01"); - assertThat(fromDouble, is(fromString)); - assertThat(new VPackBuilder().add(fromDouble).slice().getAsBigDecimal(), is(fromDouble)); - assertThat(new VPackBuilder().add(fromString).slice().getAsBigDecimal(), is(fromDouble)); - } - - public static class TestEntityArray { - private String[] a1 = { "a", "b", "cd" }; - private int[] a2 = { 1, 2, 3, 4, 5 }; - private boolean[] a3 = { true, true, false }; - private TestEnum[] a4 = TestEnum.values(); - - public String[] getA1() { - return a1; - } - - public void setA1(final String[] a1) { - this.a1 = a1; - } - - public int[] getA2() { - return a2; - } - - public void setA2(final int[] a2) { - this.a2 = a2; - } - - public boolean[] getA3() { - return a3; - } - - public void setA3(final boolean[] a3) { - this.a3 = a3; - } - - public TestEnum[] getA4() { - return a4; - } - - public void setA4(final TestEnum[] a4) { - this.a4 = a4; - } - - } - - @Test - public void fromArray() throws JsonProcessingException { - final TestEntityArray entity = new TestEntityArray(); - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice a1 = vpack.get("a1"); - assertThat(a1.isArray(), is(true)); - assertThat(a1.getLength(), is(entity.a1.length)); - for (int i = 0; i < a1.getLength(); i++) { - assertThat(a1.get(i).getAsString(), is(entity.a1[i])); - } - } - { - final VPackSlice a2 = vpack.get("a2"); - assertThat(a2.isArray(), is(true)); - assertThat(a2.getLength(), is(entity.a2.length)); - for (int i = 0; i < a2.getLength(); i++) { - assertThat(a2.get(i).getAsInt(), is(entity.a2[i])); - } - } - { - final VPackSlice a3 = vpack.get("a3"); - assertThat(a3.isArray(), is(true)); - assertThat(a3.getLength(), is(entity.a3.length)); - for (int i = 0; i < a3.getLength(); i++) { - assertThat(a3.get(i).getAsBoolean(), is(entity.a3[i])); - } - } - { - final VPackSlice a4 = vpack.get("a4"); - assertThat(a4.isArray(), is(true)); - assertThat(a4.getLength(), is(entity.a4.length)); - for (int i = 0; i < a4.getLength(); i++) { - assertThat(TestEnum.valueOf(a4.get(i).getAsString()), is(entity.a4[i])); - } - } - } - - @Test - public void toArray() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - { - builder.add("a1", ValueType.ARRAY); - builder.add("a"); - builder.add("b"); - builder.add("c"); - builder.close(); - } - { - builder.add("a2", ValueType.ARRAY); - builder.add(1); - builder.add(2); - builder.add(3); - builder.add(4); - builder.close(); - } - { - builder.add("a3", ValueType.ARRAY); - builder.add(false); - builder.add(true); - builder.close(); - } - { - builder.add("a4", ValueType.ARRAY); - builder.add(TestEnum.A.name()); - builder.add(TestEnum.B.name()); - builder.close(); - } - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityArray entity = mapper.readValue(vpack.getBuffer(), TestEntityArray.class); - assertThat(entity, is(notNullValue())); - { - assertThat(entity.a1.length, is(3)); - assertThat(entity.a1[0], is("a")); - assertThat(entity.a1[1], is("b")); - assertThat(entity.a1[2], is("c")); - } - { - assertThat(entity.a2.length, is(4)); - assertThat(entity.a2[0], is(1)); - assertThat(entity.a2[1], is(2)); - assertThat(entity.a2[2], is(3)); - assertThat(entity.a2[3], is(4)); - } - { - assertThat(entity.a3.length, is(2)); - assertThat(entity.a3[0], is(false)); - assertThat(entity.a3[1], is(true)); - } - { - assertThat(entity.a4.length, is(2)); - assertThat(entity.a4[0], is(TestEnum.A)); - assertThat(entity.a4[1], is(TestEnum.B)); - } - } - - @Test - public void fromArrayWithNull() throws JsonProcessingException { - final TestEntityArray entity = new TestEntityArray(); - entity.a1 = new String[] { "foo", null }; - - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - - final VPackSlice a1 = vpack.get("a1"); - assertThat(a1.isArray(), is(true)); - assertThat(a1.size(), is(2)); - assertThat(a1.get(0).isString(), is(true)); - assertThat(a1.get(0).getAsString(), is("foo")); - assertThat(a1.get(1).isNull(), is(true)); - } - - protected enum TestEnum { - A, B, C - } - - public static class TestEntityEnum { - private TestEnum e1 = TestEnum.A; - - public TestEnum getE1() { - return e1; - } - - public void setE1(final TestEnum e1) { - this.e1 = e1; - } - } - - @Test - public void fromEnum() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityEnum())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice e1 = vpack.get("e1"); - assertThat(e1.isString(), is(true)); - assertThat(TestEnum.valueOf(e1.getAsString()), is(TestEnum.A)); - } - } - - @Test - public void toEnum() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("e1", TestEnum.B.name()); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityEnum entity = mapper.readValue(vpack.getBuffer(), TestEntityEnum.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.e1, is(TestEnum.B)); - } - - public static class TestEntityObject { - private TestEntityLong o1 = new TestEntityLong(); - private TestEntityArray o2 = new TestEntityArray(); - - public TestEntityLong getO1() { - return o1; - } - - public void setO1(final TestEntityLong o1) { - this.o1 = o1; - } - - public TestEntityArray getO2() { - return o2; - } - - public void setO2(final TestEntityArray o2) { - this.o2 = o2; - } - } - - @Test - public void fromObject() throws JsonProcessingException { - final TestEntityObject entity = new TestEntityObject(); - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice o1 = vpack.get("o1"); - assertThat(o1.isObject(), is(true)); - { - final VPackSlice l1 = o1.get("l1"); - assertThat(l1.isInteger(), is(true)); - assertThat(l1.getAsLong(), is(1L)); - } - { - final VPackSlice l2 = o1.get("l2"); - assertThat(l2.isInteger(), is(true)); - assertThat(l2.getAsLong(), is(1L)); - } - } - { - final VPackSlice o2 = vpack.get("o2"); - assertThat(o2.isObject(), is(true)); - { - final VPackSlice a1 = o2.get("a1"); - assertThat(a1.isArray(), is(true)); - assertThat(a1.getLength(), is(entity.o2.a1.length)); - for (int i = 0; i < a1.getLength(); i++) { - assertThat(a1.get(i).getAsString(), is(entity.o2.a1[i])); - } - } - { - final VPackSlice a2 = o2.get("a2"); - assertThat(a2.isArray(), is(true)); - assertThat(a2.getLength(), is(entity.o2.a2.length)); - for (int i = 0; i < a2.getLength(); i++) { - assertThat(a2.get(i).getAsInt(), is(entity.o2.a2[i])); - } - } - { - final VPackSlice a3 = o2.get("a3"); - assertThat(a3.isArray(), is(true)); - assertThat(a3.getLength(), is(entity.o2.a3.length)); - for (int i = 0; i < a3.getLength(); i++) { - assertThat(a3.get(i).getAsBoolean(), is(entity.o2.a3[i])); - } - } - { - final VPackSlice a4 = o2.get("a4"); - assertThat(a4.isArray(), is(true)); - assertThat(a4.getLength(), is(entity.o2.a4.length)); - for (int i = 0; i < a4.getLength(); i++) { - assertThat(TestEnum.valueOf(a4.get(i).getAsString()), is(entity.o2.a4[i])); - } - } - } - } - - @Test - public void toObject() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - { - builder.add("o1", ValueType.OBJECT); - builder.add("l1", 5L); - builder.add("l2", 5L); - builder.close(); - } - { - builder.add("o2", ValueType.OBJECT); - { - builder.add("a1", ValueType.ARRAY); - builder.add("a"); - builder.add("b"); - builder.add("c"); - builder.close(); - } - { - builder.add("a2", ValueType.ARRAY); - builder.add(1); - builder.add(2); - builder.add(3); - builder.add(4); - builder.close(); - } - { - builder.add("a3", ValueType.ARRAY); - builder.add(false); - builder.add(true); - builder.close(); - } - { - builder.add("a4", ValueType.ARRAY); - builder.add(TestEnum.A.name()); - builder.add(TestEnum.B.name()); - builder.close(); - } - builder.close(); - } - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityObject entity = mapper.readValue(vpack.getBuffer(), TestEntityObject.class); - assertThat(entity, is(notNullValue())); - { - assertThat(entity.o1.l1, is(5L)); - assertThat(entity.o1.l2, is(new Long(5))); - } - { - assertThat(entity.o2.a1.length, is(3)); - assertThat(entity.o2.a1[0], is("a")); - assertThat(entity.o2.a1[1], is("b")); - assertThat(entity.o2.a1[2], is("c")); - } - { - assertThat(entity.o2.a2.length, is(4)); - assertThat(entity.o2.a2[0], is(1)); - assertThat(entity.o2.a2[1], is(2)); - assertThat(entity.o2.a2[2], is(3)); - assertThat(entity.o2.a2[3], is(4)); - } - { - assertThat(entity.o2.a3.length, is(2)); - assertThat(entity.o2.a3[0], is(false)); - assertThat(entity.o2.a3[1], is(true)); - } - { - assertThat(entity.o2.a4.length, is(2)); - assertThat(entity.o2.a4[0], is(TestEnum.A)); - assertThat(entity.o2.a4[1], is(TestEnum.B)); - } - } - - public static class TestEntityArrayInArray { - private long[][] a1; - - public long[][] getA1() { - return a1; - } - - public void setA1(final long[][] a1) { - this.a1 = a1; - } - } - - @Test - public void fromArrayInArray() throws JsonProcessingException { - final TestEntityArrayInArray entity = new TestEntityArrayInArray(); - entity.a1 = new long[][] { { 1, 2, 3 }, { 4, 5, 6 } }; - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice a1 = vpack.get("a1"); - assertThat(a1.isArray(), is(true)); - assertThat(a1.getLength(), is(entity.a1.length)); - for (int i = 0; i < a1.getLength(); i++) { - final VPackSlice at = a1.get(i); - assertThat(at.isArray(), is(true)); - assertThat(at.getLength(), is(entity.a1[i].length)); - for (int j = 0; j < at.getLength(); j++) { - final VPackSlice atat = at.get(j); - assertThat(atat.isInteger(), is(true)); - assertThat(atat.getAsLong(), is(entity.a1[i][j])); - } - } - } - } - - @Test - public void toArrayInArray() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - { - builder.add("a1", ValueType.ARRAY); - { - builder.add(ValueType.ARRAY); - builder.add(1); - builder.add(2); - builder.add(3); - builder.close(); - } - { - builder.add(ValueType.ARRAY); - builder.add(4); - builder.add(5); - builder.add(6); - builder.close(); - } - builder.close(); - } - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityArrayInArray entity = mapper.readValue(vpack.getBuffer(), TestEntityArrayInArray.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.a1.length, is(2)); - { - assertThat(entity.a1[0].length, is(3)); - assertThat(entity.a1[0][0], is(1L)); - assertThat(entity.a1[0][1], is(2L)); - assertThat(entity.a1[0][2], is(3L)); - } - { - assertThat(entity.a1[1].length, is(3)); - assertThat(entity.a1[1][0], is(4L)); - assertThat(entity.a1[1][1], is(5L)); - assertThat(entity.a1[1][2], is(6L)); - } - } - - @SuppressWarnings("serial") - public static class TestCollection extends LinkedList { - - } - - public static class TestEntityCollectionExtendedWithNulls { - - protected TestCollection a1; - - public TestCollection getA1() { - return a1; - } - - public void setA1(final TestCollection a1) { - this.a1 = a1; - } - - } - - @Test - public void fromCollectionExtendedWithNulls() throws Exception { - - final TestCollection collection = new TestCollection(); - collection.add("one"); - collection.add(null); - collection.add("two"); - - final TestEntityCollectionExtendedWithNulls entity = new TestEntityCollectionExtendedWithNulls(); - entity.setA1(collection); - - final VPackSlice vpack = new VPack.Builder().serializeNullValues(true).build().serialize(entity); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice a1 = vpack.get("a1"); - assertThat(a1.isArray(), is(true)); - assertThat(a1.getLength(), is(entity.a1.size())); - - VPackSlice at = a1.get(0); - assertThat(at.isString(), is(true)); - assertThat(at.getAsString(), is(entity.a1.get(0))); - at = a1.get(1); - assertThat(at.isNull(), is(true)); - at = a1.get(2); - assertThat(at.isString(), is(true)); - assertThat(at.getAsString(), is(entity.a1.get(2))); - } - } - - @Test - public void toCollectionExtendedWithNulls() throws Exception { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - { - builder.add("a1", ValueType.ARRAY); - builder.add("one"); - builder.add(ValueType.NULL); - builder.add("two"); - builder.close(); - } - builder.close(); - } - - final VPackSlice vpack = builder.slice(); - final TestEntityCollectionExtendedWithNulls entity = mapper.readValue(vpack.getBuffer(), - TestEntityCollectionExtendedWithNulls.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.getA1(), is(notNullValue())); - assertThat(entity.getA1().size(), is(3)); - assertThat(entity.getA1(), contains("one", null, "two")); - } - - public static class TestEntityArrayInArrayInArray { - - private double[][][] a1; - - public double[][][] getA1() { - return a1; - } - - public void setA1(final double[][][] a1) { - this.a1 = a1; - } - - } - - @Test - public void fromArrayInArrayInArray() throws JsonProcessingException { - final TestEntityArrayInArrayInArray entity = new TestEntityArrayInArrayInArray(); - entity.setA1(new double[][][] { { { 1.5, 2.25 }, { 10.5, 20.25 } }, { { 100.5 }, { 200.25 } } }); - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice a1 = vpack.get("a1"); - assertThat(a1.isArray(), is(true)); - assertThat(a1.getLength(), is(entity.a1.length)); - for (int i = 0; i < a1.getLength(); i++) { - final VPackSlice at = a1.get(i); - assertThat(at.isArray(), is(true)); - assertThat(at.getLength(), is(entity.a1[i].length)); - for (int j = 0; j < at.getLength(); j++) { - final VPackSlice atat = at.get(j); - assertThat(atat.isArray(), is(true)); - assertThat(atat.getLength(), is(entity.a1[i][j].length)); - for (int k = 0; k < atat.getLength(); k++) { - final VPackSlice atatat = atat.get(k); - assertThat(atatat.isDouble(), is(true)); - assertThat(atatat.getAsDouble(), is(entity.a1[i][j][k])); - } - } - } - } - } - - @Test - public void toArrayInArrayInArray() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - { - builder.add("a1", ValueType.ARRAY); - builder.add(ValueType.ARRAY); - { - builder.add(ValueType.ARRAY); - builder.add(1.5); - builder.add(2.5); - builder.add(3.5); - builder.close(); - } - { - builder.add(ValueType.ARRAY); - builder.add(4.5); - builder.add(5.5); - builder.add(6.5); - builder.close(); - } - { - builder.add(ValueType.ARRAY); - builder.add(7.5); - builder.add(8.5); - builder.add(9.5); - builder.close(); - } - builder.close(); - builder.add(ValueType.ARRAY); - { - builder.add(ValueType.ARRAY); - builder.add(1.5); - builder.add(2.5); - builder.add(3.5); - builder.close(); - } - { - builder.add(ValueType.ARRAY); - builder.add(4.5); - builder.add(5.5); - builder.add(6.5); - builder.close(); - } - { - builder.add(ValueType.ARRAY); - builder.add(7.5); - builder.add(8.5); - builder.add(9.5); - builder.close(); - } - builder.close(); - builder.close(); - } - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityArrayInArrayInArray entity = mapper.readValue(vpack.getBuffer(), - TestEntityArrayInArrayInArray.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.a1.length, is(2)); - { - assertThat(entity.a1[0].length, is(3)); - assertThat(entity.a1[0][0].length, is(3)); - assertThat(entity.a1[0][0][0], is(1.5)); - assertThat(entity.a1[0][0][1], is(2.5)); - assertThat(entity.a1[0][0][2], is(3.5)); - assertThat(entity.a1[0][1].length, is(3)); - assertThat(entity.a1[0][1][0], is(4.5)); - assertThat(entity.a1[0][1][1], is(5.5)); - assertThat(entity.a1[0][1][2], is(6.5)); - assertThat(entity.a1[0][2].length, is(3)); - assertThat(entity.a1[0][2][0], is(7.5)); - assertThat(entity.a1[0][2][1], is(8.5)); - assertThat(entity.a1[0][2][2], is(9.5)); - } - { - assertThat(entity.a1[1].length, is(3)); - assertThat(entity.a1[1][0].length, is(3)); - assertThat(entity.a1[1][0][0], is(1.5)); - assertThat(entity.a1[1][0][1], is(2.5)); - assertThat(entity.a1[1][0][2], is(3.5)); - assertThat(entity.a1[1][1].length, is(3)); - assertThat(entity.a1[1][1][0], is(4.5)); - assertThat(entity.a1[1][1][1], is(5.5)); - assertThat(entity.a1[1][1][2], is(6.5)); - assertThat(entity.a1[1][2].length, is(3)); - assertThat(entity.a1[1][2][0], is(7.5)); - assertThat(entity.a1[1][2][1], is(8.5)); - assertThat(entity.a1[1][2][2], is(9.5)); - } - } - - public static class TestEntityObjectInArray { - private TestEntityString[] a1; - - public TestEntityString[] getA1() { - return a1; - } - - public void setA1(final TestEntityString[] a1) { - this.a1 = a1; - } - } - - @Test - public void fromObjectInArray() throws JsonProcessingException { - final TestEntityObjectInArray entity = new TestEntityObjectInArray(); - { - final TestEntityString[] a1 = new TestEntityString[2]; - final TestEntityString s = new TestEntityString(); - s.setS("abc"); - a1[0] = s; - a1[1] = s; - entity.setA1(a1); - } - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice a1 = vpack.get("a1"); - assertThat(a1.isArray(), is(true)); - assertThat(a1.getLength(), is(2)); - for (int i = 0; i < a1.getLength(); i++) { - final VPackSlice at = a1.get(i); - assertThat(at.isObject(), is(true)); - final VPackSlice s = at.get("s"); - assertThat(s.isString(), is(true)); - assertThat(s.getAsString(), is("abc")); - } - } - } - - @Test - public void toObjectInArray() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("a1", ValueType.ARRAY); - { - builder.add(ValueType.OBJECT); - builder.add("s", "abc"); - builder.close(); - } - builder.close(); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityObjectInArray entity = mapper.readValue(vpack.getBuffer(), TestEntityObjectInArray.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.a1, is(notNullValue())); - assertThat(entity.a1.length, is(1)); - final TestEntityString st = entity.a1[0]; - assertThat(st, is(notNullValue())); - assertThat(st.s, is("abc")); - } - - public static class TestEntityA { - private String a = "a"; - - public String getA() { - return a; - } - - public void setA(final String a) { - this.a = a; - } - } - - public static class TestEntityB extends TestEntityA { - private String b = "b"; - - public String getB() { - return b; - } - - public void setB(final String b) { - this.b = b; - } - } - - @Test - public void fromInheritance() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityB())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - assertThat(vpack.getLength(), is(2)); - { - final VPackSlice a = vpack.get("a"); - assertThat(a.isString(), is(true)); - assertThat(a.getAsString(), is("a")); - } - { - final VPackSlice b = vpack.get("b"); - assertThat(b.isString(), is(true)); - assertThat(b.getAsString(), is("b")); - } - } - - @Test - public void toInheritance() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("a", "test"); - builder.add("b", "test"); - builder.close(); - } - final VPackSlice vpack = builder.slice(); - { - final TestEntityA entity = mapper.readValue(vpack.getBuffer(), TestEntityA.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.getA(), is("test")); - } - { - final TestEntityB entity = mapper.readValue(vpack.getBuffer(), TestEntityB.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.getA(), is("test")); - assertThat(entity.getB(), is("test")); - } - } - - public static class TestEntityC { - private TestEntityD d; - - public TestEntityD getD() { - return d; - } - - public void setD(final TestEntityD d) { - this.d = d; - } - } - - protected static interface TestEntityD { - String getD(); - - void setD(String d); - } - - public static class TestEntityDImpl implements TestEntityD { - private String d = "d"; - - @Override - public String getD() { - return d; - } - - @Override - public void setD(final String d) { - this.d = d; - } - } - - @Test - public void fromInterface() throws JsonProcessingException { - final TestEntityC entity = new TestEntityC(); - entity.setD(new TestEntityDImpl()); - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice d = vpack.get("d"); - assertThat(d.isObject(), is(true)); - final VPackSlice dd = d.get("d"); - assertThat(dd.isString(), is(true)); - assertThat(dd.getAsString(), is("d")); - } - } - - @Test - public void toInterface() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("d", ValueType.OBJECT); - builder.add("d", "test"); - builder.close(); - builder.close(); - } - final VPackSlice slice = builder.slice(); - final VPack vPack = new VPack.Builder() - .registerInstanceCreator(TestEntityD.class, new VPackInstanceCreator() { - @Override - public TestEntityD createInstance() { - return new TestEntityDImpl(); - } - }).build(); - final TestEntityC entity = vPack.deserialize(slice, TestEntityC.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.d, is(notNullValue())); - assertThat(entity.d.getD(), is("test")); - } - - public static class TestEntityCollection { - private Collection c1 = new LinkedList<>(); - private List c2 = new ArrayList<>(); - private ArrayList c3 = new ArrayList<>(); - private Set c4 = new LinkedHashSet<>(); - private HashSet c5 = new HashSet<>(); - - public TestEntityCollection() { - super(); - } - - public Collection getC1() { - return c1; - } - - public void setC1(final Collection c1) { - this.c1 = c1; - } - - public List getC2() { - return c2; - } - - public void setC2(final List c2) { - this.c2 = c2; - } - - public ArrayList getC3() { - return c3; - } - - public void setC3(final ArrayList c3) { - this.c3 = c3; - } - - public Set getC4() { - return c4; - } - - public void setC4(final Set c4) { - this.c4 = c4; - } - - public HashSet getC5() { - return c5; - } - - public void setC5(final HashSet c5) { - this.c5 = c5; - } - } - - @Test - public void fromCollection() throws JsonProcessingException { - final TestEntityCollection entity = new TestEntityCollection(); - { - entity.c1.add("test"); - entity.c2.add("test"); - entity.c3.add("test"); - entity.c4.add("test"); - entity.c5.add("test"); - } - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice c1 = vpack.get("c1"); - assertThat(c1.isArray(), is(true)); - assertThat(c1.getLength(), is(1)); - assertThat(c1.get(0).getAsString(), is("test")); - } - { - final VPackSlice c2 = vpack.get("c2"); - assertThat(c2.isArray(), is(true)); - assertThat(c2.getLength(), is(1)); - assertThat(c2.get(0).getAsString(), is("test")); - } - { - final VPackSlice c3 = vpack.get("c3"); - assertThat(c3.isArray(), is(true)); - assertThat(c3.getLength(), is(1)); - assertThat(c3.get(0).getAsString(), is("test")); - } - { - final VPackSlice c4 = vpack.get("c4"); - assertThat(c4.isArray(), is(true)); - assertThat(c4.getLength(), is(1)); - assertThat(c4.get(0).getAsString(), is("test")); - } - { - final VPackSlice c5 = vpack.get("c5"); - assertThat(c5.isArray(), is(true)); - assertThat(c5.getLength(), is(1)); - assertThat(c5.get(0).getAsString(), is("test")); - } - } - - @Test - public void toCollection() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - { - builder.add("c1", ValueType.ARRAY); - builder.add("test1"); - builder.add("test2"); - builder.close(); - } - { - builder.add("c2", ValueType.ARRAY); - builder.add("test1"); - builder.add("test2"); - builder.close(); - } - { - builder.add("c3", ValueType.ARRAY); - builder.add("test1"); - builder.add("test2"); - builder.close(); - } - { - builder.add("c4", ValueType.ARRAY); - builder.add("test1"); - builder.add("test2"); - builder.close(); - } - { - builder.add("c5", ValueType.ARRAY); - builder.add("test1"); - builder.add("test2"); - builder.close(); - } - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityCollection entity = mapper.readValue(vpack.getBuffer(), TestEntityCollection.class); - assertThat(entity, is(notNullValue())); - { - checkCollection(entity.c1); - checkCollection(entity.c2); - checkCollection(entity.c3); - checkCollection(entity.c4); - checkCollection(entity.c5); - } - } - - private void checkCollection(final Collection col) { - assertThat(col, is(notNullValue())); - assertThat(col.size(), is(2)); - for (final Iterator iterator = col.iterator(); iterator.hasNext();) { - final String next = iterator.next(); - assertThat("test1".equals(next) || "test2".equals(next), is(true)); - } - } - - public static class TestEntityCollectionWithObjects { - private Collection c1; - private Set c2; - - public Collection getC1() { - return c1; - } - - public void setC1(final Collection c1) { - this.c1 = c1; - } - - public Set getC2() { - return c2; - } - - public void setC2(final Set c2) { - this.c2 = c2; - } - } - - @Test - public void fromCollectionWithObjects() throws JsonProcessingException { - final TestEntityCollectionWithObjects entity = new TestEntityCollectionWithObjects(); - { - final Collection c1 = new ArrayList<>(); - c1.add(new TestEntityString()); - c1.add(new TestEntityString()); - entity.setC1(c1); - final Set c2 = new HashSet<>(); - c2.add(new TestEntityArray()); - entity.setC2(c2); - } - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice c1 = vpack.get("c1"); - assertThat(c1.isArray(), is(true)); - assertThat(c1.getLength(), is(2)); - assertThat(c1.get(0).isObject(), is(true)); - assertThat(c1.get(1).isObject(), is(true)); - { - final VPackSlice s = c1.get(0).get("s"); - assertThat(s.isString(), is(true)); - assertThat(s.getAsString(), is("test")); - } - } - { - final VPackSlice c2 = vpack.get("c2"); - assertThat(c2.isArray(), is(true)); - assertThat(c2.getLength(), is(1)); - assertThat(c2.get(0).isObject(), is(true)); - { - final VPackSlice a2 = c2.get(0).get("a2"); - assertThat(a2.isArray(), is(true)); - assertThat(a2.getLength(), is(5)); - for (int i = 0; i < a2.getLength(); i++) { - final VPackSlice at = a2.get(i); - assertThat(at.isInteger(), is(true)); - assertThat(at.getAsInt(), is(i + 1)); - } - } - } - } - - @Test - public void toCollectionWithObjects() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - { - builder.add("c1", ValueType.ARRAY); - builder.add(ValueType.OBJECT); - builder.add("s", "abc"); - builder.close(); - builder.close(); - } - { - builder.add("c2", ValueType.ARRAY); - builder.add(ValueType.OBJECT); - builder.add("a2", ValueType.ARRAY); - for (int i = 0; i < 10; i++) { - builder.add(i); - } - builder.close(); - builder.close(); - builder.close(); - } - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityCollectionWithObjects entity = mapper.readValue(vpack.getBuffer(), - TestEntityCollectionWithObjects.class); - assertThat(entity, is(notNullValue())); - { - assertThat(entity.c1, is(notNullValue())); - assertThat(entity.c1.size(), is(1)); - assertThat(entity.c1.iterator().next().s, is("abc")); - } - { - assertThat(entity.c2, is(notNullValue())); - assertThat(entity.c2.size(), is(1)); - final int[] array = entity.c2.iterator().next().a2; - for (int i = 0; i < array.length; i++) { - assertThat(array[i], is(i)); - } - } - } - - public static class TestEntityMap { - private Map m1; - private HashMap m2; - private Map m3; - - public Map getM1() { - return m1; - } - - public void setM1(final Map m1) { - this.m1 = m1; - } - - public HashMap getM2() { - return m2; - } - - public void setM2(final HashMap m2) { - this.m2 = m2; - } - - public Map getM3() { - return m3; - } - - public void setM3(final Map m3) { - this.m3 = m3; - } - } - - @Test - public void fromMap() throws JsonProcessingException { - final TestEntityMap entity = new TestEntityMap(); - { - final Map m1 = new LinkedHashMap<>(); - m1.put("a", "b"); - m1.put("c", "d"); - entity.setM1(m1); - final HashMap m2 = new HashMap<>(); - m2.put(1, "a"); - m2.put(2, "b"); - entity.setM2(m2); - final Map m3 = new HashMap<>(); - final TestEntityString s = new TestEntityString(); - s.setS("abc"); - m3.put("a", s); - entity.setM3(m3); - } - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice m1 = vpack.get("m1"); - assertThat(m1.isObject(), is(true)); - assertThat(m1.getLength(), is(2)); - { - final VPackSlice a = m1.get("a"); - assertThat(a.isString(), is(true)); - assertThat(a.getAsString(), is("b")); - } - { - final VPackSlice c = m1.get("c"); - assertThat(c.isString(), is(true)); - assertThat(c.getAsString(), is("d")); - } - } - { - final VPackSlice m2 = vpack.get("m2"); - assertThat(m2.isObject(), is(true)); - assertThat(m2.getLength(), is(2)); - { - final VPackSlice one = m2.get("1"); - assertThat(one.isString(), is(true)); - assertThat(one.getAsString(), is("a")); - } - { - final VPackSlice two = m2.get("2"); - assertThat(two.isString(), is(true)); - assertThat(two.getAsString(), is("b")); - } - } - { - final VPackSlice m3 = vpack.get("m3"); - assertThat(m3.isObject(), is(true)); - assertThat(m3.getLength(), is(1)); - final VPackSlice a = m3.get("a"); - assertThat(a.isObject(), is(true)); - final VPackSlice s = a.get("s"); - assertThat(s.isString(), is(true)); - assertThat(s.getAsString(), is("abc")); - } - } - - @Test - public void toMap() throws IOException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - { - builder.add("m1", ValueType.OBJECT); - builder.add("a", "a"); - builder.add("b", "b"); - builder.close(); - } - { - builder.add("m2", ValueType.OBJECT); - builder.add("1", "a"); - builder.add("-1", "a"); - builder.close(); - } - { - builder.add("m3", ValueType.OBJECT); - builder.add("a", ValueType.OBJECT); - builder.add("s", "abc"); - builder.close(); - builder.close(); - } - builder.close(); - } - final VPackSlice vpack = builder.slice(); - final TestEntityMap entity = mapper.readValue(vpack.getBuffer(), TestEntityMap.class); - assertThat(entity, is(notNullValue())); - { - assertThat(entity.m1, is(notNullValue())); - assertThat(entity.m1.size(), is(2)); - final String a = entity.m1.get("a"); - assertThat(a, is(notNullValue())); - assertThat(a, is("a")); - final String b = entity.m1.get("b"); - assertThat(b, is(notNullValue())); - assertThat(b, is("b")); - } - { - assertThat(entity.m2, is(notNullValue())); - assertThat(entity.m2.size(), is(2)); - final String one = entity.m2.get(1); - assertThat(one, is(notNullValue())); - assertThat(one, is("a")); - final String oneNegative = entity.m2.get(-1); - assertThat(oneNegative, is(notNullValue())); - assertThat(oneNegative, is("a")); - } - { - assertThat(entity.m3, is(notNullValue())); - assertThat(entity.m3.size(), is(1)); - final TestEntityString a = entity.m3.get("a"); - assertThat(a, is(notNullValue())); - assertThat(a.s, is("abc")); - } - } - - public static class TestEntityMapStringableKey { - private Map m1; - private Map m2; - private Map m3; - private Map m4; - private Map m5; - private Map m6; - private Map m7; - private Map m8; - private Map m9; - private Map m10; - private Map m11; - - public Map getM1() { - return m1; - } - - public void setM1(final Map m1) { - this.m1 = m1; - } - - public Map getM2() { - return m2; - } - - public void setM2(final Map m2) { - this.m2 = m2; - } - - public Map getM3() { - return m3; - } - - public void setM3(final Map m3) { - this.m3 = m3; - } - - public Map getM4() { - return m4; - } - - public void setM4(final Map m4) { - this.m4 = m4; - } - - public Map getM5() { - return m5; - } - - public void setM5(final Map m5) { - this.m5 = m5; - } - - public Map getM6() { - return m6; - } - - public void setM6(final Map m6) { - this.m6 = m6; - } - - public Map getM7() { - return m7; - } - - public void setM7(final Map m7) { - this.m7 = m7; - } - - public Map getM8() { - return m8; - } - - public void setM8(final Map m8) { - this.m8 = m8; - } - - public Map getM9() { - return m9; - } - - public void setM9(final Map m9) { - this.m9 = m9; - } - - public Map getM10() { - return m10; - } - - public void setM10(final Map m10) { - this.m10 = m10; - } - - public Map getM11() { - return m11; - } - - public void setM11(final Map m11) { - this.m11 = m11; - } - - } - - @Test - public void fromMapStringableKey() throws JsonProcessingException { - final TestEntityMapStringableKey entity = new TestEntityMapStringableKey(); - final String value = "test"; - { - final Map m1 = new HashMap<>(); - m1.put(true, value); - m1.put(false, value); - entity.setM1(m1); - } - { - final Map m2 = new HashMap<>(); - m2.put(1, value); - m2.put(2, value); - entity.setM2(m2); - } - { - final Map m3 = new HashMap<>(); - m3.put(1L, value); - m3.put(2L, value); - entity.setM3(m3); - } - { - final Map m4 = new HashMap<>(); - m4.put(1.5F, value); - m4.put(2.25F, value); - entity.setM4(m4); - } - { - final Map m5 = new HashMap<>(); - m5.put(new Short("1"), value); - m5.put(new Short("2"), value); - entity.setM5(m5); - } - { - final Map m6 = new HashMap<>(); - m6.put(1.5, value); - m6.put(2.25, value); - entity.setM6(m6); - } - { - final Map m7 = new HashMap<>(); - m7.put(1.5, value); - m7.put(1L, value); - entity.setM7(m7); - } - { - final Map m8 = new HashMap<>(); - m8.put(new BigInteger("1"), value); - m8.put(new BigInteger("2"), value); - entity.setM8(m8); - } - { - final Map m9 = new HashMap<>(); - m9.put(new BigDecimal("1.5"), value); - m9.put(new BigDecimal("2.25"), value); - entity.setM9(m9); - } - { - final Map m10 = new HashMap<>(); - m10.put('1', value); - m10.put('a', value); - entity.setM10(m10); - } - { - final Map m11 = new HashMap<>(); - m11.put(TestEnum.A, value); - m11.put(TestEnum.B, value); - entity.setM11(m11); - } - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - final VPackSlice m1 = vpack.get("m1"); - assertThat(m1.isObject(), is(true)); - assertThat(m1.getLength(), is(2)); - checkMapAttribute(m1.get("true")); - checkMapAttribute(m1.get("false")); - } - { - final VPackSlice m2 = vpack.get("m2"); - assertThat(m2.isObject(), is(true)); - assertThat(m2.getLength(), is(2)); - checkMapAttribute(m2.get("1")); - checkMapAttribute(m2.get("2")); - } - { - final VPackSlice m3 = vpack.get("m3"); - assertThat(m3.isObject(), is(true)); - assertThat(m3.getLength(), is(2)); - checkMapAttribute(m3.get("1")); - checkMapAttribute(m3.get("2")); - } - { - final VPackSlice m4 = vpack.get("m4"); - assertThat(m4.isObject(), is(true)); - assertThat(m4.getLength(), is(2)); - checkMapAttribute(m4.get("1.5")); - checkMapAttribute(m4.get("2.25")); - } - { - final VPackSlice m5 = vpack.get("m5"); - assertThat(m5.isObject(), is(true)); - assertThat(m5.getLength(), is(2)); - checkMapAttribute(m5.get("1")); - checkMapAttribute(m5.get("2")); - } - { - final VPackSlice m6 = vpack.get("m6"); - assertThat(m6.isObject(), is(true)); - assertThat(m6.getLength(), is(2)); - checkMapAttribute(m6.get("1.5")); - checkMapAttribute(m6.get("2.25")); - } - { - final VPackSlice m7 = vpack.get("m7"); - assertThat(m7.isObject(), is(true)); - assertThat(m7.getLength(), is(2)); - checkMapAttribute(m7.get("1.5")); - checkMapAttribute(m7.get("1")); - } - { - final VPackSlice m8 = vpack.get("m8"); - assertThat(m8.isObject(), is(true)); - assertThat(m8.getLength(), is(2)); - checkMapAttribute(m8.get("1")); - checkMapAttribute(m8.get("2")); - } - { - final VPackSlice m9 = vpack.get("m9"); - assertThat(m9.isObject(), is(true)); - assertThat(m9.getLength(), is(2)); - checkMapAttribute(m9.get("1.5")); - checkMapAttribute(m9.get("2.25")); - } - { - final VPackSlice m10 = vpack.get("m10"); - assertThat(m10.isObject(), is(true)); - assertThat(m10.getLength(), is(2)); - checkMapAttribute(m10.get("1")); - checkMapAttribute(m10.get("a")); - } - { - final VPackSlice m11 = vpack.get("m11"); - assertThat(m11.isObject(), is(true)); - assertThat(m11.getLength(), is(2)); - checkMapAttribute(m11.get(TestEnum.A.name())); - checkMapAttribute(m11.get(TestEnum.B.name())); - } - } - - @Test - public void toMapSringableKey() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - { - builder.add("m1", ValueType.OBJECT); - builder.add("true", "test"); - builder.add("false", "test"); - builder.close(); - } - { - builder.add("m2", ValueType.OBJECT); - builder.add("1", "test"); - builder.add("2", "test"); - builder.close(); - } - { - builder.add("m3", ValueType.OBJECT); - builder.add("1", "test"); - builder.add("2", "test"); - builder.close(); - } - { - builder.add("m4", ValueType.OBJECT); - builder.add("1.5", "test"); - builder.add("2.25", "test"); - builder.close(); - } - { - builder.add("m5", ValueType.OBJECT); - builder.add("1", "test"); - builder.add("2", "test"); - builder.close(); - } - { - builder.add("m6", ValueType.OBJECT); - builder.add("1.5", "test"); - builder.add("2.25", "test"); - builder.close(); - } - { - builder.add("m7", ValueType.OBJECT); - builder.add("1.5", "test"); - builder.add("1", "test"); - builder.close(); - } - { - builder.add("m8", ValueType.OBJECT); - builder.add("1", "test"); - builder.add("2", "test"); - builder.close(); - } - { - builder.add("m9", ValueType.OBJECT); - builder.add("1.5", "test"); - builder.add("2.25", "test"); - builder.close(); - } - { - builder.add("m10", ValueType.OBJECT); - builder.add("1", "test"); - builder.add("a", "test"); - builder.close(); - } - { - builder.add("m11", ValueType.OBJECT); - builder.add(TestEnum.A.name(), "test"); - builder.add(TestEnum.B.name(), "test"); - builder.close(); - } - builder.close(); - final TestEntityMapStringableKey entity = new VPack.Builder().build().deserialize(builder.slice(), - TestEntityMapStringableKey.class); - { - assertThat(entity.m1.size(), is(2)); - checkMapAttribute(entity.m1.get(true)); - checkMapAttribute(entity.m1.get(false)); - } - { - assertThat(entity.m2.size(), is(2)); - checkMapAttribute(entity.m2.get(1)); - checkMapAttribute(entity.m2.get(2)); - } - { - assertThat(entity.m3.size(), is(2)); - checkMapAttribute(entity.m3.get(1L)); - checkMapAttribute(entity.m3.get(2L)); - } - { - assertThat(entity.m4.size(), is(2)); - checkMapAttribute(entity.m4.get(1.5F)); - checkMapAttribute(entity.m4.get(2.25F)); - } - { - assertThat(entity.m5.size(), is(2)); - checkMapAttribute(entity.m5.get(new Short("1"))); - checkMapAttribute(entity.m5.get(new Short("2"))); - } - { - assertThat(entity.m6.size(), is(2)); - checkMapAttribute(entity.m6.get(1.5)); - checkMapAttribute(entity.m6.get(2.25)); - } - { - assertThat(entity.m7.size(), is(2)); - checkMapAttribute(entity.m7.get(new Double(1.5))); - checkMapAttribute(entity.m7.get(new Double(1L))); - } - { - assertThat(entity.m8.size(), is(2)); - checkMapAttribute(entity.m8.get(new BigInteger("1"))); - checkMapAttribute(entity.m8.get(new BigInteger("2"))); - } - { - assertThat(entity.m9.size(), is(2)); - checkMapAttribute(entity.m9.get(new BigDecimal("1.5"))); - checkMapAttribute(entity.m9.get(new BigDecimal("2.25"))); - } - { - assertThat(entity.m10.size(), is(2)); - checkMapAttribute(entity.m10.get('1')); - checkMapAttribute(entity.m10.get('a')); - } - { - assertThat(entity.m11.size(), is(2)); - checkMapAttribute(entity.m11.get(TestEnum.A)); - checkMapAttribute(entity.m11.get(TestEnum.B)); - } - } - - private void checkMapAttribute(final VPackSlice attr) { - assertThat(attr.isString(), is(true)); - assertThat(attr.getAsString(), is("test")); - } - - private void checkMapAttribute(final String attr) { - assertThat(attr, is("test")); - } - - public static class TestEntityMapWithObjectKey { - private Map m1; - private Map m2; - - public Map getM1() { - return m1; - } - - public void setM1(final Map m1) { - this.m1 = m1; - } - - public Map getM2() { - return m2; - } - - public void setM2(final Map m2) { - this.m2 = m2; - } - } - - @Test - public void toMapWithObjectKey() throws JsonProcessingException { - final int size = 2; - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - { - builder.add("m1", ValueType.ARRAY); - for (int i = 0; i < size; i++) { - builder.add(ValueType.OBJECT); - { - builder.add("key", ValueType.OBJECT); - builder.add("l1", 5L); - builder.close(); - } - { - builder.add("value", ValueType.OBJECT); - builder.add("c1", ValueType.ARRAY); - builder.add("test"); - builder.close(); - builder.close(); - } - builder.close(); - } - builder.close(); - } - { - builder.add("m2", ValueType.ARRAY); - for (int i = 0; i < size; i++) { - builder.add(ValueType.OBJECT); - { - builder.add("key", ValueType.OBJECT); - builder.add("l1", 5L); - builder.close(); - } - { - builder.add("value", "test"); - } - builder.close(); - } - builder.close(); - } - builder.close(); - final TestEntityMapWithObjectKey entity = new VPack.Builder().build().deserialize(builder.slice(), - TestEntityMapWithObjectKey.class); - assertThat(entity, is(notNullValue())); - { - assertThat(entity.m1, is(notNullValue())); - assertThat(entity.m1.size(), is(size)); - for (final Entry entry : entity.m1.entrySet()) { - assertThat(entry.getKey().l1, is(5L)); - assertThat(entry.getValue().c1.size(), is(1)); - assertThat(entry.getValue().c1.iterator().next(), is("test")); - } - } - { - assertThat(entity.m2, is(notNullValue())); - assertThat(entity.m2.size(), is(2)); - for (final Entry entry : entity.m2.entrySet()) { - assertThat(entry.getKey().l1, is(5L)); - assertThat(entry.getValue(), is("test")); - } - } - } - - public static class TestEntityEmpty { - - } - - @Test - public void fromEmptyObject() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityEmpty())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - assertThat(vpack.getLength(), is(0)); - } - - @Test - public void toEmptyObject() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - builder.close(); - final TestEntityEmpty entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityEmpty.class); - assertThat(entity, is(notNullValue())); - } - - public static class TestEntityEmptyMap { - private Map m; - - public Map getM() { - return m; - } - - public void setM(final Map m) { - this.m = m; - } - } - - @Test - public void fromEmptyMap() throws JsonProcessingException { - final TestEntityEmptyMap entity = new TestEntityEmptyMap(); - entity.setM(new HashMap()); - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - assertThat(vpack.getLength(), is(1)); - final VPackSlice m = vpack.get("m"); - assertThat(m.isObject(), is(true)); - assertThat(m.getLength(), is(0)); - } - - @Test - public void toEmptyMap() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - builder.add("m", ValueType.OBJECT); - builder.close(); - builder.close(); - final TestEntityEmptyMap entity = new VPack.Builder().build().deserialize(builder.slice(), - TestEntityEmptyMap.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.m, is(notNullValue())); - assertThat(entity.m.size(), is(0)); - } - - public static class TestEntityBaseAttributes { - private String _key = "test1"; - private String _rev = "test2"; - private String _id = "test3"; - private String _from = "test4"; - private String _to = "test5"; - - public String get_key() { - return _key; - } - - public void set_key(final String _key) { - this._key = _key; - } - - public String get_rev() { - return _rev; - } - - public void set_rev(final String _rev) { - this._rev = _rev; - } - - public String get_id() { - return _id; - } - - public void set_id(final String _id) { - this._id = _id; - } - - public String get_from() { - return _from; - } - - public void set_from(final String _from) { - this._from = _from; - } - - public String get_to() { - return _to; - } - - public void set_to(final String _to) { - this._to = _to; - } - - } - - @Test - public void fromObjectWithAttributeAdapter() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityBaseAttributes())); - assertThat(vpack.isObject(), is(true)); - assertThat(vpack.getLength(), is(5)); - { - final VPackSlice key = vpack.get("_key"); - assertThat(key.isString(), is(true)); - assertThat(key.getAsString(), is("test1")); - } - { - final VPackSlice rev = vpack.get("_rev"); - assertThat(rev.isString(), is(true)); - assertThat(rev.getAsString(), is("test2")); - } - { - final VPackSlice id = vpack.get("_id"); - assertThat(id.isString(), is(true)); - assertThat(id.getAsString(), is("test3")); - } - { - final VPackSlice from = vpack.get("_from"); - assertThat(from.isString(), is(true)); - assertThat(from.getAsString(), is("test4")); - } - { - final VPackSlice to = vpack.get("_to"); - assertThat(to.isString(), is(true)); - assertThat(to.getAsString(), is("test5")); - } - } - - @Test - public void toObjectWithAttributeAdapter() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("_key", "a"); - builder.add("_rev", "b"); - builder.add("_id", "c"); - builder.add("_from", "d"); - builder.add("_to", "e"); - builder.close(); - } - final TestEntityBaseAttributes entity = new VPack.Builder().build().deserialize(builder.slice(), - TestEntityBaseAttributes.class); - assertThat(entity, is(notNullValue())); - assertThat(entity._key, is("a")); - assertThat(entity._rev, is("b")); - assertThat(entity._id, is("c")); - assertThat(entity._from, is("d")); - assertThat(entity._to, is("e")); - } - - @Test - public void fromMapWithAttributeAdapter() throws JsonProcessingException { - final TestEntityMap entity = new TestEntityMap(); - { - final Map m1 = new HashMap<>(); - m1.put("_key", "test1"); - m1.put("_rev", "test2"); - m1.put("_id", "test3"); - m1.put("_from", "test4"); - m1.put("_to", "test5"); - entity.setM1(m1); - } - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack.isObject(), is(true)); - final VPackSlice m1 = vpack.get("m1"); - assertThat(m1.isObject(), is(true)); - assertThat(m1.getLength(), is(5)); - { - final VPackSlice key = m1.get("_key"); - assertThat(key.isString(), is(true)); - assertThat(key.getAsString(), is("test1")); - } - { - final VPackSlice rev = m1.get("_rev"); - assertThat(rev.isString(), is(true)); - assertThat(rev.getAsString(), is("test2")); - } - { - final VPackSlice id = m1.get("_id"); - assertThat(id.isString(), is(true)); - assertThat(id.getAsString(), is("test3")); - } - { - final VPackSlice from = m1.get("_from"); - assertThat(from.isString(), is(true)); - assertThat(from.getAsString(), is("test4")); - } - { - final VPackSlice to = m1.get("_to"); - assertThat(to.isString(), is(true)); - assertThat(to.getAsString(), is("test5")); - } - } - - @Test - public void toMapWithAttributeAdapter() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - { - builder.add(ValueType.OBJECT); - builder.add("m1", ValueType.OBJECT); - builder.add("_key", "a"); - builder.add("_rev", "b"); - builder.add("_id", "c"); - builder.add("_from", "d"); - builder.add("_to", "e"); - builder.close(); - builder.close(); - } - final TestEntityMap entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityMap.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.m1, is(notNullValue())); - assertThat(entity.m1.size(), is(5)); - } - - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.FIELD) - private static @interface CustomFilterAnnotation { - boolean serialize() - - default true; - - boolean deserialize() default true; - } - - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.FIELD) - private static @interface CustomNamingAnnotation { - String name(); - } - - private static class CustomAnEntity { - @CustomFilterAnnotation(serialize = false) - private String a = null; - @CustomFilterAnnotation(deserialize = false) - private String b = null; - @CustomNamingAnnotation(name = "d") - @CustomFilterAnnotation(deserialize = false) - private String c = null; - - public CustomAnEntity() { - super(); - } - } - - @Test - public void fromCutsomAnnotation() { - final CustomAnEntity entity = new CustomAnEntity(); - entity.a = "1"; - entity.b = "2"; - entity.c = "3"; - final VPackSlice vpack = new VPack.Builder().annotationFieldFilter(CustomFilterAnnotation.class, - new VPackAnnotationFieldFilter() { - - @Override - public boolean serialize(final CustomFilterAnnotation annotation) { - return annotation.serialize(); - } - - @Override - public boolean deserialize(final CustomFilterAnnotation annotation) { - return annotation.deserialize(); - } - }).annotationFieldNaming(CustomNamingAnnotation.class, - new VPackAnnotationFieldNaming() { - @Override - public String name(final CustomNamingAnnotation annotation) { - return annotation.name(); - } - }).build().serialize(entity); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - assertThat(vpack.get("a").isNone(), is(true)); - assertThat(vpack.get("b").isString(), is(true)); - assertThat(vpack.get("b").getAsString(), is("2")); - assertThat(vpack.get("c").isNone(), is(true)); - assertThat(vpack.get("d").isString(), is(true)); - assertThat(vpack.get("d").getAsString(), is("3")); - } - - @Test - public void directFromCollection() throws JsonProcessingException { - final Collection list = new ArrayList<>(); - list.add("test"); - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(list)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isArray(), is(true)); - assertThat(vpack.size(), is(1)); - final VPackSlice test = vpack.get(0); - assertThat(test.isString(), is(true)); - assertThat(test.getAsString(), is("test")); - } - - @Test - public void directFromCollectionWithType() throws JsonProcessingException { - final Collection list = new ArrayList<>(); - list.add(new TestEntityString()); - list.add(new TestEntityString()); - - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(list)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isArray(), is(true)); - assertThat(vpack.getLength(), is(list.size())); - for (int i = 0; i < list.size(); i++) { - final VPackSlice entry = vpack.get(i); - assertThat(entry.isObject(), is(true)); - assertThat(entry.getLength(), is(3)); - final VPackSlice s = entry.get("s"); - assertThat(s.isString(), is(true)); - assertThat(s.getAsString(), is("test")); - } - } - - @Test - public void directToCollection() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.ARRAY); - builder.add(ValueType.OBJECT); - builder.add("s", "abc"); - builder.close(); - builder.close(); - final List list = new VPack.Builder().build().deserialize(builder.slice(), - new Type>() { - }.getType()); - assertThat(list, is(notNullValue())); - assertThat(list.size(), is(1)); - final TestEntityString entry = list.get(0); - assertThat(entry.s, is("abc")); - } - - @Test - public void directFromStringMap() throws JsonProcessingException { - final Map map = new HashMap<>(); - map.put("a", new TestEntityString()); - map.put("b", new TestEntityString()); - - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(map)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - assertThat(vpack.getLength(), is(2)); - final VPackSlice a = vpack.get("a"); - checkStringEntity(a); - } - - @Test - public void directToStringMap() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - builder.add("a", ValueType.OBJECT); - builder.add("s", "abc"); - builder.close(); - builder.close(); - final Map map = new VPack.Builder().build().deserialize(builder.slice(), - new Type>() { - }.getType()); - assertThat(map, is(notNullValue())); - assertThat(map.size(), is(1)); - final TestEntityString a = map.get("a"); - assertThat(a, is(notNullValue())); - assertThat(a.s, is("abc")); - } - - @Test - public void directFromMap() throws JsonProcessingException { - final Map map = new HashMap<>(); - final TestEntityA entity = new TestEntityA(); - entity.a = "test"; - map.put("test", entity); - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(map)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - final VPackSlice test = vpack.get("test"); - assertThat(test.isObject(), is(true)); - final VPackSlice a = test.get("a"); - assertThat(a.isString(), is(true)); - assertThat(a.getAsString(), is("test")); - } - - @Test - public void directFromMapWithinMap() throws JsonProcessingException { - final Map map = new HashMap<>(); - final Map map2 = new HashMap<>(); - map2.put("b", "test"); - map.put("a", map2); - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(map)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - assertThat(vpack.size(), is(1)); - final VPackSlice a = vpack.get("a"); - assertThat(a.isObject(), is(true)); - assertThat(a.size(), is(1)); - final VPackSlice b = a.get("b"); - assertThat(b.isString(), is(true)); - assertThat(b.getAsString(), is("test")); - } - - private void checkStringEntity(final VPackSlice vpack) throws JsonProcessingException { - final TestEntityString expected = new TestEntityString(); - assertThat(vpack.isObject(), is(true)); - assertThat(vpack.getLength(), is(3)); - final VPackSlice s = vpack.get("s"); - assertThat(s.isString(), is(true)); - assertThat(s.getAsString(), is(expected.s)); - final VPackSlice c1 = vpack.get("c1"); - assertThat(c1.isString(), is(true)); - assertThat(new Character(c1.getAsChar()), is(expected.c1)); - final VPackSlice c2 = vpack.get("c2"); - assertThat(c2.isString(), is(true)); - assertThat(c2.getAsChar(), is(expected.c2)); - } - - @Test - public void directToObjectMap() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.ARRAY); - builder.add(ValueType.OBJECT); - builder.add("key", ValueType.OBJECT); - builder.add("s", "abc"); - builder.close(); - builder.add("value", ValueType.OBJECT); - builder.add("s", "abc"); - builder.close(); - builder.close(); - builder.close(); - final Map map = new VPack.Builder().build().deserialize(builder.slice(), - new Type>() { - }.getType()); - assertThat(map, is(notNullValue())); - assertThat(map.size(), is(1)); - for (final Entry entry : map.entrySet()) { - assertThat(entry.getKey().s, is("abc")); - assertThat(entry.getValue().s, is("abc")); - } - } - - @SuppressWarnings("unchecked") - @Test - public void directToMapWithinMap() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - builder.add("a", ValueType.OBJECT); - builder.add("b", "test"); - builder.add("c", true); - builder.add("d", 1L); - builder.add("e", 1.5); - final Date date = new Date(); - builder.add("f", date); - builder.add("g", ValueType.ARRAY); - builder.close(); - builder.close(); - builder.close(); - final Map map = new VPack.Builder().build().deserialize(builder.slice(), Map.class); - assertThat(map, is(notNullValue())); - assertThat(map.size(), is(1)); - final Object a = map.get("a"); - assertThat(Map.class.isAssignableFrom(a.getClass()), is(true)); - final Map mapA = (Map) a; - assertThat(mapA.size(), is(6)); - final Object b = mapA.get("b"); - assertThat(String.class.isAssignableFrom(b.getClass()), is(true)); - assertThat(b.toString(), is("test")); - final Object c = mapA.get("c"); - assertThat(Boolean.class.isAssignableFrom(c.getClass()), is(true)); - assertThat(Boolean.class.cast(c), is(true)); - final Object d = mapA.get("d"); - assertThat(Number.class.isAssignableFrom(d.getClass()), is(true)); - assertThat(Number.class.cast(d).longValue(), is(1L)); - final Object e = mapA.get("e"); - assertThat(Double.class.isAssignableFrom(e.getClass()), is(true)); - assertThat(Double.class.cast(e), is(1.5)); - final Object f = mapA.get("f"); - assertThat(Date.class.isAssignableFrom(f.getClass()), is(true)); - assertThat(Date.class.cast(f), is(date)); - final Object g = mapA.get("g"); - assertThat(Collection.class.isAssignableFrom(g.getClass()), is(true)); - assertThat(List.class.isAssignableFrom(g.getClass()), is(true)); - } - - @Test - public void dontSerializeNullValues() throws JsonProcessingException { - final VPack serializer = new VPack.Builder().serializeNullValues(false).build(); - final TestEntityString entity = new TestEntityString(); - entity.setS(null); - final VPackSlice vpack = serializer.serialize(entity); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - final VPackSlice s = vpack.get("s"); - assertThat(s.isNone(), is(true)); - } - - @Test - public void serializeNullValue() throws JsonProcessingException { - final VPack serializer = new VPack.Builder().serializeNullValues(true).build(); - final TestEntityString entity = new TestEntityString(); - entity.setS(null); - final VPackSlice vpack = serializer.serialize(entity); - assertThat(vpack, is(notNullValue())); - final VPackSlice s = vpack.get("s"); - assertThat(s.isNull(), is(true)); - } - - @Test - public void toNullValue() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - builder.add("s", ValueType.NULL); - builder.close(); - final TestEntityString entity = new VPack.Builder().build().deserialize(builder.slice(), - TestEntityString.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.s, is(nullValue())); - assertThat(entity.c1, is(notNullValue())); - assertThat(entity.c2, is(notNullValue())); - } - - @Test - public void toSimpleString() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add("test"); - final String s = new VPack.Builder().build().deserialize(builder.slice(), String.class); - assertThat(s, is(notNullValue())); - assertThat(s, is("test")); - } - - @Test - public void fromSimpleString() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes("test")); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isString(), is(true)); - assertThat(vpack.getAsString(), is("test")); - } - - public static class TestEntityTyped { - private T e; - } - - @Test - public void fromStringTypedEntity() throws JsonProcessingException { - final TestEntityTyped entity = new TestEntityTyped<>(); - entity.e = "test"; - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - final VPackSlice e = vpack.get("e"); - assertThat(e, is(notNullValue())); - assertThat(e.isString(), is(true)); - assertThat(e.getAsString(), is("test")); - } - - @Test - public void fromObjectTypedEntity() throws JsonProcessingException { - final TestEntityTyped entity = new TestEntityTyped<>(); - entity.e = new TestEntityString(); - entity.e.s = "test2"; - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - final VPackSlice e = vpack.get("e"); - assertThat(e, is(notNullValue())); - assertThat(e.isObject(), is(true)); - final VPackSlice s = e.get("s"); - assertThat(s, is(notNullValue())); - assertThat(s.isString(), is(true)); - assertThat(s.getAsString(), is("test2")); - } - - @Test - public void fromTypedTypedEntity() throws JsonProcessingException { - final TestEntityTyped> entity = new TestEntityTyped<>(); - entity.e = new TestEntityTyped<>(); - entity.e.e = "test"; - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - final VPackSlice e = vpack.get("e"); - assertThat(e, is(notNullValue())); - assertThat(e.isObject(), is(true)); - final VPackSlice e2 = e.get("e"); - assertThat(e2, is(notNullValue())); - assertThat(e2.isString(), is(true)); - assertThat(e2.getAsString(), is("test")); - } - - @Test - public void fieldNamingStrategySerialize() throws JsonProcessingException { - final VPackSlice vpack = new VPack.Builder().fieldNamingStrategy(new VPackFieldNamingStrategy() { - @Override - public String translateName(final Field field) { - return "bla"; - } - }).build().serialize(new TestEntityA()); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - final VPackSlice bla = vpack.get("bla"); - assertThat(bla.isString(), is(true)); - assertThat(bla.getAsString(), is("a")); - } - - @Test - public void fieldNamingStrategyDeserialize() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - builder.add("bla", "test"); - builder.close(); - final TestEntityA entity = new VPack.Builder().fieldNamingStrategy(new VPackFieldNamingStrategy() { - @Override - public String translateName(final Field field) { - return "bla"; - } - }).build().deserialize(builder.slice(), TestEntityA.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.a, is("test")); - } - - @Test - public void serializeVPack() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add("test"); - final VPackSlice slice = builder.slice(); - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(slice)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isString(), is(true)); - assertThat(vpack.getAsString(), is("test")); - } - - @Test - public void deserializeVPack() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add("test"); - final VPackSlice slice = builder.slice(); - final VPackSlice vpack = new VPack.Builder().build().deserialize(slice, slice.getClass()); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isString(), is(true)); - assertThat(vpack.getAsString(), is("test")); - } - - public static class TestEntityDate { - private java.util.Date utilDate = new Date(1474988621); - private java.sql.Date sqlDate = new java.sql.Date(1474988621); - private java.sql.Timestamp timestamp = new java.sql.Timestamp(1474988621); - - public java.util.Date getUtilDate() { - return utilDate; - } - - public void setUtilDate(final java.util.Date utilDate) { - this.utilDate = utilDate; - } - - public java.sql.Date getSqlDate() { - return sqlDate; - } - - public void setSqlDate(final java.sql.Date sqlDate) { - this.sqlDate = sqlDate; - } - - public java.sql.Timestamp getTimestamp() { - return timestamp; - } - - public void setTimestamp(final java.sql.Timestamp timestamp) { - this.timestamp = timestamp; - } - - } - - @Test - public void fromDate() throws JsonProcessingException { - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityDate())); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - { - assertThat(vpack.get("utilDate").isString(), is(true)); - assertThat(vpack.get("utilDate").getAsString(), is(DATE_FORMAT.format(new Date(1474988621)))); - } - { - assertThat(vpack.get("sqlDate").isString(), is(true)); - assertThat(vpack.get("sqlDate").getAsString(), is(DATE_FORMAT.format(new java.sql.Date(1474988621)))); - } - { - assertThat(vpack.get("timestamp").isString(), is(true)); - assertThat(vpack.get("timestamp").getAsString(), - is(DATE_FORMAT.format(new java.sql.Timestamp(1474988621)))); - } - } - - @Test - public void toDate() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - builder.add("utilDate", new Date(1475062216)); - builder.add("sqlDate", new java.sql.Date(1475062216)); - builder.add("timestamp", new java.sql.Timestamp(1475062216)); - builder.close(); - - final TestEntityDate entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityDate.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.utilDate, is(new Date(1475062216))); - assertThat(entity.sqlDate, is(new java.sql.Date(1475062216))); - assertThat(entity.timestamp, is(new java.sql.Timestamp(1475062216))); - } - - @Test - public void toDateFromString() throws JsonProcessingException { - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - builder.add("utilDate", DATE_FORMAT.format(new Date(1475062216))); - builder.add("sqlDate", DATE_FORMAT.format(new java.sql.Date(1475062216))); - builder.add("timestamp", DATE_FORMAT.format(new java.sql.Timestamp(1475062216))); - builder.close(); - - final TestEntityDate entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityDate.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.utilDate, is(new Date(1475062216))); - assertThat(entity.sqlDate, is(new java.sql.Date(1475062216))); - assertThat(entity.timestamp, is(new java.sql.Timestamp(1475062216))); - } - - public static class TestEntityUUID { - private UUID uuid; - - public UUID getUuid() { - return uuid; - } - - public void setUuid(final UUID uuid) { - this.uuid = uuid; - } - } - - @Test - public void fromUUID() throws IOException { - final TestEntityUUID entity = new TestEntityUUID(); - entity.setUuid(UUID.randomUUID()); - byte[] bytes = mapper.writeValueAsBytes(entity); - final VPackSlice vpack = new VPackSlice(bytes); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - - final VPackSlice uuid = vpack.get("uuid"); - assertThat(uuid.isString(), is(true)); - assertThat(uuid.getAsString(), is(entity.getUuid().toString())); - assertThat(mapper.readValue(bytes, TestEntityUUID.class).getUuid(), is(entity.getUuid())); - } - - @Test - public void toUUID() { - final UUID uuid = UUID.randomUUID(); - final VPackBuilder builder = new VPackBuilder(); - builder.add(ValueType.OBJECT); - builder.add("uuid", uuid.toString()); - builder.close(); - - final TestEntityUUID entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityUUID.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.uuid, is(uuid)); - } - - @Test - public void uuid() { - final TestEntityUUID entity = new TestEntityUUID(); - entity.setUuid(UUID.randomUUID()); - final VPack vpacker = new VPack.Builder().build(); - final VPackSlice vpack = vpacker.serialize(entity); - final TestEntityUUID entity2 = vpacker.deserialize(vpack, TestEntityUUID.class); - assertThat(entity2, is(notNullValue())); - assertThat(entity2.getUuid(), is(entity.getUuid())); - } - - private static class BinaryEntity { - private byte[] foo; - - public BinaryEntity() { - super(); - } - } - - @Test - public void fromBinary() throws JsonProcessingException { - final BinaryEntity entity = new BinaryEntity(); - entity.foo = "bar".getBytes(); - final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); - assertThat(vpack, is(notNullValue())); - assertThat(vpack.isObject(), is(true)); - assertThat(vpack.get("foo").isString(), is(true)); - assertThat(vpack.get("foo").getAsString(), is(Base64.getEncoder().encodeToString(entity.foo))); - } - - @Test - public void toBinary() throws IOException { - final String value = Base64.getEncoder().encodeToString("bar".getBytes()); - final VPackSlice vpack = new VPackBuilder().add(ValueType.OBJECT).add("foo", value).close().slice(); - final BinaryEntity entity = mapper.readValue(vpack.getBuffer(), BinaryEntity.class); - assertThat(entity, is(notNullValue())); - assertThat(entity.foo, is("bar".getBytes())); - } - - @Test - public void asFloatingNumber() { - final VPackSlice vpack = new VPackBuilder().add(ValueType.OBJECT).add("value", 12000).close().slice(); - assertThat(vpack.get("value").getAsInt(), is(12000)); - assertThat(vpack.get("value").getAsFloat(), is(12000F)); - assertThat(vpack.get("value").getAsDouble(), is(12000.)); - } - - @Test - public void toVPackSlice() throws IOException { - final VPackSlice value = new VPackBuilder().add(ValueType.OBJECT).add("key", "value").close().slice(); - final VPackSlice entity = mapper.readValue(value.getBuffer(), VPackSlice.class); - assertThat(entity, is(value)); - } +class VPackSerializeDeserializeTest { + + private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");// ISO 8601 + + static { + DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); + } + + private final ObjectMapper mapper = ArangoJack.createDefaultMapper(); + + public static class TestEntityBoolean { + private boolean a = true; + private boolean b = false; + private Boolean c = Boolean.TRUE; + private Boolean d = Boolean.FALSE; + + public boolean isA() { + return a; + } + + public void setA(final boolean a) { + this.a = a; + } + + public boolean isB() { + return b; + } + + public void setB(final boolean b) { + this.b = b; + } + + public Boolean getC() { + return c; + } + + public void setC(final Boolean c) { + this.c = c; + } + + public Boolean getD() { + return d; + } + + public void setD(final Boolean d) { + this.d = d; + } + } + + @Test + void fromBoolean() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityBoolean())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice a = vpack.get("a"); + assertThat(a.isBoolean()).isTrue(); + assertThat(a.getAsBoolean()).isTrue(); + } + { + final VPackSlice b = vpack.get("b"); + assertThat(b.isBoolean()).isTrue(); + assertThat(b.getAsBoolean()).isFalse(); + } + { + final VPackSlice c = vpack.get("c"); + assertThat(c.isBoolean()).isTrue(); + assertThat(c.getAsBoolean()).isTrue(); + } + { + final VPackSlice d = vpack.get("d"); + assertThat(d.isBoolean()).isTrue(); + assertThat(d.getAsBoolean()).isFalse(); + } + } + + @Test + void toBoolean() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("a", false); + builder.add("b", true); + builder.add("c", Boolean.FALSE); + builder.add("d", Boolean.TRUE); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityBoolean entity = mapper.readValue(vpack.getBuffer(), TestEntityBoolean.class); + assertThat(entity).isNotNull(); + assertThat(entity.a).isFalse(); + assertThat(entity.b).isTrue(); + assertThat(entity.c).isInstanceOf(Boolean.class).isFalse(); + assertThat(entity.d).isInstanceOf(Boolean.class).isTrue(); + } + + public static class TestEntityString { + private String s = "test"; + private Character c1 = 't'; + private char c2 = 't'; + + public String getS() { + return s; + } + + public void setS(final String s) { + this.s = s; + } + + public Character getC1() { + return c1; + } + + public void setC1(final Character c1) { + this.c1 = c1; + } + + public char getC2() { + return c2; + } + + public void setC2(final char c2) { + this.c2 = c2; + } + } + + @Test + void fromStrings() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityString())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice s = vpack.get("s"); + assertThat(s.isString()).isTrue(); + assertThat(s.getAsString()).isEqualTo("test"); + } + { + final VPackSlice c1 = vpack.get("c1"); + assertThat(c1.isString()).isTrue(); + assertThat(c1.getAsChar()).isEqualTo('t'); + } + { + final VPackSlice c2 = vpack.get("c2"); + assertThat(c2.isString()).isTrue(); + assertThat(c2.getAsChar()).isEqualTo('t'); + } + } + + @Test + void toStrings() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("s", "abc"); + builder.add("c1", 'd'); + builder.add("c2", 'd'); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityString entity = mapper.readValue(vpack.getBuffer(), TestEntityString.class); + assertThat(entity).isNotNull(); + assertThat(entity.s).isEqualTo("abc"); + assertThat(entity.c1).isEqualTo(new Character('d')); + } + + public static class TestEntityInteger { + private int i1 = 1; + private Integer i2 = 1; + + public int getI1() { + return i1; + } + + public void setI1(final int i1) { + this.i1 = i1; + } + + public Integer getI2() { + return i2; + } + + public void setI2(final Integer i2) { + this.i2 = i2; + } + } + + @Test + void fromInteger() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityInteger())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice i1 = vpack.get("i1"); + assertThat(i1.isInteger()).isTrue(); + assertThat(i1.getAsInt()).isEqualTo(1); + } + { + final VPackSlice i2 = vpack.get("i2"); + assertThat(i2.isInteger()).isTrue(); + assertThat(i2.getAsInt()).isEqualTo(1); + } + } + + @Test + void fromNegativeInteger() throws JsonProcessingException { + final TestEntityInteger entity = new TestEntityInteger(); + entity.i1 = -50; + entity.i2 = -50; + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice i1 = vpack.get("i1"); + assertThat(i1.isInteger()).isTrue(); + assertThat(i1.getAsInt()).isEqualTo(-50); + } + { + final VPackSlice i2 = vpack.get("i2"); + assertThat(i2.isInteger()).isTrue(); + assertThat(i2.getAsInt()).isEqualTo(-50); + } + } + + @Test + void toInteger() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("i1", 2); + builder.add("i2", 3); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityInteger entity = mapper.readValue(vpack.getBuffer(), TestEntityInteger.class); + assertThat(entity).isNotNull(); + assertThat(entity.i1).isEqualTo(2); + assertThat(entity.i2).isEqualTo(Integer.valueOf(3)); + } + + @Test + void toNegativeInteger() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("i1", -50); + builder.add("i2", -50); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityInteger entity = mapper.readValue(vpack.getBuffer(), TestEntityInteger.class); + assertThat(entity).isNotNull(); + assertThat(entity.i1).isEqualTo(-50); + assertThat(entity.i2).isEqualTo(Integer.valueOf(-50)); + } + + public static class TestEntityLong { + private long l1 = 1; + private Long l2 = 1L; + + public long getL1() { + return l1; + } + + public void setL1(final long l1) { + this.l1 = l1; + } + + public Long getL2() { + return l2; + } + + public void setL2(final Long l2) { + this.l2 = l2; + } + } + + @Test + void fromLong() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityLong())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice l1 = vpack.get("l1"); + assertThat(l1.isInteger()).isTrue(); + assertThat(l1.getAsLong()).isEqualTo(1L); + } + { + final VPackSlice l2 = vpack.get("l2"); + assertThat(l2.isInteger()).isTrue(); + assertThat(l2.getAsLong()).isEqualTo(1L); + } + } + + @Test + void fromNegativeLong() throws JsonProcessingException { + final TestEntityLong entity = new TestEntityLong(); + entity.l1 = -100L; + entity.l2 = -300L; + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice l1 = vpack.get("l1"); + assertThat(l1.isInteger()).isTrue(); + assertThat(l1.getAsLong()).isEqualTo(-100L); + } + { + final VPackSlice l2 = vpack.get("l2"); + assertThat(l2.isInteger()).isTrue(); + assertThat(l2.getAsLong()).isEqualTo(-300); + } + } + + @Test + void toLong() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("l1", 2); + builder.add("l2", 3); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityLong entity = mapper.readValue(vpack.getBuffer(), TestEntityLong.class); + assertThat(entity).isNotNull(); + assertThat(entity.l1).isEqualTo(2); + assertThat(entity.l2).isEqualTo(Long.valueOf(3)); + } + + @Test + void toNegativeLong() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("l1", -100L); + builder.add("l2", -300L); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityLong entity = mapper.readValue(vpack.getBuffer(), TestEntityLong.class); + assertThat(entity).isNotNull(); + assertThat(entity.l1).isEqualTo(-100L); + assertThat(entity.l2).isEqualTo(Long.valueOf(-300)); + } + + @Test + void negativeLong() { + final TestEntityLong entity = new TestEntityLong(); + entity.l1 = -100L; + entity.l2 = -300L; + final VPack vp = new VPack.Builder().build(); + final TestEntityLong out = vp.deserialize(vp.serialize(entity), TestEntityLong.class); + assertThat(out.l1).isEqualTo(entity.l1); + assertThat(out.l2).isEqualTo(entity.l2); + } + + @Test + void intToLong() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("l1", 100); + builder.add("l2", 300); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityLong entity = mapper.readValue(vpack.getBuffer(), TestEntityLong.class); + assertThat(entity).isNotNull(); + assertThat(entity.l1).isEqualTo(100); + assertThat(entity.l2).isEqualTo(Long.valueOf(300)); + } + + @Test + void negativeIntToLong() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("l1", -100); + builder.add("l2", -300); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityLong entity = mapper.readValue(vpack.getBuffer(), TestEntityLong.class); + assertThat(entity).isNotNull(); + assertThat(entity.l1).isEqualTo(-100L); + assertThat(entity.l2).isEqualTo(Long.valueOf(-300)); + } + + @Test + void negativeLongToInt() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("i1", -100L); + builder.add("i2", -300L); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityInteger entity = mapper.readValue(vpack.getBuffer(), TestEntityInteger.class); + assertThat(entity).isNotNull(); + assertThat(entity.i1).isEqualTo(-100); + assertThat(entity.i2).isEqualTo(Integer.valueOf(-300)); + } + + @Test + void negativeLongToShort() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("s1", -100L); + builder.add("s2", -300L); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityShort entity = mapper.readValue(vpack.getBuffer(), TestEntityShort.class); + assertThat(entity).isNotNull(); + assertThat(entity.s1).isEqualTo((short) -100); + assertThat(entity.s2).isEqualTo(Short.valueOf((short) -300)); + } + + @Test + void negativeShortToLong() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("l1", (short) -100); + builder.add("l2", (short) -300); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityLong entity = mapper.readValue(vpack.getBuffer(), TestEntityLong.class); + assertThat(entity).isNotNull(); + assertThat(entity.l1).isEqualTo(-100L); + assertThat(entity.l2).isEqualTo(Long.valueOf(-300)); + } + + public static class TestEntityFloat { + private float f1 = 1; + private Float f2 = 1F; + + public float getF1() { + return f1; + } + + public void setF1(final float f1) { + this.f1 = f1; + } + + public Float getF2() { + return f2; + } + + public void setF2(final Float f2) { + this.f2 = f2; + } + } + + @Test + void fromFloat() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityFloat())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice f1 = vpack.get("f1"); + assertThat(f1.isDouble()).isTrue(); + assertThat(f1.getAsFloat()).isEqualTo(1.0F); + } + { + final VPackSlice f2 = vpack.get("f2"); + assertThat(f2.isDouble()).isTrue(); + assertThat(f2.getAsFloat()).isEqualTo(1.0F); + } + } + + @Test + void toFloat() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("f1", 2F); + builder.add("f2", 3F); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityFloat entity = mapper.readValue(vpack.getBuffer(), TestEntityFloat.class); + assertThat(entity).isNotNull(); + assertThat(entity.f1).isEqualTo(2F); + assertThat(entity.f2).isEqualTo(new Float(3)); + } + + public static class TestEntityShort { + private short s1 = 1; + private Short s2 = 1; + + public short getS1() { + return s1; + } + + public void setS1(final short s1) { + this.s1 = s1; + } + + public Short getS2() { + return s2; + } + + public void setS2(final Short s2) { + this.s2 = s2; + } + } + + @Test + void fromShort() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityShort())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice s1 = vpack.get("s1"); + assertThat(s1.isInteger()).isTrue(); + assertThat(s1.getAsShort()).isEqualTo((short) 1); + } + { + final VPackSlice s2 = vpack.get("s2"); + assertThat(s2.isInteger()).isTrue(); + assertThat(s2.getAsShort()).isEqualTo((short) 1); + } + } + + @Test + void toShort() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("s1", 2); + builder.add("s2", 3); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityShort entity = mapper.readValue(vpack.getBuffer(), TestEntityShort.class); + assertThat(entity).isNotNull(); + assertThat(entity.s1).isEqualTo((short) 2); + assertThat(entity.s2).isEqualTo(Short.valueOf((short) 3)); + } + + public static class TestEntityByte { + private byte b1 = 1; // short integer path + private Byte b2 = 100; // integer path + + public byte getB1() { + return b1; + } + + public void setB1(final byte b1) { + this.b1 = b1; + } + + public Byte getB2() { + return b2; + } + + public void setB2(final Byte b2) { + this.b2 = b2; + } + } + + @Test + void fromByte() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityByte())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice b1 = vpack.get("b1"); + assertThat(b1.isInteger()).isTrue(); + assertThat(b1.getAsByte()).isEqualTo((byte) 1); + } + { + final VPackSlice b2 = vpack.get("b2"); + assertThat(b2.isInteger()).isTrue(); + assertThat(b2.getAsByte()).isEqualTo((byte) 100); + } + } + + @Test + void toByte() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("b1", 30); // integer path + builder.add("b2", 4); // short integer path + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityByte entity = mapper.readValue(vpack.getBuffer(), TestEntityByte.class); + assertThat(entity).isNotNull(); + assertThat(entity.b1).isEqualTo((byte) 30); + assertThat(entity.b2).isEqualTo(Byte.valueOf((byte) 4)); + } + + public static class TestEntityDouble { + private Double d1 = 1.5; + private double d2 = 1.5; + + public Double getD1() { + return d1; + } + + public void setD1(final Double d1) { + this.d1 = d1; + } + + public double getD2() { + return d2; + } + + public void setD2(final double d2) { + this.d2 = d2; + } + } + + @Test + void fromDouble() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityDouble())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice d1 = vpack.get("d1"); + assertThat(d1.isDouble()).isTrue(); + assertThat(d1.getAsDouble()).isEqualTo(1.5); + } + { + final VPackSlice d2 = vpack.get("d2"); + assertThat(d2.isDouble()).isTrue(); + assertThat(d2.getAsDouble()).isEqualTo(1.5); + } + } + + @Test + void toDouble() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("d1", 2.25); + builder.add("d2", 3.75); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityDouble entity = mapper.readValue(vpack.getBuffer(), TestEntityDouble.class); + assertThat(entity).isNotNull(); + assertThat(entity.d1).isEqualTo(2.25); + assertThat(entity.d2).isEqualTo(3.75); + } + + public static class TestEntityBigNumber { + private static final BigInteger BI = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE); + private static final BigDecimal BD = BigDecimal.valueOf(Double.MAX_VALUE).add(BigDecimal.ONE); + + private BigInteger bi = BI; + private BigDecimal bd = BD; + + public BigInteger getBi() { + return bi; + } + + public void setBi(final BigInteger bi) { + this.bi = bi; + } + + public BigDecimal getBd() { + return bd; + } + + public void setBd(final BigDecimal bd) { + this.bd = bd; + } + } + + @Test + void fromBigNumbers() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityBigNumber())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice bi = vpack.get("bi"); + assertThat(bi.isString()).isTrue(); + assertThat(bi.getAsBigInteger()).isEqualTo(TestEntityBigNumber.BI); + } + { + final VPackSlice bd = vpack.get("bd"); + assertThat(bd.isString()).isTrue(); + assertThat(bd.getAsBigDecimal()).isEqualTo(TestEntityBigNumber.BD); + } + } + + @Test + void toBigNumbers() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("bi", BigInteger.valueOf(2)); + builder.add("bd", BigDecimal.valueOf(3.75)); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityBigNumber entity = mapper.readValue(vpack.getBuffer(), TestEntityBigNumber.class); + assertThat(entity).isNotNull(); + assertThat(entity.bi).isEqualTo(BigInteger.valueOf(2)); + assertThat(entity.bd).isEqualTo(BigDecimal.valueOf(3.75)); + } + + @Test + void bigDecimal() { + final BigDecimal fromDouble = BigDecimal.valueOf(-710.01); + final BigDecimal fromString = new BigDecimal("-710.01"); + assertThat(fromDouble).isEqualTo(fromString); + assertThat(new VPackBuilder().add(fromDouble).slice().getAsBigDecimal()).isEqualTo(fromDouble); + assertThat(new VPackBuilder().add(fromString).slice().getAsBigDecimal()).isEqualTo(fromDouble); + } + + public static class TestEntityArray { + private String[] a1 = {"a", "b", "cd"}; + private int[] a2 = {1, 2, 3, 4, 5}; + private boolean[] a3 = {true, true, false}; + private TestEnum[] a4 = TestEnum.values(); + + public String[] getA1() { + return a1; + } + + public void setA1(final String[] a1) { + this.a1 = a1; + } + + public int[] getA2() { + return a2; + } + + public void setA2(final int[] a2) { + this.a2 = a2; + } + + public boolean[] getA3() { + return a3; + } + + public void setA3(final boolean[] a3) { + this.a3 = a3; + } + + public TestEnum[] getA4() { + return a4; + } + + public void setA4(final TestEnum[] a4) { + this.a4 = a4; + } + + } + + @Test + void fromArray() throws JsonProcessingException { + final TestEntityArray entity = new TestEntityArray(); + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice a1 = vpack.get("a1"); + assertThat(a1.isArray()).isTrue(); + assertThat(a1.getLength()).isEqualTo(entity.a1.length); + for (int i = 0; i < a1.getLength(); i++) { + assertThat(a1.get(i).getAsString()).isEqualTo(entity.a1[i]); + } + } + { + final VPackSlice a2 = vpack.get("a2"); + assertThat(a2.isArray()).isTrue(); + assertThat(a2.getLength()).isEqualTo(entity.a2.length); + for (int i = 0; i < a2.getLength(); i++) { + assertThat(a2.get(i).getAsInt()).isEqualTo(entity.a2[i]); + } + } + { + final VPackSlice a3 = vpack.get("a3"); + assertThat(a3.isArray()).isTrue(); + assertThat(a3.getLength()).isEqualTo(entity.a3.length); + for (int i = 0; i < a3.getLength(); i++) { + assertThat(a3.get(i).getAsBoolean()).isEqualTo(entity.a3[i]); + } + } + { + final VPackSlice a4 = vpack.get("a4"); + assertThat(a4.isArray()).isTrue(); + assertThat(a4.getLength()).isEqualTo(entity.a4.length); + for (int i = 0; i < a4.getLength(); i++) { + assertThat(TestEnum.valueOf(a4.get(i).getAsString())).isEqualTo(entity.a4[i]); + } + } + } + + @Test + void toArray() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("a1", ValueType.ARRAY); + builder.add("a"); + builder.add("b"); + builder.add("c"); + builder.close(); + } + { + builder.add("a2", ValueType.ARRAY); + builder.add(1); + builder.add(2); + builder.add(3); + builder.add(4); + builder.close(); + } + { + builder.add("a3", ValueType.ARRAY); + builder.add(false); + builder.add(true); + builder.close(); + } + { + builder.add("a4", ValueType.ARRAY); + builder.add(TestEnum.A.name()); + builder.add(TestEnum.B.name()); + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityArray entity = mapper.readValue(vpack.getBuffer(), TestEntityArray.class); + assertThat(entity).isNotNull(); + { + assertThat(entity.a1).hasSize(3); + assertThat(entity.a1[0]).isEqualTo("a"); + assertThat(entity.a1[1]).isEqualTo("b"); + assertThat(entity.a1[2]).isEqualTo("c"); + } + { + assertThat(entity.a2).hasSize(4); + assertThat(entity.a2[0]).isEqualTo(1); + assertThat(entity.a2[1]).isEqualTo(2); + assertThat(entity.a2[2]).isEqualTo(3); + assertThat(entity.a2[3]).isEqualTo(4); + } + { + assertThat(entity.a3).hasSize(2); + assertThat(entity.a3[0]).isFalse(); + assertThat(entity.a3[1]).isTrue(); + } + { + assertThat(entity.a4).hasSize(2); + assertThat(entity.a4[0]).isEqualTo(TestEnum.A); + assertThat(entity.a4[1]).isEqualTo(TestEnum.B); + } + } + + @Test + void fromArrayWithNull() throws JsonProcessingException { + final TestEntityArray entity = new TestEntityArray(); + entity.a1 = new String[]{"foo", null}; + + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + + final VPackSlice a1 = vpack.get("a1"); + assertThat(a1.isArray()).isTrue(); + assertThat(a1.size()).isEqualTo(2); + assertThat(a1.get(0).isString()).isTrue(); + assertThat(a1.get(0).getAsString()).isEqualTo("foo"); + assertThat(a1.get(1).isNull()).isTrue(); + } + + protected enum TestEnum { + A, B, C + } + + public static class TestEntityEnum { + private TestEnum e1 = TestEnum.A; + + public TestEnum getE1() { + return e1; + } + + public void setE1(final TestEnum e1) { + this.e1 = e1; + } + } + + @Test + void fromEnum() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityEnum())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice e1 = vpack.get("e1"); + assertThat(e1.isString()).isTrue(); + assertThat(TestEnum.valueOf(e1.getAsString())).isEqualTo(TestEnum.A); + } + } + + @Test + void toEnum() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("e1", TestEnum.B.name()); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityEnum entity = mapper.readValue(vpack.getBuffer(), TestEntityEnum.class); + assertThat(entity).isNotNull(); + assertThat(entity.e1).isEqualTo(TestEnum.B); + } + + public static class TestEntityObject { + private TestEntityLong o1 = new TestEntityLong(); + private TestEntityArray o2 = new TestEntityArray(); + + public TestEntityLong getO1() { + return o1; + } + + public void setO1(final TestEntityLong o1) { + this.o1 = o1; + } + + public TestEntityArray getO2() { + return o2; + } + + public void setO2(final TestEntityArray o2) { + this.o2 = o2; + } + } + + @Test + void fromObject() throws JsonProcessingException { + final TestEntityObject entity = new TestEntityObject(); + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice o1 = vpack.get("o1"); + assertThat(o1.isObject()).isTrue(); + { + final VPackSlice l1 = o1.get("l1"); + assertThat(l1.isInteger()).isTrue(); + assertThat(l1.getAsLong()).isEqualTo(1L); + } + { + final VPackSlice l2 = o1.get("l2"); + assertThat(l2.isInteger()).isTrue(); + assertThat(l2.getAsLong()).isEqualTo(1L); + } + } + { + final VPackSlice o2 = vpack.get("o2"); + assertThat(o2.isObject()).isTrue(); + { + final VPackSlice a1 = o2.get("a1"); + assertThat(a1.isArray()).isTrue(); + assertThat(a1.getLength()).isEqualTo(entity.o2.a1.length); + for (int i = 0; i < a1.getLength(); i++) { + assertThat(a1.get(i).getAsString()).isEqualTo(entity.o2.a1[i]); + } + } + { + final VPackSlice a2 = o2.get("a2"); + assertThat(a2.isArray()).isTrue(); + assertThat(a2.getLength()).isEqualTo(entity.o2.a2.length); + for (int i = 0; i < a2.getLength(); i++) { + assertThat(a2.get(i).getAsInt()).isEqualTo(entity.o2.a2[i]); + } + } + { + final VPackSlice a3 = o2.get("a3"); + assertThat(a3.isArray()).isTrue(); + assertThat(a3.getLength()).isEqualTo(entity.o2.a3.length); + for (int i = 0; i < a3.getLength(); i++) { + assertThat(a3.get(i).getAsBoolean()).isEqualTo(entity.o2.a3[i]); + } + } + { + final VPackSlice a4 = o2.get("a4"); + assertThat(a4.isArray()).isTrue(); + assertThat(a4.getLength()).isEqualTo(entity.o2.a4.length); + for (int i = 0; i < a4.getLength(); i++) { + assertThat(TestEnum.valueOf(a4.get(i).getAsString())).isEqualTo(entity.o2.a4[i]); + } + } + } + } + + @Test + void toObject() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("o1", ValueType.OBJECT); + builder.add("l1", 5L); + builder.add("l2", 5L); + builder.close(); + } + { + builder.add("o2", ValueType.OBJECT); + { + builder.add("a1", ValueType.ARRAY); + builder.add("a"); + builder.add("b"); + builder.add("c"); + builder.close(); + } + { + builder.add("a2", ValueType.ARRAY); + builder.add(1); + builder.add(2); + builder.add(3); + builder.add(4); + builder.close(); + } + { + builder.add("a3", ValueType.ARRAY); + builder.add(false); + builder.add(true); + builder.close(); + } + { + builder.add("a4", ValueType.ARRAY); + builder.add(TestEnum.A.name()); + builder.add(TestEnum.B.name()); + builder.close(); + } + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityObject entity = mapper.readValue(vpack.getBuffer(), TestEntityObject.class); + assertThat(entity).isNotNull(); + { + assertThat(entity.o1.l1).isEqualTo(5L); + assertThat(entity.o1.l2).isEqualTo(Long.valueOf(5)); + } + { + assertThat(entity.o2.a1).hasSize(3); + assertThat(entity.o2.a1[0]).isEqualTo("a"); + assertThat(entity.o2.a1[1]).isEqualTo("b"); + assertThat(entity.o2.a1[2]).isEqualTo("c"); + } + { + assertThat(entity.o2.a2).hasSize(4); + assertThat(entity.o2.a2[0]).isEqualTo(1); + assertThat(entity.o2.a2[1]).isEqualTo(2); + assertThat(entity.o2.a2[2]).isEqualTo(3); + assertThat(entity.o2.a2[3]).isEqualTo(4); + } + { + assertThat(entity.o2.a3).hasSize(2); + assertThat(entity.o2.a3[0]).isFalse(); + assertThat(entity.o2.a3[1]).isTrue(); + } + { + assertThat(entity.o2.a4).hasSize(2); + assertThat(entity.o2.a4[0]).isEqualTo(TestEnum.A); + assertThat(entity.o2.a4[1]).isEqualTo(TestEnum.B); + } + } + + public static class TestEntityArrayInArray { + private long[][] a1; + + public long[][] getA1() { + return a1; + } + + public void setA1(final long[][] a1) { + this.a1 = a1; + } + } + + @Test + void fromArrayInArray() throws JsonProcessingException { + final TestEntityArrayInArray entity = new TestEntityArrayInArray(); + entity.a1 = new long[][]{{1, 2, 3}, {4, 5, 6}}; + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice a1 = vpack.get("a1"); + assertThat(a1.isArray()).isTrue(); + assertThat(a1.getLength()).isEqualTo(entity.a1.length); + for (int i = 0; i < a1.getLength(); i++) { + final VPackSlice at = a1.get(i); + assertThat(at.isArray()).isTrue(); + assertThat(at.getLength()).isEqualTo(entity.a1[i].length); + for (int j = 0; j < at.getLength(); j++) { + final VPackSlice atat = at.get(j); + assertThat(atat.isInteger()).isTrue(); + assertThat(atat.getAsLong()).isEqualTo(entity.a1[i][j]); + } + } + } + } + + @Test + void toArrayInArray() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("a1", ValueType.ARRAY); + { + builder.add(ValueType.ARRAY); + builder.add(1); + builder.add(2); + builder.add(3); + builder.close(); + } + { + builder.add(ValueType.ARRAY); + builder.add(4); + builder.add(5); + builder.add(6); + builder.close(); + } + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityArrayInArray entity = mapper.readValue(vpack.getBuffer(), TestEntityArrayInArray.class); + assertThat(entity).isNotNull(); + assertThat(entity.a1.length).isEqualTo(2); + { + assertThat(entity.a1[0]).hasSize(3); + assertThat(entity.a1[0][0]).isEqualTo(1L); + assertThat(entity.a1[0][1]).isEqualTo(2L); + assertThat(entity.a1[0][2]).isEqualTo(3L); + } + { + assertThat(entity.a1[1]).hasSize(3); + assertThat(entity.a1[1][0]).isEqualTo(4L); + assertThat(entity.a1[1][1]).isEqualTo(5L); + assertThat(entity.a1[1][2]).isEqualTo(6L); + } + } + + @SuppressWarnings("serial") + public static class TestCollection extends LinkedList { + + } + + public static class TestEntityCollectionExtendedWithNulls { + + protected TestCollection a1; + + public TestCollection getA1() { + return a1; + } + + public void setA1(final TestCollection a1) { + this.a1 = a1; + } + + } + + @Test + void fromCollectionExtendedWithNulls() { + + final TestCollection collection = new TestCollection(); + collection.add("one"); + collection.add(null); + collection.add("two"); + + final TestEntityCollectionExtendedWithNulls entity = new TestEntityCollectionExtendedWithNulls(); + entity.setA1(collection); + + final VPackSlice vpack = new VPack.Builder().serializeNullValues(true).build().serialize(entity); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice a1 = vpack.get("a1"); + assertThat(a1.isArray()).isTrue(); + assertThat(a1.getLength()).isEqualTo(entity.a1.size()); + + VPackSlice at = a1.get(0); + assertThat(at.isString()).isTrue(); + assertThat(at.getAsString()).isEqualTo(entity.a1.get(0)); + at = a1.get(1); + assertThat(at.isNull()).isTrue(); + at = a1.get(2); + assertThat(at.isString()).isTrue(); + assertThat(at.getAsString()).isEqualTo(entity.a1.get(2)); + } + } + + @Test + void toCollectionExtendedWithNulls() throws Exception { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("a1", ValueType.ARRAY); + builder.add("one"); + builder.add(ValueType.NULL); + builder.add("two"); + builder.close(); + } + builder.close(); + } + + final VPackSlice vpack = builder.slice(); + final TestEntityCollectionExtendedWithNulls entity = mapper.readValue(vpack.getBuffer(), + TestEntityCollectionExtendedWithNulls.class); + assertThat(entity).isNotNull(); + assertThat(entity.getA1()).isNotNull(); + assertThat(entity.getA1()).hasSize(3); + assertThat(entity.getA1()).contains("one", null, "two"); + } + + public static class TestEntityArrayInArrayInArray { + + private double[][][] a1; + + public double[][][] getA1() { + return a1; + } + + public void setA1(final double[][][] a1) { + this.a1 = a1; + } + + } + + @Test + void fromArrayInArrayInArray() throws JsonProcessingException { + final TestEntityArrayInArrayInArray entity = new TestEntityArrayInArrayInArray(); + entity.setA1(new double[][][]{{{1.5, 2.25}, {10.5, 20.25}}, {{100.5}, {200.25}}}); + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice a1 = vpack.get("a1"); + assertThat(a1.isArray()).isTrue(); + assertThat(a1.getLength()).isEqualTo(entity.a1.length); + for (int i = 0; i < a1.getLength(); i++) { + final VPackSlice at = a1.get(i); + assertThat(at.isArray()).isTrue(); + assertThat(at.getLength()).isEqualTo(entity.a1[i].length); + for (int j = 0; j < at.getLength(); j++) { + final VPackSlice atat = at.get(j); + assertThat(atat.isArray()).isTrue(); + assertThat(atat.getLength()).isEqualTo(entity.a1[i][j].length); + for (int k = 0; k < atat.getLength(); k++) { + final VPackSlice atatat = atat.get(k); + assertThat(atatat.isDouble()).isTrue(); + assertThat(atatat.getAsDouble()).isEqualTo(entity.a1[i][j][k]); + } + } + } + } + } + + @Test + void toArrayInArrayInArray() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("a1", ValueType.ARRAY); + builder.add(ValueType.ARRAY); + { + builder.add(ValueType.ARRAY); + builder.add(1.5); + builder.add(2.5); + builder.add(3.5); + builder.close(); + } + { + builder.add(ValueType.ARRAY); + builder.add(4.5); + builder.add(5.5); + builder.add(6.5); + builder.close(); + } + { + builder.add(ValueType.ARRAY); + builder.add(7.5); + builder.add(8.5); + builder.add(9.5); + builder.close(); + } + builder.close(); + builder.add(ValueType.ARRAY); + { + builder.add(ValueType.ARRAY); + builder.add(1.5); + builder.add(2.5); + builder.add(3.5); + builder.close(); + } + { + builder.add(ValueType.ARRAY); + builder.add(4.5); + builder.add(5.5); + builder.add(6.5); + builder.close(); + } + { + builder.add(ValueType.ARRAY); + builder.add(7.5); + builder.add(8.5); + builder.add(9.5); + builder.close(); + } + builder.close(); + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityArrayInArrayInArray entity = mapper.readValue(vpack.getBuffer(), + TestEntityArrayInArrayInArray.class); + assertThat(entity).isNotNull(); + assertThat(entity.a1.length).isEqualTo(2); + { + assertThat(entity.a1[0].length).isEqualTo(3); + assertThat(entity.a1[0][0]).hasSize(3); + assertThat(entity.a1[0][0][0]).isEqualTo(1.5); + assertThat(entity.a1[0][0][1]).isEqualTo(2.5); + assertThat(entity.a1[0][0][2]).isEqualTo(3.5); + assertThat(entity.a1[0][1]).hasSize(3); + assertThat(entity.a1[0][1][0]).isEqualTo(4.5); + assertThat(entity.a1[0][1][1]).isEqualTo(5.5); + assertThat(entity.a1[0][1][2]).isEqualTo(6.5); + assertThat(entity.a1[0][2]).hasSize(3); + assertThat(entity.a1[0][2][0]).isEqualTo(7.5); + assertThat(entity.a1[0][2][1]).isEqualTo(8.5); + assertThat(entity.a1[0][2][2]).isEqualTo(9.5); + } + { + assertThat(entity.a1[1].length).isEqualTo(3); + assertThat(entity.a1[1][0]).hasSize(3); + assertThat(entity.a1[1][0][0]).isEqualTo(1.5); + assertThat(entity.a1[1][0][1]).isEqualTo(2.5); + assertThat(entity.a1[1][0][2]).isEqualTo(3.5); + assertThat(entity.a1[1][1]).hasSize(3); + assertThat(entity.a1[1][1][0]).isEqualTo(4.5); + assertThat(entity.a1[1][1][1]).isEqualTo(5.5); + assertThat(entity.a1[1][1][2]).isEqualTo(6.5); + assertThat(entity.a1[1][2]).hasSize(3); + assertThat(entity.a1[1][2][0]).isEqualTo(7.5); + assertThat(entity.a1[1][2][1]).isEqualTo(8.5); + assertThat(entity.a1[1][2][2]).isEqualTo(9.5); + } + } + + public static class TestEntityObjectInArray { + private TestEntityString[] a1; + + public TestEntityString[] getA1() { + return a1; + } + + public void setA1(final TestEntityString[] a1) { + this.a1 = a1; + } + } + + @Test + void fromObjectInArray() throws JsonProcessingException { + final TestEntityObjectInArray entity = new TestEntityObjectInArray(); + { + final TestEntityString[] a1 = new TestEntityString[2]; + final TestEntityString s = new TestEntityString(); + s.setS("abc"); + a1[0] = s; + a1[1] = s; + entity.setA1(a1); + } + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice a1 = vpack.get("a1"); + assertThat(a1.isArray()).isTrue(); + assertThat(a1.getLength()).isEqualTo(2); + for (int i = 0; i < a1.getLength(); i++) { + final VPackSlice at = a1.get(i); + assertThat(at.isObject()).isTrue(); + final VPackSlice s = at.get("s"); + assertThat(s.isString()).isTrue(); + assertThat(s.getAsString()).isEqualTo("abc"); + } + } + } + + @Test + void toObjectInArray() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("a1", ValueType.ARRAY); + { + builder.add(ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + } + builder.close(); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityObjectInArray entity = mapper.readValue(vpack.getBuffer(), TestEntityObjectInArray.class); + assertThat(entity).isNotNull(); + assertThat(entity.a1).hasSize(1); + final TestEntityString st = entity.a1[0]; + assertThat(st).isNotNull(); + assertThat(st.s).isEqualTo("abc"); + } + + public static class TestEntityA { + private String a = "a"; + + public String getA() { + return a; + } + + public void setA(final String a) { + this.a = a; + } + } + + public static class TestEntityB extends TestEntityA { + private String b = "b"; + + public String getB() { + return b; + } + + public void setB(final String b) { + this.b = b; + } + } + + @Test + void fromInheritance() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityB())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + assertThat(vpack.getLength()).isEqualTo(2); + { + final VPackSlice a = vpack.get("a"); + assertThat(a.isString()).isTrue(); + assertThat(a.getAsString()).isEqualTo("a"); + } + { + final VPackSlice b = vpack.get("b"); + assertThat(b.isString()).isTrue(); + assertThat(b.getAsString()).isEqualTo("b"); + } + } + + @Test + void toInheritance() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("a", "test"); + builder.add("b", "test"); + builder.close(); + } + final VPackSlice vpack = builder.slice(); + { + final TestEntityA entity = mapper.readValue(vpack.getBuffer(), TestEntityA.class); + assertThat(entity).isNotNull(); + assertThat(entity.getA()).isEqualTo("test"); + } + { + final TestEntityB entity = mapper.readValue(vpack.getBuffer(), TestEntityB.class); + assertThat(entity).isNotNull(); + assertThat(entity.getA()).isEqualTo("test"); + assertThat(entity.getB()).isEqualTo("test"); + } + } + + public static class TestEntityC { + private TestEntityD d; + + public TestEntityD getD() { + return d; + } + + public void setD(final TestEntityD d) { + this.d = d; + } + } + + protected interface TestEntityD { + String getD(); + + void setD(String d); + } + + public static class TestEntityDImpl implements TestEntityD { + private String d = "d"; + + @Override + public String getD() { + return d; + } + + @Override + public void setD(final String d) { + this.d = d; + } + } + + @Test + void fromInterface() throws JsonProcessingException { + final TestEntityC entity = new TestEntityC(); + entity.setD(new TestEntityDImpl()); + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice d = vpack.get("d"); + assertThat(d.isObject()).isTrue(); + final VPackSlice dd = d.get("d"); + assertThat(dd.isString()).isTrue(); + assertThat(dd.getAsString()).isEqualTo("d"); + } + } + + @Test + void toInterface() { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("d", ValueType.OBJECT); + builder.add("d", "test"); + builder.close(); + builder.close(); + } + final VPackSlice slice = builder.slice(); + final VPack vPack = new VPack.Builder() + .registerInstanceCreator(TestEntityD.class, (VPackInstanceCreator) TestEntityDImpl::new).build(); + final TestEntityC entity = vPack.deserialize(slice, TestEntityC.class); + assertThat(entity).isNotNull(); + assertThat(entity.d).isNotNull(); + assertThat(entity.d.getD()).isEqualTo("test"); + } + + public static class TestEntityCollection { + private Collection c1 = new LinkedList<>(); + private List c2 = new ArrayList<>(); + private ArrayList c3 = new ArrayList<>(); + private Set c4 = new LinkedHashSet<>(); + private HashSet c5 = new HashSet<>(); + + public TestEntityCollection() { + super(); + } + + public Collection getC1() { + return c1; + } + + public void setC1(final Collection c1) { + this.c1 = c1; + } + + public List getC2() { + return c2; + } + + public void setC2(final List c2) { + this.c2 = c2; + } + + public ArrayList getC3() { + return c3; + } + + public void setC3(final ArrayList c3) { + this.c3 = c3; + } + + public Set getC4() { + return c4; + } + + public void setC4(final Set c4) { + this.c4 = c4; + } + + public HashSet getC5() { + return c5; + } + + public void setC5(final HashSet c5) { + this.c5 = c5; + } + } + + @Test + void fromCollection() throws JsonProcessingException { + final TestEntityCollection entity = new TestEntityCollection(); + { + entity.c1.add("test"); + entity.c2.add("test"); + entity.c3.add("test"); + entity.c4.add("test"); + entity.c5.add("test"); + } + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice c1 = vpack.get("c1"); + assertThat(c1.isArray()).isTrue(); + assertThat(c1.getLength()).isEqualTo(1); + assertThat(c1.get(0).getAsString()).isEqualTo("test"); + } + { + final VPackSlice c2 = vpack.get("c2"); + assertThat(c2.isArray()).isTrue(); + assertThat(c2.getLength()).isEqualTo(1); + assertThat(c2.get(0).getAsString()).isEqualTo("test"); + } + { + final VPackSlice c3 = vpack.get("c3"); + assertThat(c3.isArray()).isTrue(); + assertThat(c3.getLength()).isEqualTo(1); + assertThat(c3.get(0).getAsString()).isEqualTo("test"); + } + { + final VPackSlice c4 = vpack.get("c4"); + assertThat(c4.isArray()).isTrue(); + assertThat(c4.getLength()).isEqualTo(1); + assertThat(c4.get(0).getAsString()).isEqualTo("test"); + } + { + final VPackSlice c5 = vpack.get("c5"); + assertThat(c5.isArray()).isTrue(); + assertThat(c5.getLength()).isEqualTo(1); + assertThat(c5.get(0).getAsString()).isEqualTo("test"); + } + } + + @Test + void toCollection() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("c1", ValueType.ARRAY); + builder.add("test1"); + builder.add("test2"); + builder.close(); + } + { + builder.add("c2", ValueType.ARRAY); + builder.add("test1"); + builder.add("test2"); + builder.close(); + } + { + builder.add("c3", ValueType.ARRAY); + builder.add("test1"); + builder.add("test2"); + builder.close(); + } + { + builder.add("c4", ValueType.ARRAY); + builder.add("test1"); + builder.add("test2"); + builder.close(); + } + { + builder.add("c5", ValueType.ARRAY); + builder.add("test1"); + builder.add("test2"); + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityCollection entity = mapper.readValue(vpack.getBuffer(), TestEntityCollection.class); + assertThat(entity).isNotNull(); + { + checkCollection(entity.c1); + checkCollection(entity.c2); + checkCollection(entity.c3); + checkCollection(entity.c4); + checkCollection(entity.c5); + } + } + + private void checkCollection(final Collection col) { + assertThat(col).isNotNull(); + assertThat(col).hasSize(2); + for (final String next : col) { + assertThat("test1".equals(next) || "test2".equals(next)).isTrue(); + } + } + + public static class TestEntityCollectionWithObjects { + private Collection c1; + private Set c2; + + public Collection getC1() { + return c1; + } + + public void setC1(final Collection c1) { + this.c1 = c1; + } + + public Set getC2() { + return c2; + } + + public void setC2(final Set c2) { + this.c2 = c2; + } + } + + @Test + void fromCollectionWithObjects() throws JsonProcessingException { + final TestEntityCollectionWithObjects entity = new TestEntityCollectionWithObjects(); + { + final Collection c1 = new ArrayList<>(); + c1.add(new TestEntityString()); + c1.add(new TestEntityString()); + entity.setC1(c1); + final Set c2 = new HashSet<>(); + c2.add(new TestEntityArray()); + entity.setC2(c2); + } + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice c1 = vpack.get("c1"); + assertThat(c1.isArray()).isTrue(); + assertThat(c1.getLength()).isEqualTo(2); + assertThat(c1.get(0).isObject()).isTrue(); + assertThat(c1.get(1).isObject()).isTrue(); + { + final VPackSlice s = c1.get(0).get("s"); + assertThat(s.isString()).isTrue(); + assertThat(s.getAsString()).isEqualTo("test"); + } + } + { + final VPackSlice c2 = vpack.get("c2"); + assertThat(c2.isArray()).isTrue(); + assertThat(c2.getLength()).isEqualTo(1); + assertThat(c2.get(0).isObject()).isTrue(); + { + final VPackSlice a2 = c2.get(0).get("a2"); + assertThat(a2.isArray()).isTrue(); + assertThat(a2.getLength()).isEqualTo(5); + for (int i = 0; i < a2.getLength(); i++) { + final VPackSlice at = a2.get(i); + assertThat(at.isInteger()).isTrue(); + assertThat(at.getAsInt()).isEqualTo(i + 1); + } + } + } + } + + @Test + void toCollectionWithObjects() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("c1", ValueType.ARRAY); + builder.add(ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.close(); + } + { + builder.add("c2", ValueType.ARRAY); + builder.add(ValueType.OBJECT); + builder.add("a2", ValueType.ARRAY); + for (int i = 0; i < 10; i++) { + builder.add(i); + } + builder.close(); + builder.close(); + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityCollectionWithObjects entity = mapper.readValue(vpack.getBuffer(), + TestEntityCollectionWithObjects.class); + assertThat(entity).isNotNull(); + { + assertThat(entity.c1).isNotNull(); + assertThat(entity.c1).hasSize(1); + assertThat(entity.c1.iterator().next().s).isEqualTo("abc"); + } + { + assertThat(entity.c2).isNotNull(); + assertThat(entity.c2).hasSize(1); + final int[] array = entity.c2.iterator().next().a2; + for (int i = 0; i < array.length; i++) { + assertThat(array[i]).isEqualTo(i); + } + } + } + + public static class TestEntityMap { + private Map m1; + private HashMap m2; + private Map m3; + + public Map getM1() { + return m1; + } + + public void setM1(final Map m1) { + this.m1 = m1; + } + + public HashMap getM2() { + return m2; + } + + public void setM2(final HashMap m2) { + this.m2 = m2; + } + + public Map getM3() { + return m3; + } + + public void setM3(final Map m3) { + this.m3 = m3; + } + } + + @Test + void fromMap() throws JsonProcessingException { + final TestEntityMap entity = new TestEntityMap(); + { + final Map m1 = new LinkedHashMap<>(); + m1.put("a", "b"); + m1.put("c", "d"); + entity.setM1(m1); + final HashMap m2 = new HashMap<>(); + m2.put(1, "a"); + m2.put(2, "b"); + entity.setM2(m2); + final Map m3 = new HashMap<>(); + final TestEntityString s = new TestEntityString(); + s.setS("abc"); + m3.put("a", s); + entity.setM3(m3); + } + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice m1 = vpack.get("m1"); + assertThat(m1.isObject()).isTrue(); + assertThat(m1.getLength()).isEqualTo(2); + { + final VPackSlice a = m1.get("a"); + assertThat(a.isString()).isTrue(); + assertThat(a.getAsString()).isEqualTo("b"); + } + { + final VPackSlice c = m1.get("c"); + assertThat(c.isString()).isTrue(); + assertThat(c.getAsString()).isEqualTo("d"); + } + } + { + final VPackSlice m2 = vpack.get("m2"); + assertThat(m2.isObject()).isTrue(); + assertThat(m2.getLength()).isEqualTo(2); + { + final VPackSlice one = m2.get("1"); + assertThat(one.isString()).isTrue(); + assertThat(one.getAsString()).isEqualTo("a"); + } + { + final VPackSlice two = m2.get("2"); + assertThat(two.isString()).isTrue(); + assertThat(two.getAsString()).isEqualTo("b"); + } + } + { + final VPackSlice m3 = vpack.get("m3"); + assertThat(m3.isObject()).isTrue(); + assertThat(m3.getLength()).isEqualTo(1); + final VPackSlice a = m3.get("a"); + assertThat(a.isObject()).isTrue(); + final VPackSlice s = a.get("s"); + assertThat(s.isString()).isTrue(); + assertThat(s.getAsString()).isEqualTo("abc"); + } + } + + @Test + void toMap() throws IOException { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + { + builder.add("m1", ValueType.OBJECT); + builder.add("a", "a"); + builder.add("b", "b"); + builder.close(); + } + { + builder.add("m2", ValueType.OBJECT); + builder.add("1", "a"); + builder.add("-1", "a"); + builder.close(); + } + { + builder.add("m3", ValueType.OBJECT); + builder.add("a", ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.close(); + } + builder.close(); + } + final VPackSlice vpack = builder.slice(); + final TestEntityMap entity = mapper.readValue(vpack.getBuffer(), TestEntityMap.class); + assertThat(entity).isNotNull(); + { + assertThat(entity.m1).isNotNull(); + assertThat(entity.m1).hasSize(2); + final String a = entity.m1.get("a"); + assertThat(a).isNotNull(); + assertThat(a).isEqualTo("a"); + final String b = entity.m1.get("b"); + assertThat(b).isNotNull(); + assertThat(b).isEqualTo("b"); + } + { + assertThat(entity.m2).isNotNull(); + assertThat(entity.m2).hasSize(2); + final String one = entity.m2.get(1); + assertThat(one).isNotNull(); + assertThat(one).isEqualTo("a"); + final String oneNegative = entity.m2.get(-1); + assertThat(oneNegative).isNotNull(); + assertThat(oneNegative).isEqualTo("a"); + } + { + assertThat(entity.m3).isNotNull(); + assertThat(entity.m3).hasSize(1); + final TestEntityString a = entity.m3.get("a"); + assertThat(a).isNotNull(); + assertThat(a.s).isEqualTo("abc"); + } + } + + public static class TestEntityMapStringableKey { + private Map m1; + private Map m2; + private Map m3; + private Map m4; + private Map m5; + private Map m6; + private Map m7; + private Map m8; + private Map m9; + private Map m10; + private Map m11; + + public Map getM1() { + return m1; + } + + public void setM1(final Map m1) { + this.m1 = m1; + } + + public Map getM2() { + return m2; + } + + public void setM2(final Map m2) { + this.m2 = m2; + } + + public Map getM3() { + return m3; + } + + public void setM3(final Map m3) { + this.m3 = m3; + } + + public Map getM4() { + return m4; + } + + public void setM4(final Map m4) { + this.m4 = m4; + } + + public Map getM5() { + return m5; + } + + public void setM5(final Map m5) { + this.m5 = m5; + } + + public Map getM6() { + return m6; + } + + public void setM6(final Map m6) { + this.m6 = m6; + } + + public Map getM7() { + return m7; + } + + public void setM7(final Map m7) { + this.m7 = m7; + } + + public Map getM8() { + return m8; + } + + public void setM8(final Map m8) { + this.m8 = m8; + } + + public Map getM9() { + return m9; + } + + public void setM9(final Map m9) { + this.m9 = m9; + } + + public Map getM10() { + return m10; + } + + public void setM10(final Map m10) { + this.m10 = m10; + } + + public Map getM11() { + return m11; + } + + public void setM11(final Map m11) { + this.m11 = m11; + } + + } + + @Test + void fromMapStringableKey() throws JsonProcessingException { + final TestEntityMapStringableKey entity = new TestEntityMapStringableKey(); + final String value = "test"; + { + final Map m1 = new HashMap<>(); + m1.put(true, value); + m1.put(false, value); + entity.setM1(m1); + } + { + final Map m2 = new HashMap<>(); + m2.put(1, value); + m2.put(2, value); + entity.setM2(m2); + } + { + final Map m3 = new HashMap<>(); + m3.put(1L, value); + m3.put(2L, value); + entity.setM3(m3); + } + { + final Map m4 = new HashMap<>(); + m4.put(1.5F, value); + m4.put(2.25F, value); + entity.setM4(m4); + } + { + final Map m5 = new HashMap<>(); + m5.put(Short.valueOf("1"), value); + m5.put(Short.valueOf("2"), value); + entity.setM5(m5); + } + { + final Map m6 = new HashMap<>(); + m6.put(1.5, value); + m6.put(2.25, value); + entity.setM6(m6); + } + { + final Map m7 = new HashMap<>(); + m7.put(1.5, value); + m7.put(1L, value); + entity.setM7(m7); + } + { + final Map m8 = new HashMap<>(); + m8.put(new BigInteger("1"), value); + m8.put(new BigInteger("2"), value); + entity.setM8(m8); + } + { + final Map m9 = new HashMap<>(); + m9.put(new BigDecimal("1.5"), value); + m9.put(new BigDecimal("2.25"), value); + entity.setM9(m9); + } + { + final Map m10 = new HashMap<>(); + m10.put('1', value); + m10.put('a', value); + entity.setM10(m10); + } + { + final Map m11 = new HashMap<>(); + m11.put(TestEnum.A, value); + m11.put(TestEnum.B, value); + entity.setM11(m11); + } + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + final VPackSlice m1 = vpack.get("m1"); + assertThat(m1.isObject()).isTrue(); + assertThat(m1.getLength()).isEqualTo(2); + checkMapAttribute(m1.get("true")); + checkMapAttribute(m1.get("false")); + } + { + final VPackSlice m2 = vpack.get("m2"); + assertThat(m2.isObject()).isTrue(); + assertThat(m2.getLength()).isEqualTo(2); + checkMapAttribute(m2.get("1")); + checkMapAttribute(m2.get("2")); + } + { + final VPackSlice m3 = vpack.get("m3"); + assertThat(m3.isObject()).isTrue(); + assertThat(m3.getLength()).isEqualTo(2); + checkMapAttribute(m3.get("1")); + checkMapAttribute(m3.get("2")); + } + { + final VPackSlice m4 = vpack.get("m4"); + assertThat(m4.isObject()).isTrue(); + assertThat(m4.getLength()).isEqualTo(2); + checkMapAttribute(m4.get("1.5")); + checkMapAttribute(m4.get("2.25")); + } + { + final VPackSlice m5 = vpack.get("m5"); + assertThat(m5.isObject()).isTrue(); + assertThat(m5.getLength()).isEqualTo(2); + checkMapAttribute(m5.get("1")); + checkMapAttribute(m5.get("2")); + } + { + final VPackSlice m6 = vpack.get("m6"); + assertThat(m6.isObject()).isTrue(); + assertThat(m6.getLength()).isEqualTo(2); + checkMapAttribute(m6.get("1.5")); + checkMapAttribute(m6.get("2.25")); + } + { + final VPackSlice m7 = vpack.get("m7"); + assertThat(m7.isObject()).isTrue(); + assertThat(m7.getLength()).isEqualTo(2); + checkMapAttribute(m7.get("1.5")); + checkMapAttribute(m7.get("1")); + } + { + final VPackSlice m8 = vpack.get("m8"); + assertThat(m8.isObject()).isTrue(); + assertThat(m8.getLength()).isEqualTo(2); + checkMapAttribute(m8.get("1")); + checkMapAttribute(m8.get("2")); + } + { + final VPackSlice m9 = vpack.get("m9"); + assertThat(m9.isObject()).isTrue(); + assertThat(m9.getLength()).isEqualTo(2); + checkMapAttribute(m9.get("1.5")); + checkMapAttribute(m9.get("2.25")); + } + { + final VPackSlice m10 = vpack.get("m10"); + assertThat(m10.isObject()).isTrue(); + assertThat(m10.getLength()).isEqualTo(2); + checkMapAttribute(m10.get("1")); + checkMapAttribute(m10.get("a")); + } + { + final VPackSlice m11 = vpack.get("m11"); + assertThat(m11.isObject()).isTrue(); + assertThat(m11.getLength()).isEqualTo(2); + checkMapAttribute(m11.get(TestEnum.A.name())); + checkMapAttribute(m11.get(TestEnum.B.name())); + } + } + + @Test + void toMapSringableKey() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + { + builder.add("m1", ValueType.OBJECT); + builder.add("true", "test"); + builder.add("false", "test"); + builder.close(); + } + { + builder.add("m2", ValueType.OBJECT); + builder.add("1", "test"); + builder.add("2", "test"); + builder.close(); + } + { + builder.add("m3", ValueType.OBJECT); + builder.add("1", "test"); + builder.add("2", "test"); + builder.close(); + } + { + builder.add("m4", ValueType.OBJECT); + builder.add("1.5", "test"); + builder.add("2.25", "test"); + builder.close(); + } + { + builder.add("m5", ValueType.OBJECT); + builder.add("1", "test"); + builder.add("2", "test"); + builder.close(); + } + { + builder.add("m6", ValueType.OBJECT); + builder.add("1.5", "test"); + builder.add("2.25", "test"); + builder.close(); + } + { + builder.add("m7", ValueType.OBJECT); + builder.add("1.5", "test"); + builder.add("1", "test"); + builder.close(); + } + { + builder.add("m8", ValueType.OBJECT); + builder.add("1", "test"); + builder.add("2", "test"); + builder.close(); + } + { + builder.add("m9", ValueType.OBJECT); + builder.add("1.5", "test"); + builder.add("2.25", "test"); + builder.close(); + } + { + builder.add("m10", ValueType.OBJECT); + builder.add("1", "test"); + builder.add("a", "test"); + builder.close(); + } + { + builder.add("m11", ValueType.OBJECT); + builder.add(TestEnum.A.name(), "test"); + builder.add(TestEnum.B.name(), "test"); + builder.close(); + } + builder.close(); + final TestEntityMapStringableKey entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntityMapStringableKey.class); + { + assertThat(entity.m1).hasSize(2); + checkMapAttribute(entity.m1.get(true)); + checkMapAttribute(entity.m1.get(false)); + } + { + assertThat(entity.m2).hasSize(2); + checkMapAttribute(entity.m2.get(1)); + checkMapAttribute(entity.m2.get(2)); + } + { + assertThat(entity.m3).hasSize(2); + checkMapAttribute(entity.m3.get(1L)); + checkMapAttribute(entity.m3.get(2L)); + } + { + assertThat(entity.m4).hasSize(2); + checkMapAttribute(entity.m4.get(1.5F)); + checkMapAttribute(entity.m4.get(2.25F)); + } + { + assertThat(entity.m5).hasSize(2); + checkMapAttribute(entity.m5.get(Short.valueOf("1"))); + checkMapAttribute(entity.m5.get(Short.valueOf("2"))); + } + { + assertThat(entity.m6).hasSize(2); + checkMapAttribute(entity.m6.get(1.5)); + checkMapAttribute(entity.m6.get(2.25)); + } + { + assertThat(entity.m7).hasSize(2); + checkMapAttribute(entity.m7.get(1.5)); + checkMapAttribute(entity.m7.get((double) 1L)); + } + { + assertThat(entity.m8).hasSize(2); + checkMapAttribute(entity.m8.get(new BigInteger("1"))); + checkMapAttribute(entity.m8.get(new BigInteger("2"))); + } + { + assertThat(entity.m9).hasSize(2); + checkMapAttribute(entity.m9.get(new BigDecimal("1.5"))); + checkMapAttribute(entity.m9.get(new BigDecimal("2.25"))); + } + { + assertThat(entity.m10).hasSize(2); + checkMapAttribute(entity.m10.get('1')); + checkMapAttribute(entity.m10.get('a')); + } + { + assertThat(entity.m11).hasSize(2); + checkMapAttribute(entity.m11.get(TestEnum.A)); + checkMapAttribute(entity.m11.get(TestEnum.B)); + } + } + + private void checkMapAttribute(final VPackSlice attr) { + assertThat(attr.isString()).isTrue(); + assertThat(attr.getAsString()).isEqualTo("test"); + } + + private void checkMapAttribute(final String attr) { + assertThat(attr).isEqualTo("test"); + } + + public static class TestEntityMapWithObjectKey { + private Map m1; + private Map m2; + + public Map getM1() { + return m1; + } + + public void setM1(final Map m1) { + this.m1 = m1; + } + + public Map getM2() { + return m2; + } + + public void setM2(final Map m2) { + this.m2 = m2; + } + } + + @Test + void toMapWithObjectKey() { + final int size = 2; + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + { + builder.add("m1", ValueType.ARRAY); + for (int i = 0; i < size; i++) { + builder.add(ValueType.OBJECT); + { + builder.add("key", ValueType.OBJECT); + builder.add("l1", 5L); + builder.close(); + } + { + builder.add("value", ValueType.OBJECT); + builder.add("c1", ValueType.ARRAY); + builder.add("test"); + builder.close(); + builder.close(); + } + builder.close(); + } + builder.close(); + } + { + builder.add("m2", ValueType.ARRAY); + for (int i = 0; i < size; i++) { + builder.add(ValueType.OBJECT); + { + builder.add("key", ValueType.OBJECT); + builder.add("l1", 5L); + builder.close(); + } + { + builder.add("value", "test"); + } + builder.close(); + } + builder.close(); + } + builder.close(); + final TestEntityMapWithObjectKey entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntityMapWithObjectKey.class); + assertThat(entity).isNotNull(); + { + assertThat(entity.m1).isNotNull(); + assertThat(entity.m1).hasSize(size); + for (final Entry entry : entity.m1.entrySet()) { + assertThat(entry.getKey().l1).isEqualTo(5L); + assertThat(entry.getValue().c1).hasSize(1); + assertThat(entry.getValue().c1.iterator().next()).isEqualTo("test"); + } + } + { + assertThat(entity.m2).isNotNull(); + assertThat(entity.m2).hasSize(2); + for (final Entry entry : entity.m2.entrySet()) { + assertThat(entry.getKey().l1).isEqualTo(5L); + assertThat(entry.getValue()).isEqualTo("test"); + } + } + } + + public static class TestEntityEmpty { + + } + + @Test + void fromEmptyObject() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityEmpty())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + assertThat(vpack.getLength()).isZero(); + } + + @Test + void toEmptyObject() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.close(); + final TestEntityEmpty entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityEmpty.class); + assertThat(entity).isNotNull(); + } + + public static class TestEntityEmptyMap { + private Map m; + + public Map getM() { + return m; + } + + public void setM(final Map m) { + this.m = m; + } + } + + @Test + void fromEmptyMap() throws JsonProcessingException { + final TestEntityEmptyMap entity = new TestEntityEmptyMap(); + entity.setM(new HashMap<>()); + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + assertThat(vpack.getLength()).isEqualTo(1); + final VPackSlice m = vpack.get("m"); + assertThat(m.isObject()).isTrue(); + assertThat(m.getLength()).isZero(); + } + + @Test + void toEmptyMap() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("m", ValueType.OBJECT); + builder.close(); + builder.close(); + final TestEntityEmptyMap entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntityEmptyMap.class); + assertThat(entity).isNotNull(); + assertThat(entity.m).isNotNull(); + assertThat(entity.m).isEmpty(); + } + + public static class TestEntityBaseAttributes { + private String _key = "test1"; + private String _rev = "test2"; + private String _id = "test3"; + private String _from = "test4"; + private String _to = "test5"; + + public String get_key() { + return _key; + } + + public void set_key(final String _key) { + this._key = _key; + } + + public String get_rev() { + return _rev; + } + + public void set_rev(final String _rev) { + this._rev = _rev; + } + + public String get_id() { + return _id; + } + + public void set_id(final String _id) { + this._id = _id; + } + + public String get_from() { + return _from; + } + + public void set_from(final String _from) { + this._from = _from; + } + + public String get_to() { + return _to; + } + + public void set_to(final String _to) { + this._to = _to; + } + + } + + @Test + void fromObjectWithAttributeAdapter() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityBaseAttributes())); + assertThat(vpack.isObject()).isTrue(); + assertThat(vpack.getLength()).isEqualTo(5); + { + final VPackSlice key = vpack.get("_key"); + assertThat(key.isString()).isTrue(); + assertThat(key.getAsString()).isEqualTo("test1"); + } + { + final VPackSlice rev = vpack.get("_rev"); + assertThat(rev.isString()).isTrue(); + assertThat(rev.getAsString()).isEqualTo("test2"); + } + { + final VPackSlice id = vpack.get("_id"); + assertThat(id.isString()).isTrue(); + assertThat(id.getAsString()).isEqualTo("test3"); + } + { + final VPackSlice from = vpack.get("_from"); + assertThat(from.isString()).isTrue(); + assertThat(from.getAsString()).isEqualTo("test4"); + } + { + final VPackSlice to = vpack.get("_to"); + assertThat(to.isString()).isTrue(); + assertThat(to.getAsString()).isEqualTo("test5"); + } + } + + @Test + void toObjectWithAttributeAdapter() { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("_key", "a"); + builder.add("_rev", "b"); + builder.add("_id", "c"); + builder.add("_from", "d"); + builder.add("_to", "e"); + builder.close(); + } + final TestEntityBaseAttributes entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntityBaseAttributes.class); + assertThat(entity).isNotNull(); + assertThat(entity._key).isEqualTo("a"); + assertThat(entity._rev).isEqualTo("b"); + assertThat(entity._id).isEqualTo("c"); + assertThat(entity._from).isEqualTo("d"); + assertThat(entity._to).isEqualTo("e"); + } + + @Test + void fromMapWithAttributeAdapter() throws JsonProcessingException { + final TestEntityMap entity = new TestEntityMap(); + { + final Map m1 = new HashMap<>(); + m1.put("_key", "test1"); + m1.put("_rev", "test2"); + m1.put("_id", "test3"); + m1.put("_from", "test4"); + m1.put("_to", "test5"); + entity.setM1(m1); + } + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack.isObject()).isTrue(); + final VPackSlice m1 = vpack.get("m1"); + assertThat(m1.isObject()).isTrue(); + assertThat(m1.getLength()).isEqualTo(5); + { + final VPackSlice key = m1.get("_key"); + assertThat(key.isString()).isTrue(); + assertThat(key.getAsString()).isEqualTo("test1"); + } + { + final VPackSlice rev = m1.get("_rev"); + assertThat(rev.isString()).isTrue(); + assertThat(rev.getAsString()).isEqualTo("test2"); + } + { + final VPackSlice id = m1.get("_id"); + assertThat(id.isString()).isTrue(); + assertThat(id.getAsString()).isEqualTo("test3"); + } + { + final VPackSlice from = m1.get("_from"); + assertThat(from.isString()).isTrue(); + assertThat(from.getAsString()).isEqualTo("test4"); + } + { + final VPackSlice to = m1.get("_to"); + assertThat(to.isString()).isTrue(); + assertThat(to.getAsString()).isEqualTo("test5"); + } + } + + @Test + void toMapWithAttributeAdapter() { + final VPackBuilder builder = new VPackBuilder(); + { + builder.add(ValueType.OBJECT); + builder.add("m1", ValueType.OBJECT); + builder.add("_key", "a"); + builder.add("_rev", "b"); + builder.add("_id", "c"); + builder.add("_from", "d"); + builder.add("_to", "e"); + builder.close(); + builder.close(); + } + final TestEntityMap entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityMap.class); + assertThat(entity).isNotNull(); + assertThat(entity.m1).hasSize(5); + } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + private @interface CustomFilterAnnotation { + boolean serialize() + + default true; + + boolean deserialize() default true; + } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + private @interface CustomNamingAnnotation { + String name(); + } + + private static class CustomAnEntity { + @CustomFilterAnnotation(serialize = false) + private String a = null; + @CustomFilterAnnotation(deserialize = false) + private String b = null; + @CustomNamingAnnotation(name = "d") + @CustomFilterAnnotation(deserialize = false) + private String c = null; + + CustomAnEntity() { + super(); + } + } + + @Test + void fromCutsomAnnotation() { + final CustomAnEntity entity = new CustomAnEntity(); + entity.a = "1"; + entity.b = "2"; + entity.c = "3"; + final VPackSlice vpack = new VPack.Builder().annotationFieldFilter(CustomFilterAnnotation.class, + new VPackAnnotationFieldFilter() { + + @Override + public boolean serialize(final CustomFilterAnnotation annotation) { + return annotation.serialize(); + } + + @Override + public boolean deserialize(final CustomFilterAnnotation annotation) { + return annotation.deserialize(); + } + }).annotationFieldNaming(CustomNamingAnnotation.class, + CustomNamingAnnotation::name).build().serialize(entity); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + assertThat(vpack.get("a").isNone()).isTrue(); + assertThat(vpack.get("b").isString()).isTrue(); + assertThat(vpack.get("b").getAsString()).isEqualTo("2"); + assertThat(vpack.get("c").isNone()).isTrue(); + assertThat(vpack.get("d").isString()).isTrue(); + assertThat(vpack.get("d").getAsString()).isEqualTo("3"); + } + + @Test + void directFromCollection() throws JsonProcessingException { + final Collection list = new ArrayList<>(); + list.add("test"); + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(list)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isArray()).isTrue(); + assertThat(vpack.size()).isEqualTo(1); + final VPackSlice test = vpack.get(0); + assertThat(test.isString()).isTrue(); + assertThat(test.getAsString()).isEqualTo("test"); + } + + @Test + void directFromCollectionWithType() throws JsonProcessingException { + final Collection list = new ArrayList<>(); + list.add(new TestEntityString()); + list.add(new TestEntityString()); + + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(list)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isArray()).isTrue(); + assertThat(vpack.getLength()).isEqualTo(list.size()); + for (int i = 0; i < list.size(); i++) { + final VPackSlice entry = vpack.get(i); + assertThat(entry.isObject()).isTrue(); + assertThat(entry.getLength()).isEqualTo(3); + final VPackSlice s = entry.get("s"); + assertThat(s.isString()).isTrue(); + assertThat(s.getAsString()).isEqualTo("test"); + } + } + + @Test + void directToCollection() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + builder.add(ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.close(); + final List list = new VPack.Builder().build().deserialize(builder.slice(), + new Type>() { + }.getType()); + assertThat(list).hasSize(1); + final TestEntityString entry = list.get(0); + assertThat(entry.s).isEqualTo("abc"); + } + + @Test + void directFromStringMap() throws JsonProcessingException { + final Map map = new HashMap<>(); + map.put("a", new TestEntityString()); + map.put("b", new TestEntityString()); + + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(map)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + assertThat(vpack.getLength()).isEqualTo(2); + final VPackSlice a = vpack.get("a"); + checkStringEntity(a); + } + + @Test + void directToStringMap() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.close(); + final Map map = new VPack.Builder().build().deserialize(builder.slice(), + new Type>() { + }.getType()); + assertThat(map).hasSize(1); + final TestEntityString a = map.get("a"); + assertThat(a).isNotNull(); + assertThat(a.s).isEqualTo("abc"); + } + + @Test + void directFromMap() throws JsonProcessingException { + final Map map = new HashMap<>(); + final TestEntityA entity = new TestEntityA(); + entity.a = "test"; + map.put("test", entity); + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(map)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + final VPackSlice test = vpack.get("test"); + assertThat(test.isObject()).isTrue(); + final VPackSlice a = test.get("a"); + assertThat(a.isString()).isTrue(); + assertThat(a.getAsString()).isEqualTo("test"); + } + + @Test + void directFromMapWithinMap() throws JsonProcessingException { + final Map map = new HashMap<>(); + final Map map2 = new HashMap<>(); + map2.put("b", "test"); + map.put("a", map2); + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(map)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + assertThat(vpack.size()).isEqualTo(1); + final VPackSlice a = vpack.get("a"); + assertThat(a.isObject()).isTrue(); + assertThat(a.size()).isEqualTo(1); + final VPackSlice b = a.get("b"); + assertThat(b.isString()).isTrue(); + assertThat(b.getAsString()).isEqualTo("test"); + } + + private void checkStringEntity(final VPackSlice vpack) { + final TestEntityString expected = new TestEntityString(); + assertThat(vpack.isObject()).isTrue(); + assertThat(vpack.getLength()).isEqualTo(3); + final VPackSlice s = vpack.get("s"); + assertThat(s.isString()).isTrue(); + assertThat(s.getAsString()).isEqualTo(expected.s); + final VPackSlice c1 = vpack.get("c1"); + assertThat(c1.isString()).isTrue(); + assertThat(new Character(c1.getAsChar())).isEqualTo(expected.c1); + final VPackSlice c2 = vpack.get("c2"); + assertThat(c2.isString()).isTrue(); + assertThat(c2.getAsChar()).isEqualTo(expected.c2); + } + + @Test + void directToObjectMap() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.ARRAY); + builder.add(ValueType.OBJECT); + builder.add("key", ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.add("value", ValueType.OBJECT); + builder.add("s", "abc"); + builder.close(); + builder.close(); + builder.close(); + final Map map = new VPack.Builder().build().deserialize(builder.slice(), + new Type>() { + }.getType()); + assertThat(map).hasSize(1); + for (final Entry entry : map.entrySet()) { + assertThat(entry.getKey().s).isEqualTo("abc"); + assertThat(entry.getValue().s).isEqualTo("abc"); + } + } + + @SuppressWarnings("unchecked") + @Test + void directToMapWithinMap() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("a", ValueType.OBJECT); + builder.add("b", "test"); + builder.add("c", true); + builder.add("d", 1L); + builder.add("e", 1.5); + final Date date = new Date(); + builder.add("f", date); + builder.add("g", ValueType.ARRAY); + builder.close(); + builder.close(); + builder.close(); + final Map map = new VPack.Builder().build().deserialize(builder.slice(), Map.class); + assertThat(map).hasSize(1); + final Object a = map.get("a"); + assertThat(Map.class.isAssignableFrom(a.getClass())).isTrue(); + final Map mapA = (Map) a; + assertThat(mapA).hasSize(6); + final Object b = mapA.get("b"); + assertThat(String.class.isAssignableFrom(b.getClass())).isTrue(); + assertThat(b).hasToString("test"); + final Object c = mapA.get("c"); + assertThat(Boolean.class.isAssignableFrom(c.getClass())).isTrue(); + assertThat((Boolean) c).isTrue(); + final Object d = mapA.get("d"); + assertThat(Number.class.isAssignableFrom(d.getClass())).isTrue(); + assertThat(((Number) d).longValue()).isEqualTo(1L); + final Object e = mapA.get("e"); + assertThat(Double.class.isAssignableFrom(e.getClass())).isTrue(); + assertThat((Double) e).isEqualTo(1.5); + final Object f = mapA.get("f"); + assertThat(Date.class.isAssignableFrom(f.getClass())).isTrue(); + assertThat((Date) f).isEqualTo(date); + final Object g = mapA.get("g"); + assertThat(Collection.class.isAssignableFrom(g.getClass())).isTrue(); + assertThat(List.class.isAssignableFrom(g.getClass())).isTrue(); + } + + @Test + void dontSerializeNullValues() { + final VPack serializer = new VPack.Builder().serializeNullValues(false).build(); + final TestEntityString entity = new TestEntityString(); + entity.setS(null); + final VPackSlice vpack = serializer.serialize(entity); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + final VPackSlice s = vpack.get("s"); + assertThat(s.isNone()).isTrue(); + } + + @Test + void serializeNullValue() { + final VPack serializer = new VPack.Builder().serializeNullValues(true).build(); + final TestEntityString entity = new TestEntityString(); + entity.setS(null); + final VPackSlice vpack = serializer.serialize(entity); + assertThat(vpack).isNotNull(); + final VPackSlice s = vpack.get("s"); + assertThat(s.isNull()).isTrue(); + } + + @Test + void toNullValue() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("s", ValueType.NULL); + builder.close(); + final TestEntityString entity = new VPack.Builder().build().deserialize(builder.slice(), + TestEntityString.class); + assertThat(entity).isNotNull(); + assertThat(entity.s).isNull(); + assertThat(entity.c1).isNotNull(); + assertThat(entity.c2).isNotNull(); + } + + @Test + void toSimpleString() { + final VPackBuilder builder = new VPackBuilder(); + builder.add("test"); + final String s = new VPack.Builder().build().deserialize(builder.slice(), String.class); + assertThat(s).isEqualTo("test"); + } + + @Test + void fromSimpleString() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes("test")); + assertThat(vpack).isNotNull(); + assertThat(vpack.isString()).isTrue(); + assertThat(vpack.getAsString()).isEqualTo("test"); + } + + public static class TestEntityTyped { + private T e; + } + + @Test + void fromStringTypedEntity() throws JsonProcessingException { + final TestEntityTyped entity = new TestEntityTyped<>(); + entity.e = "test"; + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + final VPackSlice e = vpack.get("e"); + assertThat(e).isNotNull(); + assertThat(e.isString()).isTrue(); + assertThat(e.getAsString()).isEqualTo("test"); + } + + @Test + void fromObjectTypedEntity() throws JsonProcessingException { + final TestEntityTyped entity = new TestEntityTyped<>(); + entity.e = new TestEntityString(); + entity.e.s = "test2"; + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + final VPackSlice e = vpack.get("e"); + assertThat(e).isNotNull(); + assertThat(e.isObject()).isTrue(); + final VPackSlice s = e.get("s"); + assertThat(s).isNotNull(); + assertThat(s.isString()).isTrue(); + assertThat(s.getAsString()).isEqualTo("test2"); + } + + @Test + void fromTypedTypedEntity() throws JsonProcessingException { + final TestEntityTyped> entity = new TestEntityTyped<>(); + entity.e = new TestEntityTyped<>(); + entity.e.e = "test"; + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + final VPackSlice e = vpack.get("e"); + assertThat(e).isNotNull(); + assertThat(e.isObject()).isTrue(); + final VPackSlice e2 = e.get("e"); + assertThat(e2).isNotNull(); + assertThat(e2.isString()).isTrue(); + assertThat(e2.getAsString()).isEqualTo("test"); + } + + @Test + void fieldNamingStrategySerialize() { + final VPackSlice vpack = new VPack.Builder().fieldNamingStrategy(field -> "bla").build().serialize(new TestEntityA()); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + final VPackSlice bla = vpack.get("bla"); + assertThat(bla.isString()).isTrue(); + assertThat(bla.getAsString()).isEqualTo("a"); + } + + @Test + void fieldNamingStrategyDeserialize() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("bla", "test"); + builder.close(); + final TestEntityA entity = new VPack.Builder().fieldNamingStrategy(field -> "bla").build().deserialize(builder.slice(), TestEntityA.class); + assertThat(entity).isNotNull(); + assertThat(entity.a).isEqualTo("test"); + } + + @Test + void serializeVPack() throws JsonProcessingException { + final VPackBuilder builder = new VPackBuilder(); + builder.add("test"); + final VPackSlice slice = builder.slice(); + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(slice)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isString()).isTrue(); + assertThat(vpack.getAsString()).isEqualTo("test"); + } + + @Test + void deserializeVPack() { + final VPackBuilder builder = new VPackBuilder(); + builder.add("test"); + final VPackSlice slice = builder.slice(); + final VPackSlice vpack = new VPack.Builder().build().deserialize(slice, slice.getClass()); + assertThat(vpack).isNotNull(); + assertThat(vpack.isString()).isTrue(); + assertThat(vpack.getAsString()).isEqualTo("test"); + } + + public static class TestEntityDate { + private java.util.Date utilDate = new Date(1474988621); + private java.sql.Date sqlDate = new java.sql.Date(1474988621); + private java.sql.Timestamp timestamp = new java.sql.Timestamp(1474988621); + + public java.util.Date getUtilDate() { + return utilDate; + } + + public void setUtilDate(final java.util.Date utilDate) { + this.utilDate = utilDate; + } + + public java.sql.Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(final java.sql.Date sqlDate) { + this.sqlDate = sqlDate; + } + + public java.sql.Timestamp getTimestamp() { + return timestamp; + } + + public void setTimestamp(final java.sql.Timestamp timestamp) { + this.timestamp = timestamp; + } + + } + + @Test + void fromDate() throws JsonProcessingException { + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityDate())); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + { + assertThat(vpack.get("utilDate").isString()).isTrue(); + assertThat(vpack.get("utilDate").getAsString()).isEqualTo(DATE_FORMAT.format(new Date(1474988621))); + } + { + assertThat(vpack.get("sqlDate").isString()).isTrue(); + assertThat(vpack.get("sqlDate").getAsString()).isEqualTo(DATE_FORMAT.format(new java.sql.Date(1474988621))); + } + { + assertThat(vpack.get("timestamp").isString()).isTrue(); + assertThat(vpack.get("timestamp").getAsString()).isEqualTo(DATE_FORMAT.format(new java.sql.Timestamp(1474988621))); + } + } + + @Test + void toDate() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("utilDate", new Date(1475062216)); + builder.add("sqlDate", new java.sql.Date(1475062216)); + builder.add("timestamp", new java.sql.Timestamp(1475062216)); + builder.close(); + + final TestEntityDate entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityDate.class); + assertThat(entity).isNotNull(); + assertThat(entity.utilDate).isEqualTo(new Date(1475062216)); + assertThat(entity.sqlDate).isEqualTo(new java.sql.Date(1475062216)); + assertThat(entity.timestamp).isEqualTo(new java.sql.Timestamp(1475062216)); + } + + @Test + void toDateFromString() { + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("utilDate", DATE_FORMAT.format(new Date(1475062216))); + builder.add("sqlDate", DATE_FORMAT.format(new java.sql.Date(1475062216))); + builder.add("timestamp", DATE_FORMAT.format(new java.sql.Timestamp(1475062216))); + builder.close(); + + final TestEntityDate entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityDate.class); + assertThat(entity).isNotNull(); + assertThat(entity.utilDate).isEqualTo(new Date(1475062216)); + assertThat(entity.sqlDate).isEqualTo(new java.sql.Date(1475062216)); + assertThat(entity.timestamp).isEqualTo(new java.sql.Timestamp(1475062216)); + } + + public static class TestEntityUUID { + private UUID uuid; + + UUID getUuid() { + return uuid; + } + + void setUuid(final UUID uuid) { + this.uuid = uuid; + } + } + + @Test + void fromUUID() throws IOException { + final TestEntityUUID entity = new TestEntityUUID(); + entity.setUuid(UUID.randomUUID()); + byte[] bytes = mapper.writeValueAsBytes(entity); + final VPackSlice vpack = new VPackSlice(bytes); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + + final VPackSlice uuid = vpack.get("uuid"); + assertThat(uuid.isString()).isTrue(); + assertThat(uuid.getAsString()).isEqualTo(entity.getUuid().toString()); + assertThat(mapper.readValue(bytes, TestEntityUUID.class).getUuid()).isEqualTo(entity.getUuid()); + } + + @Test + void toUUID() { + final UUID uuid = UUID.randomUUID(); + final VPackBuilder builder = new VPackBuilder(); + builder.add(ValueType.OBJECT); + builder.add("uuid", uuid.toString()); + builder.close(); + + final TestEntityUUID entity = new VPack.Builder().build().deserialize(builder.slice(), TestEntityUUID.class); + assertThat(entity).isNotNull(); + assertThat(entity.uuid).isEqualTo(uuid); + } + + @Test + void uuid() { + final TestEntityUUID entity = new TestEntityUUID(); + entity.setUuid(UUID.randomUUID()); + final VPack vpacker = new VPack.Builder().build(); + final VPackSlice vpack = vpacker.serialize(entity); + final TestEntityUUID entity2 = vpacker.deserialize(vpack, TestEntityUUID.class); + assertThat(entity2).isNotNull(); + assertThat(entity2.getUuid()).isEqualTo(entity.getUuid()); + } + + private static class BinaryEntity { + private byte[] foo; + + BinaryEntity() { + super(); + } + } + + @Test + void fromBinary() throws JsonProcessingException { + final BinaryEntity entity = new BinaryEntity(); + entity.foo = "bar".getBytes(); + final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity)); + assertThat(vpack).isNotNull(); + assertThat(vpack.isObject()).isTrue(); + assertThat(vpack.get("foo").isString()).isTrue(); + assertThat(vpack.get("foo").getAsString()).isEqualTo(Base64.getEncoder().encodeToString(entity.foo)); + } + + @Test + void toBinary() throws IOException { + final String value = Base64.getEncoder().encodeToString("bar".getBytes()); + final VPackSlice vpack = new VPackBuilder().add(ValueType.OBJECT).add("foo", value).close().slice(); + final BinaryEntity entity = mapper.readValue(vpack.getBuffer(), BinaryEntity.class); + assertThat(entity).isNotNull(); + assertThat(entity.foo).isEqualTo("bar".getBytes()); + } + + @Test + void asFloatingNumber() { + final VPackSlice vpack = new VPackBuilder().add(ValueType.OBJECT).add("value", 12000).close().slice(); + assertThat(vpack.get("value").getAsInt()).isEqualTo(12000); + assertThat(vpack.get("value").getAsFloat()).isEqualTo(12000F); + assertThat(vpack.get("value").getAsDouble()).isEqualTo(12000.); + } + + @Test + void toVPackSlice() throws IOException { + final VPackSlice value = new VPackBuilder().add(ValueType.OBJECT).add("key", "value").close().slice(); + final VPackSlice entity = mapper.readValue(value.getBuffer(), VPackSlice.class); + assertThat(entity).isEqualTo(value); + } } diff --git a/src/test/java/com/arangodb/mapping/annotations/ArangoAnnotationsTest.java b/src/test/java/com/arangodb/mapping/annotations/ArangoAnnotationsTest.java index b94574347..de290b615 100644 --- a/src/test/java/com/arangodb/mapping/annotations/ArangoAnnotationsTest.java +++ b/src/test/java/com/arangodb/mapping/annotations/ArangoAnnotationsTest.java @@ -23,103 +23,104 @@ import com.arangodb.entity.DocumentField; import com.arangodb.mapping.ArangoJack; import com.arangodb.velocypack.VPackSlice; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michele Rastelli */ -public class ArangoAnnotationsTest { - - private final ArangoJack mapper = new ArangoJack(); - - @Test - public void documentField() { - DocumentFieldEntity e = new DocumentFieldEntity(); - e.setId("Id"); - e.setKey("Key"); - e.setRev("Rev"); - e.setFrom("From"); - e.setTo("To"); - - VPackSlice slice = mapper.serialize(e); - System.out.println(slice); - Map deserialized = mapper.deserialize(slice, Object.class); - assertThat(deserialized.get(DocumentField.Type.ID.getSerializeName()), is(e.getId())); - assertThat(deserialized.get(DocumentField.Type.KEY.getSerializeName()), is(e.getKey())); - assertThat(deserialized.get(DocumentField.Type.REV.getSerializeName()), is(e.getRev())); - assertThat(deserialized.get(DocumentField.Type.FROM.getSerializeName()), is(e.getFrom())); - assertThat(deserialized.get(DocumentField.Type.TO.getSerializeName()), is(e.getTo())); - assertThat(deserialized.size(), is(DocumentField.Type.values().length)); - - DocumentFieldEntity deserializedEntity = mapper.deserialize(slice, DocumentFieldEntity.class); - assertThat(deserializedEntity, is(e)); - } - - @Test - public void serializedName() { - SerializedNameEntity e = new SerializedNameEntity(); - e.setA("A"); - e.setB("B"); - e.setC("C"); - - VPackSlice slice = mapper.serialize(e); - System.out.println(slice); - Map deserialized = mapper.deserialize(slice, Object.class); - assertThat(deserialized.get(SerializedNameEntity.SERIALIZED_NAME_A), is(e.getA())); - assertThat(deserialized.get(SerializedNameEntity.SERIALIZED_NAME_B), is(e.getB())); - assertThat(deserialized.get(SerializedNameEntity.SERIALIZED_NAME_C), is(e.getC())); - assertThat(deserialized.size(), is(3)); - - SerializedNameEntity deserializedEntity = mapper.deserialize(slice, SerializedNameEntity.class); - assertThat(deserializedEntity, is(e)); - } - - @Test - public void serializedNameParameter() { - Map e = new HashMap<>(); - e.put(SerializedNameParameterEntity.SERIALIZED_NAME_A, "A"); - e.put(SerializedNameParameterEntity.SERIALIZED_NAME_B, "B"); - e.put(SerializedNameParameterEntity.SERIALIZED_NAME_C, "C"); - - VPackSlice slice = mapper.serialize(e); - SerializedNameParameterEntity deserializedEntity = mapper - .deserialize(slice, SerializedNameParameterEntity.class); - assertThat(deserializedEntity, is(new SerializedNameParameterEntity("A", "B", "C"))); - } - - @Test - public void expose() { - ExposeEntity e = new ExposeEntity(); - e.setReadWrite("readWrite"); - e.setReadOnly("readOnly"); - e.setWriteOnly("writeOnly"); - e.setIgnored("ignored"); - - VPackSlice serializedEntity = mapper.serialize(e); - Map deserializedEntity = mapper.deserialize(serializedEntity, Object.class); - assertThat(deserializedEntity.get("readWrite"), is("readWrite")); - assertThat(deserializedEntity.get("readOnly"), is("readOnly")); - assertThat(deserializedEntity.size(), is(2)); - - Map map = new HashMap<>(); - map.put("readWrite", "readWrite"); - map.put("readOnly", "readOnly"); - map.put("writeOnly", "writeOnly"); - map.put("ignored", "ignored"); - - VPackSlice serializedMap = mapper.serialize(map); - ExposeEntity deserializedMap = mapper.deserialize(serializedMap, ExposeEntity.class); - assertThat(deserializedMap.getIgnored(), is(nullValue())); - assertThat(deserializedMap.getReadOnly(), is(nullValue())); - assertThat(deserializedMap.getWriteOnly(), is("writeOnly")); - assertThat(deserializedMap.getReadWrite(), is("readWrite")); - } +class ArangoAnnotationsTest { + + private final ArangoJack mapper = new ArangoJack(); + + @Test + void documentField() { + DocumentFieldEntity e = new DocumentFieldEntity(); + e.setId("Id"); + e.setKey("Key"); + e.setRev("Rev"); + e.setFrom("From"); + e.setTo("To"); + + VPackSlice slice = mapper.serialize(e); + System.out.println(slice); + Map deserialized = mapper.deserialize(slice, Object.class); + assertThat(deserialized) + .containsEntry(DocumentField.Type.ID.getSerializeName(), e.getId()) + .containsEntry(DocumentField.Type.KEY.getSerializeName(), e.getKey()) + .containsEntry(DocumentField.Type.REV.getSerializeName(), e.getRev()) + .containsEntry(DocumentField.Type.FROM.getSerializeName(), e.getFrom()) + .containsEntry(DocumentField.Type.TO.getSerializeName(), e.getTo()) + .hasSize(DocumentField.Type.values().length); + + DocumentFieldEntity deserializedEntity = mapper.deserialize(slice, DocumentFieldEntity.class); + assertThat(deserializedEntity).isEqualTo(e); + } + + @Test + void serializedName() { + SerializedNameEntity e = new SerializedNameEntity(); + e.setA("A"); + e.setB("B"); + e.setC("C"); + + VPackSlice slice = mapper.serialize(e); + System.out.println(slice); + Map deserialized = mapper.deserialize(slice, Object.class); + assertThat(deserialized) + .containsEntry(SerializedNameEntity.SERIALIZED_NAME_A, e.getA()) + .containsEntry(SerializedNameEntity.SERIALIZED_NAME_B, e.getB()) + .containsEntry(SerializedNameEntity.SERIALIZED_NAME_C, e.getC()) + .hasSize(3); + + SerializedNameEntity deserializedEntity = mapper.deserialize(slice, SerializedNameEntity.class); + assertThat(deserializedEntity).isEqualTo(e); + } + + @Test + void serializedNameParameter() { + Map e = new HashMap<>(); + e.put(SerializedNameParameterEntity.SERIALIZED_NAME_A, "A"); + e.put(SerializedNameParameterEntity.SERIALIZED_NAME_B, "B"); + e.put(SerializedNameParameterEntity.SERIALIZED_NAME_C, "C"); + + VPackSlice slice = mapper.serialize(e); + SerializedNameParameterEntity deserializedEntity = mapper + .deserialize(slice, SerializedNameParameterEntity.class); + assertThat(deserializedEntity).isEqualTo(new SerializedNameParameterEntity("A", "B", "C")); + } + + @Test + void expose() { + ExposeEntity e = new ExposeEntity(); + e.setReadWrite("readWrite"); + e.setReadOnly("readOnly"); + e.setWriteOnly("writeOnly"); + e.setIgnored("ignored"); + + VPackSlice serializedEntity = mapper.serialize(e); + Map deserializedEntity = mapper.deserialize(serializedEntity, Object.class); + assertThat(deserializedEntity) + .containsEntry("readWrite", "readWrite") + .containsEntry("readOnly", "readOnly") + .hasSize(2); + + Map map = new HashMap<>(); + map.put("readWrite", "readWrite"); + map.put("readOnly", "readOnly"); + map.put("writeOnly", "writeOnly"); + map.put("ignored", "ignored"); + + VPackSlice serializedMap = mapper.serialize(map); + ExposeEntity deserializedMap = mapper.deserialize(serializedMap, ExposeEntity.class); + assertThat(deserializedMap.getIgnored()).isNull(); + assertThat(deserializedMap.getReadOnly()).isNull(); + assertThat(deserializedMap.getWriteOnly()).isEqualTo("writeOnly"); + assertThat(deserializedMap.getReadWrite()).isEqualTo("readWrite"); + } } diff --git a/src/test/java/com/arangodb/serde/CustomSerdeTest.java b/src/test/java/com/arangodb/serde/CustomSerdeTest.java index e56b1f7b5..834d1cd56 100644 --- a/src/test/java/com/arangodb/serde/CustomSerdeTest.java +++ b/src/test/java/com/arangodb/serde/CustomSerdeTest.java @@ -24,6 +24,7 @@ import com.arangodb.ArangoCollection; import com.arangodb.ArangoDB; import com.arangodb.ArangoDatabase; +import com.arangodb.DbName; import com.arangodb.entity.BaseDocument; import com.arangodb.mapping.ArangoJack; import com.arangodb.model.DocumentCreateOptions; @@ -39,9 +40,9 @@ import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.module.SimpleModule; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigInteger; @@ -52,15 +53,14 @@ import static com.arangodb.internal.util.ArangoSerializationFactory.Serializer.CUSTOM; import static com.fasterxml.jackson.databind.DeserializationFeature.USE_BIG_INTEGER_FOR_INTS; import static com.fasterxml.jackson.databind.SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.*; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michele Rastelli */ -public class CustomSerdeTest { +class CustomSerdeTest { private static final String COLLECTION_NAME = "collection"; private static final String PERSON_SERIALIZER_ADDED_PREFIX = "MyNameIs"; @@ -82,7 +82,7 @@ public void serialize(Person value, JsonGenerator gen, SerializerProvider serial static class PersonDeserializer extends JsonDeserializer { @Override - public Person deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException { + public Person deserialize(JsonParser parser, DeserializationContext ctx) throws IOException { Person person = new Person(); JsonNode rootNode = parser.getCodec().readTree(parser); JsonNode nameNode = rootNode.get("name"); @@ -94,12 +94,12 @@ public Person deserialize(JsonParser parser, DeserializationContext ctxt) throws } @JsonSerialize(using = PersonSerializer.class) - public static class Person { - public String name; + static class Person { + String name; } - @BeforeClass - public static void init() { + @BeforeAll + static void init() { ArangoJack arangoJack = new ArangoJack(); arangoJack.configure((mapper) -> { mapper.configure(WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true); @@ -110,8 +110,7 @@ public static void init() { }); arangoDB = new ArangoDB.Builder().serializer(arangoJack).build(); - String TEST_DB = "custom-serde-test"; - db = arangoDB.db(TEST_DB); + db = arangoDB.db(DbName.of("custom-serde-test")); if (!db.exists()) { db.create(); } @@ -122,36 +121,36 @@ public static void init() { } } - @AfterClass - public static void shutdown() { + @AfterAll + static void shutdown() { if (db.exists()) db.drop(); } @Test - public void customPersonDeserializer() { + void customPersonDeserializer() { Person person = new Person(); person.name = "Joe"; Person result = collection.insertDocument( person, new DocumentCreateOptions().returnNew(true) ).getNew(); - assertThat(result.name, is(PERSON_DESERIALIZER_ADDED_PREFIX + PERSON_SERIALIZER_ADDED_PREFIX + person.name)); + assertThat(result.name).isEqualTo(PERSON_DESERIALIZER_ADDED_PREFIX + PERSON_SERIALIZER_ADDED_PREFIX + person.name); } @Test - public void manualCustomPersonDeserializer() { + void manualCustomPersonDeserializer() { Person person = new Person(); person.name = "Joe"; ArangoSerialization serialization = arangoDB.util(CUSTOM); VPackSlice serializedPerson = serialization.serialize(person); Person deserializedPerson = serialization.deserialize(serializedPerson, Person.class); - assertThat(deserializedPerson.name, is(PERSON_DESERIALIZER_ADDED_PREFIX + PERSON_SERIALIZER_ADDED_PREFIX + person.name)); + assertThat(deserializedPerson.name).isEqualTo(PERSON_DESERIALIZER_ADDED_PREFIX + PERSON_SERIALIZER_ADDED_PREFIX + person.name); } @Test - public void aqlSerialization() { - String key = "test-" + UUID.randomUUID().toString(); + void aqlSerialization() { + String key = "test-" + UUID.randomUUID(); BaseDocument doc = new BaseDocument(key); doc.addAttribute("arr", Collections.singletonList("hello")); @@ -165,17 +164,17 @@ public void aqlSerialization() { "INSERT @doc INTO @@collection RETURN NEW", params, BaseDocument.class - ).first(); + ).next(); - assertThat(result.getAttribute("arr"), instanceOf(String.class)); - assertThat(result.getAttribute("arr"), is("hello")); - assertThat(result.getAttribute("int"), instanceOf(BigInteger.class)); - assertThat(result.getAttribute("int"), is(BigInteger.valueOf(10))); + assertThat(result.getAttribute("arr")).isInstanceOf(String.class); + assertThat(result.getAttribute("arr")).isEqualTo("hello"); + assertThat(result.getAttribute("int")).isInstanceOf(BigInteger.class); + assertThat(result.getAttribute("int")).isEqualTo(BigInteger.valueOf(10)); } @Test - public void aqlDeserialization() { - String key = "test-" + UUID.randomUUID().toString(); + void aqlDeserialization() { + String key = "test-" + UUID.randomUUID(); BaseDocument doc = new BaseDocument(key); doc.addAttribute("arr", Collections.singletonList("hello")); @@ -187,17 +186,17 @@ public void aqlDeserialization() { "RETURN DOCUMENT(@docId)", Collections.singletonMap("docId", COLLECTION_NAME + "/" + key), BaseDocument.class - ).first(); + ).next(); - assertThat(result.getAttribute("arr"), instanceOf(String.class)); - assertThat(result.getAttribute("arr"), is("hello")); - assertThat(result.getAttribute("int"), instanceOf(BigInteger.class)); - assertThat(result.getAttribute("int"), is(BigInteger.valueOf(10))); + assertThat(result.getAttribute("arr")).isInstanceOf(String.class); + assertThat(result.getAttribute("arr")).isEqualTo("hello"); + assertThat(result.getAttribute("int")).isInstanceOf(BigInteger.class); + assertThat(result.getAttribute("int")).isEqualTo(BigInteger.valueOf(10)); } @Test - public void insertDocument() { - String key = "test-" + UUID.randomUUID().toString(); + void insertDocument() { + String key = "test-" + UUID.randomUUID(); BaseDocument doc = new BaseDocument(key); doc.addAttribute("arr", Collections.singletonList("hello")); @@ -208,15 +207,15 @@ public void insertDocument() { new DocumentCreateOptions().returnNew(true) ).getNew(); - assertThat(result.getAttribute("arr"), instanceOf(String.class)); - assertThat(result.getAttribute("arr"), is("hello")); - assertThat(result.getAttribute("int"), instanceOf(BigInteger.class)); - assertThat(result.getAttribute("int"), is(BigInteger.valueOf(10))); + assertThat(result.getAttribute("arr")).isInstanceOf(String.class); + assertThat(result.getAttribute("arr")).isEqualTo("hello"); + assertThat(result.getAttribute("int")).isInstanceOf(BigInteger.class); + assertThat(result.getAttribute("int")).isEqualTo(BigInteger.valueOf(10)); } @Test - public void getDocument() { - String key = "test-" + UUID.randomUUID().toString(); + void getDocument() { + String key = "test-" + UUID.randomUUID(); BaseDocument doc = new BaseDocument(key); doc.addAttribute("arr", Collections.singletonList("hello")); @@ -229,16 +228,16 @@ public void getDocument() { BaseDocument.class, null); - assertThat(result.getAttribute("arr"), instanceOf(String.class)); - assertThat(result.getAttribute("arr"), is("hello")); - assertThat(result.getAttribute("int"), instanceOf(BigInteger.class)); - assertThat(result.getAttribute("int"), is(BigInteger.valueOf(10))); + assertThat(result.getAttribute("arr")).isInstanceOf(String.class); + assertThat(result.getAttribute("arr")).isEqualTo("hello"); + assertThat(result.getAttribute("int")).isInstanceOf(BigInteger.class); + assertThat(result.getAttribute("int")).isEqualTo(BigInteger.valueOf(10)); } @Test - public void parseNullString() { + void parseNullString() { final String json = arangoDB.util(CUSTOM).deserialize(new VPackBuilder().add((String) null).slice(), String.class); - assertThat(json, nullValue()); + assertThat(json).isNull(); } } diff --git a/src/test/java/com/arangodb/serde/CustomTypeHintTest.java b/src/test/java/com/arangodb/serde/CustomTypeHintTest.java index 558fc3359..a19eda063 100644 --- a/src/test/java/com/arangodb/serde/CustomTypeHintTest.java +++ b/src/test/java/com/arangodb/serde/CustomTypeHintTest.java @@ -24,21 +24,22 @@ import com.arangodb.ArangoCollection; import com.arangodb.ArangoDB; import com.arangodb.ArangoDatabase; +import com.arangodb.DbName; import com.arangodb.mapping.ArangoJack; import com.arangodb.model.DocumentCreateOptions; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; /** * @author Michele Rastelli */ -public class CustomTypeHintTest { +class CustomTypeHintTest { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "type") public interface Animal { @@ -87,14 +88,13 @@ public void setAnimal(Animal animal) { private ArangoDatabase db; private ArangoCollection collection; - @Before - public void init() { + @BeforeEach + void init() { ArangoDB arangoDB = new ArangoDB.Builder() .serializer(new ArangoJack()) .build(); - String TEST_DB = "custom-serde-test"; - db = arangoDB.db(TEST_DB); + db = arangoDB.db(DbName.of("custom-serde-test")); if (!db.exists()) { db.create(); } @@ -105,14 +105,14 @@ public void init() { } } - @After - public void shutdown() { + @AfterEach + void shutdown() { if (db.exists()) db.drop(); } @Test - public void insertDocument() { + void insertDocument() { Gorilla gorilla = new Gorilla(); gorilla.setName("kingKong"); @@ -124,7 +124,7 @@ public void insertDocument() { new DocumentCreateOptions().returnNew(true) ).getNew(); - assertThat((insertedDoc.getAnimal().getName()), is("kingKong")); + assertThat((insertedDoc.getAnimal().getName())).isEqualTo("kingKong"); String key = insertedDoc.getKey(); @@ -141,6 +141,6 @@ public void insertDocument() { Zoo.class, null); - assertThat((readDoc.getAnimal().getName()), is("kingKong")); + assertThat((readDoc.getAnimal().getName())).isEqualTo("kingKong"); } } diff --git a/src/test/java/com/arangodb/util/ArangoSerializationTest.java b/src/test/java/com/arangodb/util/ArangoSerializationTest.java index 3adf974dc..d17bd27c4 100644 --- a/src/test/java/com/arangodb/util/ArangoSerializationTest.java +++ b/src/test/java/com/arangodb/util/ArangoSerializationTest.java @@ -22,66 +22,66 @@ import com.arangodb.ArangoDB; import com.arangodb.entity.BaseDocument; +import com.arangodb.mapping.ArangoJack; import com.arangodb.velocypack.*; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Mark Vollmary */ -public class ArangoSerializationTest { +class ArangoSerializationTest { private static ArangoSerialization util; - @BeforeClass - public static void setup() { - final ArangoDB arangoDB = new ArangoDB.Builder().build(); + @BeforeAll + static void setup() { + final ArangoDB arangoDB = new ArangoDB.Builder().serializer(new ArangoJack()).build(); util = arangoDB.util(); } @Test - public void deseriarlize() { + void deserialize() { final VPackBuilder builder = new VPackBuilder().add(ValueType.OBJECT).add("foo", "bar").close(); final BaseDocument doc = util.deserialize(builder.slice(), BaseDocument.class); - assertThat(doc.getAttribute("foo").toString(), is("bar")); + assertThat(doc.getAttribute("foo")).isEqualTo("bar"); } @Test - public void serialize() { + void serialize() { final BaseDocument entity = new BaseDocument(); entity.addAttribute("foo", "bar"); final VPackSlice vpack = util.serialize(entity); - assertThat(vpack.get("foo").isString(), is(true)); - assertThat(vpack.get("foo").getAsString(), is("bar")); + assertThat(vpack.get("foo").isString()).isTrue(); + assertThat(vpack.get("foo").getAsString()).isEqualTo("bar"); } @Test - public void serializeNullValues() { + void serializeNullValues() { final BaseDocument entity = new BaseDocument(); entity.addAttribute("foo", null); final VPackSlice vpack = util.serialize(entity, new ArangoSerializer.Options().serializeNullValues(true)); - assertThat(vpack.get("foo").isNull(), is(true)); + assertThat(vpack.get("foo").isNull()).isTrue(); } @Test - public void skipSerializeNullValues() { + void skipSerializeNullValues() { final BaseDocument entity = new BaseDocument(); entity.addAttribute("bar", null); final VPackSlice vpack = util.serialize(entity); - assertThat(vpack.get("bar").isNone(), is(true)); + assertThat(vpack.get("bar").isNone()).isTrue(); } @Test - public void serializeType() { + void serializeType() { final Collection list = new ArrayList<>(); list.add(new BaseDocument()); list.add(new BaseDocument()); @@ -89,22 +89,22 @@ public void serializeType() { final VPackSlice vpack = util.serialize(list, new ArangoSerializer.Options().type(new Type>() { }.getType())); - assertThat(vpack.isArray(), is(true)); - assertThat(vpack.getLength(), is(list.size())); + assertThat(vpack.isArray()).isTrue(); + assertThat(vpack.getLength()).isEqualTo(list.size()); } @Test - public void parseJsonIncludeNull() { + void parseJsonIncludeNull() { final Map entity = new HashMap<>(); entity.put("value", new String[]{"test", null}); final String json = util.deserialize(util.serialize(entity, new ArangoSerializer.Options()), String.class); - assertThat(json, is("{\"value\":[\"test\",null]}")); + assertThat(json).isEqualTo("{\"value\":[\"test\",null]}"); } @Test - public void parseNullString() { + void parseNullString() { final String json = util.deserialize(new VPackBuilder().add((String) null).slice(), String.class); - assertThat(json, nullValue()); + assertThat(json).isNull(); } } diff --git a/src/test/java/com/arangodb/util/MapBuilderTest.java b/src/test/java/com/arangodb/util/MapBuilderTest.java index 09feb7cc5..53633d646 100644 --- a/src/test/java/com/arangodb/util/MapBuilderTest.java +++ b/src/test/java/com/arangodb/util/MapBuilderTest.java @@ -20,25 +20,24 @@ package com.arangodb.util; -import org.junit.Test; + +import org.junit.jupiter.api.Test; import java.util.Map; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Vollmary */ -public class MapBuilderTest { - - @Test - public void build() { - final Map map = new MapBuilder().put("foo", "bar").get(); - assertThat(map.size(), is(1)); - assertThat(map.get("foo"), is(notNullValue())); - assertThat(map.get("foo").toString(), is("bar")); - } +class MapBuilderTest { + + @Test + void build() { + final Map map = new MapBuilder().put("foo", "bar").get(); + assertThat(map).hasSize(1); + assertThat(map.get("foo")).isNotNull(); + assertThat(map).containsEntry("foo", "bar"); + } } diff --git a/src/test/java/com/arangodb/util/UnicodeUtilsTest.java b/src/test/java/com/arangodb/util/UnicodeUtilsTest.java index 42e388837..c4b21b6de 100644 --- a/src/test/java/com/arangodb/util/UnicodeUtilsTest.java +++ b/src/test/java/com/arangodb/util/UnicodeUtilsTest.java @@ -1,17 +1,20 @@ package com.arangodb.util; import com.arangodb.internal.util.EncodeUtils; +import org.graalvm.home.Version; +import org.graalvm.nativeimage.ImageInfo; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Value; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; -public class UnicodeUtilsTest { + +class UnicodeUtilsTest { private static Context context; private static Value jsEncoder; @@ -19,37 +22,38 @@ public class UnicodeUtilsTest { private static final String encodeFn = "(function encode(x){return encodeURIComponent(x);})"; private static final String normalizeFn = "(function normalize(x){return x.normalize('NFC');})"; - @BeforeClass - public static void beforeClass() { - assumeTrue("This test requires GraalVM", org.graalvm.home.Version.getCurrent().isRelease()); + @BeforeAll + static void beforeClass() { + assumeFalse(ImageInfo.inImageCode(), "skipped in native mode"); + assumeTrue(Version.getCurrent().isRelease(), "This test requires GraalVM"); context = Context.create(); jsEncoder = context.eval("js", encodeFn); jsNormalizer = context.eval("js", normalizeFn); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { if (context != null) context.close(); } @Test - public void normalizeShouldBehaveAsJs() { + void normalizeShouldBehaveAsJs() { for (int i = 0; i < 10_000; i++) { String value = TestUtils.generateRandomDbName(100, true); String jsNormalized = jsNormalizer.execute(value).as(String.class); String javaNormalized = UnicodeUtils.normalize(value); - assertThat(javaNormalized, is(jsNormalized)); + assertThat(javaNormalized).isEqualTo(jsNormalized); } } @Test - public void encodeURIComponentShouldBehaveAsJs() { + void encodeURIComponentShouldBehaveAsJs() { for (int i = 0; i < 10_000; i++) { String value = TestUtils.generateRandomDbName(100, true); String jsEncoded = jsEncoder.execute(value).as(String.class); String driverJavaEncoded = EncodeUtils.encodeURIComponent(value); - assertThat(driverJavaEncoded, is(jsEncoded)); + assertThat(driverJavaEncoded).isEqualTo(jsEncoded); } } diff --git a/src/test/java/perf/SimpleSyncPerfTest.java b/src/test/java/perf/SimpleSyncPerfTest.java index 849f3b18e..e801659ab 100644 --- a/src/test/java/perf/SimpleSyncPerfTest.java +++ b/src/test/java/perf/SimpleSyncPerfTest.java @@ -22,55 +22,35 @@ import com.arangodb.ArangoDB; import com.arangodb.Protocol; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import com.arangodb.mapping.ArangoJack; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; -import java.util.Arrays; -import java.util.Collection; import java.util.Date; /** * @author Michele Rastelli */ -@Ignore -@RunWith(Parameterized.class) -public class SimpleSyncPerfTest { +@Disabled +class SimpleSyncPerfTest { private static final int REPETITIONS = 50_000; - private final ArangoDB arangoDB; - @Parameterized.Parameters - public static Collection protocols() { - return Arrays.asList( - Protocol.VST, - Protocol.HTTP_VPACK, - Protocol.HTTP_JSON - ); - } - - public SimpleSyncPerfTest(final Protocol protocol) { - System.out.println("---"); - System.out.println(protocol); - this.arangoDB = new ArangoDB.Builder().useProtocol(protocol).build(); - } - - @Before - public void warmup() { - doGetVersion(); - } - - private void doGetVersion() { + private void doGetVersion(ArangoDB arangoDB) { for (int i = 0; i < REPETITIONS; i++) { arangoDB.getVersion(); } } - @Test - public void getVersion() throws InterruptedException { + @ParameterizedTest + @EnumSource(Protocol.class) + void getVersion(Protocol protocol) throws InterruptedException { + ArangoDB arangoDB = new ArangoDB.Builder().useProtocol(protocol).serializer(new ArangoJack()).build(); + // warmup + doGetVersion(arangoDB); + long start = new Date().getTime(); - doGetVersion(); + doGetVersion(arangoDB); long end = new Date().getTime(); System.out.println("elapsed ms: " + (end - start)); Thread.sleep(5000); diff --git a/src/test/resources/META-INF/native-image/native-image.properties b/src/test/resources/META-INF/native-image/native-image.properties new file mode 100644 index 000000000..a18c4a2fe --- /dev/null +++ b/src/test/resources/META-INF/native-image/native-image.properties @@ -0,0 +1,3 @@ +Args=\ + -H:ResourceConfigurationFiles=test-classes/META-INF/native-image/resource-config.json \ + -H:ReflectionConfigurationResources=${.}/reflect-config.json diff --git a/src/test/resources/META-INF/native-image/reflect-config.json b/src/test/resources/META-INF/native-image/reflect-config.json new file mode 100644 index 000000000..36a06cd9d --- /dev/null +++ b/src/test/resources/META-INF/native-image/reflect-config.json @@ -0,0 +1,583 @@ +[ + { + "name": "ch.qos.logback.classic.encoder.PatternLayoutEncoder", + "allPublicMethods": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "ch.qos.logback.classic.pattern.DateConverter", + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "ch.qos.logback.classic.pattern.LevelConverter", + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "ch.qos.logback.classic.pattern.LineSeparatorConverter", + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "ch.qos.logback.classic.pattern.LoggerConverter", + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "ch.qos.logback.classic.pattern.MessageConverter", + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "ch.qos.logback.classic.pattern.ThreadConverter", + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "ch.qos.logback.core.ConsoleAppender", + "allPublicMethods": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.arangodb.ArangoCollectionTest$TestUpdateEntity", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.ArangoDatabaseTest$TransactionTestEntity", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.async.ArangoDatabaseTest$TransactionTestEntity", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.async.example.document.AqlQueryWithSpecialReturnTypesExampleTest$Gender", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.async.example.document.TestEntity", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.async.example.graph.AQLActorsAndMoviesExampleTest$Actor", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.async.example.graph.AQLActorsAndMoviesExampleTest$Movie", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.async.example.graph.Circle", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.async.example.graph.CircleEdge", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.async.example.graph.ShortestPathInAQLExampleTest$Pair", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.example.document.AqlQueryWithSpecialReturnTypesExampleTest$Gender", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.example.document.TestEntity", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.example.graph.AQLActorsAndMoviesExampleTest$Actor", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.example.graph.AQLActorsAndMoviesExampleTest$Movie", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.example.graph.Circle", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.example.graph.CircleEdge", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.example.graph.ShortestPathInAQLExampleTest$Pair", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$BinaryEntity", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allDeclaredConstructors": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$CustomAnEntity", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$CustomFilterAnnotation" + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$CustomNamingAnnotation" + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestCollection", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityA", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityArray", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityArrayInArray", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityArrayInArrayInArray", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityB", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityBaseAttributes", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityBigNumber", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityBoolean", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityByte", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityC", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityCollection", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityCollectionExtendedWithNulls", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityCollectionWithObjects", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityD", + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityDImpl", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityDate", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityDouble", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityEmpty", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityEmptyMap", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityEnum", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityFloat", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityInteger", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityLong", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityMap", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityMapStringableKey", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityMapWithObjectKey", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityObject", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityObjectInArray", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityShort", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityString", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityTyped", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEntityUUID", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.VPackSerializeDeserializeTest$TestEnum", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.annotations.DocumentFieldEntity", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.annotations.ExposeEntity", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.annotations.SerializedNameEntity", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.mapping.annotations.SerializedNameParameterEntity", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.serde.CustomSerdeTest$Person", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.serde.CustomSerdeTest$PersonDeserializer", + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.serde.CustomSerdeTest$PersonSerializer", + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredClasses": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.arangodb.serde.CustomTypeHintTest$Animal", + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.serde.CustomTypeHintTest$Gorilla", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "com.arangodb.serde.CustomTypeHintTest$Zoo", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allPublicMethods": true, + "allDeclaredConstructors": true, + "allDeclaredClasses": true + }, + { + "name": "java.util.HashSet", + "allDeclaredMethods": true, + "allDeclaredConstructors": true + } +] diff --git a/src/test/resources/META-INF/native-image/resource-config.json b/src/test/resources/META-INF/native-image/resource-config.json new file mode 100644 index 000000000..a603a885a --- /dev/null +++ b/src/test/resources/META-INF/native-image/resource-config.json @@ -0,0 +1,22 @@ +{ + "resources": { + "includes": [ + { + "pattern": "\\Qarangodb.properties\\E" + }, + { + "pattern": "\\Qarangodb-bad.properties\\E" + }, + { + "pattern": "\\Qarangodb-bad2.properties\\E" + }, + { + "pattern": "\\Qlogback-test.xml\\E" + }, + { + "pattern": "\\Qexample.truststore\\E" + } + ] + }, + "bundles": [] +}