Browse Source

Upgrade to junit-jupiter (#993)

pull/994/head
kallestenflo 5 months ago committed by GitHub
parent
commit
af031cdbb2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 28
      build.gradle
  2. 6
      json-path-assert/build.gradle
  3. 24
      json-path-assert/src/test/java/com/jayway/jsonassert/JsonAssertTest.java
  4. 8
      json-path-assert/src/test/java/com/jayway/jsonpath/matchers/DemoTest.java
  5. 4
      json-path-assert/src/test/java/com/jayway/jsonpath/matchers/HasNoJsonPathTest.java
  6. 12
      json-path-assert/src/test/java/com/jayway/jsonpath/matchers/IsJsonFileTest.java
  7. 12
      json-path-assert/src/test/java/com/jayway/jsonpath/matchers/IsJsonStringTest.java
  8. 12
      json-path-assert/src/test/java/com/jayway/jsonpath/matchers/IsJsonTest.java
  9. 12
      json-path-assert/src/test/java/com/jayway/jsonpath/matchers/JsonPathMatchersTest.java
  10. 9
      json-path-assert/src/test/java/com/jayway/jsonpath/matchers/WithJsonPathTest.java
  11. 4
      json-path-assert/src/test/java/com/jayway/jsonpath/matchers/WithoutJsonPathTest.java
  12. 12
      json-path/build.gradle
  13. 2
      json-path/src/test/java/com/jayway/jsonpath/DeepScanTest.java
  14. 10
      json-path/src/test/java/com/jayway/jsonpath/EscapeTest.java
  15. 2
      json-path/src/test/java/com/jayway/jsonpath/EvaluationListenerTest.java
  16. 14
      json-path/src/test/java/com/jayway/jsonpath/FilterCompilerTest.java
  17. 2
      json-path/src/test/java/com/jayway/jsonpath/FilterParseTest.java
  18. 2
      json-path/src/test/java/com/jayway/jsonpath/FilterTest.java
  19. 113
      json-path/src/test/java/com/jayway/jsonpath/GsonJsonProviderTest.java
  20. 163
      json-path/src/test/java/com/jayway/jsonpath/InlineFilterTest.java
  21. 2
      json-path/src/test/java/com/jayway/jsonpath/Issue_487.java
  22. 2
      json-path/src/test/java/com/jayway/jsonpath/Issue_537.java
  23. 6
      json-path/src/test/java/com/jayway/jsonpath/Issue_721.java
  24. 4
      json-path/src/test/java/com/jayway/jsonpath/Issue_762.java
  25. 2
      json-path/src/test/java/com/jayway/jsonpath/Issue_786.java
  26. 2
      json-path/src/test/java/com/jayway/jsonpath/Issue_970.java
  27. 2
      json-path/src/test/java/com/jayway/jsonpath/Issue_973.java
  28. 35
      json-path/src/test/java/com/jayway/jsonpath/JacksonJsonNodeJsonProviderMapperSupportTest.java
  29. 8
      json-path/src/test/java/com/jayway/jsonpath/JacksonJsonNodeJsonProviderTest.java
  30. 3
      json-path/src/test/java/com/jayway/jsonpath/JacksonTest.java
  31. 547
      json-path/src/test/java/com/jayway/jsonpath/JakartaJsonProviderTest.java
  32. 2
      json-path/src/test/java/com/jayway/jsonpath/JsonOrgJsonProviderTest.java
  33. 37
      json-path/src/test/java/com/jayway/jsonpath/JsonProviderTest.java
  34. 69
      json-path/src/test/java/com/jayway/jsonpath/JsonProviderTestObjectMapping.java
  35. 2
      json-path/src/test/java/com/jayway/jsonpath/MapperTest.java
  36. 7
      json-path/src/test/java/com/jayway/jsonpath/MultiPropTest.java
  37. 43
      json-path/src/test/java/com/jayway/jsonpath/OptionsTest.java
  38. 64
      json-path/src/test/java/com/jayway/jsonpath/PathCompilerTest.java
  39. 2
      json-path/src/test/java/com/jayway/jsonpath/PredicateTest.java
  40. 29
      json-path/src/test/java/com/jayway/jsonpath/ProviderInTest.java
  41. 2
      json-path/src/test/java/com/jayway/jsonpath/ReadContextTest.java
  42. 17
      json-path/src/test/java/com/jayway/jsonpath/ReturnTypeTest.java
  43. 2
      json-path/src/test/java/com/jayway/jsonpath/ScientificNotationTest.java
  44. 2
      json-path/src/test/java/com/jayway/jsonpath/TapestryJsonProviderTest.java
  45. 47
      json-path/src/test/java/com/jayway/jsonpath/TestSuppressExceptions.java
  46. 35
      json-path/src/test/java/com/jayway/jsonpath/WriteTest.java
  47. 2
      json-path/src/test/java/com/jayway/jsonpath/internal/JsonContextTest.java
  48. 126
      json-path/src/test/java/com/jayway/jsonpath/internal/UtilsTest.java
  49. 56
      json-path/src/test/java/com/jayway/jsonpath/internal/filter/PatternFlagTest.java
  50. 79
      json-path/src/test/java/com/jayway/jsonpath/internal/filter/RegexpEvaluatorTest.java
  51. 14
      json-path/src/test/java/com/jayway/jsonpath/internal/filter/RelationalOperatorTest.java
  52. 23
      json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue191.java
  53. 2
      json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue234.java
  54. 20
      json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue273.java
  55. 28
      json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue612.java
  56. 12
      json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue629.java
  57. 5
      json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue680.java
  58. 2
      json-path/src/test/java/com/jayway/jsonpath/internal/function/JSONEntityPathFunctionTest.java
  59. 2
      json-path/src/test/java/com/jayway/jsonpath/internal/function/KeySetFunctionTest.java
  60. 112
      json-path/src/test/java/com/jayway/jsonpath/internal/function/NestedFunctionTest.java
  61. 78
      json-path/src/test/java/com/jayway/jsonpath/internal/function/NumericPathFunctionTest.java
  62. 2
      json-path/src/test/java/com/jayway/jsonpath/internal/function/SequentialPathFunctionTest.java
  63. 2
      json-path/src/test/java/com/jayway/jsonpath/internal/path/PathTokenTest.java
  64. 2
      json-path/src/test/java/com/jayway/jsonpath/issue_613.java
  65. 41
      json-path/src/test/java/com/jayway/jsonpath/old/ArraySlicingTest.java
  66. 10
      json-path/src/test/java/com/jayway/jsonpath/old/ComplianceTest.java
  67. 29
      json-path/src/test/java/com/jayway/jsonpath/old/FilterTest.java
  68. 100
      json-path/src/test/java/com/jayway/jsonpath/old/IssuesTest.java
  69. 44
      json-path/src/test/java/com/jayway/jsonpath/old/JsonPathTest.java
  70. 2
      json-path/src/test/java/com/jayway/jsonpath/old/JsonProviderTest.java
  71. 12
      json-path/src/test/java/com/jayway/jsonpath/old/NullHandlingTest.java
  72. 10
      json-path/src/test/java/com/jayway/jsonpath/old/internal/ArrayIndexFilterTest.java
  73. 2
      json-path/src/test/java/com/jayway/jsonpath/old/internal/ArrayPathTokenTest.java
  74. 2
      json-path/src/test/java/com/jayway/jsonpath/old/internal/PredicatePathTokenTest.java
  75. 20
      json-path/src/test/java/com/jayway/jsonpath/old/internal/PropertyPathTokenTest.java
  76. 2
      json-path/src/test/java/com/jayway/jsonpath/old/internal/ScanPathTokenTest.java
  77. 2
      json-path/src/test/java/com/jayway/jsonpath/old/internal/TestInternal3.java

28
build.gradle

@ -13,21 +13,20 @@ buildscript {
ext {
libs = [
jsonSmart: 'net.minidev:json-smart:2.5.0',
slf4jApi: 'org.slf4j:slf4j-api:2.0.11',
gson: 'com.google.code.gson:gson:2.10.1',
hamcrest: 'org.hamcrest:hamcrest:2.2',
jsonSmart : 'net.minidev:json-smart:2.5.0',
slf4jApi : 'org.slf4j:slf4j-api:2.0.11',
gson : 'com.google.code.gson:gson:2.10.1',
hamcrest : 'org.hamcrest:hamcrest:2.2',
jacksonDatabind: 'com.fasterxml.jackson.core:jackson-databind:2.16.1',
jettison: 'org.codehaus.jettison:jettison:1.5.4',
jsonOrg: 'org.json:json:20231013',
tapestryJson: 'org.apache.tapestry:tapestry-json:5.8.3',
jakartaJsonP: 'jakarta.json:jakarta.json-api:2.0.2',
jakartaJsonB: 'jakarta.json.bind:jakarta.json.bind-api:2.0.0',
jettison : 'org.codehaus.jettison:jettison:1.5.4',
jsonOrg : 'org.json:json:20231013',
tapestryJson : 'org.apache.tapestry:tapestry-json:5.8.3',
jakartaJsonP : 'jakarta.json:jakarta.json-api:2.0.2',
jakartaJsonB : 'jakarta.json.bind:jakarta.json.bind-api:2.0.0',
test: [
test : [
'commons-io:commons-io:2.15.0',
'junit:junit:4.13.+',
'org.junit.vintage:junit-vintage-engine:5.10.+',
'org.junit.jupiter:junit-jupiter:5.10.1',
'org.assertj:assertj-core:3.25.1',
'org.hamcrest:hamcrest:2.2',
'org.glassfish:jakarta.json:2.0.1',
@ -80,9 +79,6 @@ subprojects {
test {
useJUnitPlatform()
systemProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager")
testLogging {
events "passed", "skipped", "failed"
}
@ -98,7 +94,7 @@ subprojects {
options.addStringOption('Xdoclint:none', '-quiet')
}
if(JavaVersion.current().isJava9Compatible()) {
if (JavaVersion.current().isJava9Compatible()) {
options.addBooleanOption('html5', true)
}
}

6
json-path-assert/build.gradle

@ -1,10 +1,9 @@
description = "Assertions on Json using JsonPath"
jar {
baseName 'json-path-assert'
bnd (
'Implementation-Title': 'json-path-assert', 'Implementation-Version': archiveVersion
bnd(
'Implementation-Title': 'json-path-assert', 'Implementation-Version': archiveVersion
)
}
@ -15,5 +14,4 @@ dependencies {
testImplementation libs.jsonSmart
testImplementation libs.test
testRuntimeOnly 'org.junit.vintage:junit-vintage-engine'
}

24
json-path-assert/src/test/java/com/jayway/jsonassert/JsonAssertTest.java

@ -1,11 +1,12 @@
package com.jayway.jsonassert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import static com.jayway.jsonassert.JsonAssert.*;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class JsonAssertTest {
@ -52,10 +53,10 @@ public class JsonAssertTest {
}
@Test(expected = AssertionError.class)
@Test
public void has_path() throws Exception {
with(JSON).assertNotDefined("$.store.bicycle[?(@.color == 'red' )]");
assertThrows(AssertionError.class, () -> with(JSON).assertNotDefined("$.store.bicycle[?(@.color == 'red' )]"));
}
@Test
@ -66,10 +67,10 @@ public class JsonAssertTest {
with(JSON).assertThat("$.store.bicycle[?(@.escape == 'Esc\\b\\f\\n\\r\\t\\u002A')]", is(collectionWithSize(equalTo(1))));
}
@Test(expected = AssertionError.class)
@Test
public void failed_error_message() throws Exception {
with(JSON).assertThat("$.store.book[0].category", endsWith("foobar"));
assertThrows(AssertionError.class, () -> with(JSON).assertThat("$.store.book[0].category", endsWith("foobar")));
}
@Test
@ -168,25 +169,26 @@ public class JsonAssertTest {
}
@Test(expected = AssertionError.class)
@Test
public void assert_that_invalid_path_is_thrown() {
JsonAsserter asserter = JsonAssert.with("{\"foo\":\"bar\"}");
asserter.assertEquals("$foo", "bar");
assertThrows(AssertionError.class, () -> asserter.assertEquals("$foo", "bar"));
}
@Test
public void testAssertEqualsInteger() throws Exception {
with(getResourceAsStream("lotto.json")).assertEquals("lotto.winners[0].winnerId", 23);
}
@Test(expected = AssertionError.class)
@Test
public void testAssertEqualsIntegerInvalidExpected() throws Exception {
with(getResourceAsStream("lotto.json")).assertEquals("lotto.winners[0].winnerId", 24);
assertThrows(AssertionError.class, () -> with(getResourceAsStream("lotto.json")).assertEquals("lotto.winners[0].winnerId", 24));
}
@Test(expected = AssertionError.class)
@Test
public void testAssertEqualsIntegerInvalidField() throws Exception {
with(getResourceAsStream("lotto.json")).assertEquals("lotto.winners[0].winnerId1", 24);
assertThrows(AssertionError.class, () -> with(getResourceAsStream("lotto.json")).assertEquals("lotto.winners[0].winnerId1", 24));
}
private InputStream getResourceAsStream(String resourceName) {

8
json-path-assert/src/test/java/com/jayway/jsonpath/matchers/DemoTest.java

@ -1,17 +1,17 @@
package com.jayway.jsonpath.matchers;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.io.File;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.*;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resourceAsFile;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
@Ignore
@Disabled
public class DemoTest {
@Test
public void shouldFailOnJsonString() {

4
json-path-assert/src/test/java/com/jayway/jsonpath/matchers/HasNoJsonPathTest.java

@ -1,10 +1,10 @@
package com.jayway.jsonpath.matchers;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasNoJsonPath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class HasNoJsonPathTest {
private static final String JSON_STRING = "{" +

12
json-path-assert/src/test/java/com/jayway/jsonpath/matchers/IsJsonFileTest.java

@ -5,28 +5,28 @@ import com.jayway.jsonpath.matchers.helpers.StrictParsingConfiguration;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
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.File;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.isJsonFile;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resourceAsFile;
import static com.jayway.jsonpath.matchers.helpers.TestingMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class IsJsonFileTest {
private static final File BOOKS_JSON = resourceAsFile("books.json");
private static final File INVALID_JSON = resourceAsFile("invalid.json");
@BeforeClass
@BeforeAll
public static void setupStrictJsonParsing() {
Configuration.setDefaults(new StrictParsingConfiguration());
}
@AfterClass
@AfterAll
public static void setupDefaultJsonParsing() {
Configuration.setDefaults(null);
}

12
json-path-assert/src/test/java/com/jayway/jsonpath/matchers/IsJsonStringTest.java

@ -5,25 +5,25 @@ import com.jayway.jsonpath.matchers.helpers.StrictParsingConfiguration;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
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 com.jayway.jsonpath.matchers.JsonPathMatchers.isJsonString;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource;
import static com.jayway.jsonpath.matchers.helpers.TestingMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class IsJsonStringTest {
private static final String BOOKS_JSON = resource("books.json");
@BeforeClass
@BeforeAll
public static void setupStrictJsonParsing() {
Configuration.setDefaults(new StrictParsingConfiguration());
}
@AfterClass
@AfterAll
public static void setupDefaultJsonParsing() {
Configuration.setDefaults(null);
}

12
json-path-assert/src/test/java/com/jayway/jsonpath/matchers/IsJsonTest.java

@ -6,9 +6,9 @@ import com.jayway.jsonpath.matchers.helpers.TestingMatchers;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
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.File;
@ -16,8 +16,8 @@ import static com.jayway.jsonpath.matchers.JsonPathMatchers.isJson;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resourceAsFile;
import static com.jayway.jsonpath.matchers.helpers.TestingMatchers.withPathEvaluatedTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class IsJsonTest {
private static final String VALID_JSON = resource("example.json");
@ -26,12 +26,12 @@ public class IsJsonTest {
private static final File BOOKS_JSON_FILE = resourceAsFile("books.json");
private static final Object BOOKS_JSON_PARSED = parseJson(BOOKS_JSON_STRING);
@BeforeClass
@BeforeAll
public static void setupStrictJsonParsing() {
Configuration.setDefaults(new StrictParsingConfiguration());
}
@AfterClass
@AfterAll
public static void setupDefaultJsonParsing() {
Configuration.setDefaults(null);
}

12
json-path-assert/src/test/java/com/jayway/jsonpath/matchers/JsonPathMatchersTest.java

@ -4,9 +4,9 @@ import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
import com.jayway.jsonpath.matchers.helpers.StrictParsingConfiguration;
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.File;
import java.util.List;
@ -15,21 +15,21 @@ import java.util.Map;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.*;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resourceAsFile;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class JsonPathMatchersTest {
private static final String BOOKS_JSON = resource("books.json");
private static final String INVALID_JSON = "{ invalid-json }";
private static final File BOOKS_JSON_FILE = resourceAsFile("books.json");
@BeforeClass
@BeforeAll
public static void setupStrictJsonParsing() {
// NOTE: Evaluation depends on the default configuration of JsonPath
Configuration.setDefaults(new StrictParsingConfiguration());
}
@AfterClass
@AfterAll
public static void setupDefaultJsonParsing() {
Configuration.setDefaults(null);
}

9
json-path-assert/src/test/java/com/jayway/jsonpath/matchers/WithJsonPathTest.java

@ -6,7 +6,7 @@ import com.jayway.jsonpath.ReadContext;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.List;
@ -14,8 +14,9 @@ import java.util.List;
import static com.jayway.jsonpath.JsonPath.compile;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.withJsonPath;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class WithJsonPathTest {
private static final ReadContext BOOKS_JSON = JsonPath.parse(resource("books.json"));
@ -82,9 +83,9 @@ public class WithJsonPathTest {
assertThat(BOOKS_JSON, withJsonPath("$..book[2].title", hasItem("Moby Dick")));
}
@Test(expected = InvalidPathException.class)
@Test
public void shouldFailOnInvalidJsonPath() {
withJsonPath("$[}");
assertThrows(InvalidPathException.class, () -> withJsonPath("$[}"));
}
@Test

4
json-path-assert/src/test/java/com/jayway/jsonpath/matchers/WithoutJsonPathTest.java

@ -2,12 +2,12 @@ package com.jayway.jsonpath.matchers;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static com.jayway.jsonpath.JsonPath.compile;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.withoutJsonPath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class WithoutJsonPathTest {
private static final String JSON_STRING = "{" +

12
json-path/build.gradle

@ -1,13 +1,12 @@
description = "Java port of Stefan Goessner JsonPath."
jar {
baseName 'json-path'
bnd (
'Automatic-Module-Name': 'json.path',
'Implementation-Title': 'json-path', 'Implementation-Version': archiveVersion,
'Import-Package': 'org.json.*;resolution:=optional, com.google.gson.*;resolution:=optional, com.fasterxml.jackson.*;resolution:=optional, org.apache.tapestry5.json.*;resolution:=optional, org.codehaus.jettison.*;resolution:=optional, jakarta.json.*;resolution:=optional, *',
'Export-Package': 'com.jayway.jsonpath,com.jayway.jsonpath.spi,com.jayway.jsonpath.spi.cache,com.jayway.jsonpath.spi.json,com.jayway.jsonpath.spi.mapper'
bnd(
'Automatic-Module-Name': 'json.path',
'Implementation-Title': 'json-path', 'Implementation-Version': archiveVersion,
'Import-Package': 'org.json.*;resolution:=optional, com.google.gson.*;resolution:=optional, com.fasterxml.jackson.*;resolution:=optional, org.apache.tapestry5.json.*;resolution:=optional, org.codehaus.jettison.*;resolution:=optional, jakarta.json.*;resolution:=optional, *',
'Export-Package': 'com.jayway.jsonpath,com.jayway.jsonpath.spi,com.jayway.jsonpath.spi.cache,com.jayway.jsonpath.spi.json,com.jayway.jsonpath.spi.mapper'
)
}
@ -23,5 +22,4 @@ dependencies {
compileOnly libs.jakartaJsonB// , optional
testImplementation libs.test
testRuntimeOnly 'org.junit.vintage:junit-vintage-engine'
}

2
json-path/src/test/java/com/jayway/jsonpath/DeepScanTest.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;

10
json-path/src/test/java/com/jayway/jsonpath/EscapeTest.java

@ -2,9 +2,9 @@ package com.jayway.jsonpath;
import net.minidev.json.JSONStyle;
import net.minidev.json.JSONValue;
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.assertj.core.api.Assertions.assertThat;
@ -12,13 +12,13 @@ public class EscapeTest extends BaseTest {
private static JSONStyle style;
@BeforeClass
@BeforeAll
public static void before(){
style = JSONValue.COMPRESSION;
JSONValue.COMPRESSION = JSONStyle.LT_COMPRESS;
}
@AfterClass
@AfterAll
public static void after(){
JSONValue.COMPRESSION = style;
}

2
json-path/src/test/java/com/jayway/jsonpath/EvaluationListenerTest.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;

14
json-path/src/test/java/com/jayway/jsonpath/FilterCompilerTest.java

@ -1,9 +1,10 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static com.jayway.jsonpath.internal.filter.FilterCompiler.compile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class FilterCompilerTest {
@ -60,9 +61,9 @@ public class FilterCompilerTest {
assertThat(compile("[?(@[\")]@$)]\"] == \")]@$)]\")]").toString()).isEqualTo("[?(@[\")]@$)]\"] == \")]@$)]\")]");
}
@Test(expected = InvalidPathException.class)
@Test
public void invalid_path_when_string_literal_is_unquoted() {
compile("[?(@.foo == x)]");
assertThrows(InvalidPathException.class, () -> compile("[?(@.foo == x)]"));
}
@Test
@ -86,19 +87,18 @@ public class FilterCompilerTest {
@Test
// issue #178
public void compile_and_serialize_not_exists_filter(){
public void compile_and_serialize_not_exists_filter() {
Filter compiled = compile("[?(!@.foo)]");
String serialized = compiled.toString();
assertThat(serialized).isEqualTo("[?(!@['foo'])]");
}
private void assertInvalidPathException(String filter){
private void assertInvalidPathException(String filter) {
try {
compile(filter);
throw new AssertionError("Expected " + filter + " to throw InvalidPathException");
} catch (InvalidPathException e){
} catch (InvalidPathException e) {
//e.printStackTrace();
}
}

2
json-path/src/test/java/com/jayway/jsonpath/FilterParseTest.java

@ -1,7 +1,7 @@
package com.jayway.jsonpath;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.regex.Pattern;

2
json-path/src/test/java/com/jayway/jsonpath/FilterTest.java

@ -1,7 +1,7 @@
package com.jayway.jsonpath;
import org.assertj.core.util.Lists;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;

113
json-path/src/test/java/com/jayway/jsonpath/GsonJsonProviderTest.java

@ -6,7 +6,7 @@ import com.google.gson.JsonObject;
import com.jayway.jsonpath.spi.json.GsonJsonProvider;
import com.jayway.jsonpath.spi.mapper.GsonMappingProvider;
import com.jayway.jsonpath.spi.mapper.MappingException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.math.BigDecimal;
@ -16,41 +16,42 @@ import java.util.List;
import static com.jayway.jsonpath.JsonPath.using;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class GsonJsonProviderTest extends BaseTest {
private static final String JSON =
"[" +
"{\n" +
" \"foo\" : \"foo0\",\n" +
" \"bar\" : 0,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"eric\" : \"yepp\"}" +
"}," +
"{\n" +
" \"foo\" : \"foo1\",\n" +
" \"bar\" : 1,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"eric\" : \"yepp\"}" +
"}," +
"{\n" +
" \"foo\" : \"foo2\",\n" +
" \"bar\" : 2,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"eric\" : \"yepp\"}" +
"}" +
"]";
"{\n" +
" \"foo\" : \"foo0\",\n" +
" \"bar\" : 0,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"eric\" : \"yepp\"}" +
"}," +
"{\n" +
" \"foo\" : \"foo1\",\n" +
" \"bar\" : 1,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"eric\" : \"yepp\"}" +
"}," +
"{\n" +
" \"foo\" : \"foo2\",\n" +
" \"bar\" : 2,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"eric\" : \"yepp\"}" +
"}" +
"]";
@Test
public void json_can_be_parsed() {
JsonObject node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$");
JsonObject node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$");
assertThat(node.get("string-property").getAsString()).isEqualTo("string-value");
}
@Test
public void strings_are_unwrapped() {
JsonElement node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.string-property");
String unwrapped = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.string-property", String.class);
JsonElement node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.string-property");
String unwrapped = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.string-property", String.class);
assertThat(unwrapped).isEqualTo("string-value");
assertThat(unwrapped).isEqualTo(node.getAsString());
@ -58,8 +59,8 @@ public class GsonJsonProviderTest extends BaseTest {
@Test
public void ints_are_unwrapped() {
JsonElement node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.int-max-property");
int unwrapped = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.int-max-property", int.class);
JsonElement node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.int-max-property");
int unwrapped = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.int-max-property", int.class);
assertThat(unwrapped).isEqualTo(Integer.MAX_VALUE);
assertThat(unwrapped).isEqualTo(node.getAsInt());
@ -67,8 +68,8 @@ public class GsonJsonProviderTest extends BaseTest {
@Test
public void longs_are_unwrapped() {
JsonElement node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.long-max-property");
long val = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.long-max-property", Long.class);
JsonElement node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.long-max-property");
long val = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.long-max-property", Long.class);
assertThat(val).isEqualTo(Long.MAX_VALUE);
assertThat(val).isEqualTo(node.getAsLong());
@ -78,8 +79,8 @@ public class GsonJsonProviderTest extends BaseTest {
public void doubles_are_unwrapped() {
final String json = "{double-property = 56.78}";
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.double-property");
Double val = using(GSON_CONFIGURATION).parse(json).read("$.double-property", Double.class);
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.double-property");
Double val = using(GSON_CONFIGURATION).parse(json).read("$.double-property", Double.class);
assertThat(val).isEqualTo(56.78);
assertThat(val).isEqualTo(node.getAsDouble());
@ -90,8 +91,8 @@ public class GsonJsonProviderTest extends BaseTest {
final BigDecimal bd = BigDecimal.valueOf(Long.MAX_VALUE).add(BigDecimal.valueOf(10.5));
final String json = "{bd-property = " + bd.toString() + "}";
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bd-property");
BigDecimal val = using(GSON_CONFIGURATION).parse(json).read("$.bd-property", BigDecimal.class);
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bd-property");
BigDecimal val = using(GSON_CONFIGURATION).parse(json).read("$.bd-property", BigDecimal.class);
assertThat(val).isEqualTo(bd);
assertThat(val).isEqualTo(node.getAsBigDecimal());
@ -102,8 +103,8 @@ public class GsonJsonProviderTest extends BaseTest {
final BigDecimal bd = BigDecimal.valueOf(10.5);
final String json = "{bd-property = " + bd.toString() + "}";
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bd-property");
BigDecimal val = using(GSON_CONFIGURATION).parse(json).read("$.bd-property", BigDecimal.class);
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bd-property");
BigDecimal val = using(GSON_CONFIGURATION).parse(json).read("$.bd-property", BigDecimal.class);
assertThat(val).isEqualTo(bd);
assertThat(val).isEqualTo(node.getAsBigDecimal());
@ -114,8 +115,8 @@ public class GsonJsonProviderTest extends BaseTest {
final BigInteger bi = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.TEN);
final String json = "{bi-property = " + bi.toString() + "}";
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bi-property");
BigInteger val = using(GSON_CONFIGURATION).parse(json).read("$.bi-property", BigInteger.class);
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bi-property");
BigInteger val = using(GSON_CONFIGURATION).parse(json).read("$.bi-property", BigInteger.class);
assertThat(val).isEqualTo(bi);
assertThat(val).isEqualTo(node.getAsBigInteger());
@ -126,8 +127,8 @@ public class GsonJsonProviderTest extends BaseTest {
final BigInteger bi = BigInteger.valueOf(Long.MAX_VALUE);
final String json = "{bi-property = " + bi.toString() + "}";
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bi-property");
BigInteger val = using(GSON_CONFIGURATION).parse(json).read("$.bi-property", BigInteger.class);
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bi-property");
BigInteger val = using(GSON_CONFIGURATION).parse(json).read("$.bi-property", BigInteger.class);
assertThat(val).isEqualTo(bi);
assertThat(val).isEqualTo(node.getAsBigInteger());
@ -145,7 +146,7 @@ public class GsonJsonProviderTest extends BaseTest {
@Test
public void list_of_numbers() {
JsonArray objs = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.store.book[*].display-price");
JsonArray objs = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.store.book[*].display-price");
List<Double> actual = new ArrayList<>();
for (JsonElement obj : objs) {
actual.add(obj.getAsDouble());
@ -173,36 +174,38 @@ public class GsonJsonProviderTest extends BaseTest {
@Test
public void test_type_ref() throws IOException {
TypeRef<List<FooBarBaz<Gen>>> typeRef = new TypeRef<List<FooBarBaz<Gen>>>() {};
TypeRef<List<FooBarBaz<Gen>>> typeRef = new TypeRef<List<FooBarBaz<Gen>>>() {
};
List<FooBarBaz<Gen>> list = JsonPath.using(GSON_CONFIGURATION).parse(JSON).read("$", typeRef);
assertThat(list.get(0).gen.eric).isEqualTo("yepp");
}
@Test(expected = MappingException.class)
@Test
public void test_type_ref_fail() throws IOException {
TypeRef<List<FooBarBaz<Integer>>> typeRef = new TypeRef<List<FooBarBaz<Integer>>>() {};
TypeRef<List<FooBarBaz<Integer>>> typeRef = new TypeRef<List<FooBarBaz<Integer>>>() {
};
using(GSON_CONFIGURATION).parse(JSON).read("$", typeRef);
assertThrows(MappingException.class, () -> using(GSON_CONFIGURATION).parse(JSON).read("$", typeRef));
}
@Test
// https://github.com/json-path/JsonPath/issues/351
public void no_error_when_mapping_null() throws IOException {
Configuration configuration = Configuration
.builder()
.mappingProvider(new GsonMappingProvider())
.jsonProvider(new GsonJsonProvider())
.options(Option.DEFAULT_PATH_LEAF_TO_NULL, Option.SUPPRESS_EXCEPTIONS)
.build();
String json = "{\"M\":[]}";
String result = JsonPath.using(configuration).parse(json).read("$.M[0].A[0]", String.class);
Configuration configuration = Configuration
.builder()
.mappingProvider(new GsonMappingProvider())
.jsonProvider(new GsonJsonProvider())
.options(Option.DEFAULT_PATH_LEAF_TO_NULL, Option.SUPPRESS_EXCEPTIONS)
.build();
String json = "{\"M\":[]}";
assertThat(result).isNull();
String result = JsonPath.using(configuration).parse(json).read("$.M[0].A[0]", String.class);
assertThat(result).isNull();
}
@ -225,6 +228,4 @@ public class GsonJsonProviderTest extends BaseTest {
}
}

163
json-path/src/test/java/com/jayway/jsonpath/InlineFilterTest.java

@ -1,8 +1,8 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.math.BigDecimal;
import java.util.ArrayList;
@ -14,66 +14,61 @@ import static com.jayway.jsonpath.TestUtils.assertHasOneResult;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(Parameterized.class)
public class InlineFilterTest extends BaseTest {
private static int bookCount = 4;
public static final String MULTI_STORE_JSON_DOCUMENT = "{\n" +
" \"store\" : [{\n" +
" \"name\": \"First\"," +
" \"book\" : [\n" +
" {\n" +
" \"category\" : \"reference\",\n" +
" \"author\" : \"Nigel Rees\",\n" +
" \"title\" : \"Sayings of the Century\",\n" +
" \"display-price\" : 8.95\n" +
" },\n" +
" {\n" +
" \"category\" : \"fiction\",\n" +
" \"author\" : \"Evelyn Waugh\",\n" +
" \"title\" : \"Sword of Honour\",\n" +
" \"display-price\" : 12.99\n" +
" },\n" +
" {\n" +
" \"category\" : \"fiction\",\n" +
" \"author\" : \"Herman Melville\",\n" +
" \"title\" : \"Moby Dick\",\n" +
" \"isbn\" : \"0-553-21311-3\",\n" +
" \"display-price\" : 8.99\n" +
" },\n" +
" {\n" +
" \"category\" : \"fiction\",\n" +
" \"author\" : \"J. R. R. Tolkien\",\n" +
" \"title\" : \"The Lord of the Rings\",\n" +
" \"isbn\" : \"0-395-19395-8\",\n" +
" \"display-price\" : 22.99\n" +
" }]\n" +
" },\n" +
" {\n" +
" \"name\": \"Second\",\n" +
" \"book\": [\n" +
" {\n" +
" \"category\" : \"fiction\",\n" +
" \"author\" : \"Ernest Hemmingway\",\n" +
" \"title\" : \"The Old Man and the Sea\",\n" +
" \"display-price\" : 12.99\n" +
" }]\n" +
" }]}";
private Configuration conf = Configurations.GSON_CONFIGURATION;
public InlineFilterTest(Configuration conf) {
this.conf = conf;
}
" \"store\" : [{\n" +
" \"name\": \"First\"," +
" \"book\" : [\n" +
" {\n" +
" \"category\" : \"reference\",\n" +
" \"author\" : \"Nigel Rees\",\n" +
" \"title\" : \"Sayings of the Century\",\n" +
" \"display-price\" : 8.95\n" +
" },\n" +
" {\n" +
" \"category\" : \"fiction\",\n" +
" \"author\" : \"Evelyn Waugh\",\n" +
" \"title\" : \"Sword of Honour\",\n" +
" \"display-price\" : 12.99\n" +
" },\n" +
" {\n" +
" \"category\" : \"fiction\",\n" +
" \"author\" : \"Herman Melville\",\n" +
" \"title\" : \"Moby Dick\",\n" +
" \"isbn\" : \"0-553-21311-3\",\n" +
" \"display-price\" : 8.99\n" +
" },\n" +
" {\n" +
" \"category\" : \"fiction\",\n" +
" \"author\" : \"J. R. R. Tolkien\",\n" +
" \"title\" : \"The Lord of the Rings\",\n" +
" \"isbn\" : \"0-395-19395-8\",\n" +
" \"display-price\" : 22.99\n" +
" }]\n" +
" },\n" +
" {\n" +
" \"name\": \"Second\",\n" +
" \"book\": [\n" +
" {\n" +
" \"category\" : \"fiction\",\n" +
" \"author\" : \"Ernest Hemmingway\",\n" +
" \"title\" : \"The Old Man and the Sea\",\n" +
" \"display-price\" : 12.99\n" +
" }]\n" +
" }]}";
@Parameterized.Parameters
public static Iterable<Configuration> configurations() {
return Configurations.configurations();
}
@Test
public void root_context_can_be_referred_in_predicate() {
@ParameterizedTest
@MethodSource("configurations")
public void root_context_can_be_referred_in_predicate(Configuration conf) {
List<?> prices = using(conf).parse(JSON_DOCUMENT).read("store.book[?(@.display-price <= $.max-price)].display-price", List.class);
assertThat(prices.stream().map(this::asDouble)).containsAll(asList(8.95D, 8.99D));
@ -84,8 +79,9 @@ public class InlineFilterTest extends BaseTest {
return object instanceof BigDecimal ? ((BigDecimal) object).doubleValue() : (Double) object;
}
@Test
public void multiple_context_object_can_be_refered() {
@ParameterizedTest
@MethodSource("configurations")
public void multiple_context_object_can_be_refered(Configuration conf) {
List all = using(conf).parse(JSON_DOCUMENT).read("store.book[ ?(@.category == @.category) ]", List.class);
assertThat(all.size()).isEqualTo(bookCount);
@ -104,8 +100,9 @@ public class InlineFilterTest extends BaseTest {
}
@Test
public void simple_inline_or_statement_evaluates() {
@ParameterizedTest
@MethodSource("configurations")
public void simple_inline_or_statement_evaluates(Configuration conf) {
List a = using(conf).parse(JSON_DOCUMENT).read("store.book[ ?(@.author == 'Nigel Rees' || @.author == 'Evelyn Waugh') ].author", List.class);
assertThat(a).containsExactly("Nigel Rees", "Evelyn Waugh");
@ -120,7 +117,7 @@ public class InlineFilterTest extends BaseTest {
assertThat(d).containsExactly("Nigel Rees");
}
@Test
public void no_path_ref_in_filter_hit_all() {
List<String> res = JsonPath.parse(JSON_DOCUMENT).read("$.store.book[?('a' == 'a')].author");
@ -199,18 +196,19 @@ public class InlineFilterTest extends BaseTest {
List<Integer> hits = JsonPath.parse(ints).read("$[?(@)]");
assertThat(hits).containsExactly(0,1,null,2,3);
assertThat(hits).containsExactly(0, 1, null, 2, 3);
hits = JsonPath.parse(ints).read("$[?(@ != null)]");
assertThat(hits).containsExactly(0,1,2,3);
assertThat(hits).containsExactly(0, 1, 2, 3);
List<Integer> isNull = JsonPath.parse(ints).read("$[?(!@)]");
assertThat(isNull).containsExactly(new Integer[]{});
assertThat(isNull).containsExactly(new Integer[]{});
}
@Test
public void equality_check_does_not_break_evaluation() {
@ParameterizedTest
@MethodSource("configurations")
public void equality_check_does_not_break_evaluation(Configuration conf) {
assertHasOneResult("[{\"value\":\"5\"}]", "$[?(@.value=='5')]", conf);
assertHasOneResult("[{\"value\":5}]", "$[?(@.value==5)]", conf);
@ -225,8 +223,9 @@ public class InlineFilterTest extends BaseTest {
assertHasNoResults("[{\"value\":\"5.1.26\"}]", "$[?(@.value==5.1)]", conf);
}
@Test
public void lt_check_does_not_break_evaluation() {
@ParameterizedTest
@MethodSource("configurations")
public void lt_check_does_not_break_evaluation(Configuration conf) {
assertHasOneResult("[{\"value\":\"5\"}]", "$[?(@.value<'7')]", conf);
assertHasNoResults("[{\"value\":\"7\"}]", "$[?(@.value<'5')]", conf);
@ -241,44 +240,50 @@ public class InlineFilterTest extends BaseTest {
assertHasNoResults("[{\"value\":7.1}]", "$[?(@.value<5)]", conf);
}
@Test
public void escaped_literals() {
if(conf.jsonProvider().getClass().getSimpleName().startsWith("Jackson")){
@ParameterizedTest
@MethodSource("configurations")
public void escaped_literals(Configuration conf) {
if (conf.jsonProvider().getClass().getSimpleName().startsWith("Jackson")) {
return;
}
if(conf.jsonProvider().getClass().getSimpleName().startsWith("Jakarta")){
if (conf.jsonProvider().getClass().getSimpleName().startsWith("Jakarta")) {
// single quotes are not valid in JSON; see json.org
return;
}
assertHasOneResult("[\"\\'foo\"]", "$[?(@ == '\\'foo')]", conf);
}
@Test
public void escaped_literals2() {
if(conf.jsonProvider().getClass().getSimpleName().startsWith("Jackson")){
@ParameterizedTest
@MethodSource("configurations")
public void escaped_literals2(Configuration conf) {
if (conf.jsonProvider().getClass().getSimpleName().startsWith("Jackson")) {
return;
}
assertHasOneResult("[\"\\\\'foo\"]", "$[?(@ == \"\\\\'foo\")]", conf);
}
@Test
public void escape_pattern() {
@ParameterizedTest
@MethodSource("configurations")
public void escape_pattern(Configuration conf) {
assertHasOneResult("[\"x\"]", "$[?(@ =~ /\\/|x/)]", conf);
}
@Test
public void escape_pattern_after_literal() {
@ParameterizedTest
@MethodSource("configurations")
public void escape_pattern_after_literal(Configuration conf) {
assertHasOneResult("[\"x\"]", "$[?(@ == \"abc\" || @ =~ /\\/|x/)]", conf);
}
@Test
public void escape_pattern_before_literal() {
@ParameterizedTest
@MethodSource("configurations")
public void escape_pattern_before_literal(Configuration conf) {
assertHasOneResult("[\"x\"]", "$[?(@ =~ /\\/|x/ || @ == \"abc\")]", conf);
}
@Test
public void filter_evaluation_does_not_break_path_evaluation() {
@ParameterizedTest
@MethodSource("configurations")
public void filter_evaluation_does_not_break_path_evaluation(Configuration conf) {
assertHasOneResult("[{\"s\": \"fo\", \"expected_size\": \"m\"}, {\"s\": \"lo\", \"expected_size\": 2}]", "$[?(@.s size @.expected_size)]", conf);
}
}

2
json-path/src/test/java/com/jayway/jsonpath/Issue_487.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class Issue_487 {

2
json-path/src/test/java/com/jayway/jsonpath/Issue_537.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;

6
json-path/src/test/java/com/jayway/jsonpath/Issue_721.java

@ -1,10 +1,6 @@
package com.jayway.jsonpath;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class Issue_721 {

4
json-path/src/test/java/com/jayway/jsonpath/Issue_762.java

@ -1,8 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import static com.jayway.jsonpath.BaseTest.JSON_DOCUMENT;
import org.junit.jupiter.api.Test;
/**

2
json-path/src/test/java/com/jayway/jsonpath/Issue_786.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;

2
json-path/src/test/java/com/jayway/jsonpath/Issue_970.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThatNoException;

2
json-path/src/test/java/com/jayway/jsonpath/Issue_973.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;

35
json-path/src/test/java/com/jayway/jsonpath/JacksonJsonNodeJsonProviderMapperSupportTest.java

@ -1,28 +1,23 @@
package com.jayway.jsonpath;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TextNode;
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class JacksonJsonNodeJsonProviderMapperSupportTest {
import static org.assertj.core.api.Assertions.assertThat;
private final TestData testData;
public class JacksonJsonNodeJsonProviderMapperSupportTest {
public JacksonJsonNodeJsonProviderMapperSupportTest(final TestData testData) {
this.testData = testData;
}
@Test
public void mapMethod_withJacksonJsonNodeJsonProvider_shouldUsingJsonNodeForMappingValues() {
@ParameterizedTest
@MethodSource("testDataSource")
public void mapMethod_withJacksonJsonNodeJsonProvider_shouldUsingJsonNodeForMappingValues(TestData testData) {
DocumentContext testJsonDocumentContext = cloneDocumentContext(testData.jsonDocumentContext);
testJsonDocumentContext.map(testData.jsonPath, (value, config) -> {
@ -33,16 +28,20 @@ public class JacksonJsonNodeJsonProviderMapperSupportTest {
.isEqualTo(testData.expectedUpdatedJsonDocument);
}
@Test
public void readMethod_withJacksonJsonNodeJsonProvider_shouldReturnJsonNode() {
@ParameterizedTest
@MethodSource("testDataSource")
public void readMethod_withJacksonJsonNodeJsonProvider_shouldReturnJsonNode(TestData testData) {
DocumentContext testJsonDocumentContext = cloneDocumentContext(testData.jsonDocumentContext);
final JsonNode actualJsonValue = testJsonDocumentContext.read(testData.jsonPath);
assertThat(actualJsonValue).isEqualTo(testData.expectedJsonValue);
}
@Test
public void setMethod_withJacksonJsonNodeJsonProvider_shouldAcceptJsonNode() {
@ParameterizedTest
@MethodSource("testDataSource")
public void setMethod_withJacksonJsonNodeJsonProvider_shouldAcceptJsonNode(TestData testData) {
DocumentContext testJsonDocumentContext = cloneDocumentContext(testData.jsonDocumentContext);
testJsonDocumentContext.set(testData.jsonPath, testData.newJsonValue);
@ -75,7 +74,7 @@ public class JacksonJsonNodeJsonProviderMapperSupportTest {
}
}
@Parameterized.Parameters
public static List<TestData> testDataSource() throws Exception {
final Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())

8
json-path/src/test/java/com/jayway/jsonpath/JacksonJsonNodeJsonProviderTest.java

@ -13,7 +13,9 @@ import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import com.jayway.jsonpath.spi.mapper.MappingException;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.math.BigDecimal;
@ -186,11 +188,11 @@ public class JacksonJsonNodeJsonProviderTest extends BaseTest {
assertThat(list.get(0).gen.eric).isEqualTo("yepp");
}
@Test(expected = MappingException.class)
@Test
public void test_type_ref_fail() throws IOException {
TypeRef<List<FooBarBaz<Integer>>> typeRef = new TypeRef<List<FooBarBaz<Integer>>>() {};
using(JACKSON_JSON_NODE_CONFIGURATION).parse(JSON).read("$", typeRef);
Assertions.assertThrows(MappingException.class, () -> using(JACKSON_JSON_NODE_CONFIGURATION).parse(JSON).read("$", typeRef));
}
@Test

3
json-path/src/test/java/com/jayway/jsonpath/JacksonTest.java

@ -1,7 +1,8 @@
package com.jayway.jsonpath;
import org.junit.jupiter.api.Test;
import java.util.Date;
import org.junit.Test;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonMap;

547
json-path/src/test/java/com/jayway/jsonpath/JakartaJsonProviderTest.java

@ -2,204 +2,211 @@ package com.jayway.jsonpath;
import jakarta.json.JsonObject;
import jakarta.json.JsonString;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import static com.jayway.jsonpath.JsonPath.parse;
import static com.jayway.jsonpath.JsonPath.using;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class JakartaJsonProviderTest extends BaseTest {
private static final Map<String, Object> EMPTY_MAP = emptyMap();
@Test
public void an_object_can_be_read() {
JsonObject book = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_DOCUMENT)
.read("$.store.book[0]");
assertThat(((JsonString) book.get("author")).getChars()).isEqualTo("Nigel Rees");
}
@Test
public void an_object_can_be_read_from_bytes() {
JsonObject book = using(JAKARTA_JSON_CONFIGURATION)
.parseUtf8(JSON_DOCUMENT.getBytes(UTF_8))
.read("$.store.book[0]");
assertThat(((JsonString) book.get("author")).getChars()).isEqualTo("Nigel Rees");
}
@Test
public void a_property_can_be_read() {
JsonString category = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_DOCUMENT)
.read("$.store.book[0].category");
assertThat(category.getString()).isEqualTo("reference");
}
@Test
public void a_filter_can_be_applied() {
List<Object> fictionBooks = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_DOCUMENT)
.read("$.store.book[?(@.category == 'fiction')]");
assertThat(fictionBooks.size()).isEqualTo(3);
}
@Test
public void result_can_be_mapped_to_object() {
@SuppressWarnings("unchecked")
List<Map<String, Object>> books = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_DOCUMENT)
.read("$.store.book", List.class);
assertThat(books.size()).isEqualTo(4);
}
@Test
public void read_books_with_isbn() {
List<Object> books = using(JAKARTA_JSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$..book[?(@.isbn)]");
assertThat(books.size()).isEqualTo(2);
}
/**
* Functions take parameters, the length parameter for example takes an entire document which we anticipate
* will compute to a document that is an array of elements which can determine its length.
*
* Since we translate this query from $..books.length() to length($..books) verify that this particular translation
* works as anticipated.
*/
@Test
public void read_book_length_using_translated_query() {
Integer result = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_BOOK_STORE_DOCUMENT)
.read("$..book.length()");
assertThat(result).isEqualTo(4);
}
@Test
public void read_book_length() {
Object result = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_BOOK_STORE_DOCUMENT)
.read("$.length($..book)");
assertThat(result).isEqualTo(4);
}
@Test
public void issue_97() {
String json = "{ \"books\": [ " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" } ] }";
DocumentContext dc = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(json)
.delete("$.books[?(@.category == 'reference')]");
//System.out.println((Object) dc.read("$"));
@SuppressWarnings("unchecked")
List<String> categories = dc.read("$..category", List.class);
assertThat(categories).containsOnly("fiction");
}
@Test
public void test_delete_2() {
DocumentContext dc = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse("[" +
"{\"top\": {\"middle\": null}}," +
"{\"top\": {\"middle\": {} }}," +
"{\"top\": {\"middle\": {\"bottom\": 2} }}" +
"]")
.delete(JsonPath.compile("$[*].top.middle.bottom"));
Object ans = dc.read("$");
//System.out.println(ans);
assert(ans.toString().equals("[{\"top\":{\"middle\":null}},{\"top\":{\"middle\":{}}},{\"top\":{\"middle\":{}}}]"));
}
@Test
public void an_object_can_be_read() {
JsonObject book = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_DOCUMENT)
.read("$.store.book[0]");
assertThat(((JsonString) book.get("author")).getChars()).isEqualTo("Nigel Rees");
}
@Test
public void an_object_can_be_read_from_bytes() {
JsonObject book = using(JAKARTA_JSON_CONFIGURATION)
.parseUtf8(JSON_DOCUMENT.getBytes(UTF_8))
.read("$.store.book[0]");
assertThat(((JsonString) book.get("author")).getChars()).isEqualTo("Nigel Rees");
}
@Test
public void a_property_can_be_read() {
JsonString category = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_DOCUMENT)
.read("$.store.book[0].category");
assertThat(category.getString()).isEqualTo("reference");
}
@Test
public void a_filter_can_be_applied() {
List<Object> fictionBooks = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_DOCUMENT)
.read("$.store.book[?(@.category == 'fiction')]");
assertThat(fictionBooks.size()).isEqualTo(3);
}
@Test
public void result_can_be_mapped_to_object() {
@SuppressWarnings("unchecked")
List<Map<String, Object>> books = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_DOCUMENT)
.read("$.store.book", List.class);
assertThat(books.size()).isEqualTo(4);
}
@Test
public void read_books_with_isbn() {
List<Object> books = using(JAKARTA_JSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$..book[?(@.isbn)]");
assertThat(books.size()).isEqualTo(2);
}
/**
* Functions take parameters, the length parameter for example takes an entire document which we anticipate
* will compute to a document that is an array of elements which can determine its length.
* <p>
* Since we translate this query from $..books.length() to length($..books) verify that this particular translation
* works as anticipated.
*/
@Test
public void read_book_length_using_translated_query() {
Integer result = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_BOOK_STORE_DOCUMENT)
.read("$..book.length()");
assertThat(result).isEqualTo(4);
}
@Test
public void read_book_length() {
Object result = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_BOOK_STORE_DOCUMENT)
.read("$.length($..book)");
assertThat(result).isEqualTo(4);
}
@Test
public void issue_97() {
String json = "{ \"books\": [ " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" } ] }";
DocumentContext dc = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(json)
.delete("$.books[?(@.category == 'reference')]");
//System.out.println((Object) dc.read("$"));
@SuppressWarnings("unchecked")
List<String> categories = dc.read("$..category", List.class);
assertThat(categories).containsOnly("fiction");
}
@Test
public void test_delete_2() {
DocumentContext dc = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse("[" +
"{\"top\": {\"middle\": null}}," +
"{\"top\": {\"middle\": {} }}," +
"{\"top\": {\"middle\": {\"bottom\": 2} }}" +
"]")
.delete(JsonPath.compile("$[*].top.middle.bottom"));
Object ans = dc.read("$");
//System.out.println(ans);
assert (ans.toString().equals("[{\"top\":{\"middle\":null}},{\"top\":{\"middle\":{}}},{\"top\":{\"middle\":{}}}]"));
}
@Test
public void an_root_property_can_be_updated() {
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.set("$.int-max-property", 1)
.json();
.parse(JSON_DOCUMENT)
.set("$.int-max-property", 1)
.json();
Integer result = using(JAKARTA_JSON_RW_CONFIGURATION).parse(o)
.read("$.int-max-property", Integer.class);
.read("$.int-max-property", Integer.class);
assertThat(result).isEqualTo(1);
}
@Test
public void an_deep_scan_can_update() {
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.set("$..display-price", 1)
.json();
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.set("$..display-price", 1)
.json();
List<Integer> result = using(JAKARTA_JSON_RW_CONFIGURATION).parse(o)
.read("$..display-price", new TypeRef<List<Integer>>() {});
.read("$..display-price", new TypeRef<List<Integer>>() {
});
assertThat(result).containsExactly(1, 1, 1, 1, 1);
}
@Test
public void an_filter_can_update() {
final String updatePathFunction = "$.store.book[?(@.display-price)].display-price";
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.set(updatePathFunction, 1)
.json();
final String updatePathFunction = "$.store.book[?(@.display-price)].display-price";
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.set(updatePathFunction, 1)
.json();
List<Integer> result = using(JAKARTA_JSON_RW_CONFIGURATION).parse(o)
.read(updatePathFunction, new TypeRef<List<Integer>>() {});
.read(updatePathFunction, new TypeRef<List<Integer>>() {
});
assertThat(result).containsExactly(1, 1, 1, 1);
}
@Test
public void a_path_can_be_deleted() {
final String deletePath = "$.store.book[*].display-price";
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.delete(deletePath)
.json();
final String deletePath = "$.store.book[*].display-price";
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.delete(deletePath)
.json();
List<Integer> result = using(JAKARTA_JSON_RW_CONFIGURATION).parse(o)
.read(deletePath, new TypeRef<List<Integer>>() {});
.read(deletePath, new TypeRef<List<Integer>>() {
});
assertThat(result).isEmpty();
}
@Test
public void operations_can_chained() {
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.delete("$.store.book[*].display-price")
.set("$.store.book[*].category", "A")
.json();
List<Integer> prices = using(JAKARTA_JSON_RW_CONFIGURATION).parse(o)
.read("$.store.book[*].display-price", new TypeRef<List<Integer>>() {});
.read("$.store.book[*].display-price", new TypeRef<List<Integer>>() {
});
List<String> categories = using(JAKARTA_JSON_RW_CONFIGURATION).parse(o)
.read("$.store.book[*].category", new TypeRef<List<String>>() {});
.read("$.store.book[*].category", new TypeRef<List<String>>() {
});
assertThat(prices).isEmpty();
assertThat(categories).containsExactly("A", "A", "A", "A");
@ -208,9 +215,9 @@ public class JakartaJsonProviderTest extends BaseTest {
@Test
public void an_array_index_can_be_updated() {
String res = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.set("$.store.book[0]", "a")
.read("$.store.book[0]", String.class);
.parse(JSON_DOCUMENT)
.set("$.store.book[0]", "a")
.read("$.store.book[0]", String.class);
assertThat(res).isEqualTo("a");
}
@ -218,9 +225,10 @@ public class JakartaJsonProviderTest extends BaseTest {
@Test
public void an_array_slice_can_be_updated() {
List<String> res = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.set("$.store.book[0:2]", "a")
.read("$.store.book[0:2]", new TypeRef<List<String>>() {});
.parse(JSON_DOCUMENT)
.set("$.store.book[0:2]", "a")
.read("$.store.book[0:2]", new TypeRef<List<String>>() {
});
assertThat(res).containsExactly("a", "a");
}
@ -228,9 +236,10 @@ public class JakartaJsonProviderTest extends BaseTest {
@Test
public void an_array_criteria_can_be_updated() {
List<String> res = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.parse(JSON_DOCUMENT)
.set("$.store.book[?(@.category == 'fiction')]", "a")
.read("$.store.book[?(@ == 'a')]", new TypeRef<List<String>>() {});
.read("$.store.book[?(@ == 'a')]", new TypeRef<List<String>>() {
});
assertThat(res).containsExactly("a", "a", "a");
}
@ -238,15 +247,16 @@ public class JakartaJsonProviderTest extends BaseTest {
@Test
public void an_array_criteria_can_be_deleted() {
List<String> res = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.parse(JSON_DOCUMENT)
.delete("$.store.book[?(@.category == 'fiction')]")
.read("$.store.book[*].category", new TypeRef<List<String>>() {});
.read("$.store.book[*].category", new TypeRef<List<String>>() {
});
assertThat(res).containsExactly("reference");
}
@Test
public void an_array_criteria_with_multiple_results_can_be_deleted(){
public void an_array_criteria_with_multiple_results_can_be_deleted() {
InputStream stream = this.getClass().getResourceAsStream("/json_array_multiple_delete.json");
String deletePath = "$._embedded.mandates[?(@.count=~/0/)]";
DocumentContext dc = using(JAKARTA_JSON_RW_CONFIGURATION).parse(stream).delete(deletePath);
@ -257,9 +267,10 @@ public class JakartaJsonProviderTest extends BaseTest {
@Test
public void multi_prop_delete() {
List<Map<String, Object>> res = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.delete("$.store.book[*]['author', 'category']")
.read("$.store.book[*]['author', 'category']", new TypeRef<List<Map<String, Object>>>() {});
.parse(JSON_DOCUMENT)
.delete("$.store.book[*]['author', 'category']")
.read("$.store.book[*]['author', 'category']", new TypeRef<List<Map<String, Object>>>() {
});
assertThat(res).containsExactly(EMPTY_MAP, EMPTY_MAP, EMPTY_MAP, EMPTY_MAP);
}
@ -267,124 +278,128 @@ public class JakartaJsonProviderTest extends BaseTest {
@Test
public void multi_prop_update() {
@SuppressWarnings("serial")
Map<String, Object> expected = new HashMap<String, Object>(){{
Map<String, Object> expected = new HashMap<String, Object>() {{
put("author", "a");
put("category", "a");
}};
List<Map<String, Object>> res = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.set("$.store.book[*]['author', 'category']", "a")
.read("$.store.book[*]['author', 'category']", new TypeRef<List<Map<String, Object>>>() {});
.parse(JSON_DOCUMENT)
.set("$.store.book[*]['author', 'category']", "a")
.read("$.store.book[*]['author', 'category']", new TypeRef<List<Map<String, Object>>>() {
});
assertThat(res).containsExactly(expected, expected, expected, expected);
}
@Test
public void add_to_array() {
Object res = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.add("$.store.book", 1)
.read("$.store.book[4]");
res = JAKARTA_JSON_RW_CONFIGURATION.jsonProvider().unwrap(res);
assertThat(res).isEqualTo(1);
}
@Test
public void add_to_object() {
Object res = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.put("$.store.book[0]", "new-key", "new-value")
.read("$.store.book[0].new-key");
res = JAKARTA_JSON_RW_CONFIGURATION.jsonProvider().unwrap(res);
assertThat(res).isEqualTo("new-value");
}
@Test(expected = InvalidModificationException.class)
public void add_to_object_on_array() {
using(JAKARTA_JSON_RW_CONFIGURATION).parse(JSON_DOCUMENT).put("$.store.book", "new-key", "new-value");
}
@Test(expected = InvalidModificationException.class)
public void add_to_array_on_object() {
using(JAKARTA_JSON_RW_CONFIGURATION).parse(JSON_DOCUMENT).add("$.store.book[0]", "new-value");
}
@Test
public void a_path_can_be_renamed(){
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.renameKey("$.store", "book", "updated-book")
.json();
List<Object> result = parse(o).read("$.store.updated-book");
assertThat(result).isNotEmpty();
}
@Test
public void map_array_items_can_be_renamed(){
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.renameKey("$.store.book[*]", "category", "renamed-category")
.json();
List<Object> result = parse(o).read("$.store.book[*].renamed-category");
assertThat(result).isNotEmpty();
}
@Test(expected = PathNotFoundException.class)
public void non_existent_key_rename_not_allowed() {
using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.renameKey("$", "fake", "new-fake")
.json();
}
@Test
public void single_match_value_can_be_mapped() {
MapFunction mapFunction = new ToStringMapFunction();
String stringResult = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.map("$.string-property", mapFunction)
.read("$.string-property", String.class);
assertThat(stringResult.endsWith("converted")).isTrue();
}
@Test
public void object_can_be_mapped() {
TypeRef<List<String>> typeRef = new TypeRef<List<String>>() {};
MapFunction mapFunction = new ToStringMapFunction();
DocumentContext dc = using(JAKARTA_JSON_RW_CONFIGURATION).parse(JSON_DOCUMENT);
Object list = dc.read("$..book");
assertThat(list).isInstanceOf(List.class);
Object res = dc.map("$..book", mapFunction).read("$..book", typeRef).get(0);
assertThat(res).isInstanceOf(String.class);
assertThat((String) res).endsWith("converted");
}
@Test
public void multi_match_path_can_be_mapped() {
MapFunction mapFunction = new ToStringMapFunction();
List<Double> doubleResult = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.read("$..display-price", new TypeRef<List<Double>>() {});
for (Double dRes : doubleResult){
assertThat(dRes).isInstanceOf(Double.class);
}
List<String> stringResult = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.map("$..display-price", mapFunction)
.read("$..display-price", new TypeRef<List<String>>() {});
for (String sRes : stringResult){
assertThat(sRes).isInstanceOf(String.class);
assertThat(sRes.endsWith("converted")).isTrue();
}
}
// Helper converter implementation for test cases.
private class ToStringMapFunction implements MapFunction {
@Override
public Object map(Object currentValue, Configuration configuration) {
return currentValue.toString()+"converted";
}
}
@Test
public void add_to_array() {
Object res = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.add("$.store.book", 1)
.read("$.store.book[4]");
res = JAKARTA_JSON_RW_CONFIGURATION.jsonProvider().unwrap(res);
assertThat(res).isEqualTo(1);
}
@Test
public void add_to_object() {
Object res = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.put("$.store.book[0]", "new-key", "new-value")
.read("$.store.book[0].new-key");
res = JAKARTA_JSON_RW_CONFIGURATION.jsonProvider().unwrap(res);
assertThat(res).isEqualTo("new-value");
}
@Test
public void add_to_object_on_array() {
assertThrows(InvalidModificationException.class, () -> using(JAKARTA_JSON_RW_CONFIGURATION).parse(JSON_DOCUMENT).put("$.store.book", "new-key", "new-value"));
}
@Test
public void add_to_array_on_object() {
assertThrows(InvalidModificationException.class, () -> using(JAKARTA_JSON_RW_CONFIGURATION).parse(JSON_DOCUMENT).add("$.store.book[0]", "new-value"));
}
@Test
public void a_path_can_be_renamed() {
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.renameKey("$.store", "book", "updated-book")
.json();
List<Object> result = parse(o).read("$.store.updated-book");
assertThat(result).isNotEmpty();
}
@Test
public void map_array_items_can_be_renamed() {
Object o = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.renameKey("$.store.book[*]", "category", "renamed-category")
.json();
List<Object> result = parse(o).read("$.store.book[*].renamed-category");
assertThat(result).isNotEmpty();
}
@Test
public void non_existent_key_rename_not_allowed() {
assertThrows(PathNotFoundException.class, () -> using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.renameKey("$", "fake", "new-fake")
.json());
}
@Test
public void single_match_value_can_be_mapped() {
MapFunction mapFunction = new ToStringMapFunction();
String stringResult = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.map("$.string-property", mapFunction)
.read("$.string-property", String.class);
assertThat(stringResult.endsWith("converted")).isTrue();
}
@Test
public void object_can_be_mapped() {
TypeRef<List<String>> typeRef = new TypeRef<List<String>>() {
};
MapFunction mapFunction = new ToStringMapFunction();
DocumentContext dc = using(JAKARTA_JSON_RW_CONFIGURATION).parse(JSON_DOCUMENT);
Object list = dc.read("$..book");
assertThat(list).isInstanceOf(List.class);
Object res = dc.map("$..book", mapFunction).read("$..book", typeRef).get(0);
assertThat(res).isInstanceOf(String.class);
assertThat((String) res).endsWith("converted");
}
@Test
public void multi_match_path_can_be_mapped() {
MapFunction mapFunction = new ToStringMapFunction();
List<Double> doubleResult = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.read("$..display-price", new TypeRef<List<Double>>() {
});
for (Double dRes : doubleResult) {
assertThat(dRes).isInstanceOf(Double.class);
}
List<String> stringResult = using(JAKARTA_JSON_RW_CONFIGURATION)
.parse(JSON_DOCUMENT)
.map("$..display-price", mapFunction)
.read("$..display-price", new TypeRef<List<String>>() {
});
for (String sRes : stringResult) {
assertThat(sRes).isInstanceOf(String.class);
assertThat(sRes.endsWith("converted")).isTrue();
}
}
// Helper converter implementation for test cases.
private class ToStringMapFunction implements MapFunction {
@Override
public Object map(Object currentValue, Configuration configuration) {
return currentValue.toString() + "converted";
}
}
}

2
json-path/src/test/java/com/jayway/jsonpath/JsonOrgJsonProviderTest.java

@ -4,7 +4,7 @@ import com.jayway.jsonpath.spi.json.JsonOrgJsonProvider;
import com.jayway.jsonpath.spi.mapper.JsonOrgMappingProvider;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;

37
json-path/src/test/java/com/jayway/jsonpath/JsonProviderTest.java

@ -1,44 +1,35 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static com.jayway.jsonpath.JsonPath.using;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(Parameterized.class)
public class JsonProviderTest extends BaseTest {
private final Configuration conf;
public JsonProviderTest(Configuration conf) {
this.conf = conf;
}
@Parameterized.Parameters
public static Iterable<Configuration> configurations() {
return Configurations.configurations();
}
@Test
public void strings_are_unwrapped() {
@ParameterizedTest
@MethodSource("configurations")
public void strings_are_unwrapped(Configuration conf) {
assertThat(using(conf).parse(JSON_DOCUMENT).read("$.string-property", String.class)).isEqualTo("string-value");
}
@Test
public void integers_are_unwrapped() {
@ParameterizedTest
@MethodSource("configurations")
public void integers_are_unwrapped(Configuration conf) {
assertThat(using(conf).parse(JSON_DOCUMENT).read("$.int-max-property", Integer.class)).isEqualTo(Integer.MAX_VALUE);
}
@Test
public void ints_are_unwrapped() {
@ParameterizedTest
@MethodSource("configurations")
public void ints_are_unwrapped(Configuration conf) {
assertThat(using(conf).parse(JSON_DOCUMENT).read("$.int-max-property", int.class)).isEqualTo(Integer.MAX_VALUE);
}
}

69
json-path/src/test/java/com/jayway/jsonpath/JsonProviderTestObjectMapping.java

@ -1,8 +1,7 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.io.IOException;
import java.util.List;
@ -10,53 +9,51 @@ import java.util.List;
import static com.jayway.jsonpath.JsonPath.using;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(Parameterized.class)
public class JsonProviderTestObjectMapping extends BaseTest {
private static final String JSON =
"[" +
"{\n" +
" \"foo\" : \"foo0\",\n" +
" \"bar\" : 0,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"prop\" : \"yepp0\"}" +
"}," +
"{\n" +
" \"foo\" : \"foo1\",\n" +
" \"bar\" : 1,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"prop\" : \"yepp1\"}" +
"}," +
"{\n" +
" \"foo\" : \"foo2\",\n" +
" \"bar\" : 2,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"prop\" : \"yepp2\"}" +
"}" +
"]";
private final Configuration conf;
public JsonProviderTestObjectMapping(Configuration conf) {
this.conf = conf;
}
"{\n" +
" \"foo\" : \"foo0\",\n" +
" \"bar\" : 0,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"prop\" : \"yepp0\"}" +
"}," +
"{\n" +
" \"foo\" : \"foo1\",\n" +
" \"bar\" : 1,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"prop\" : \"yepp1\"}" +
"}," +
"{\n" +
" \"foo\" : \"foo2\",\n" +
" \"bar\" : 2,\n" +
" \"baz\" : true,\n" +
" \"gen\" : {\"prop\" : \"yepp2\"}" +
"}" +
"]";
@Parameterized.Parameters
public static Iterable<Configuration> configurations() {
return Configurations.objectMappingConfigurations();
}
@Test
public void list_of_numbers() {
TypeRef<List<Double>> typeRef = new TypeRef<List<Double>>() {};
@ParameterizedTest
@MethodSource("configurations")
public void list_of_numbers(Configuration conf) {
TypeRef<List<Double>> typeRef = new TypeRef<List<Double>>() {
};
assertThat(using(conf).parse(JSON_DOCUMENT).read("$.store.book[*].display-price", typeRef)).containsExactly(8.95D, 12.99D, 8.99D, 22.99D);
}
@Test
public void test_type_ref() throws IOException {
TypeRef<List<FooBarBaz<Sub>>> typeRef = new TypeRef<List<FooBarBaz<Sub>>>() {};
@ParameterizedTest
@MethodSource("configurations")
public void test_type_ref(Configuration conf) throws IOException {
TypeRef<List<FooBarBaz<Sub>>> typeRef = new TypeRef<List<FooBarBaz<Sub>>>() {
};
assertThat(using(conf).parse(JSON).read("$", typeRef)).extracting("foo").containsExactly("foo0", "foo1", "foo2");
}

2
json-path/src/test/java/com/jayway/jsonpath/MapperTest.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.math.BigInteger;

7
json-path/src/test/java/com/jayway/jsonpath/MultiPropTest.java

@ -1,6 +1,7 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
@ -48,7 +49,7 @@ public class MultiPropTest {
.containsEntry("d", null);
}
@Test(expected = PathNotFoundException.class)
@Test
public void multi_props_can_be_required() {
Map<String, Object> model = new HashMap<String, Object>(){{
@ -59,7 +60,7 @@ public class MultiPropTest {
Configuration conf = Configuration.defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES);
using(conf).parse(model).read("$['a', 'x']", Map.class);
Assertions.assertThrows(PathNotFoundException.class, () -> using(conf).parse(model).read("$['a', 'x']", Map.class));
}
@Test

43
json-path/src/test/java/com/jayway/jsonpath/OptionsTest.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
@ -13,15 +13,16 @@ import static java.util.Arrays.asList;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class OptionsTest extends BaseTest {
@Test(expected = PathNotFoundException.class)
@Test
public void a_leafs_is_not_defaulted_to_null() {
Configuration conf = Configuration.defaultConfiguration();
assertThat((String)using(conf).parse("{\"foo\" : \"bar\"}").read("$.baz")).isNull();
assertThrows(PathNotFoundException.class, () -> using(conf).parse("{\"foo\" : \"bar\"}").read("$.baz"));
}
@Test
@ -37,7 +38,7 @@ public class OptionsTest extends BaseTest {
Configuration conf = Configuration.defaultConfiguration();
assertThat((String)using(conf).parse("{\"foo\" : \"bar\"}").read("$.foo")).isInstanceOf(String.class);
assertThat((String) using(conf).parse("{\"foo\" : \"bar\"}").read("$.foo")).isInstanceOf(String.class);
}
@Test
@ -45,11 +46,11 @@ public class OptionsTest extends BaseTest {
Configuration conf = Configuration.builder().options(ALWAYS_RETURN_LIST).build();
assertThat((List)using(conf).parse("{\"foo\" : \"bar\"}").read("$.foo")).isInstanceOf(List.class);
assertThat((List) using(conf).parse("{\"foo\" : \"bar\"}").read("$.foo")).isInstanceOf(List.class);
assertThat((List)using(conf).parse("{\"foo\": null}").read("$.foo")).isInstanceOf(List.class);
assertThat((List) using(conf).parse("{\"foo\": null}").read("$.foo")).isInstanceOf(List.class);
assertThat((List)using(conf).parse("{\"foo\": [1, 4, 8]}").read("$.foo")).asList()
assertThat((List) using(conf).parse("{\"foo\": [1, 4, 8]}").read("$.foo")).asList()
.containsExactly(Arrays.asList(1, 4, 8));
}
@ -61,7 +62,7 @@ public class OptionsTest extends BaseTest {
assertThat(result).hasSize(1);
assertThat(result.get(0)).isNull();
assertThat((List)using(conf).parse("{\"bar\": {\"foo\": [1, 4, 8]}}").read("$..foo")).asList()
assertThat((List) using(conf).parse("{\"bar\": {\"foo\": [1, 4, 8]}}").read("$..foo")).asList()
.containsExactly(Arrays.asList(1, 4, 8));
}
@ -69,7 +70,7 @@ public class OptionsTest extends BaseTest {
public void a_path_evaluation_is_returned_as_VALUE_by_default() {
Configuration conf = Configuration.defaultConfiguration();
assertThat((String)using(conf).parse("{\"foo\" : \"bar\"}").read("$.foo")).isEqualTo("bar");
assertThat((String) using(conf).parse("{\"foo\" : \"bar\"}").read("$.foo")).isEqualTo("bar");
}
@Test
@ -103,7 +104,7 @@ public class OptionsTest extends BaseTest {
@Test
public void when_property_is_required_exception_is_thrown() {
List<Map<String, String>> model = asList(singletonMap("a", "a-val"),singletonMap("b", "b-val"));
List<Map<String, String>> model = asList(singletonMap("a", "a-val"), singletonMap("b", "b-val"));
Configuration conf = Configuration.defaultConfiguration();
@ -112,10 +113,11 @@ public class OptionsTest extends BaseTest {
conf = conf.addOptions(Option.REQUIRE_PROPERTIES);
try{
try {
using(conf).parse(model).read("$[*].a", List.class);
fail("Should throw PathNotFoundException");
} catch (PathNotFoundException pnf){}
} catch (PathNotFoundException pnf) {
}
}
@Test
@ -131,10 +133,11 @@ public class OptionsTest extends BaseTest {
conf = conf.addOptions(Option.REQUIRE_PROPERTIES);
try{
try {
using(conf).parse(model).read("$.*.a-key", List.class);
fail("Should throw PathNotFoundException");
} catch (PathNotFoundException pnf){}
} catch (PathNotFoundException pnf) {
}
}
@ -142,20 +145,20 @@ public class OptionsTest extends BaseTest {
public void issue_suppress_exceptions_does_not_break_indefinite_evaluation() {
Configuration conf = Configuration.builder().options(SUPPRESS_EXCEPTIONS).build();
assertThat((List)using(conf).parse("{\"foo2\": [5]}").read("$..foo2[0]")).asList().containsOnly(5);
assertThat((List)using(conf).parse("{\"foo\" : {\"foo2\": [5]}}").read("$..foo2[0]")).asList().containsOnly(5);
assertThat((List)using(conf).parse("[null, [{\"foo\" : {\"foo2\": [5]}}]]").read("$..foo2[0]")).asList().containsOnly(5);
assertThat((List) using(conf).parse("{\"foo2\": [5]}").read("$..foo2[0]")).asList().containsOnly(5);
assertThat((List) using(conf).parse("{\"foo\" : {\"foo2\": [5]}}").read("$..foo2[0]")).asList().containsOnly(5);
assertThat((List) using(conf).parse("[null, [{\"foo\" : {\"foo2\": [5]}}]]").read("$..foo2[0]")).asList().containsOnly(5);
assertThat((List)using(conf).parse("[null, [{\"foo\" : {\"foo2\": [5]}}]]").read("$..foo.foo2[0]")).asList().containsOnly(5);
assertThat((List) using(conf).parse("[null, [{\"foo\" : {\"foo2\": [5]}}]]").read("$..foo.foo2[0]")).asList().containsOnly(5);
assertThat((List)using(conf).parse("{\"aoo\" : {}, \"foo\" : {\"foo2\": [5]}, \"zoo\" : {}}").read("$[*].foo2[0]")).asList().containsOnly(5);
assertThat((List) using(conf).parse("{\"aoo\" : {}, \"foo\" : {\"foo2\": [5]}, \"zoo\" : {}}").read("$[*].foo2[0]")).asList().containsOnly(5);
}
@Test
public void isbn_is_defaulted_when_option_is_provided() {
List<String> result1 = JsonPath.using(JSON_SMART_CONFIGURATION).parse(JSON_DOCUMENT).read("$.store.book.*.isbn");
assertThat(result1).containsExactly("0-553-21311-3","0-395-19395-8");
assertThat(result1).containsExactly("0-553-21311-3", "0-395-19395-8");
List<String> result2 = JsonPath.using(JSON_SMART_CONFIGURATION.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)).parse(JSON_DOCUMENT).read("$.store.book.*.isbn");

64
json-path/src/test/java/com/jayway/jsonpath/PathCompilerTest.java

@ -1,32 +1,32 @@
package com.jayway.jsonpath;
import com.jayway.jsonpath.internal.ParseContextImpl;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.List;
import static com.jayway.jsonpath.internal.path.PathCompiler.compile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class PathCompilerTest {
@Ignore("Backward compatibility <= 2.0.0")
@Test(expected = InvalidPathException.class)
@Disabled("Backward compatibility <= 2.0.0")
@Test
public void a_path_must_start_with_$_or_at() {
compile("x");
assertThrows(InvalidPathException.class, () -> compile("x"));
}
@Ignore("Backward compatibility <= 2.0.0")
@Test(expected = InvalidPathException.class)
@Disabled("Backward compatibility <= 2.0.0")
@Test
public void a_square_bracket_may_not_follow_a_period() {
compile("$.[");
assertThrows(InvalidPathException.class, () -> compile("$.["));
}
@Test(expected = InvalidPathException.class)
@Test
public void a_root_path_must_be_followed_by_period_or_bracket() {
compile("$X");
assertThrows(InvalidPathException.class, () -> compile("$X"));
}
@Test
@ -35,24 +35,24 @@ public class PathCompilerTest {
assertThat(compile("@").toString()).isEqualTo("@");
}
@Test(expected = InvalidPathException.class)
@Test
public void a_path_may_not_end_with_period() {
compile("$.");
assertThrows(InvalidPathException.class, () -> compile("$."));
}
@Test(expected = InvalidPathException.class)
@Test
public void a_path_may_not_end_with_period_2() {
compile("$.prop.");
assertThrows(InvalidPathException.class, () -> compile("$.prop."));
}
@Test(expected = InvalidPathException.class)
@Test
public void a_path_may_not_end_with_scan() {
compile("$..");
assertThrows(InvalidPathException.class, () -> compile("$.."));
}
@Test(expected = InvalidPathException.class)
@Test
public void a_path_may_not_end_with_scan_2() {
compile("$.prop..");
assertThrows(InvalidPathException.class, () -> compile("$.prop.."));
}
@Test
@ -84,9 +84,9 @@ public class PathCompilerTest {
assertThat(compile("$.aaa.bbb.ccc").toString()).isEqualTo("$['aaa']['bbb']['ccc']");
}
@Test(expected = InvalidPathException.class)
@Test
public void a_property_may_not_contain_blanks() {
assertThat(compile("$.foo bar").toString());
assertThrows(InvalidPathException.class, () -> compile("$.foo bar"));
}
@Test
@ -242,7 +242,7 @@ public class PathCompilerTest {
String json = "{\n"
+ " \"logs\": [\n"
+ " {\n"
+ " \"message\": \"\\\"it\\\"\",\n"
+ " \"message\": \"\\\"it\\\"\"\n"
+ " }\n"
+ " ]\n"
+ "}";
@ -255,7 +255,7 @@ public class PathCompilerTest {
String json = "{\n"
+ " \"logs\": [\n"
+ " {\n"
+ " \"message\": \"'it'\",\n"
+ " \"message\": \"'it'\"\n"
+ " }\n"
+ " ]\n"
+ "}";
@ -270,7 +270,7 @@ public class PathCompilerTest {
String json = "{\n"
+ " \"logs\": [\n"
+ " {\n"
+ " \"message\": \"'it'\",\n"
+ " \"message\": \"'it'\"\n"
+ " }\n"
+ " ]\n"
+ "}";
@ -304,23 +304,23 @@ public class PathCompilerTest {
assertThat(compile("$.aaa.foo(5,10,15)").toString()).isEqualTo("$['aaa'].foo(...)");
}
@Test(expected = InvalidPathException.class)
@Test
public void array_indexes_must_be_separated_by_commas() {
compile("$[0, 1, 2 4]");
assertThrows(InvalidPathException.class, () -> compile("$[0, 1, 2 4]"));
}
@Test(expected = InvalidPathException.class)
@Test
public void trailing_comma_after_list_is_not_accepted() {
compile("$['1','2',]");
assertThrows(InvalidPathException.class, () -> compile("$['1','2',]"));
}
@Test(expected = InvalidPathException.class)
@Test
public void accept_only_a_single_comma_between_indexes() {
compile("$['1', ,'3']");
assertThrows(InvalidPathException.class, () -> compile("$['1', ,'3']"));
}
@Test(expected = InvalidPathException.class)
@Test
public void property_must_be_separated_by_commas() {
compile("$['aaa'}'bbb']");
assertThrows(InvalidPathException.class, () -> compile("$['aaa'}'bbb']"));
}
}

2
json-path/src/test/java/com/jayway/jsonpath/PredicateTest.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;

29
json-path/src/test/java/com/jayway/jsonpath/ProviderInTest.java

@ -2,23 +2,14 @@ package com.jayway.jsonpath;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.gson.JsonArray;
import com.jayway.jsonpath.spi.json.GsonJsonProvider;
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.json.JakartaJsonProvider;
import com.jayway.jsonpath.spi.json.JsonOrgJsonProvider;
import com.jayway.jsonpath.spi.json.JsonSmartJsonProvider;
import com.jayway.jsonpath.spi.mapper.GsonMappingProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import com.jayway.jsonpath.spi.mapper.JakartaMappingProvider;
import com.jayway.jsonpath.spi.mapper.JsonOrgMappingProvider;
import com.jayway.jsonpath.spi.mapper.JsonSmartMappingProvider;
import com.jayway.jsonpath.spi.json.*;
import com.jayway.jsonpath.spi.mapper.*;
import org.assertj.core.util.Lists;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ProviderInTest {
private final String JSON = "[{\"foo\": \"bar\"}, {\"foo\": \"baz\"}]";
@ -33,7 +24,7 @@ public class ProviderInTest {
@Test
public void testJsonPathQuotesJackson() throws Exception {
public void testJsonPathQuotesJackson() {
final Configuration jackson = Configuration.builder().jsonProvider(new JacksonJsonProvider()).mappingProvider(new JacksonMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(jackson).parse(JSON);
@ -52,7 +43,7 @@ public class ProviderInTest {
@Test
public void testJsonPathQuotesJacksonJsonNode() throws Exception {
public void testJsonPathQuotesJacksonJsonNode() {
final Configuration jacksonJsonNode = Configuration.builder().jsonProvider(new JacksonJsonNodeJsonProvider()).mappingProvider(new JacksonMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(jacksonJsonNode).parse(JSON);
@ -70,7 +61,7 @@ public class ProviderInTest {
}
@Test
public void testJsonPathQuotesGson() throws Exception {
public void testJsonPathQuotesGson() {
final Configuration gson = Configuration.builder().jsonProvider(new GsonJsonProvider()).mappingProvider(new GsonMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(gson).parse(JSON);
@ -88,7 +79,7 @@ public class ProviderInTest {
}
@Test
public void testJsonPathQuotesJsonOrg() throws Exception {
public void testJsonPathQuotesJsonOrg() {
final Configuration jsonOrg = Configuration.builder().jsonProvider(new JsonOrgJsonProvider()).mappingProvider(new JsonOrgMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(jsonOrg).parse(JSON);
@ -106,7 +97,7 @@ public class ProviderInTest {
}
@Test
public void testJsonPathQuotesJsonSmart() throws Exception {
public void testJsonPathQuotesJsonSmart() {
final Configuration jsonSmart = Configuration.builder().jsonProvider(new JsonSmartJsonProvider()).mappingProvider(new JsonSmartMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(jsonSmart).parse(JSON);
@ -124,7 +115,7 @@ public class ProviderInTest {
}
@Test
public void testJsonPathQuotesJakarta() throws Exception {
public void testJsonPathQuotesJakarta() {
final Configuration gson = Configuration.builder().jsonProvider(new JakartaJsonProvider()).mappingProvider(new JakartaMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(gson).parse(JSON);

2
json-path/src/test/java/com/jayway/jsonpath/ReadContextTest.java

@ -1,7 +1,7 @@
package com.jayway.jsonpath;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static com.jayway.jsonpath.JsonPath.using;

17
json-path/src/test/java/com/jayway/jsonpath/ReturnTypeTest.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
@ -9,6 +9,7 @@ import static com.jayway.jsonpath.JsonPath.parse;
import static com.jayway.jsonpath.JsonPath.using;
import static com.jayway.jsonpath.Option.AS_PATH_LIST;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
@SuppressWarnings("ALL")
public class ReturnTypeTest extends BaseTest {
@ -18,7 +19,7 @@ public class ReturnTypeTest extends BaseTest {
@Test
public void assert_strings_can_be_read() {
assertThat((String)reader.read("$.string-property")).isEqualTo("string-value");
assertThat((String) reader.read("$.string-property")).isEqualTo("string-value");
}
@Test
@ -28,17 +29,17 @@ public class ReturnTypeTest extends BaseTest {
@Test
public void assert_longs_can_be_read() {
assertThat((Long)reader.read("$.long-max-property")).isEqualTo(Long.MAX_VALUE);
assertThat((Long) reader.read("$.long-max-property")).isEqualTo(Long.MAX_VALUE);
}
@Test
public void assert_boolean_values_can_be_read() {
assertThat((Boolean)reader.read("$.boolean-property")).isEqualTo(true);
assertThat((Boolean) reader.read("$.boolean-property")).isEqualTo(true);
}
@Test
public void assert_null_values_can_be_read() {
assertThat((String)reader.read("$.null-property")).isNull();
assertThat((String) reader.read("$.null-property")).isNull();
}
@Test
@ -78,8 +79,10 @@ public class ReturnTypeTest extends BaseTest {
}
@Test(expected = ClassCastException.class)
@Test
public void class_cast_exception_is_thrown_when_return_type_is_not_expected() {
List<String> list = reader.read("$.store.book[0].author");
assertThrows(ClassCastException.class, () -> {
List<String> list = reader.read("$.store.book[0].author");
});
}
}

2
json-path/src/test/java/com/jayway/jsonpath/ScientificNotationTest.java

@ -1,7 +1,7 @@
package com.jayway.jsonpath;
import com.google.gson.JsonArray;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;

2
json-path/src/test/java/com/jayway/jsonpath/TapestryJsonProviderTest.java

@ -8,7 +8,7 @@ import java.util.Map;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TapestryJsonProviderTest extends BaseTest {

47
json-path/src/test/java/com/jayway/jsonpath/TestSuppressExceptions.java

@ -2,36 +2,35 @@ package com.jayway.jsonpath;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertNull;
public class TestSuppressExceptions {
@Test
public void testSuppressExceptionsIsRespected() {
ParseContext parseContext = JsonPath.using(
new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider())
.mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS)
.build());
String json = "{}";
assertNull(parseContext.parse(json).read(JsonPath.compile("$.missing")));
}
@Test
public void testSuppressExceptionsIsRespectedPath() {
ParseContext parseContext = JsonPath.using(
new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider())
.mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS, Option.AS_PATH_LIST)
.build());
String json = "{}";
List<String> result = parseContext.parse(json).read(JsonPath.compile("$.missing"));
assertThat(result).isEmpty();
}
@Test
public void testSuppressExceptionsIsRespected() {
ParseContext parseContext = JsonPath.using(
new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider())
.mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS)
.build());
String json = "{}";
assertNull(parseContext.parse(json).read(JsonPath.compile("$.missing")));
}
@Test
public void testSuppressExceptionsIsRespectedPath() {
ParseContext parseContext = JsonPath.using(
new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider())
.mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS, Option.AS_PATH_LIST)
.build());
String json = "{}";
List<String> result = parseContext.parse(json).read(JsonPath.compile("$.missing"));
assertThat(result).isEmpty();
}
}

35
json-path/src/test/java/com/jayway/jsonpath/WriteTest.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.util.HashMap;
@ -11,6 +11,7 @@ import java.util.Map;
import static com.jayway.jsonpath.JsonPath.parse;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class WriteTest extends BaseTest {
@ -187,7 +188,7 @@ public class WriteTest extends BaseTest {
@Test
public void item_can_be_added_to_root_array() {
List<Integer> model = new LinkedList<Integer>();
List<Integer> model = new LinkedList<>();
model.add(1);
model.add(2);
@ -206,23 +207,23 @@ public class WriteTest extends BaseTest {
assertThat(newVal).isEqualTo("new-val");
}
@Test(expected = InvalidModificationException.class)
@Test
public void add_to_object_on_array() {
parse(JSON_DOCUMENT).put("$.store.book", "new-key", "new-value");
assertThrows(InvalidModificationException.class, () -> parse(JSON_DOCUMENT).put("$.store.book", "new-key", "new-value"));
}
@Test(expected = InvalidModificationException.class)
@Test
public void add_to_array_on_object() {
parse(JSON_DOCUMENT).add("$.store.book[0]", "new-value");
assertThrows(InvalidModificationException.class, () -> parse(JSON_DOCUMENT).add("$.store.book[0]", "new-value"));
}
@Test(expected = InvalidModificationException.class)
@Test
public void root_object_can_not_be_updated() {
Map model = new HashMap();
model.put("a", "a-val");
parse(model).set("$[?(@.a == 'a-val')]", 1);
assertThrows(InvalidModificationException.class, () -> parse(model).set("$[?(@.a == 'a-val')]", 1));
}
@Test
@ -247,25 +248,25 @@ public class WriteTest extends BaseTest {
assertThat(result).isNotEmpty();
}
@Test(expected = InvalidModificationException.class)
@Test
public void non_map_array_items_cannot_be_renamed(){
List<Integer> model = new LinkedList<Integer>();
List<Integer> model = new LinkedList<>();
model.add(1);
model.add(2);
parse(model).renameKey("$[*]", "oldKey", "newKey");
assertThrows(InvalidModificationException.class, () -> parse(model).renameKey("$[*]", "oldKey", "newKey"));
}
@Test(expected = InvalidModificationException.class)
@Test
public void multiple_properties_cannot_be_renamed(){
parse(JSON_DOCUMENT).renameKey("$.store.book[*]['author', 'category']", "old-key", "new-key");
assertThrows(InvalidModificationException.class, () ->parse(JSON_DOCUMENT).renameKey("$.store.book[*]['author', 'category']", "old-key", "new-key"));
}
@Test(expected = PathNotFoundException.class)
@Test
public void non_existent_key_rename_not_allowed(){
Object o = parse(JSON_DOCUMENT).renameKey("$", "fake", "new-fake").json();
assertThrows(PathNotFoundException.class, () -> parse(JSON_DOCUMENT).renameKey("$", "fake", "new-fake").json());
}
@Test(expected = InvalidModificationException.class)
@Test
public void rootCannotBeMapped(){
MapFunction mapFunction = new MapFunction() {
@Override
@ -273,7 +274,7 @@ public class WriteTest extends BaseTest {
return currentValue.toString()+"converted";
}
};
Object o = parse(JSON_DOCUMENT).map("$", mapFunction).json();
assertThrows(InvalidModificationException.class, () -> parse(JSON_DOCUMENT).map("$", mapFunction).json());
}
@Test

2
json-path/src/test/java/com/jayway/jsonpath/internal/JsonContextTest.java

@ -6,7 +6,7 @@ import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.Filter;
import com.jayway.jsonpath.JsonPath;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;

126
json-path/src/test/java/com/jayway/jsonpath/internal/UtilsTest.java

@ -1,16 +1,13 @@
package com.jayway.jsonpath.internal;
import com.jayway.jsonpath.JsonPathException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class UtilsTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void testJoin() {
@ -19,92 +16,87 @@ public class UtilsTest {
strings.add("bar");
strings.add("baz");
Assert.assertEquals("foo,bar,baz", Utils.join(",", strings));
Assert.assertEquals("", Utils.join(",", new ArrayList<String>()));
Assertions.assertEquals("foo,bar,baz", Utils.join(",", strings));
Assertions.assertEquals("", Utils.join(",", new ArrayList<String>()));
}
@Test
public void testConcat() {
Assert.assertEquals("", Utils.concat());
Assert.assertEquals("", Utils.concat(""));
Assert.assertEquals("", Utils.concat("", ""));
Assert.assertEquals("a", Utils.concat("a"));
Assert.assertEquals("a", Utils.concat("", "a", ""));
Assert.assertEquals("abc", Utils.concat("a", "b", "c"));
Assertions.assertEquals("", Utils.concat());
Assertions.assertEquals("", Utils.concat(""));
Assertions.assertEquals("", Utils.concat("", ""));
Assertions.assertEquals("a", Utils.concat("a"));
Assertions.assertEquals("a", Utils.concat("", "a", ""));
Assertions.assertEquals("abc", Utils.concat("a", "b", "c"));
}
@Test
public void testEscape() {
Assert.assertNull(Utils.escape(null, true));
Assertions.assertNull(Utils.escape(null, true));
Assert.assertEquals("\\\\f\\'o\\\"o\\rb\\fa\\t\\nr\\bb\\/a",
Utils.escape("\\f\'o\"o\rb\fa\t\nr\bb/a", true));
Assert.assertEquals("\\uFFFF\\u0FFF\\u00FF\\u000F\\u0010",
Utils.escape("\uffff\u0fff\u00ff\u000f\u0010", true));
Assertions.assertEquals("\\\\f\\'o\\\"o\\rb\\fa\\t\\nr\\bb\\/a", Utils.escape("\\f\'o\"o\rb\fa\t\nr\bb/a", true));
Assertions.assertEquals("\\uFFFF\\u0FFF\\u00FF\\u000F\\u0010", Utils.escape("\uffff\u0fff\u00ff\u000f\u0010", true));
}
@Test
public void testUnescape() {
Assert.assertNull(Utils.unescape(null));
Assertions.assertNull(Utils.unescape(null));
Assert.assertEquals("foo", Utils.unescape("foo"));
Assert.assertEquals("\\", Utils.unescape("\\"));
Assert.assertEquals("\\", Utils.unescape("\\\\"));
Assert.assertEquals("\'", Utils.unescape("\\\'"));
Assert.assertEquals("\"", Utils.unescape("\\\""));
Assert.assertEquals("\r", Utils.unescape("\\r"));
Assert.assertEquals("\f", Utils.unescape("\\f"));
Assert.assertEquals("\t", Utils.unescape("\\t"));
Assert.assertEquals("\n", Utils.unescape("\\n"));
Assert.assertEquals("\b", Utils.unescape("\\b"));
Assert.assertEquals("a", Utils.unescape("\\a"));
Assert.assertEquals("\uffff", Utils.unescape("\\uffff"));
Assertions.assertEquals("foo", Utils.unescape("foo"));
Assertions.assertEquals("\\", Utils.unescape("\\"));
Assertions.assertEquals("\\", Utils.unescape("\\\\"));
Assertions.assertEquals("\'", Utils.unescape("\\\'"));
Assertions.assertEquals("\"", Utils.unescape("\\\""));
Assertions.assertEquals("\r", Utils.unescape("\\r"));
Assertions.assertEquals("\f", Utils.unescape("\\f"));
Assertions.assertEquals("\t", Utils.unescape("\\t"));
Assertions.assertEquals("\n", Utils.unescape("\\n"));
Assertions.assertEquals("\b", Utils.unescape("\\b"));
Assertions.assertEquals("a", Utils.unescape("\\a"));
Assertions.assertEquals("\uffff", Utils.unescape("\\uffff"));
}
@Test
public void testUnescapeThrow() {
thrown.expect(JsonPathException.class);
Utils.unescape("\\uuuuu");
Assertions.assertThrows(JsonPathException.class, () -> Utils.unescape("\\uuuuu"));
}
@Test
public void testHex() {
Assert.assertEquals("61", Utils.hex('a'));
Assert.assertEquals("24", Utils.hex('$'));
Assertions.assertEquals("61", Utils.hex('a'));
Assertions.assertEquals("24", Utils.hex('$'));
}
@Test
public void testIsEmpty() {
Assert.assertTrue(Utils.isEmpty(null));
Assert.assertTrue(Utils.isEmpty(""));
Assertions.assertTrue(Utils.isEmpty(null));
Assertions.assertTrue(Utils.isEmpty(""));
Assert.assertFalse(Utils.isEmpty("foo"));
Assertions.assertFalse(Utils.isEmpty("foo"));
}
@Test
public void testIndexOf() {
Assert.assertEquals(-1, Utils.indexOf("bar", "foo", 0));
Assert.assertEquals(-1, Utils.indexOf("bar", "a", 2));
Assert.assertEquals(1, Utils.indexOf("bar", "a", 0));
Assert.assertEquals(1, Utils.indexOf("bar", "a", 1));
Assertions.assertEquals(-1, Utils.indexOf("bar", "foo", 0));
Assertions.assertEquals(-1, Utils.indexOf("bar", "a", 2));
Assertions.assertEquals(1, Utils.indexOf("bar", "a", 0));
Assertions.assertEquals(1, Utils.indexOf("bar", "a", 1));
}
@Test
public void testNotNull() {
Assert.assertEquals("", Utils.notNull("", "bar", "a", "b", "c"));
Assert.assertEquals("foo", Utils.notNull("foo", "bar", "a", "b", "c"));
Assertions.assertEquals("", Utils.notNull("", "bar", "a", "b", "c"));
Assertions.assertEquals("foo", Utils.notNull("foo", "bar", "a", "b", "c"));
}
@Test
public void testNotNullThrow() {
thrown.expect(IllegalArgumentException.class);
Utils.notNull(null, "bar", "a", "b", "c");
Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.notNull(null, "bar", "a", "b", "c"));
}
@Test
public void testCloseQuietly() throws IllegalArgumentException {
thrown.expect(IllegalArgumentException.class);
Utils.notNull(null, "bar", "a", "b", "c");
Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.notNull(null, "bar", "a", "b", "c"));
}
@Test
@ -114,56 +106,50 @@ public class UtilsTest {
@Test
public void testIsTrueThrow() {
thrown.expect(IllegalArgumentException.class);
Utils.isTrue(false, "foo");
Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.isTrue(false, "foo"));
}
@Test
public void testOnlyOneIsTrueThrow1() {
thrown.expect(IllegalArgumentException.class);
Utils.onlyOneIsTrue("foo", false, false);
Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.onlyOneIsTrue("foo", false, false));
}
@Test
public void testOnlyOneIsTrueThrow2() {
thrown.expect(IllegalArgumentException.class);
Utils.onlyOneIsTrue("foo", true, true);
Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.onlyOneIsTrue("foo", true, true));
}
@Test
public void testOnlyOneIsTrueNonThrow() {
Assert.assertTrue(Utils.onlyOneIsTrueNonThrow(true));
Assertions.assertTrue(Utils.onlyOneIsTrueNonThrow(true));
Assert.assertFalse(Utils.onlyOneIsTrueNonThrow(true, true, true));
Assert.assertFalse(Utils.onlyOneIsTrueNonThrow(true, true, false));
Assert.assertFalse(Utils.onlyOneIsTrueNonThrow(false, false, false));
Assertions.assertFalse(Utils.onlyOneIsTrueNonThrow(true, true, true));
Assertions.assertFalse(Utils.onlyOneIsTrueNonThrow(true, true, false));
Assertions.assertFalse(Utils.onlyOneIsTrueNonThrow(false, false, false));
}
@Test
public void testNotEmpty() {
Assert.assertEquals("bar", Utils.notEmpty("bar", "foo", 1, 2, 3));
Assert.assertEquals("baz",
Utils.notEmpty("baz", "bar", "b", "a", "r"));
Assertions.assertEquals("bar", Utils.notEmpty("bar", "foo", 1, 2, 3));
Assertions.assertEquals("baz", Utils.notEmpty("baz", "bar", "b", "a", "r"));
}
@Test
public void testNotEmptyThrowNull() {
thrown.expect(IllegalArgumentException.class);
Utils.notEmpty(null, "foo", 1, 2, 3);
Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.notEmpty(null, "foo", 1, 2, 3));
}
@Test
public void testNotEmptyThrowLength0() {
thrown.expect(IllegalArgumentException.class);
Utils.notEmpty("", "foo", 1, 2, 3);
Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.notEmpty("", "foo", 1, 2, 3));
}
@Test
public void testToString() {
Assert.assertNull(Utils.toString(null));
Assertions.assertNull(Utils.toString(null));
Assert.assertEquals("", Utils.toString(""));
Assert.assertEquals("foo", Utils.toString("foo"));
Assert.assertEquals("123", Utils.toString(123));
Assertions.assertEquals("", Utils.toString(""));
Assertions.assertEquals("foo", Utils.toString("foo"));
Assertions.assertEquals("123", Utils.toString(123));
}
}

56
json-path/src/test/java/com/jayway/jsonpath/internal/filter/PatternFlagTest.java

@ -1,47 +1,37 @@
package com.jayway.jsonpath.internal.filter;
import com.jayway.jsonpath.BaseTest;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.stream.Stream;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
@RunWith(Parameterized.class)
public class PatternFlagTest extends BaseTest {
private final int flags;
private final String expectedFlags;
public PatternFlagTest(int flags, String expectedFlags) {
this.flags = flags;
this.expectedFlags = expectedFlags;
@ParameterizedTest
@MethodSource("testData")
public void testParseFlags(int flags, String expectedFlags) {
assertEquals(expectedFlags, PatternFlag.parseFlags(flags));
}
@Test
public void testParseFlags() {
Assert.assertEquals(expectedFlags, PatternFlag.parseFlags(flags));
}
@Parameterized.Parameters
public static Iterable data() {
return Arrays.asList(
new Object[][]{
{ 1, "d" },
{ 2, "i" },
{ 4, "x" },
{ 8, "m" },
{ 32, "s" },
{ 64, "u" },
{ 256, "U" },
{ 300, "xmsU" },
{ 13, "dxm" },
{ 7, "dix" },
{ 100, "xsu" },
{ 367, "dixmsuU" }
}
public static Stream<Arguments> testData() {
return Stream.of(
Arguments.arguments(1, "d"),
Arguments.arguments(2, "i"),
Arguments.arguments(4, "x"),
Arguments.arguments(8, "m"),
Arguments.arguments(32, "s"),
Arguments.arguments(64, "u"),
Arguments.arguments(256, "U"),
Arguments.arguments(300, "xmsU"),
Arguments.arguments(13, "dxm"),
Arguments.arguments(7, "dix"),
Arguments.arguments(100, "xsu"),
Arguments.arguments(367, "dixmsuU")
);
}
}

79
json-path/src/test/java/com/jayway/jsonpath/internal/filter/RegexpEvaluatorTest.java

@ -5,35 +5,24 @@ import com.jayway.jsonpath.Predicate;
import com.jayway.jsonpath.internal.Path;
import com.jayway.jsonpath.internal.path.CompiledPath;
import com.jayway.jsonpath.internal.path.PathTokenFactory;
import org.assertj.core.util.Maps;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
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.HashMap;
import java.util.stream.Stream;
import static com.jayway.jsonpath.internal.filter.ValueNode.*;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static com.jayway.jsonpath.internal.filter.ValueNode.*;
import static org.hamcrest.MatcherAssert.assertThat;
@RunWith(Parameterized.class)
public class RegexpEvaluatorTest extends BaseTest {
private String regexp;
private ValueNode valueNode;
private boolean expectedResult;
public RegexpEvaluatorTest(String regexp, ValueNode valueNode, boolean expectedResult) {
this.regexp = regexp;
this.valueNode = valueNode;
this.expectedResult = expectedResult;
}
@Test
public void should_evaluate_regular_expression() {
@ParameterizedTest
@MethodSource("testData")
public void should_evaluate_regular_expression(String regexp, ValueNode valueNode, boolean expectedResult) {
//given
Evaluator evaluator = EvaluatorFactory.createEvaluator(RelationalOperator.REGEX);
ValueNode patternNode = createPatternNode(regexp);
@ -46,33 +35,29 @@ public class RegexpEvaluatorTest extends BaseTest {
assertThat(result, is(equalTo(expectedResult)));
}
@Parameterized.Parameters(name="Regexp {0} for {1} node should evaluate to {2}")
public static Iterable data() {
return Arrays.asList(
new Object[][]{
{ "/true|false/", createStringNode("true", true), true },
{ "/9.*9/", createNumberNode("9979"), true },
{ "/fa.*se/", createBooleanNode("false"), true },
{ "/Eval.*or/", createClassNode(String.class), false },
{ "/JsonNode/", createJsonNode(json()), false },
{ "/PathNode/", createPathNode(path()), false },
{ "/Undefined/", createUndefinedNode(), false },
{ "/NullNode/", createNullNode(), false },
{ "/test/i", createStringNode("tEsT", true), true },
{ "/test/", createStringNode("tEsT", true), false },
{ "/\u00de/ui", createStringNode("\u00fe", true), true },
{ "/\u00de/", createStringNode("\u00fe", true), false },
{ "/\u00de/i", createStringNode("\u00fe", true), false },
{ "/test# code/", createStringNode("test", true), false },
{ "/test# code/x", createStringNode("test", true), true },
{ "/.*test.*/d", createStringNode("my\rtest", true), true },
{ "/.*test.*/", createStringNode("my\rtest", true), false },
{ "/.*tEst.*/is", createStringNode("test\ntest", true), true },
{ "/.*tEst.*/i", createStringNode("test\ntest", true), false },
{ "/^\\w+$/U", createStringNode("\u00fe", true), true },
{ "/^\\w+$/", createStringNode("\u00fe", true), false },
{ "/^test$\\ntest$/m", createStringNode("test\ntest", true), true }
}
public static Stream<Arguments> testData() {
return Stream.of(
Arguments.arguments("/true|false/", createStringNode("true", true), true),
Arguments.arguments("/9.*9/", createNumberNode("9979"), true),
Arguments.arguments("/fa.*se/", createBooleanNode("false"), true),
Arguments.arguments("/Eval.*or/", createClassNode(String.class), false),
Arguments.arguments("/JsonNode/", createJsonNode(json()), false),
Arguments.arguments("/PathNode/", createPathNode(path()), false),
Arguments.arguments("/Undefined/", createUndefinedNode(), false),
Arguments.arguments("/NullNode/", createNullNode(), false),
Arguments.arguments("/test/i", createStringNode("tEsT", true), true),
Arguments.arguments("/test/", createStringNode("tEsT", true), false),
Arguments.arguments("/\u00de/ui", createStringNode("\u00fe", true), true),
Arguments.arguments("/\u00de/", createStringNode("\u00fe", true), false),
Arguments.arguments("/\u00de/i", createStringNode("\u00fe", true), false),
Arguments.arguments("/test# code/", createStringNode("test", true), false),
Arguments.arguments("/test# code/x", createStringNode("test", true), true),
Arguments.arguments("/.*test.*/d", createStringNode("my\rtest", true), true),
Arguments.arguments("/.*test.*/", createStringNode("my\rtest", true), false),
Arguments.arguments("/.*tEst.*/is", createStringNode("test\ntest", true), true),
Arguments.arguments("/.*tEst.*/i", createStringNode("test\ntest", true), false),
Arguments.arguments("/^\\w+$/U", createStringNode("\u00fe", true), true),
Arguments.arguments("/^\\w+$/", createStringNode("\u00fe", true), false)
);
}

14
json-path/src/test/java/com/jayway/jsonpath/internal/filter/RelationalOperatorTest.java

@ -1,23 +1,23 @@
package com.jayway.jsonpath.internal.filter;
import static org.junit.Assert.*;
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.util.Locale;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class RelationalOperatorTest {
Locale locale;
@Before
@BeforeEach
public void saveDefaultLocale() {
locale = Locale.getDefault();
}
@After
@AfterEach
public void restoreDefaultLocale() {
Locale.setDefault(locale);
}

23
json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue191.java

@ -3,17 +3,16 @@ package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Configurations;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import static org.junit.Assert.assertEquals;
/**
* TDD for Issue 191
*
* <p>
* Shows aggregation across fields rather than within a single entity.
*
*/
public class Issue191 {
@ -23,45 +22,41 @@ public class Issue191 {
public void testResultSetNumericComputation() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
Long value = JsonPath.parse(stream).read("$.sum($..timestamp)", Long.class);
assertEquals("Expected the max function to consume the aggregation parameters and calculate the max over the result set",
Long.valueOf(35679716813L), value);
Assertions.assertEquals(Long.valueOf(35679716813L), value, "Expected the max function to consume the aggregation parameters and calculate the max over the result set");
}
@Test
public void testResultSetNumericComputationTail() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
Long value = JsonPath.parse(stream).read("$..timestamp.sum()", Long.class);
assertEquals("Expected the max function to consume the aggregation parameters and calculate the max over the result set",
Long.valueOf(35679716813L), value);
Assertions.assertEquals(Long.valueOf(35679716813L), value, "Expected the max function to consume the aggregation parameters and calculate the max over the result set");
}
@Test
public void testResultSetNumericComputationRecursiveReplacement() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
Long value = JsonPath.parse(stream).read("$.max($..timestamp.avg(), $..timestamp.stddev())", Long.class);
assertEquals("Expected the max function to consume the aggregation parameters and calculate the max over the result set",
Long.valueOf(1427188672L), value);
Assertions.assertEquals(Long.valueOf(1427188672L), value, "Expected the max function to consume the aggregation parameters and calculate the max over the result set");
}
@Test
public void testMultipleResultSetSums() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
Long value = JsonPath.parse(stream).read("$.sum($..timestamp, $..cpus)", Long.class);
assertEquals("Expected the max function to consume the aggregation parameters and calculate the max over the result set",
Long.valueOf(35679716835L), value);
Assertions.assertEquals(Long.valueOf(35679716835L), value, "Expected the max function to consume the aggregation parameters and calculate the max over the result set");
}
@Test
public void testConcatResultSet() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
String concatResult = JsonPath.parse(stream).read("$.concat($..state)", String.class);
assertEquals("Expected a string length to be a concat of all of the states", concatResult.length(), 806);
Assertions.assertEquals(concatResult.length(), 806, "Expected a string length to be a concat of all of the states");
}
@Test
public void testConcatWithNumericValueAsString() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
String concatResult = JsonPath.parse(stream).read("$.concat($..cpus)", String.class);
assertEquals("Expected a string length to be a concat of all of the cpus", concatResult.length(), 489);
Assertions.assertEquals(concatResult.length(), 489, "Expected a string length to be a concat of all of the cpus");
}
}

2
json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue234.java

@ -1,7 +1,7 @@
package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;

20
json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue273.java

@ -1,15 +1,13 @@
package com.jayway.jsonpath.internal.function;
import net.minidev.json.JSONArray;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import net.minidev.json.JSONArray;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class Issue273 {
@Test
public void testGetPropertyFromArray(){
public void testGetPropertyFromArray() {
String json = "[\n" +
" [\n" +
" {\n" +
@ -45,12 +43,12 @@ public class Issue273 {
" }\n" +
"]\n";
JSONArray arr = JsonPath.read(json,"$..[2].author");
assertEquals(arr.get(0), "Herman Melville");
JSONArray arr = JsonPath.read(json, "$..[2].author");
Assertions.assertEquals(arr.get(0), "Herman Melville");
}
@Test
public void testGetPropertyFromObject(){
public void testGetPropertyFromObject() {
String json = "{\n" +
" \"store\": {\n" +
" \"book\": [\n" +
@ -89,7 +87,7 @@ public class Issue273 {
" \"expensive\": 10\n" +
"}\n" +
" ";
JSONArray arr = JsonPath.read(json,"$..[2].author");
assertEquals(arr.get(0), "Herman Melville");
JSONArray arr = JsonPath.read(json, "$..[2].author");
Assertions.assertEquals(arr.get(0), "Herman Melville");
}
}

28
json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue612.java

@ -1,17 +1,11 @@
package com.jayway.jsonpath.internal.function;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.jayway.jsonpath.*;
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import org.junit.Assert;
import org.junit.Test;
import static com.jayway.jsonpath.JsonPath.using;
import static com.jayway.jsonpath.internal.path.PathCompiler.fail;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class Issue612 {
@Test
@ -22,16 +16,18 @@ public class Issue612 {
String json = "{\"1\":{\"2\":null}}";
DocumentContext documentContext = JsonPath.using(config).parse(json);
JsonPath query = JsonPath.compile("$.1.2.a.b.c");
Assert.assertNull(documentContext.read(query));
Assert.assertNull(documentContext.map(query, (object, configuration) -> object));
Assertions.assertNull(documentContext.read(query));
Assertions.assertNull(documentContext.map(query, (object, configuration) -> object));
}
@Test(expected = Exception.class)
@Test
public void test2() {
Configuration config = Configuration.builder()
.build();
String json = "{\"1\":{\"2\":null}}";
DocumentContext documentContext = JsonPath.using(config).parse(json);
JsonPath query = JsonPath.compile("$.1.2.a.b.c");
documentContext.map(query, (object, configuration) -> object);
Assertions.assertThrows(Exception.class, () -> documentContext.map(query, (object, configuration) -> object));
}
}

12
json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue629.java

@ -1,12 +1,12 @@
package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class Issue629 {
@ -15,8 +15,7 @@ public class Issue629 {
try {
JsonPath jsonPath = JsonPath.compile("$.A.B.C.D(");
fail("accepted jsonpath with unclosed parentheses");
}
catch (Exception e) {
} catch (Exception e) {
assertTrue(e.getMessage().startsWith("Arguments to function:"));
}
}
@ -26,8 +25,7 @@ public class Issue629 {
try {
JsonPath jsonPath = JsonPath.compile("$.A.B.C.sum(D()");
fail("accepted jsonpath with unclosed parentheses");
}
catch (Exception e) {
} catch (Exception e) {
assertTrue(e.getMessage().startsWith("Arguments to function:"));
}
}

5
json-path/src/test/java/com/jayway/jsonpath/internal/function/Issue680.java

@ -1,10 +1,7 @@
package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.json.JsonSmartJsonProvider;
import com.jayway.jsonpath.spi.mapper.JsonSmartMappingProvider;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;

2
json-path/src/test/java/com/jayway/jsonpath/internal/function/JSONEntityPathFunctionTest.java

@ -3,7 +3,7 @@ package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Configurations;
import net.minidev.json.JSONArray;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Verifies methods that are helper implementations of functions for manipulating JSON entities, i.e.

2
json-path/src/test/java/com/jayway/jsonpath/internal/function/KeySetFunctionTest.java

@ -3,7 +3,7 @@ package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Configurations;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashSet;

112
json-path/src/test/java/com/jayway/jsonpath/internal/function/NestedFunctionTest.java

@ -2,125 +2,139 @@ package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Configurations;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.jayway.jsonpath.JsonPath.using;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Created by matt@mjgreenwood.net on 12/10/15.
*/
@RunWith(Parameterized.class)
public class NestedFunctionTest extends BaseFunctionTest {
private static final Logger logger = LoggerFactory.getLogger(NumericPathFunctionTest.class);
private Configuration conf = Configurations.GSON_CONFIGURATION;
public NestedFunctionTest(Configuration conf) {
logger.debug("Testing with configuration {}", conf.getClass().getName());
this.conf = conf;
}
@Parameterized.Parameters
public static Iterable<Configuration> configurations() {
return Configurations.configurations();
}
@Test
public void testParameterAverageFunctionCall() {
@ParameterizedTest
@MethodSource("configurations")
public void testParameterAverageFunctionCall(Configuration conf) {
verifyMathFunction(conf, "$.avg($.numbers.min(), $.numbers.max())", 5.5);
}
@Test
public void testArrayAverageFunctionCall() {
@ParameterizedTest
@MethodSource("configurations")
public void testArrayAverageFunctionCall(Configuration conf) {
verifyMathFunction(conf, "$.numbers.avg()", 5.5);
}
/**
* This test calculates the following:
*
* <p>
* For each number in $.numbers 1 -> 10 add each number up,
* then add 1 (min), 10 (max)
*
* <p>
* Alternatively 1+2+3+4+5+6+7+8+9+10+1+10 == 66
*/
@Test
public void testArrayAverageFunctionCallWithParameters() {
@ParameterizedTest
@MethodSource("configurations")
public void testArrayAverageFunctionCallWithParameters(Configuration conf) {
verifyMathFunction(conf, "$.numbers.sum($.numbers.min(), $.numbers.max())", 66.0);
}
@Test
public void testJsonInnerArgumentArray() {
@ParameterizedTest
@MethodSource("configurations")
public void testJsonInnerArgumentArray(Configuration conf) {
verifyMathFunction(conf, "$.sum(5, 3, $.numbers.max(), 2)", 20.0);
}
@Test
public void testSimpleLiteralArgument() {
@ParameterizedTest
@MethodSource("configurations")
public void testSimpleLiteralArgument(Configuration conf) {
verifyMathFunction(conf, "$.sum(5)", 5.0);
verifyMathFunction(conf, "$.sum(50)", 50.0);
}
@Test
public void testStringConcat() {
@ParameterizedTest
@MethodSource("configurations")
public void testStringConcat(Configuration conf) {
verifyTextFunction(conf, "$.text.concat()", "abcdef");
}
@Test
public void testStringAndNumberConcat() {
@ParameterizedTest
@MethodSource("configurations")
public void testStringAndNumberConcat(Configuration conf) {
verifyTextAndNumberFunction(conf, "$.concat($.text[0], $.numbers[0])", "a1");
}
@Test
public void testStringConcatWithJSONParameter() {
@ParameterizedTest
@MethodSource("configurations")
public void testStringConcatWithJSONParameter(Configuration conf) {
verifyTextFunction(conf, "$.text.concat(\"-\", \"ghijk\")", "abcdef-ghijk");
}
@Test
public void testAppendNumber() {
@ParameterizedTest
@MethodSource("configurations")
public void testAppendNumber(Configuration conf) {
verifyMathFunction(conf, "$.numbers.append(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0).avg()", 10.0);
}
/**
* Aggregation function should ignore text values
*/
@Test
public void testAppendTextAndNumberThenSum() {
@ParameterizedTest
@MethodSource("configurations")
public void testAppendTextAndNumberThenSum(Configuration conf) {
verifyMathFunction(conf, "$.numbers.append(\"0\", \"11\").sum()", 55.0);
}
@Test
public void testErrantCloseBraceNegative() {
@ParameterizedTest
@MethodSource("configurations")
public void testErrantCloseBraceNegative(Configuration conf) {
try {
using(conf).parse(this.NUMBER_SERIES).read("$.numbers.append(0, 1, 2}).avg()");
assert(false);
}
catch (Exception e) {
assert (false);
} catch (Exception e) {
assertTrue(e.getMessage().startsWith("Unexpected close brace"));
}
}
@Test
public void testErrantCloseBracketNegative() {
@ParameterizedTest
@MethodSource("configurations")
public void testErrantCloseBracketNegative(Configuration conf) {
try {
using(conf).parse(this.NUMBER_SERIES).read("$.numbers.append(0, 1, 2]).avg()");
assert(false);
}
catch (Exception e) {
assert (false);
} catch (Exception e) {
assertTrue(e.getMessage().startsWith("Unexpected close bracket"));
}
}
@Test
public void testUnclosedFunctionCallNegative() {
@ParameterizedTest
@MethodSource("configurations")
public void testUnclosedFunctionCallNegative(Configuration conf) {
try {
using(conf).parse(this.NUMBER_SERIES).read("$.numbers.append(0, 1, 2");
assert(false);
}
catch (Exception e) {
assert (false);
} catch (Exception e) {
assertTrue(e.getMessage().startsWith("Arguments to function: 'append'"));
}
}

78
json-path/src/test/java/com/jayway/jsonpath/internal/function/NumericPathFunctionTest.java

@ -3,52 +3,40 @@ package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Configurations;
import com.jayway.jsonpath.JsonPathException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.runners.Parameterized.Parameters;
/**
* Defines functional tests around executing:
*
* <p>
* - sum
* - avg
* - stddev
*
* <p>
* for each of the above, executes the test and verifies that the results are as expected based on a static input
* and static output.
*
* <p>
* Created by mattg on 6/26/15.
*/
@RunWith(Parameterized.class)
public class NumericPathFunctionTest extends BaseFunctionTest {
private static final Logger logger = LoggerFactory.getLogger(NumericPathFunctionTest.class);
private Configuration conf = Configurations.GSON_CONFIGURATION;
public NumericPathFunctionTest(Configuration conf) {
logger.debug("Testing with configuration {}", conf.getClass().getName());
this.conf = conf;
}
@Parameters
public static Iterable<Configuration> configurations() {
return Configurations.configurations();
}
@Test
public void testAverageOfDoubles() {
@ParameterizedTest
@MethodSource("configurations")
public void testAverageOfDoubles(Configuration conf) {
verifyMathFunction(conf, "$.numbers.avg()", 5.5);
}
@Test
public void testAverageOfEmptyListNegative() {
@ParameterizedTest
@MethodSource("configurations")
public void testAverageOfEmptyListNegative(Configuration conf) {
try {
verifyMathFunction(conf, "$.empty.avg()", null);
} catch (JsonPathException e) {
@ -56,13 +44,15 @@ public class NumericPathFunctionTest extends BaseFunctionTest {
}
}
@Test
public void testSumOfDouble() {
@ParameterizedTest
@MethodSource("configurations")
public void testSumOfDouble(Configuration conf) {
verifyMathFunction(conf, "$.numbers.sum()", (10d * (10d + 1d)) / 2d);
}
@Test
public void testSumOfEmptyListNegative() {
@ParameterizedTest
@MethodSource("configurations")
public void testSumOfEmptyListNegative(Configuration conf) {
try {
verifyMathFunction(conf, "$.empty.sum()", null);
} catch (JsonPathException e) {
@ -70,13 +60,15 @@ public class NumericPathFunctionTest extends BaseFunctionTest {
}
}
@Test
public void testMaxOfDouble() {
@ParameterizedTest
@MethodSource("configurations")
public void testMaxOfDouble(Configuration conf) {
verifyMathFunction(conf, "$.numbers.max()", 10d);
}
@Test
public void testMaxOfEmptyListNegative() {
@ParameterizedTest
@MethodSource("configurations")
public void testMaxOfEmptyListNegative(Configuration conf) {
try {
verifyMathFunction(conf, "$.empty.max()", null);
} catch (JsonPathException e) {
@ -84,13 +76,15 @@ public class NumericPathFunctionTest extends BaseFunctionTest {
}
}
@Test
public void testMinOfDouble() {
@ParameterizedTest
@MethodSource("configurations")
public void testMinOfDouble(Configuration conf) {
verifyMathFunction(conf, "$.numbers.min()", 1d);
}
@Test
public void testMinOfEmptyListNegative() {
@ParameterizedTest
@MethodSource("configurations")
public void testMinOfEmptyListNegative(Configuration conf) {
try {
verifyMathFunction(conf, "$.empty.min()", null);
} catch (JsonPathException e) {
@ -99,13 +93,15 @@ public class NumericPathFunctionTest extends BaseFunctionTest {
}
@Test
public void testStdDevOfDouble() {
@ParameterizedTest
@MethodSource("configurations")
public void testStdDevOfDouble(Configuration conf) {
verifyMathFunction(conf, "$.numbers.stddev()", 2.8722813232690143d);
}
@Test
public void testStddevOfEmptyListNegative() {
@ParameterizedTest
@MethodSource("configurations")
public void testStddevOfEmptyListNegative(Configuration conf) {
try {
verifyMathFunction(conf, "$.empty.stddev()", null);
} catch (JsonPathException e) {

2
json-path/src/test/java/com/jayway/jsonpath/internal/function/SequentialPathFunctionTest.java

@ -2,7 +2,7 @@ package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Configurations;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test cases for functions

2
json-path/src/test/java/com/jayway/jsonpath/internal/path/PathTokenTest.java

@ -1,7 +1,7 @@
package com.jayway.jsonpath.internal.path;
import com.jayway.jsonpath.BaseTest;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Arrays;

2
json-path/src/test/java/com/jayway/jsonpath/issue_613.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

41
json-path/src/test/java/com/jayway/jsonpath/old/ArraySlicingTest.java

@ -2,91 +2,88 @@ package com.jayway.jsonpath.old;
import com.jayway.jsonpath.JsonPath;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
*
* If you have a list
* nums = [1, 3, 5, 7, 8, 13, 20]
* then it is possible to slice by using a notation similar to element retrieval:
*
* <p>
* nums[3] #equals 7, no slicing
* nums[:3] #equals [1, 3, 5], from index 0 (inclusive) until index 3 (exclusive)
* nums[1:5] #equals [3, 5, 7, 8]
* nums[-3:] #equals [8, 13, 20]
* nums[3:] #equals [8, 13, 20]
*
* <p>
* Note that Python allows negative list indices. The index -1 represents the last element, -2 the penultimate element, etc.
* Python also allows a step property by appending an extra colon and a value. For example:
*
* <p>
* nums[3::] #equals [7, 8, 13, 20], same as nums[3:]
* nums[::3] #equals [1, 7, 20] (starting at index 0 and getting every third element)
* nums[1:5:2] #equals [3, 7] (from index 1 until index 5 and getting every second element)
*
*/
public class ArraySlicingTest {
public static final String JSON_ARRAY = "[1, 3, 5, 7, 8, 13, 20]";
@Test
public void get_by_position(){
public void get_by_position() {
Integer result = JsonPath.read(JSON_ARRAY, "$[3]");
assertEquals(7, result.intValue());
}
@Test
public void get_from_index(){
public void get_from_index() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[:3]");
assertThat(result, Matchers.contains(1,3,5));
assertThat(result, Matchers.contains(1, 3, 5));
}
@Test
public void get_between_index(){
public void get_between_index() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[1:5]");
assertThat(result, Matchers.contains(3, 5, 7, 8));
}
@Test
public void get_between_index_2(){
public void get_between_index_2() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[0:1]");
assertThat(result, Matchers.contains(1));
}
@Test
public void get_between_index_3(){
public void get_between_index_3() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[0:2]");
assertThat(result, Matchers.contains(1,3));
assertThat(result, Matchers.contains(1, 3));
}
@Test
public void get_between_index_out_of_bounds(){
public void get_between_index_out_of_bounds() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[1:15]");
assertThat(result, Matchers.contains(3, 5, 7, 8, 13, 20));
}
@Test
public void get_from_tail_index(){
public void get_from_tail_index() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[-3:]");
assertThat(result, Matchers.contains(8, 13, 20));
}
@Test
public void get_from_tail(){
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[3:]");
public void get_from_tail() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[3:]");
assertThat(result, Matchers.contains(7, 8, 13, 20));
}
@Test
public void get_indexes(){
public void get_indexes() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[0,1,2]");
assertThat(result, Matchers.contains(1,3,5));
assertThat(result, Matchers.contains(1, 3, 5));
}
}

10
json-path/src/test/java/com/jayway/jsonpath/old/ComplianceTest.java

@ -2,14 +2,14 @@ package com.jayway.jsonpath.old;
import com.jayway.jsonpath.JsonPath;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* test defined in http://jsonpath.googlecode.com/svn/trunk/tests/jsonpath-test-js.html
@ -31,7 +31,7 @@ public class ComplianceTest {
assertThat(JsonPath.<String>read(json, "$.['c d']"), is(equalTo("e")));
assertThat(JsonPath.<List<String>>read(json, "$[*]"), hasItems("a", "b", "e"));
}
@Test
public void test_two() throws Exception {
String json = "[ 1, \"2\", 3.14, true, null ]";
@ -43,7 +43,7 @@ public class ComplianceTest {
new String("2"),
new Double(3.14),
new Boolean(true),
(Comparable)null));
(Comparable) null));
List<Object> res = JsonPath.read(json, "$[-1:]");

29
json-path/src/test/java/com/jayway/jsonpath/old/FilterTest.java

@ -1,13 +1,9 @@
package com.jayway.jsonpath.old;
import com.jayway.jsonpath.BaseTest;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Filter;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Predicate;
import com.jayway.jsonpath.*;
import com.jayway.jsonpath.spi.json.JsonProvider;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
@ -18,9 +14,9 @@ import java.util.regex.Pattern;
import static com.jayway.jsonpath.Criteria.where;
import static com.jayway.jsonpath.Filter.filter;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
public class FilterTest extends BaseTest {
@ -75,7 +71,6 @@ public class FilterTest extends BaseTest {
}
@Test
public void ne_filters_evaluates() throws Exception {
final Map<String, Object> check = new HashMap<String, Object>();
@ -270,17 +265,17 @@ public class FilterTest extends BaseTest {
Filter filter = filter(
where("first-name").is("Jock")
.and("address.state").is("Texas"));
.and("address.state").is("Texas"));
List<Map<String, Object>> jocksInTexas1 = JsonPath.read(json, "$[?]", filter);
List<Map<String, Object>> jocksInTexas2 = JsonPath.read(json, "$[?(@.first-name == 'Jock' && @.address.state == 'Texas')]");
List<Map<String, Object>> jocksInTexas2 = JsonPath.read(json, "$[?(@.first-name == 'Jock' && @.address.state == 'Texas')]");
JsonPath.parse(json).json();
assertThat((String)JsonPath.read(jocksInTexas1, "$[0].address.state"), is("Texas"));
assertThat((String)JsonPath.read(jocksInTexas1, "$[0].first-name"), is("Jock"));
assertThat((String)JsonPath.read(jocksInTexas1, "$[0].last-name"), is("Ewing"));
assertThat((String) JsonPath.read(jocksInTexas1, "$[0].address.state"), is("Texas"));
assertThat((String) JsonPath.read(jocksInTexas1, "$[0].first-name"), is("Jock"));
assertThat((String) JsonPath.read(jocksInTexas1, "$[0].last-name"), is("Ewing"));
}
@ -308,8 +303,6 @@ public class FilterTest extends BaseTest {
}
@Test
public void arrays_of_maps_can_be_filtered() throws Exception {
@ -340,7 +333,7 @@ public class FilterTest extends BaseTest {
root.put("children", asList(rootChild_A, rootChild_B, rootChild_C));
Predicate customFilter = new Predicate () {
Predicate customFilter = new Predicate() {
@Override
public boolean apply(PredicateContext ctx) {
if (ctx.configuration().jsonProvider().getMapValue(ctx.item(), "name").equals("rootGrandChild_A")) {
@ -366,7 +359,7 @@ public class FilterTest extends BaseTest {
Predicate customFilter = new Predicate() {
@Override
public boolean apply(PredicateContext ctx) {
return 1 == (Integer)ctx.item();
return 1 == (Integer) ctx.item();
}
};

100
json-path/src/test/java/com/jayway/jsonpath/old/IssuesTest.java

@ -2,14 +2,7 @@ package com.jayway.jsonpath.old;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.JsonObject;
import com.jayway.jsonpath.BaseTest;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.Filter;
import com.jayway.jsonpath.InvalidPathException;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.PathNotFoundException;
import com.jayway.jsonpath.*;
import com.jayway.jsonpath.internal.Utils;
import com.jayway.jsonpath.spi.cache.LRUCache;
import com.jayway.jsonpath.spi.json.GsonJsonProvider;
@ -22,7 +15,7 @@ import net.minidev.json.JSONAware;
import net.minidev.json.parser.JSONParser;
import org.assertj.core.api.Assertions;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.util.Collections;
@ -35,13 +28,11 @@ import static com.jayway.jsonpath.Criteria.where;
import static com.jayway.jsonpath.Filter.filter;
import static com.jayway.jsonpath.JsonPath.read;
import static com.jayway.jsonpath.JsonPath.using;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
public class IssuesTest extends BaseTest {
@ -51,7 +42,7 @@ public class IssuesTest extends BaseTest {
public void issue_143() {
String json = "{ \"foo\": { \"bar\" : \"val\" }, \"moo\": { \"cow\" : \"val\" } }";
Configuration configuration = Configuration.builder().options( Option.AS_PATH_LIST ).build();
Configuration configuration = Configuration.builder().options(Option.AS_PATH_LIST).build();
List<String> pathList = JsonPath.using(configuration).parse(json).read(JsonPath.compile("$.*.bar"));
@ -67,7 +58,7 @@ public class IssuesTest extends BaseTest {
"}}";
List<String> result = read(json, "$.p.['s', 't'].u");
assertThat(result).containsExactly("su","tu");
assertThat(result).containsExactly("su", "tu");
}
@Test
@ -86,9 +77,9 @@ public class IssuesTest extends BaseTest {
assertThat(result).isEmpty();
}
@Test(expected = InvalidPathException.class)
@Test
public void issue_114_d() {
read(JSON_BOOK_DOCUMENT, "$..book[(@.length-1)] ");
assertThrows(InvalidPathException.class, () -> read(JSON_BOOK_DOCUMENT, "$..book[(@.length-1)] "));
}
@ -121,7 +112,7 @@ public class IssuesTest extends BaseTest {
List<Integer> result = read(json, "$.datas.selling['3','206'].*");
assertThat(result).containsExactly(26452067,31625950,32381852,32489262);
assertThat(result).containsExactly(26452067, 31625950, 32381852, 32489262);
}
@Test
@ -161,10 +152,10 @@ public class IssuesTest extends BaseTest {
assertTrue(result.isEmpty());
}
@Test(expected = PathNotFoundException.class)
@Test
public void issue_11b() throws Exception {
String json = "{ \"foo\" : [] }";
read(json, "$.foo[0].uri");
assertThrows(PathNotFoundException.class, () -> read(json, "$.foo[0].uri"));
}
@Test
@ -318,13 +309,13 @@ public class IssuesTest extends BaseTest {
}
@Test(expected = PathNotFoundException.class)
@Test
public void issue_22() throws Exception {
Configuration configuration = Configuration.defaultConfiguration();
String json = "{\"a\":{\"b\":1,\"c\":2}}";
JsonPath.parse(json, configuration).read("a.d");
assertThrows(PathNotFoundException.class, () -> JsonPath.parse(json, configuration).read("a.d"));
}
@Test
@ -344,10 +335,10 @@ public class IssuesTest extends BaseTest {
assertThat(res).hasSize(1).containsNull();
}
@Test(expected = PathNotFoundException.class)
@Test
public void issue_26() throws Exception {
String json = "[{\"a\":[{\"b\":1,\"c\":2}]}]";
Object o = read(json, "$.a");
assertThrows(PathNotFoundException.class, () -> read(json, "$.a"));
}
@Test
@ -434,7 +425,7 @@ public class IssuesTest extends BaseTest {
assertEquals(Integer.valueOf(1), read(json, "$[0].a"));
}
@Test(expected = PathNotFoundException.class)
@Test
public void a_test() {
String json = "{\n" +
@ -448,7 +439,7 @@ public class IssuesTest extends BaseTest {
" \"version\": 1371160528774\n" +
"}";
Object read = read(json, "$.data.passes[0].id");
assertThrows(PathNotFoundException.class, () -> read(json, "$.data.passes[0].id"));
}
@ -471,9 +462,9 @@ public class IssuesTest extends BaseTest {
String json = "{\"test\":null}";
assertThat((String)read(json, "test")).isNull();
assertThat((String) read(json, "test")).isNull();
assertThat((String)JsonPath.using(Configuration.defaultConfiguration().setOptions(Option.SUPPRESS_EXCEPTIONS)).parse(json).read("nonExistingProperty")).isNull();
assertThat((String) JsonPath.using(Configuration.defaultConfiguration().setOptions(Option.SUPPRESS_EXCEPTIONS)).parse(json).read("nonExistingProperty")).isNull();
try {
read(json, "nonExistingProperty");
@ -498,7 +489,7 @@ public class IssuesTest extends BaseTest {
public void issue_45() {
String json = "{\"rootkey\":{\"sub.key\":\"value\"}}";
assertThat((String)read(json, "rootkey['sub.key']")).isEqualTo("value");
assertThat((String) read(json, "rootkey['sub.key']")).isEqualTo("value");
}
@Test
@ -508,7 +499,7 @@ public class IssuesTest extends BaseTest {
String json = "{\"a\": {}}";
Configuration configuration = Configuration.defaultConfiguration().setOptions(Option.SUPPRESS_EXCEPTIONS);
assertThat((String)JsonPath.using(configuration).parse(json).read("a.x")).isNull();
assertThat((String) JsonPath.using(configuration).parse(json).read("a.x")).isNull();
try {
read(json, "a.x");
@ -818,7 +809,7 @@ public class IssuesTest extends BaseTest {
assertThat(parsed.apply(createPredicateContext(noMatch))).isFalse();
}
private PredicateContext createPredicateContext(final Map<String, Integer> map){
private PredicateContext createPredicateContext(final Map<String, Integer> map) {
return new PredicateContext() {
@Override
public Object item() {
@ -827,7 +818,7 @@ public class IssuesTest extends BaseTest {
@Override
public <T> T item(Class<T> clazz) throws MappingException {
return (T)map;
return (T) map;
}
@Override
@ -951,14 +942,14 @@ public class IssuesTest extends BaseTest {
assertThat(numbers).containsExactly(8.95D, 12.99D, 8.99D, 22.99D);
}
@Test(expected = PathNotFoundException.class)
@Test
public void github_89() {
com.google.gson.JsonObject json = new JsonObject();
json.addProperty("foo", "bar");
JsonPath path = JsonPath.compile("$.foo");
String object = path.read(json);
assertThrows(PathNotFoundException.class, () -> path.read(json));
}
@ -1003,7 +994,7 @@ public class IssuesTest extends BaseTest {
}
@Test
public void issue_309(){
public void issue_309() {
String json = "{\n" +
"\"jsonArr\": [\n" +
@ -1018,27 +1009,27 @@ public class IssuesTest extends BaseTest {
DocumentContext doc = JsonPath.parse(json).set("$.jsonArr[1].name", "Jayway");
assertThat((String)doc.read("$.jsonArr[0].name")).isEqualTo("nOne");
assertThat((String)doc.read("$.jsonArr[1].name")).isEqualTo("Jayway");
assertThat((String) doc.read("$.jsonArr[0].name")).isEqualTo("nOne");
assertThat((String) doc.read("$.jsonArr[1].name")).isEqualTo("Jayway");
}
@Test
public void issue_378(){
public void issue_378() {
String json = "{\n" +
" \"nodes\": {\n" +
" \"unnamed1\": {\n" +
" \"ntpServers\": [\n" +
" \"1.2.3.4\"\n" +
" ]\n" +
" }\n" +
" }\n" +
"}";
" \"nodes\": {\n" +
" \"unnamed1\": {\n" +
" \"ntpServers\": [\n" +
" \"1.2.3.4\"\n" +
" ]\n" +
" }\n" +
" }\n" +
"}";
Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
DocumentContext ctx = JsonPath.using(configuration).parse(json);
@ -1050,7 +1041,7 @@ public class IssuesTest extends BaseTest {
//CS304 (manually written) Issue link: https://github.com/json-path/JsonPath/issues/620
@Test
public void issue_620_1(){
public void issue_620_1() {
String json = "{\n" +
" \"complexText\": {\n" +
" \"nestedFields\": [\n" +
@ -1077,12 +1068,13 @@ public class IssuesTest extends BaseTest {
"$.complexText.nestedFields[1].name," +
"$.complexText.nestedFields[0].name)";
assertThat((String)JsonPath.read(json,path1)).isEqualTo("CBA");
assertThat((String)JsonPath.read(json,path2)).isEqualTo("CBA");
assertThat((String) JsonPath.read(json, path1)).isEqualTo("CBA");
assertThat((String) JsonPath.read(json, path2)).isEqualTo("CBA");
}
//CS304 (manually written) Issue link: https://github.com/json-path/JsonPath/issues/620
@Test
public void issue_620_2(){
public void issue_620_2() {
String json = "{\n" +
" \"complexText\": {\n" +
" \"nestedFields\": [\n" +
@ -1109,7 +1101,7 @@ public class IssuesTest extends BaseTest {
boolean thrown = false;
try {
Object result = (Object) JsonPath.read(json,path1);
Object result = (Object) JsonPath.read(json, path1);
} catch (Exception e) {
thrown = true;
}

44
json-path/src/test/java/com/jayway/jsonpath/old/JsonPathTest.java

@ -1,21 +1,17 @@
package com.jayway.jsonpath.old;
import com.jayway.jsonpath.BaseTest;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.InvalidPathException;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.PathNotFoundException;
import com.jayway.jsonpath.*;
import com.jayway.jsonpath.internal.path.PathCompiler;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
public class JsonPathTest extends BaseTest {
@ -81,12 +77,10 @@ public class JsonPathTest extends BaseTest {
private final static String ARRAY_EXPAND = "[{\"parent\": \"ONE\", \"child\": {\"name\": \"NAME_ONE\"}}, [{\"parent\": \"TWO\", \"child\": {\"name\": \"NAME_TWO\"}}]]";
@Test(expected = PathNotFoundException.class)
@Test
public void missing_prop() {
//Object read = JsonPath.using(Configuration.defaultConfiguration().setOptions(Option.THROW_ON_MISSING_PROPERTY)).parse(DOCUMENT).read("$.store.book[*].fooBar");
//Object read = JsonPath.using(Configuration.defaultConfiguration()).parse(DOCUMENT).read("$.store.book[*].fooBar");
Object read2 = JsonPath.using(Configuration.defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(DOCUMENT).read("$.store.book[*].fooBar.not");
assertThrows(PathNotFoundException.class, () -> JsonPath.using(Configuration.defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(DOCUMENT).read("$.store.book[*].fooBar.not"));
}
@ -133,7 +127,7 @@ public class JsonPathTest extends BaseTest {
Assertions.fail("Expected PathNotFoundException");
} catch (PathNotFoundException e) {
}
Assertions.assertThat((String)JsonPath.read(json, "$.data2.passes[0].id")).isEqualTo("1");
Assertions.assertThat((String) JsonPath.read(json, "$.data2.passes[0].id")).isEqualTo("1");
}
@Test
@ -296,9 +290,9 @@ public class JsonPathTest extends BaseTest {
List<String> all = JsonPath.read(DOCUMENT, "$..*");
}
@Test(expected = PathNotFoundException.class)
@Test
public void access_index_out_of_bounds_does_not_throw_exception() throws Exception {
JsonPath.read(DOCUMENT, "$.store.book[100].author");
assertThrows(PathNotFoundException.class, () -> JsonPath.read(DOCUMENT, "$.store.book[100].author"));
}
@Test
@ -311,21 +305,21 @@ public class JsonPathTest extends BaseTest {
@Test
// see https://code.google.com/p/json-path/issues/detail?id=58
public void invalid_paths_throw_invalid_path_exception() throws Exception {
for (String path : new String[]{"$.", "$.results[?"}){
try{
JsonPath.compile(path);
} catch (InvalidPathException e){
// that's expected
} catch (Exception e){
fail("Expected an InvalidPathException trying to compile '"+path+"', but got a "+e.getClass().getName());
}
for (String path : new String[]{"$.", "$.results[?"}) {
try {
JsonPath.compile(path);
} catch (InvalidPathException e) {
// that's expected
} catch (Exception e) {
fail("Expected an InvalidPathException trying to compile '" + path + "', but got a " + e.getClass().getName());
}
}
}
@Test(expected = InvalidPathException.class)
@Test
//see https://github.com/json-path/JsonPath/issues/428
public void prevent_stack_overflow_error_when_unclosed_property() {
JsonPath.compile("$['boo','foo][?(@ =~ /bar/)]");
assertThrows(InvalidPathException.class, () -> JsonPath.compile("$['boo','foo][?(@ =~ /bar/)]"));
}
}

2
json-path/src/test/java/com/jayway/jsonpath/old/JsonProviderTest.java

@ -1,7 +1,7 @@
package com.jayway.jsonpath.old;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class JsonProviderTest {

12
json-path/src/test/java/com/jayway/jsonpath/old/NullHandlingTest.java

@ -5,12 +5,12 @@ import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.PathNotFoundException;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class NullHandlingTest {
@ -36,9 +36,9 @@ public class NullHandlingTest {
"}";
@Test(expected = PathNotFoundException.class)
@Test
public void not_defined_property_throws_PathNotFoundException() {
JsonPath.read(DOCUMENT, "$.children[0].child.age");
assertThrows(PathNotFoundException.class, () -> JsonPath.read(DOCUMENT, "$.children[0].child.age"));
}
@ -53,7 +53,7 @@ public class NullHandlingTest {
@Test
public void null_property_returns_null() {
Integer age = JsonPath.read(DOCUMENT, "$.children[1].age");
assertEquals(null, age);
assertNull(age);
}
@Test

10
json-path/src/test/java/com/jayway/jsonpath/old/internal/ArrayIndexFilterTest.java

@ -1,19 +1,17 @@
package com.jayway.jsonpath.old.internal;
import com.jayway.jsonpath.JsonPath;
import org.junit.Assert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ArrayIndexFilterTest {
private static final String JSON = "[1, 3, 5, 7, 8, 13, 20]";
private static final String JSON = "[1, 3, 5, 7, 8, 13, 20]";
@Test
public void tail_does_not_throw_when_index_out_of_bounds() {
@ -49,7 +47,7 @@ public class ArrayIndexFilterTest {
@Test
public void can_access_items_from_end_with_negative_index() {
int result = JsonPath.parse(JSON).read("$[-3]");
Assert.assertEquals(8, result);
assertEquals(8, result);
}
}

2
json-path/src/test/java/com/jayway/jsonpath/old/internal/ArrayPathTokenTest.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath.old.internal;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;

2
json-path/src/test/java/com/jayway/jsonpath/old/internal/PredicatePathTokenTest.java

@ -2,7 +2,7 @@ package com.jayway.jsonpath.old.internal;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;

20
json-path/src/test/java/com/jayway/jsonpath/old/internal/PropertyPathTokenTest.java

@ -4,14 +4,15 @@ import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.PathNotFoundException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class PropertyPathTokenTest {
@ -52,21 +53,14 @@ public class PropertyPathTokenTest {
}
@Test(expected = PathNotFoundException.class)
@Test
public void property_not_found_deep() {
String result = JsonPath.read(SIMPLE_MAP, "$.foo.not-found");
assertThat(result).isNull();
assertThrows(PathNotFoundException.class, () -> JsonPath.read(SIMPLE_MAP, "$.foo.not-found"));
}
@Test(expected = PathNotFoundException.class)
@Test
public void property_not_found_option_throw() {
//String result = JsonPath.using(Configuration.defaultConfiguration().setOptions(Option.THROW_ON_MISSING_PROPERTY)).parse(SIMPLE_MAP).read("$.not-found");
String result = JsonPath.using(Configuration.defaultConfiguration()).parse(SIMPLE_MAP).read("$.not-found");
assertThat(result).isNull();
assertThrows(PathNotFoundException.class, () -> JsonPath.using(Configuration.defaultConfiguration()).parse(SIMPLE_MAP).read("$.not-found"));
}
@Test

2
json-path/src/test/java/com/jayway/jsonpath/old/internal/ScanPathTokenTest.java

@ -2,7 +2,7 @@ package com.jayway.jsonpath.old.internal;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.internal.path.PathCompiler;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;

2
json-path/src/test/java/com/jayway/jsonpath/old/internal/TestInternal3.java

@ -1,6 +1,6 @@
package com.jayway.jsonpath.old.internal;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;

Loading…
Cancel
Save