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

6
json-path-assert/build.gradle

@ -1,10 +1,9 @@
description = "Assertions on Json using JsonPath" description = "Assertions on Json using JsonPath"
jar { jar {
baseName 'json-path-assert' baseName 'json-path-assert'
bnd ( bnd(
'Implementation-Title': 'json-path-assert', 'Implementation-Version': archiveVersion 'Implementation-Title': 'json-path-assert', 'Implementation-Version': archiveVersion
) )
} }
@ -15,5 +14,4 @@ dependencies {
testImplementation libs.jsonSmart testImplementation libs.jsonSmart
testImplementation libs.test 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; package com.jayway.jsonassert;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.InputStream; import java.io.InputStream;
import static com.jayway.jsonassert.JsonAssert.*; import static com.jayway.jsonassert.JsonAssert.*;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class JsonAssertTest { public class JsonAssertTest {
@ -52,10 +53,10 @@ public class JsonAssertTest {
} }
@Test(expected = AssertionError.class) @Test
public void has_path() throws Exception { public void has_path() throws Exception {
with(JSON).assertNotDefined("$.store.bicycle[?(@.color == 'red' )]"); assertThrows(AssertionError.class, () -> with(JSON).assertNotDefined("$.store.bicycle[?(@.color == 'red' )]"));
} }
@Test @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)))); 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 { 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 @Test
@ -168,25 +169,26 @@ public class JsonAssertTest {
} }
@Test(expected = AssertionError.class) @Test
public void assert_that_invalid_path_is_thrown() { public void assert_that_invalid_path_is_thrown() {
JsonAsserter asserter = JsonAssert.with("{\"foo\":\"bar\"}"); JsonAsserter asserter = JsonAssert.with("{\"foo\":\"bar\"}");
asserter.assertEquals("$foo", "bar"); assertThrows(AssertionError.class, () -> asserter.assertEquals("$foo", "bar"));
} }
@Test @Test
public void testAssertEqualsInteger() throws Exception { public void testAssertEqualsInteger() throws Exception {
with(getResourceAsStream("lotto.json")).assertEquals("lotto.winners[0].winnerId", 23); with(getResourceAsStream("lotto.json")).assertEquals("lotto.winners[0].winnerId", 23);
} }
@Test(expected = AssertionError.class) @Test
public void testAssertEqualsIntegerInvalidExpected() throws Exception { 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 { 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) { 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; package com.jayway.jsonpath.matchers;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.*; import static com.jayway.jsonpath.matchers.JsonPathMatchers.*;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource; 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.ResourceHelpers.resourceAsFile;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
@Ignore @Disabled
public class DemoTest { public class DemoTest {
@Test @Test
public void shouldFailOnJsonString() { 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; 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 com.jayway.jsonpath.matchers.JsonPathMatchers.hasNoJsonPath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class HasNoJsonPathTest { public class HasNoJsonPathTest {
private static final String JSON_STRING = "{" + 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.Description;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import org.hamcrest.StringDescription; import org.hamcrest.StringDescription;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.isJsonFile; import static com.jayway.jsonpath.matchers.JsonPathMatchers.isJsonFile;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resourceAsFile; import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resourceAsFile;
import static com.jayway.jsonpath.matchers.helpers.TestingMatchers.*; import static com.jayway.jsonpath.matchers.helpers.TestingMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class IsJsonFileTest { public class IsJsonFileTest {
private static final File BOOKS_JSON = resourceAsFile("books.json"); private static final File BOOKS_JSON = resourceAsFile("books.json");
private static final File INVALID_JSON = resourceAsFile("invalid.json"); private static final File INVALID_JSON = resourceAsFile("invalid.json");
@BeforeClass @BeforeAll
public static void setupStrictJsonParsing() { public static void setupStrictJsonParsing() {
Configuration.setDefaults(new StrictParsingConfiguration()); Configuration.setDefaults(new StrictParsingConfiguration());
} }
@AfterClass @AfterAll
public static void setupDefaultJsonParsing() { public static void setupDefaultJsonParsing() {
Configuration.setDefaults(null); 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.Description;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import org.hamcrest.StringDescription; import org.hamcrest.StringDescription;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.isJsonString; import static com.jayway.jsonpath.matchers.JsonPathMatchers.isJsonString;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource; import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource;
import static com.jayway.jsonpath.matchers.helpers.TestingMatchers.*; import static com.jayway.jsonpath.matchers.helpers.TestingMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class IsJsonStringTest { public class IsJsonStringTest {
private static final String BOOKS_JSON = resource("books.json"); private static final String BOOKS_JSON = resource("books.json");
@BeforeClass @BeforeAll
public static void setupStrictJsonParsing() { public static void setupStrictJsonParsing() {
Configuration.setDefaults(new StrictParsingConfiguration()); Configuration.setDefaults(new StrictParsingConfiguration());
} }
@AfterClass @AfterAll
public static void setupDefaultJsonParsing() { public static void setupDefaultJsonParsing() {
Configuration.setDefaults(null); 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.Description;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import org.hamcrest.StringDescription; import org.hamcrest.StringDescription;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; 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.resource;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resourceAsFile; import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resourceAsFile;
import static com.jayway.jsonpath.matchers.helpers.TestingMatchers.withPathEvaluatedTo; import static com.jayway.jsonpath.matchers.helpers.TestingMatchers.withPathEvaluatedTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class IsJsonTest { public class IsJsonTest {
private static final String VALID_JSON = resource("example.json"); 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 File BOOKS_JSON_FILE = resourceAsFile("books.json");
private static final Object BOOKS_JSON_PARSED = parseJson(BOOKS_JSON_STRING); private static final Object BOOKS_JSON_PARSED = parseJson(BOOKS_JSON_STRING);
@BeforeClass @BeforeAll
public static void setupStrictJsonParsing() { public static void setupStrictJsonParsing() {
Configuration.setDefaults(new StrictParsingConfiguration()); Configuration.setDefaults(new StrictParsingConfiguration());
} }
@AfterClass @AfterAll
public static void setupDefaultJsonParsing() { public static void setupDefaultJsonParsing() {
Configuration.setDefaults(null); 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.JsonPath;
import com.jayway.jsonpath.ReadContext; import com.jayway.jsonpath.ReadContext;
import com.jayway.jsonpath.matchers.helpers.StrictParsingConfiguration; import com.jayway.jsonpath.matchers.helpers.StrictParsingConfiguration;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
import java.util.List; 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.JsonPathMatchers.*;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource; 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.ResourceHelpers.resourceAsFile;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class JsonPathMatchersTest { public class JsonPathMatchersTest {
private static final String BOOKS_JSON = resource("books.json"); private static final String BOOKS_JSON = resource("books.json");
private static final String INVALID_JSON = "{ invalid-json }"; private static final String INVALID_JSON = "{ invalid-json }";
private static final File BOOKS_JSON_FILE = resourceAsFile("books.json"); private static final File BOOKS_JSON_FILE = resourceAsFile("books.json");
@BeforeClass @BeforeAll
public static void setupStrictJsonParsing() { public static void setupStrictJsonParsing() {
// NOTE: Evaluation depends on the default configuration of JsonPath // NOTE: Evaluation depends on the default configuration of JsonPath
Configuration.setDefaults(new StrictParsingConfiguration()); Configuration.setDefaults(new StrictParsingConfiguration());
} }
@AfterClass @AfterAll
public static void setupDefaultJsonParsing() { public static void setupDefaultJsonParsing() {
Configuration.setDefaults(null); 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.Description;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import org.hamcrest.StringDescription; import org.hamcrest.StringDescription;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -14,8 +14,9 @@ import java.util.List;
import static com.jayway.jsonpath.JsonPath.compile; import static com.jayway.jsonpath.JsonPath.compile;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.withJsonPath; import static com.jayway.jsonpath.matchers.JsonPathMatchers.withJsonPath;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource; import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows;
public class WithJsonPathTest { public class WithJsonPathTest {
private static final ReadContext BOOKS_JSON = JsonPath.parse(resource("books.json")); 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"))); assertThat(BOOKS_JSON, withJsonPath("$..book[2].title", hasItem("Moby Dick")));
} }
@Test(expected = InvalidPathException.class) @Test
public void shouldFailOnInvalidJsonPath() { public void shouldFailOnInvalidJsonPath() {
withJsonPath("$[}"); assertThrows(InvalidPathException.class, () -> withJsonPath("$[}"));
} }
@Test @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.JsonPath;
import com.jayway.jsonpath.ReadContext; 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.JsonPath.compile;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.withoutJsonPath; import static com.jayway.jsonpath.matchers.JsonPathMatchers.withoutJsonPath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class WithoutJsonPathTest { public class WithoutJsonPathTest {
private static final String JSON_STRING = "{" + private static final String JSON_STRING = "{" +

12
json-path/build.gradle

@ -1,13 +1,12 @@
description = "Java port of Stefan Goessner JsonPath." description = "Java port of Stefan Goessner JsonPath."
jar { jar {
baseName 'json-path' baseName 'json-path'
bnd ( bnd(
'Automatic-Module-Name': 'json.path', 'Automatic-Module-Name': 'json.path',
'Implementation-Title': 'json-path', 'Implementation-Version': archiveVersion, '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, *', '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' '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 compileOnly libs.jakartaJsonB// , optional
testImplementation libs.test 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; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; 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.JSONStyle;
import net.minidev.json.JSONValue; import net.minidev.json.JSONValue;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -12,13 +12,13 @@ public class EscapeTest extends BaseTest {
private static JSONStyle style; private static JSONStyle style;
@BeforeClass @BeforeAll
public static void before(){ public static void before(){
style = JSONValue.COMPRESSION; style = JSONValue.COMPRESSION;
JSONValue.COMPRESSION = JSONStyle.LT_COMPRESS; JSONValue.COMPRESSION = JSONStyle.LT_COMPRESS;
} }
@AfterClass @AfterAll
public static void after(){ public static void after(){
JSONValue.COMPRESSION = style; JSONValue.COMPRESSION = style;
} }

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

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

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

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

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

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

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

@ -1,7 +1,7 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import org.assertj.core.util.Lists; import org.assertj.core.util.Lists;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; 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.json.GsonJsonProvider;
import com.jayway.jsonpath.spi.mapper.GsonMappingProvider; import com.jayway.jsonpath.spi.mapper.GsonMappingProvider;
import com.jayway.jsonpath.spi.mapper.MappingException; import com.jayway.jsonpath.spi.mapper.MappingException;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.IOException; import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
@ -16,41 +16,42 @@ import java.util.List;
import static com.jayway.jsonpath.JsonPath.using; import static com.jayway.jsonpath.JsonPath.using;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class GsonJsonProviderTest extends BaseTest { public class GsonJsonProviderTest extends BaseTest {
private static final String JSON = private static final String JSON =
"[" + "[" +
"{\n" + "{\n" +
" \"foo\" : \"foo0\",\n" + " \"foo\" : \"foo0\",\n" +
" \"bar\" : 0,\n" + " \"bar\" : 0,\n" +
" \"baz\" : true,\n" + " \"baz\" : true,\n" +
" \"gen\" : {\"eric\" : \"yepp\"}" + " \"gen\" : {\"eric\" : \"yepp\"}" +
"}," + "}," +
"{\n" + "{\n" +
" \"foo\" : \"foo1\",\n" + " \"foo\" : \"foo1\",\n" +
" \"bar\" : 1,\n" + " \"bar\" : 1,\n" +
" \"baz\" : true,\n" + " \"baz\" : true,\n" +
" \"gen\" : {\"eric\" : \"yepp\"}" + " \"gen\" : {\"eric\" : \"yepp\"}" +
"}," + "}," +
"{\n" + "{\n" +
" \"foo\" : \"foo2\",\n" + " \"foo\" : \"foo2\",\n" +
" \"bar\" : 2,\n" + " \"bar\" : 2,\n" +
" \"baz\" : true,\n" + " \"baz\" : true,\n" +
" \"gen\" : {\"eric\" : \"yepp\"}" + " \"gen\" : {\"eric\" : \"yepp\"}" +
"}" + "}" +
"]"; "]";
@Test @Test
public void json_can_be_parsed() { 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"); assertThat(node.get("string-property").getAsString()).isEqualTo("string-value");
} }
@Test @Test
public void strings_are_unwrapped() { public void strings_are_unwrapped() {
JsonElement node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.string-property"); JsonElement node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.string-property");
String unwrapped = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.string-property", String.class); String unwrapped = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.string-property", String.class);
assertThat(unwrapped).isEqualTo("string-value"); assertThat(unwrapped).isEqualTo("string-value");
assertThat(unwrapped).isEqualTo(node.getAsString()); assertThat(unwrapped).isEqualTo(node.getAsString());
@ -58,8 +59,8 @@ public class GsonJsonProviderTest extends BaseTest {
@Test @Test
public void ints_are_unwrapped() { public void ints_are_unwrapped() {
JsonElement node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.int-max-property"); 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); int unwrapped = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.int-max-property", int.class);
assertThat(unwrapped).isEqualTo(Integer.MAX_VALUE); assertThat(unwrapped).isEqualTo(Integer.MAX_VALUE);
assertThat(unwrapped).isEqualTo(node.getAsInt()); assertThat(unwrapped).isEqualTo(node.getAsInt());
@ -67,8 +68,8 @@ public class GsonJsonProviderTest extends BaseTest {
@Test @Test
public void longs_are_unwrapped() { public void longs_are_unwrapped() {
JsonElement node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.long-max-property"); 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); long val = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.long-max-property", Long.class);
assertThat(val).isEqualTo(Long.MAX_VALUE); assertThat(val).isEqualTo(Long.MAX_VALUE);
assertThat(val).isEqualTo(node.getAsLong()); assertThat(val).isEqualTo(node.getAsLong());
@ -78,8 +79,8 @@ public class GsonJsonProviderTest extends BaseTest {
public void doubles_are_unwrapped() { public void doubles_are_unwrapped() {
final String json = "{double-property = 56.78}"; final String json = "{double-property = 56.78}";
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.double-property"); JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.double-property");
Double val = using(GSON_CONFIGURATION).parse(json).read("$.double-property", Double.class); Double val = using(GSON_CONFIGURATION).parse(json).read("$.double-property", Double.class);
assertThat(val).isEqualTo(56.78); assertThat(val).isEqualTo(56.78);
assertThat(val).isEqualTo(node.getAsDouble()); 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 BigDecimal bd = BigDecimal.valueOf(Long.MAX_VALUE).add(BigDecimal.valueOf(10.5));
final String json = "{bd-property = " + bd.toString() + "}"; final String json = "{bd-property = " + bd.toString() + "}";
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bd-property"); JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bd-property");
BigDecimal val = using(GSON_CONFIGURATION).parse(json).read("$.bd-property", BigDecimal.class); BigDecimal val = using(GSON_CONFIGURATION).parse(json).read("$.bd-property", BigDecimal.class);
assertThat(val).isEqualTo(bd); assertThat(val).isEqualTo(bd);
assertThat(val).isEqualTo(node.getAsBigDecimal()); assertThat(val).isEqualTo(node.getAsBigDecimal());
@ -102,8 +103,8 @@ public class GsonJsonProviderTest extends BaseTest {
final BigDecimal bd = BigDecimal.valueOf(10.5); final BigDecimal bd = BigDecimal.valueOf(10.5);
final String json = "{bd-property = " + bd.toString() + "}"; final String json = "{bd-property = " + bd.toString() + "}";
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bd-property"); JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bd-property");
BigDecimal val = using(GSON_CONFIGURATION).parse(json).read("$.bd-property", BigDecimal.class); BigDecimal val = using(GSON_CONFIGURATION).parse(json).read("$.bd-property", BigDecimal.class);
assertThat(val).isEqualTo(bd); assertThat(val).isEqualTo(bd);
assertThat(val).isEqualTo(node.getAsBigDecimal()); 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 BigInteger bi = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.TEN);
final String json = "{bi-property = " + bi.toString() + "}"; final String json = "{bi-property = " + bi.toString() + "}";
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bi-property"); JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bi-property");
BigInteger val = using(GSON_CONFIGURATION).parse(json).read("$.bi-property", BigInteger.class); BigInteger val = using(GSON_CONFIGURATION).parse(json).read("$.bi-property", BigInteger.class);
assertThat(val).isEqualTo(bi); assertThat(val).isEqualTo(bi);
assertThat(val).isEqualTo(node.getAsBigInteger()); assertThat(val).isEqualTo(node.getAsBigInteger());
@ -126,8 +127,8 @@ public class GsonJsonProviderTest extends BaseTest {
final BigInteger bi = BigInteger.valueOf(Long.MAX_VALUE); final BigInteger bi = BigInteger.valueOf(Long.MAX_VALUE);
final String json = "{bi-property = " + bi.toString() + "}"; final String json = "{bi-property = " + bi.toString() + "}";
JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bi-property"); JsonElement node = using(GSON_CONFIGURATION).parse(json).read("$.bi-property");
BigInteger val = using(GSON_CONFIGURATION).parse(json).read("$.bi-property", BigInteger.class); BigInteger val = using(GSON_CONFIGURATION).parse(json).read("$.bi-property", BigInteger.class);
assertThat(val).isEqualTo(bi); assertThat(val).isEqualTo(bi);
assertThat(val).isEqualTo(node.getAsBigInteger()); assertThat(val).isEqualTo(node.getAsBigInteger());
@ -145,7 +146,7 @@ public class GsonJsonProviderTest extends BaseTest {
@Test @Test
public void list_of_numbers() { 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<>(); List<Double> actual = new ArrayList<>();
for (JsonElement obj : objs) { for (JsonElement obj : objs) {
actual.add(obj.getAsDouble()); actual.add(obj.getAsDouble());
@ -173,36 +174,38 @@ public class GsonJsonProviderTest extends BaseTest {
@Test @Test
public void test_type_ref() throws IOException { 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); List<FooBarBaz<Gen>> list = JsonPath.using(GSON_CONFIGURATION).parse(JSON).read("$", typeRef);
assertThat(list.get(0).gen.eric).isEqualTo("yepp"); assertThat(list.get(0).gen.eric).isEqualTo("yepp");
} }
@Test(expected = MappingException.class) @Test
public void test_type_ref_fail() throws IOException { 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 @Test
// https://github.com/json-path/JsonPath/issues/351 // https://github.com/json-path/JsonPath/issues/351
public void no_error_when_mapping_null() throws IOException { 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; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runners.Parameterized; import org.junit.jupiter.params.provider.MethodSource;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
@ -14,66 +14,61 @@ import static com.jayway.jsonpath.TestUtils.assertHasOneResult;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@RunWith(Parameterized.class)
public class InlineFilterTest extends BaseTest { public class InlineFilterTest extends BaseTest {
private static int bookCount = 4; private static int bookCount = 4;
public static final String MULTI_STORE_JSON_DOCUMENT = "{\n" + public static final String MULTI_STORE_JSON_DOCUMENT = "{\n" +
" \"store\" : [{\n" + " \"store\" : [{\n" +
" \"name\": \"First\"," + " \"name\": \"First\"," +
" \"book\" : [\n" + " \"book\" : [\n" +
" {\n" + " {\n" +
" \"category\" : \"reference\",\n" + " \"category\" : \"reference\",\n" +
" \"author\" : \"Nigel Rees\",\n" + " \"author\" : \"Nigel Rees\",\n" +
" \"title\" : \"Sayings of the Century\",\n" + " \"title\" : \"Sayings of the Century\",\n" +
" \"display-price\" : 8.95\n" + " \"display-price\" : 8.95\n" +
" },\n" + " },\n" +
" {\n" + " {\n" +
" \"category\" : \"fiction\",\n" + " \"category\" : \"fiction\",\n" +
" \"author\" : \"Evelyn Waugh\",\n" + " \"author\" : \"Evelyn Waugh\",\n" +
" \"title\" : \"Sword of Honour\",\n" + " \"title\" : \"Sword of Honour\",\n" +
" \"display-price\" : 12.99\n" + " \"display-price\" : 12.99\n" +
" },\n" + " },\n" +
" {\n" + " {\n" +
" \"category\" : \"fiction\",\n" + " \"category\" : \"fiction\",\n" +
" \"author\" : \"Herman Melville\",\n" + " \"author\" : \"Herman Melville\",\n" +
" \"title\" : \"Moby Dick\",\n" + " \"title\" : \"Moby Dick\",\n" +
" \"isbn\" : \"0-553-21311-3\",\n" + " \"isbn\" : \"0-553-21311-3\",\n" +
" \"display-price\" : 8.99\n" + " \"display-price\" : 8.99\n" +
" },\n" + " },\n" +
" {\n" + " {\n" +
" \"category\" : \"fiction\",\n" + " \"category\" : \"fiction\",\n" +
" \"author\" : \"J. R. R. Tolkien\",\n" + " \"author\" : \"J. R. R. Tolkien\",\n" +
" \"title\" : \"The Lord of the Rings\",\n" + " \"title\" : \"The Lord of the Rings\",\n" +
" \"isbn\" : \"0-395-19395-8\",\n" + " \"isbn\" : \"0-395-19395-8\",\n" +
" \"display-price\" : 22.99\n" + " \"display-price\" : 22.99\n" +
" }]\n" + " }]\n" +
" },\n" + " },\n" +
" {\n" + " {\n" +
" \"name\": \"Second\",\n" + " \"name\": \"Second\",\n" +
" \"book\": [\n" + " \"book\": [\n" +
" {\n" + " {\n" +
" \"category\" : \"fiction\",\n" + " \"category\" : \"fiction\",\n" +
" \"author\" : \"Ernest Hemmingway\",\n" + " \"author\" : \"Ernest Hemmingway\",\n" +
" \"title\" : \"The Old Man and the Sea\",\n" + " \"title\" : \"The Old Man and the Sea\",\n" +
" \"display-price\" : 12.99\n" + " \"display-price\" : 12.99\n" +
" }]\n" + " }]\n" +
" }]}"; " }]}";
private Configuration conf = Configurations.GSON_CONFIGURATION;
public InlineFilterTest(Configuration conf) {
this.conf = conf;
}
@Parameterized.Parameters
public static Iterable<Configuration> configurations() { public static Iterable<Configuration> configurations() {
return Configurations.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); 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)); 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; return object instanceof BigDecimal ? ((BigDecimal) object).doubleValue() : (Double) object;
} }
@Test @ParameterizedTest
public void multiple_context_object_can_be_refered() { @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); List all = using(conf).parse(JSON_DOCUMENT).read("store.book[ ?(@.category == @.category) ]", List.class);
assertThat(all.size()).isEqualTo(bookCount); assertThat(all.size()).isEqualTo(bookCount);
@ -104,8 +100,9 @@ public class InlineFilterTest extends BaseTest {
} }
@Test @ParameterizedTest
public void simple_inline_or_statement_evaluates() { @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); 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"); assertThat(a).containsExactly("Nigel Rees", "Evelyn Waugh");
@ -120,7 +117,7 @@ public class InlineFilterTest extends BaseTest {
assertThat(d).containsExactly("Nigel Rees"); assertThat(d).containsExactly("Nigel Rees");
} }
@Test
public void no_path_ref_in_filter_hit_all() { public void no_path_ref_in_filter_hit_all() {
List<String> res = JsonPath.parse(JSON_DOCUMENT).read("$.store.book[?('a' == 'a')].author"); 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("$[?(@)]"); 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)]"); 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("$[?(!@)]"); List<Integer> isNull = JsonPath.parse(ints).read("$[?(!@)]");
assertThat(isNull).containsExactly(new Integer[]{}); assertThat(isNull).containsExactly(new Integer[]{});
assertThat(isNull).containsExactly(new Integer[]{}); assertThat(isNull).containsExactly(new Integer[]{});
} }
@Test @ParameterizedTest
public void equality_check_does_not_break_evaluation() { @MethodSource("configurations")
public void equality_check_does_not_break_evaluation(Configuration conf) {
assertHasOneResult("[{\"value\":\"5\"}]", "$[?(@.value=='5')]", conf); assertHasOneResult("[{\"value\":\"5\"}]", "$[?(@.value=='5')]", 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); assertHasNoResults("[{\"value\":\"5.1.26\"}]", "$[?(@.value==5.1)]", conf);
} }
@Test @ParameterizedTest
public void lt_check_does_not_break_evaluation() { @MethodSource("configurations")
public void lt_check_does_not_break_evaluation(Configuration conf) {
assertHasOneResult("[{\"value\":\"5\"}]", "$[?(@.value<'7')]", conf); assertHasOneResult("[{\"value\":\"5\"}]", "$[?(@.value<'7')]", conf);
assertHasNoResults("[{\"value\":\"7\"}]", "$[?(@.value<'5')]", conf); assertHasNoResults("[{\"value\":\"7\"}]", "$[?(@.value<'5')]", conf);
@ -241,44 +240,50 @@ public class InlineFilterTest extends BaseTest {
assertHasNoResults("[{\"value\":7.1}]", "$[?(@.value<5)]", conf); assertHasNoResults("[{\"value\":7.1}]", "$[?(@.value<5)]", conf);
} }
@Test @ParameterizedTest
public void escaped_literals() { @MethodSource("configurations")
if(conf.jsonProvider().getClass().getSimpleName().startsWith("Jackson")){ public void escaped_literals(Configuration conf) {
if (conf.jsonProvider().getClass().getSimpleName().startsWith("Jackson")) {
return; 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 // single quotes are not valid in JSON; see json.org
return; return;
} }
assertHasOneResult("[\"\\'foo\"]", "$[?(@ == '\\'foo')]", conf); assertHasOneResult("[\"\\'foo\"]", "$[?(@ == '\\'foo')]", conf);
} }
@Test @ParameterizedTest
public void escaped_literals2() { @MethodSource("configurations")
if(conf.jsonProvider().getClass().getSimpleName().startsWith("Jackson")){ public void escaped_literals2(Configuration conf) {
if (conf.jsonProvider().getClass().getSimpleName().startsWith("Jackson")) {
return; return;
} }
assertHasOneResult("[\"\\\\'foo\"]", "$[?(@ == \"\\\\'foo\")]", conf); assertHasOneResult("[\"\\\\'foo\"]", "$[?(@ == \"\\\\'foo\")]", conf);
} }
@Test @ParameterizedTest
public void escape_pattern() { @MethodSource("configurations")
public void escape_pattern(Configuration conf) {
assertHasOneResult("[\"x\"]", "$[?(@ =~ /\\/|x/)]", conf); assertHasOneResult("[\"x\"]", "$[?(@ =~ /\\/|x/)]", conf);
} }
@Test @ParameterizedTest
public void escape_pattern_after_literal() { @MethodSource("configurations")
public void escape_pattern_after_literal(Configuration conf) {
assertHasOneResult("[\"x\"]", "$[?(@ == \"abc\" || @ =~ /\\/|x/)]", conf); assertHasOneResult("[\"x\"]", "$[?(@ == \"abc\" || @ =~ /\\/|x/)]", conf);
} }
@Test @ParameterizedTest
public void escape_pattern_before_literal() { @MethodSource("configurations")
public void escape_pattern_before_literal(Configuration conf) {
assertHasOneResult("[\"x\"]", "$[?(@ =~ /\\/|x/ || @ == \"abc\")]", conf); assertHasOneResult("[\"x\"]", "$[?(@ =~ /\\/|x/ || @ == \"abc\")]", conf);
} }
@Test @ParameterizedTest
public void filter_evaluation_does_not_break_path_evaluation() { @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); 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; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class Issue_487 { public class Issue_487 {

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

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

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

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

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

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

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

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

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

@ -1,6 +1,6 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThatNoException; 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; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*; 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; package com.jayway.jsonpath;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TextNode; import com.fasterxml.jackson.databind.node.TextNode;
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider; import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; 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.Arrays;
import java.util.List; import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class) import static org.assertj.core.api.Assertions.assertThat;
public class JacksonJsonNodeJsonProviderMapperSupportTest {
private final TestData testData; public class JacksonJsonNodeJsonProviderMapperSupportTest {
public JacksonJsonNodeJsonProviderMapperSupportTest(final TestData testData) { @ParameterizedTest
this.testData = testData; @MethodSource("testDataSource")
} public void mapMethod_withJacksonJsonNodeJsonProvider_shouldUsingJsonNodeForMappingValues(TestData testData) {
@Test
public void mapMethod_withJacksonJsonNodeJsonProvider_shouldUsingJsonNodeForMappingValues() {
DocumentContext testJsonDocumentContext = cloneDocumentContext(testData.jsonDocumentContext); DocumentContext testJsonDocumentContext = cloneDocumentContext(testData.jsonDocumentContext);
testJsonDocumentContext.map(testData.jsonPath, (value, config) -> { testJsonDocumentContext.map(testData.jsonPath, (value, config) -> {
@ -33,16 +28,20 @@ public class JacksonJsonNodeJsonProviderMapperSupportTest {
.isEqualTo(testData.expectedUpdatedJsonDocument); .isEqualTo(testData.expectedUpdatedJsonDocument);
} }
@Test
public void readMethod_withJacksonJsonNodeJsonProvider_shouldReturnJsonNode() { @ParameterizedTest
@MethodSource("testDataSource")
public void readMethod_withJacksonJsonNodeJsonProvider_shouldReturnJsonNode(TestData testData) {
DocumentContext testJsonDocumentContext = cloneDocumentContext(testData.jsonDocumentContext); DocumentContext testJsonDocumentContext = cloneDocumentContext(testData.jsonDocumentContext);
final JsonNode actualJsonValue = testJsonDocumentContext.read(testData.jsonPath); final JsonNode actualJsonValue = testJsonDocumentContext.read(testData.jsonPath);
assertThat(actualJsonValue).isEqualTo(testData.expectedJsonValue); 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); DocumentContext testJsonDocumentContext = cloneDocumentContext(testData.jsonDocumentContext);
testJsonDocumentContext.set(testData.jsonPath, testData.newJsonValue); testJsonDocumentContext.set(testData.jsonPath, testData.newJsonValue);
@ -75,7 +74,7 @@ public class JacksonJsonNodeJsonProviderMapperSupportTest {
} }
} }
@Parameterized.Parameters
public static List<TestData> testDataSource() throws Exception { public static List<TestData> testDataSource() throws Exception {
final Configuration configuration = Configuration.builder() final Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider()) .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.JacksonMappingProvider;
import com.jayway.jsonpath.spi.mapper.MappingException; import com.jayway.jsonpath.spi.mapper.MappingException;
import java.nio.charset.StandardCharsets; 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.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
@ -186,11 +188,11 @@ public class JacksonJsonNodeJsonProviderTest extends BaseTest {
assertThat(list.get(0).gen.eric).isEqualTo("yepp"); assertThat(list.get(0).gen.eric).isEqualTo("yepp");
} }
@Test(expected = MappingException.class) @Test
public void test_type_ref_fail() throws IOException { 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(JACKSON_JSON_NODE_CONFIGURATION).parse(JSON).read("$", typeRef); Assertions.assertThrows(MappingException.class, () -> using(JACKSON_JSON_NODE_CONFIGURATION).parse(JSON).read("$", typeRef));
} }
@Test @Test

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

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

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

@ -1,44 +1,35 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runner.RunWith; import org.junit.jupiter.params.provider.MethodSource;
import org.junit.runners.Parameterized;
import static com.jayway.jsonpath.JsonPath.using; import static com.jayway.jsonpath.JsonPath.using;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@RunWith(Parameterized.class)
public class JsonProviderTest extends BaseTest { public class JsonProviderTest extends BaseTest {
private final Configuration conf;
public JsonProviderTest(Configuration conf) {
this.conf = conf;
}
@Parameterized.Parameters
public static Iterable<Configuration> configurations() { public static Iterable<Configuration> configurations() {
return Configurations.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"); 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); 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); 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; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runner.RunWith; import org.junit.jupiter.params.provider.MethodSource;
import org.junit.runners.Parameterized;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
@ -10,53 +9,51 @@ import java.util.List;
import static com.jayway.jsonpath.JsonPath.using; import static com.jayway.jsonpath.JsonPath.using;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@RunWith(Parameterized.class)
public class JsonProviderTestObjectMapping extends BaseTest { public class JsonProviderTestObjectMapping extends BaseTest {
private static final String JSON = private static final String JSON =
"[" + "[" +
"{\n" + "{\n" +
" \"foo\" : \"foo0\",\n" + " \"foo\" : \"foo0\",\n" +
" \"bar\" : 0,\n" + " \"bar\" : 0,\n" +
" \"baz\" : true,\n" + " \"baz\" : true,\n" +
" \"gen\" : {\"prop\" : \"yepp0\"}" + " \"gen\" : {\"prop\" : \"yepp0\"}" +
"}," + "}," +
"{\n" + "{\n" +
" \"foo\" : \"foo1\",\n" + " \"foo\" : \"foo1\",\n" +
" \"bar\" : 1,\n" + " \"bar\" : 1,\n" +
" \"baz\" : true,\n" + " \"baz\" : true,\n" +
" \"gen\" : {\"prop\" : \"yepp1\"}" + " \"gen\" : {\"prop\" : \"yepp1\"}" +
"}," + "}," +
"{\n" + "{\n" +
" \"foo\" : \"foo2\",\n" + " \"foo\" : \"foo2\",\n" +
" \"bar\" : 2,\n" + " \"bar\" : 2,\n" +
" \"baz\" : true,\n" + " \"baz\" : true,\n" +
" \"gen\" : {\"prop\" : \"yepp2\"}" + " \"gen\" : {\"prop\" : \"yepp2\"}" +
"}" + "}" +
"]"; "]";
private final Configuration conf;
public JsonProviderTestObjectMapping(Configuration conf) {
this.conf = conf;
}
@Parameterized.Parameters
public static Iterable<Configuration> configurations() { public static Iterable<Configuration> configurations() {
return Configurations.objectMappingConfigurations(); 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); 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 { @ParameterizedTest
TypeRef<List<FooBarBaz<Sub>>> typeRef = new TypeRef<List<FooBarBaz<Sub>>>() {}; @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"); 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; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;

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

@ -1,6 +1,7 @@
package com.jayway.jsonpath; 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.HashMap;
import java.util.List; import java.util.List;
@ -48,7 +49,7 @@ public class MultiPropTest {
.containsEntry("d", null); .containsEntry("d", null);
} }
@Test(expected = PathNotFoundException.class) @Test
public void multi_props_can_be_required() { public void multi_props_can_be_required() {
Map<String, Object> model = new HashMap<String, Object>(){{ Map<String, Object> model = new HashMap<String, Object>(){{
@ -59,7 +60,7 @@ public class MultiPropTest {
Configuration conf = Configuration.defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES); 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 @Test

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

@ -1,6 +1,6 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -13,15 +13,16 @@ import static java.util.Arrays.asList;
import static java.util.Collections.singletonMap; import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class OptionsTest extends BaseTest { public class OptionsTest extends BaseTest {
@Test(expected = PathNotFoundException.class) @Test
public void a_leafs_is_not_defaulted_to_null() { public void a_leafs_is_not_defaulted_to_null() {
Configuration conf = Configuration.defaultConfiguration(); 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 @Test
@ -37,7 +38,7 @@ public class OptionsTest extends BaseTest {
Configuration conf = Configuration.defaultConfiguration(); 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 @Test
@ -45,11 +46,11 @@ public class OptionsTest extends BaseTest {
Configuration conf = Configuration.builder().options(ALWAYS_RETURN_LIST).build(); 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)); .containsExactly(Arrays.asList(1, 4, 8));
} }
@ -61,7 +62,7 @@ public class OptionsTest extends BaseTest {
assertThat(result).hasSize(1); assertThat(result).hasSize(1);
assertThat(result.get(0)).isNull(); 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)); .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() { public void a_path_evaluation_is_returned_as_VALUE_by_default() {
Configuration conf = Configuration.defaultConfiguration(); 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 @Test
@ -103,7 +104,7 @@ public class OptionsTest extends BaseTest {
@Test @Test
public void when_property_is_required_exception_is_thrown() { 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(); Configuration conf = Configuration.defaultConfiguration();
@ -112,10 +113,11 @@ public class OptionsTest extends BaseTest {
conf = conf.addOptions(Option.REQUIRE_PROPERTIES); conf = conf.addOptions(Option.REQUIRE_PROPERTIES);
try{ try {
using(conf).parse(model).read("$[*].a", List.class); using(conf).parse(model).read("$[*].a", List.class);
fail("Should throw PathNotFoundException"); fail("Should throw PathNotFoundException");
} catch (PathNotFoundException pnf){} } catch (PathNotFoundException pnf) {
}
} }
@Test @Test
@ -131,10 +133,11 @@ public class OptionsTest extends BaseTest {
conf = conf.addOptions(Option.REQUIRE_PROPERTIES); conf = conf.addOptions(Option.REQUIRE_PROPERTIES);
try{ try {
using(conf).parse(model).read("$.*.a-key", List.class); using(conf).parse(model).read("$.*.a-key", List.class);
fail("Should throw PathNotFoundException"); 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() { public void issue_suppress_exceptions_does_not_break_indefinite_evaluation() {
Configuration conf = Configuration.builder().options(SUPPRESS_EXCEPTIONS).build(); 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("{\"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("{\"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("$..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 @Test
public void isbn_is_defaulted_when_option_is_provided() { public void isbn_is_defaulted_when_option_is_provided() {
List<String> result1 = JsonPath.using(JSON_SMART_CONFIGURATION).parse(JSON_DOCUMENT).read("$.store.book.*.isbn"); 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"); 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; package com.jayway.jsonpath;
import com.jayway.jsonpath.internal.ParseContextImpl; import org.junit.jupiter.api.Disabled;
import org.junit.Ignore; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.List; import java.util.List;
import static com.jayway.jsonpath.internal.path.PathCompiler.compile; import static com.jayway.jsonpath.internal.path.PathCompiler.compile;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class PathCompilerTest { public class PathCompilerTest {
@Ignore("Backward compatibility <= 2.0.0") @Disabled("Backward compatibility <= 2.0.0")
@Test(expected = InvalidPathException.class) @Test
public void a_path_must_start_with_$_or_at() { public void a_path_must_start_with_$_or_at() {
compile("x"); assertThrows(InvalidPathException.class, () -> compile("x"));
} }
@Ignore("Backward compatibility <= 2.0.0") @Disabled("Backward compatibility <= 2.0.0")
@Test(expected = InvalidPathException.class) @Test
public void a_square_bracket_may_not_follow_a_period() { 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() { public void a_root_path_must_be_followed_by_period_or_bracket() {
compile("$X"); assertThrows(InvalidPathException.class, () -> compile("$X"));
} }
@Test @Test
@ -35,24 +35,24 @@ public class PathCompilerTest {
assertThat(compile("@").toString()).isEqualTo("@"); assertThat(compile("@").toString()).isEqualTo("@");
} }
@Test(expected = InvalidPathException.class) @Test
public void a_path_may_not_end_with_period() { 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() { 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() { 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() { public void a_path_may_not_end_with_scan_2() {
compile("$.prop.."); assertThrows(InvalidPathException.class, () -> compile("$.prop.."));
} }
@Test @Test
@ -84,9 +84,9 @@ public class PathCompilerTest {
assertThat(compile("$.aaa.bbb.ccc").toString()).isEqualTo("$['aaa']['bbb']['ccc']"); assertThat(compile("$.aaa.bbb.ccc").toString()).isEqualTo("$['aaa']['bbb']['ccc']");
} }
@Test(expected = InvalidPathException.class) @Test
public void a_property_may_not_contain_blanks() { public void a_property_may_not_contain_blanks() {
assertThat(compile("$.foo bar").toString()); assertThrows(InvalidPathException.class, () -> compile("$.foo bar"));
} }
@Test @Test
@ -242,7 +242,7 @@ public class PathCompilerTest {
String json = "{\n" String json = "{\n"
+ " \"logs\": [\n" + " \"logs\": [\n"
+ " {\n" + " {\n"
+ " \"message\": \"\\\"it\\\"\",\n" + " \"message\": \"\\\"it\\\"\"\n"
+ " }\n" + " }\n"
+ " ]\n" + " ]\n"
+ "}"; + "}";
@ -255,7 +255,7 @@ public class PathCompilerTest {
String json = "{\n" String json = "{\n"
+ " \"logs\": [\n" + " \"logs\": [\n"
+ " {\n" + " {\n"
+ " \"message\": \"'it'\",\n" + " \"message\": \"'it'\"\n"
+ " }\n" + " }\n"
+ " ]\n" + " ]\n"
+ "}"; + "}";
@ -270,7 +270,7 @@ public class PathCompilerTest {
String json = "{\n" String json = "{\n"
+ " \"logs\": [\n" + " \"logs\": [\n"
+ " {\n" + " {\n"
+ " \"message\": \"'it'\",\n" + " \"message\": \"'it'\"\n"
+ " }\n" + " }\n"
+ " ]\n" + " ]\n"
+ "}"; + "}";
@ -304,23 +304,23 @@ public class PathCompilerTest {
assertThat(compile("$.aaa.foo(5,10,15)").toString()).isEqualTo("$['aaa'].foo(...)"); 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() { 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() { 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() { 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() { 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; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import java.util.Map; 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.fasterxml.jackson.databind.node.ArrayNode;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.jayway.jsonpath.spi.json.GsonJsonProvider; import com.jayway.jsonpath.spi.json.*;
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider; import com.jayway.jsonpath.spi.mapper.*;
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 org.assertj.core.util.Lists; import org.assertj.core.util.Lists;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class ProviderInTest { public class ProviderInTest {
private final String JSON = "[{\"foo\": \"bar\"}, {\"foo\": \"baz\"}]"; private final String JSON = "[{\"foo\": \"bar\"}, {\"foo\": \"baz\"}]";
@ -33,7 +24,7 @@ public class ProviderInTest {
@Test @Test
public void testJsonPathQuotesJackson() throws Exception { public void testJsonPathQuotesJackson() {
final Configuration jackson = Configuration.builder().jsonProvider(new JacksonJsonProvider()).mappingProvider(new JacksonMappingProvider()).build(); final Configuration jackson = Configuration.builder().jsonProvider(new JacksonJsonProvider()).mappingProvider(new JacksonMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(jackson).parse(JSON); final DocumentContext ctx = JsonPath.using(jackson).parse(JSON);
@ -52,7 +43,7 @@ public class ProviderInTest {
@Test @Test
public void testJsonPathQuotesJacksonJsonNode() throws Exception { public void testJsonPathQuotesJacksonJsonNode() {
final Configuration jacksonJsonNode = Configuration.builder().jsonProvider(new JacksonJsonNodeJsonProvider()).mappingProvider(new JacksonMappingProvider()).build(); final Configuration jacksonJsonNode = Configuration.builder().jsonProvider(new JacksonJsonNodeJsonProvider()).mappingProvider(new JacksonMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(jacksonJsonNode).parse(JSON); final DocumentContext ctx = JsonPath.using(jacksonJsonNode).parse(JSON);
@ -70,7 +61,7 @@ public class ProviderInTest {
} }
@Test @Test
public void testJsonPathQuotesGson() throws Exception { public void testJsonPathQuotesGson() {
final Configuration gson = Configuration.builder().jsonProvider(new GsonJsonProvider()).mappingProvider(new GsonMappingProvider()).build(); final Configuration gson = Configuration.builder().jsonProvider(new GsonJsonProvider()).mappingProvider(new GsonMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(gson).parse(JSON); final DocumentContext ctx = JsonPath.using(gson).parse(JSON);
@ -88,7 +79,7 @@ public class ProviderInTest {
} }
@Test @Test
public void testJsonPathQuotesJsonOrg() throws Exception { public void testJsonPathQuotesJsonOrg() {
final Configuration jsonOrg = Configuration.builder().jsonProvider(new JsonOrgJsonProvider()).mappingProvider(new JsonOrgMappingProvider()).build(); final Configuration jsonOrg = Configuration.builder().jsonProvider(new JsonOrgJsonProvider()).mappingProvider(new JsonOrgMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(jsonOrg).parse(JSON); final DocumentContext ctx = JsonPath.using(jsonOrg).parse(JSON);
@ -106,7 +97,7 @@ public class ProviderInTest {
} }
@Test @Test
public void testJsonPathQuotesJsonSmart() throws Exception { public void testJsonPathQuotesJsonSmart() {
final Configuration jsonSmart = Configuration.builder().jsonProvider(new JsonSmartJsonProvider()).mappingProvider(new JsonSmartMappingProvider()).build(); final Configuration jsonSmart = Configuration.builder().jsonProvider(new JsonSmartJsonProvider()).mappingProvider(new JsonSmartMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(jsonSmart).parse(JSON); final DocumentContext ctx = JsonPath.using(jsonSmart).parse(JSON);
@ -124,7 +115,7 @@ public class ProviderInTest {
} }
@Test @Test
public void testJsonPathQuotesJakarta() throws Exception { public void testJsonPathQuotesJakarta() {
final Configuration gson = Configuration.builder().jsonProvider(new JakartaJsonProvider()).mappingProvider(new JakartaMappingProvider()).build(); final Configuration gson = Configuration.builder().jsonProvider(new JakartaJsonProvider()).mappingProvider(new JakartaMappingProvider()).build();
final DocumentContext ctx = JsonPath.using(gson).parse(JSON); 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; package com.jayway.jsonpath;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static com.jayway.jsonpath.JsonPath.using; 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; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import java.util.Map; 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.JsonPath.using;
import static com.jayway.jsonpath.Option.AS_PATH_LIST; import static com.jayway.jsonpath.Option.AS_PATH_LIST;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
@SuppressWarnings("ALL") @SuppressWarnings("ALL")
public class ReturnTypeTest extends BaseTest { public class ReturnTypeTest extends BaseTest {
@ -18,7 +19,7 @@ public class ReturnTypeTest extends BaseTest {
@Test @Test
public void assert_strings_can_be_read() { 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 @Test
@ -28,17 +29,17 @@ public class ReturnTypeTest extends BaseTest {
@Test @Test
public void assert_longs_can_be_read() { 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 @Test
public void assert_boolean_values_can_be_read() { 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 @Test
public void assert_null_values_can_be_read() { public void assert_null_values_can_be_read() {
assertThat((String)reader.read("$.null-property")).isNull(); assertThat((String) reader.read("$.null-property")).isNull();
} }
@Test @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() { 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; package com.jayway.jsonpath;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; 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.JSONArray;
import org.apache.tapestry5.json.JSONObject; import org.apache.tapestry5.json.JSONObject;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class TapestryJsonProviderTest extends BaseTest { 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.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; 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 { public class TestSuppressExceptions {
@Test @Test
public void testSuppressExceptionsIsRespected() { public void testSuppressExceptionsIsRespected() {
ParseContext parseContext = JsonPath.using( ParseContext parseContext = JsonPath.using(
new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider()) new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider())
.mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS) .mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS)
.build()); .build());
String json = "{}"; String json = "{}";
assertNull(parseContext.parse(json).read(JsonPath.compile("$.missing"))); assertNull(parseContext.parse(json).read(JsonPath.compile("$.missing")));
} }
@Test @Test
public void testSuppressExceptionsIsRespectedPath() { public void testSuppressExceptionsIsRespectedPath() {
ParseContext parseContext = JsonPath.using( ParseContext parseContext = JsonPath.using(
new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider()) new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider())
.mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS, Option.AS_PATH_LIST) .mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS, Option.AS_PATH_LIST)
.build()); .build());
String json = "{}"; String json = "{}";
List<String> result = parseContext.parse(json).read(JsonPath.compile("$.missing")); List<String> result = parseContext.parse(json).read(JsonPath.compile("$.missing"));
assertThat(result).isEmpty(); assertThat(result).isEmpty();
} }
} }

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

@ -1,6 +1,6 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.InputStream; import java.io.InputStream;
import java.util.HashMap; import java.util.HashMap;
@ -11,6 +11,7 @@ import java.util.Map;
import static com.jayway.jsonpath.JsonPath.parse; import static com.jayway.jsonpath.JsonPath.parse;
import static java.util.Collections.emptyMap; import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class WriteTest extends BaseTest { public class WriteTest extends BaseTest {
@ -187,7 +188,7 @@ public class WriteTest extends BaseTest {
@Test @Test
public void item_can_be_added_to_root_array() { 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(1);
model.add(2); model.add(2);
@ -206,23 +207,23 @@ public class WriteTest extends BaseTest {
assertThat(newVal).isEqualTo("new-val"); assertThat(newVal).isEqualTo("new-val");
} }
@Test(expected = InvalidModificationException.class) @Test
public void add_to_object_on_array() { 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() { 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() { public void root_object_can_not_be_updated() {
Map model = new HashMap(); Map model = new HashMap();
model.put("a", "a-val"); model.put("a", "a-val");
parse(model).set("$[?(@.a == 'a-val')]", 1); assertThrows(InvalidModificationException.class, () -> parse(model).set("$[?(@.a == 'a-val')]", 1));
} }
@Test @Test
@ -247,25 +248,25 @@ public class WriteTest extends BaseTest {
assertThat(result).isNotEmpty(); assertThat(result).isNotEmpty();
} }
@Test(expected = InvalidModificationException.class) @Test
public void non_map_array_items_cannot_be_renamed(){ 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(1);
model.add(2); 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(){ 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(){ 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(){ public void rootCannotBeMapped(){
MapFunction mapFunction = new MapFunction() { MapFunction mapFunction = new MapFunction() {
@Override @Override
@ -273,7 +274,7 @@ public class WriteTest extends BaseTest {
return currentValue.toString()+"converted"; return currentValue.toString()+"converted";
} }
}; };
Object o = parse(JSON_DOCUMENT).map("$", mapFunction).json(); assertThrows(InvalidModificationException.class, () -> parse(JSON_DOCUMENT).map("$", mapFunction).json());
} }
@Test @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.Filter;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; 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; package com.jayway.jsonpath.internal;
import com.jayway.jsonpath.JsonPathException; import com.jayway.jsonpath.JsonPathException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class UtilsTest { public class UtilsTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testJoin() { public void testJoin() {
@ -19,92 +16,87 @@ public class UtilsTest {
strings.add("bar"); strings.add("bar");
strings.add("baz"); strings.add("baz");
Assert.assertEquals("foo,bar,baz", Utils.join(",", strings)); Assertions.assertEquals("foo,bar,baz", Utils.join(",", strings));
Assert.assertEquals("", Utils.join(",", new ArrayList<String>())); Assertions.assertEquals("", Utils.join(",", new ArrayList<String>()));
} }
@Test @Test
public void testConcat() { public void testConcat() {
Assert.assertEquals("", Utils.concat()); Assertions.assertEquals("", Utils.concat());
Assert.assertEquals("", Utils.concat("")); Assertions.assertEquals("", Utils.concat(""));
Assert.assertEquals("", Utils.concat("", "")); Assertions.assertEquals("", Utils.concat("", ""));
Assert.assertEquals("a", Utils.concat("a")); Assertions.assertEquals("a", Utils.concat("a"));
Assert.assertEquals("a", Utils.concat("", "a", "")); Assertions.assertEquals("a", Utils.concat("", "a", ""));
Assert.assertEquals("abc", Utils.concat("a", "b", "c")); Assertions.assertEquals("abc", Utils.concat("a", "b", "c"));
} }
@Test @Test
public void testEscape() { 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", Assertions.assertEquals("\\\\f\\'o\\\"o\\rb\\fa\\t\\nr\\bb\\/a", Utils.escape("\\f\'o\"o\rb\fa\t\nr\bb/a", true));
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));
Assert.assertEquals("\\uFFFF\\u0FFF\\u00FF\\u000F\\u0010",
Utils.escape("\uffff\u0fff\u00ff\u000f\u0010", true));
} }
@Test @Test
public void testUnescape() { public void testUnescape() {
Assert.assertNull(Utils.unescape(null)); Assertions.assertNull(Utils.unescape(null));
Assert.assertEquals("foo", Utils.unescape("foo")); Assertions.assertEquals("foo", Utils.unescape("foo"));
Assert.assertEquals("\\", Utils.unescape("\\")); Assertions.assertEquals("\\", Utils.unescape("\\"));
Assert.assertEquals("\\", Utils.unescape("\\\\")); Assertions.assertEquals("\\", Utils.unescape("\\\\"));
Assert.assertEquals("\'", Utils.unescape("\\\'")); Assertions.assertEquals("\'", Utils.unescape("\\\'"));
Assert.assertEquals("\"", Utils.unescape("\\\"")); Assertions.assertEquals("\"", Utils.unescape("\\\""));
Assert.assertEquals("\r", Utils.unescape("\\r")); Assertions.assertEquals("\r", Utils.unescape("\\r"));
Assert.assertEquals("\f", Utils.unescape("\\f")); Assertions.assertEquals("\f", Utils.unescape("\\f"));
Assert.assertEquals("\t", Utils.unescape("\\t")); Assertions.assertEquals("\t", Utils.unescape("\\t"));
Assert.assertEquals("\n", Utils.unescape("\\n")); Assertions.assertEquals("\n", Utils.unescape("\\n"));
Assert.assertEquals("\b", Utils.unescape("\\b")); Assertions.assertEquals("\b", Utils.unescape("\\b"));
Assert.assertEquals("a", Utils.unescape("\\a")); Assertions.assertEquals("a", Utils.unescape("\\a"));
Assert.assertEquals("\uffff", Utils.unescape("\\uffff")); Assertions.assertEquals("\uffff", Utils.unescape("\\uffff"));
} }
@Test @Test
public void testUnescapeThrow() { public void testUnescapeThrow() {
thrown.expect(JsonPathException.class); Assertions.assertThrows(JsonPathException.class, () -> Utils.unescape("\\uuuuu"));
Utils.unescape("\\uuuuu");
} }
@Test @Test
public void testHex() { public void testHex() {
Assert.assertEquals("61", Utils.hex('a')); Assertions.assertEquals("61", Utils.hex('a'));
Assert.assertEquals("24", Utils.hex('$')); Assertions.assertEquals("24", Utils.hex('$'));
} }
@Test @Test
public void testIsEmpty() { public void testIsEmpty() {
Assert.assertTrue(Utils.isEmpty(null)); Assertions.assertTrue(Utils.isEmpty(null));
Assert.assertTrue(Utils.isEmpty("")); Assertions.assertTrue(Utils.isEmpty(""));
Assert.assertFalse(Utils.isEmpty("foo")); Assertions.assertFalse(Utils.isEmpty("foo"));
} }
@Test @Test
public void testIndexOf() { public void testIndexOf() {
Assert.assertEquals(-1, Utils.indexOf("bar", "foo", 0)); Assertions.assertEquals(-1, Utils.indexOf("bar", "foo", 0));
Assert.assertEquals(-1, Utils.indexOf("bar", "a", 2)); Assertions.assertEquals(-1, Utils.indexOf("bar", "a", 2));
Assert.assertEquals(1, Utils.indexOf("bar", "a", 0)); Assertions.assertEquals(1, Utils.indexOf("bar", "a", 0));
Assert.assertEquals(1, Utils.indexOf("bar", "a", 1)); Assertions.assertEquals(1, Utils.indexOf("bar", "a", 1));
} }
@Test @Test
public void testNotNull() { public void testNotNull() {
Assert.assertEquals("", Utils.notNull("", "bar", "a", "b", "c")); Assertions.assertEquals("", Utils.notNull("", "bar", "a", "b", "c"));
Assert.assertEquals("foo", Utils.notNull("foo", "bar", "a", "b", "c")); Assertions.assertEquals("foo", Utils.notNull("foo", "bar", "a", "b", "c"));
} }
@Test @Test
public void testNotNullThrow() { public void testNotNullThrow() {
thrown.expect(IllegalArgumentException.class); Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.notNull(null, "bar", "a", "b", "c"));
Utils.notNull(null, "bar", "a", "b", "c");
} }
@Test @Test
public void testCloseQuietly() throws IllegalArgumentException { public void testCloseQuietly() throws IllegalArgumentException {
thrown.expect(IllegalArgumentException.class); Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.notNull(null, "bar", "a", "b", "c"));
Utils.notNull(null, "bar", "a", "b", "c");
} }
@Test @Test
@ -114,56 +106,50 @@ public class UtilsTest {
@Test @Test
public void testIsTrueThrow() { public void testIsTrueThrow() {
thrown.expect(IllegalArgumentException.class); Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.isTrue(false, "foo"));
Utils.isTrue(false, "foo");
} }
@Test @Test
public void testOnlyOneIsTrueThrow1() { public void testOnlyOneIsTrueThrow1() {
thrown.expect(IllegalArgumentException.class); Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.onlyOneIsTrue("foo", false, false));
Utils.onlyOneIsTrue("foo", false, false);
} }
@Test @Test
public void testOnlyOneIsTrueThrow2() { public void testOnlyOneIsTrueThrow2() {
thrown.expect(IllegalArgumentException.class); Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.onlyOneIsTrue("foo", true, true));
Utils.onlyOneIsTrue("foo", true, true);
} }
@Test @Test
public void testOnlyOneIsTrueNonThrow() { public void testOnlyOneIsTrueNonThrow() {
Assert.assertTrue(Utils.onlyOneIsTrueNonThrow(true)); Assertions.assertTrue(Utils.onlyOneIsTrueNonThrow(true));
Assert.assertFalse(Utils.onlyOneIsTrueNonThrow(true, true, true)); Assertions.assertFalse(Utils.onlyOneIsTrueNonThrow(true, true, true));
Assert.assertFalse(Utils.onlyOneIsTrueNonThrow(true, true, false)); Assertions.assertFalse(Utils.onlyOneIsTrueNonThrow(true, true, false));
Assert.assertFalse(Utils.onlyOneIsTrueNonThrow(false, false, false)); Assertions.assertFalse(Utils.onlyOneIsTrueNonThrow(false, false, false));
} }
@Test @Test
public void testNotEmpty() { public void testNotEmpty() {
Assert.assertEquals("bar", Utils.notEmpty("bar", "foo", 1, 2, 3)); Assertions.assertEquals("bar", Utils.notEmpty("bar", "foo", 1, 2, 3));
Assert.assertEquals("baz", Assertions.assertEquals("baz", Utils.notEmpty("baz", "bar", "b", "a", "r"));
Utils.notEmpty("baz", "bar", "b", "a", "r"));
} }
@Test @Test
public void testNotEmptyThrowNull() { public void testNotEmptyThrowNull() {
thrown.expect(IllegalArgumentException.class); Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.notEmpty(null, "foo", 1, 2, 3));
Utils.notEmpty(null, "foo", 1, 2, 3);
} }
@Test @Test
public void testNotEmptyThrowLength0() { public void testNotEmptyThrowLength0() {
thrown.expect(IllegalArgumentException.class); Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.notEmpty("", "foo", 1, 2, 3));
Utils.notEmpty("", "foo", 1, 2, 3);
} }
@Test @Test
public void testToString() { public void testToString() {
Assert.assertNull(Utils.toString(null)); Assertions.assertNull(Utils.toString(null));
Assert.assertEquals("", Utils.toString("")); Assertions.assertEquals("", Utils.toString(""));
Assert.assertEquals("foo", Utils.toString("foo")); Assertions.assertEquals("foo", Utils.toString("foo"));
Assert.assertEquals("123", Utils.toString(123)); 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; package com.jayway.jsonpath.internal.filter;
import com.jayway.jsonpath.BaseTest; 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 java.util.stream.Stream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays; import static org.junit.jupiter.api.Assertions.assertEquals;
@RunWith(Parameterized.class)
public class PatternFlagTest extends BaseTest { public class PatternFlagTest extends BaseTest {
private final int flags;
private final String expectedFlags;
public PatternFlagTest(int flags, String expectedFlags) { @ParameterizedTest
this.flags = flags; @MethodSource("testData")
this.expectedFlags = expectedFlags; public void testParseFlags(int flags, String expectedFlags) {
assertEquals(expectedFlags, PatternFlag.parseFlags(flags));
} }
@Test public static Stream<Arguments> testData() {
public void testParseFlags() { return Stream.of(
Assert.assertEquals(expectedFlags, PatternFlag.parseFlags(flags)); Arguments.arguments(1, "d"),
} Arguments.arguments(2, "i"),
Arguments.arguments(4, "x"),
@Parameterized.Parameters Arguments.arguments(8, "m"),
public static Iterable data() { Arguments.arguments(32, "s"),
return Arrays.asList( Arguments.arguments(64, "u"),
new Object[][]{ Arguments.arguments(256, "U"),
{ 1, "d" }, Arguments.arguments(300, "xmsU"),
{ 2, "i" }, Arguments.arguments(13, "dxm"),
{ 4, "x" }, Arguments.arguments(7, "dix"),
{ 8, "m" }, Arguments.arguments(100, "xsu"),
{ 32, "s" }, Arguments.arguments(367, "dixmsuU")
{ 64, "u" },
{ 256, "U" },
{ 300, "xmsU" },
{ 13, "dxm" },
{ 7, "dix" },
{ 100, "xsu" },
{ 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;
import com.jayway.jsonpath.internal.path.CompiledPath; import com.jayway.jsonpath.internal.path.CompiledPath;
import com.jayway.jsonpath.internal.path.PathTokenFactory; import com.jayway.jsonpath.internal.path.PathTokenFactory;
import org.assertj.core.util.Maps; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.Test; import org.junit.jupiter.params.provider.Arguments;
import org.junit.runner.RunWith; import org.junit.jupiter.params.provider.MethodSource;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.HashMap; 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.equalTo;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static com.jayway.jsonpath.internal.filter.ValueNode.*;
@RunWith(Parameterized.class)
public class RegexpEvaluatorTest extends BaseTest { 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 @ParameterizedTest
public void should_evaluate_regular_expression() { @MethodSource("testData")
public void should_evaluate_regular_expression(String regexp, ValueNode valueNode, boolean expectedResult) {
//given //given
Evaluator evaluator = EvaluatorFactory.createEvaluator(RelationalOperator.REGEX); Evaluator evaluator = EvaluatorFactory.createEvaluator(RelationalOperator.REGEX);
ValueNode patternNode = createPatternNode(regexp); ValueNode patternNode = createPatternNode(regexp);
@ -46,33 +35,29 @@ public class RegexpEvaluatorTest extends BaseTest {
assertThat(result, is(equalTo(expectedResult))); assertThat(result, is(equalTo(expectedResult)));
} }
@Parameterized.Parameters(name="Regexp {0} for {1} node should evaluate to {2}") public static Stream<Arguments> testData() {
public static Iterable data() { return Stream.of(
return Arrays.asList( Arguments.arguments("/true|false/", createStringNode("true", true), true),
new Object[][]{ Arguments.arguments("/9.*9/", createNumberNode("9979"), true),
{ "/true|false/", createStringNode("true", true), true }, Arguments.arguments("/fa.*se/", createBooleanNode("false"), true),
{ "/9.*9/", createNumberNode("9979"), true }, Arguments.arguments("/Eval.*or/", createClassNode(String.class), false),
{ "/fa.*se/", createBooleanNode("false"), true }, Arguments.arguments("/JsonNode/", createJsonNode(json()), false),
{ "/Eval.*or/", createClassNode(String.class), false }, Arguments.arguments("/PathNode/", createPathNode(path()), false),
{ "/JsonNode/", createJsonNode(json()), false }, Arguments.arguments("/Undefined/", createUndefinedNode(), false),
{ "/PathNode/", createPathNode(path()), false }, Arguments.arguments("/NullNode/", createNullNode(), false),
{ "/Undefined/", createUndefinedNode(), false }, Arguments.arguments("/test/i", createStringNode("tEsT", true), true),
{ "/NullNode/", createNullNode(), false }, Arguments.arguments("/test/", createStringNode("tEsT", true), false),
{ "/test/i", createStringNode("tEsT", true), true }, Arguments.arguments("/\u00de/ui", createStringNode("\u00fe", true), true),
{ "/test/", createStringNode("tEsT", true), false }, Arguments.arguments("/\u00de/", createStringNode("\u00fe", true), false),
{ "/\u00de/ui", createStringNode("\u00fe", true), true }, Arguments.arguments("/\u00de/i", createStringNode("\u00fe", true), false),
{ "/\u00de/", createStringNode("\u00fe", true), false }, Arguments.arguments("/test# code/", createStringNode("test", true), false),
{ "/\u00de/i", createStringNode("\u00fe", true), false }, Arguments.arguments("/test# code/x", createStringNode("test", true), true),
{ "/test# code/", createStringNode("test", true), false }, Arguments.arguments("/.*test.*/d", createStringNode("my\rtest", true), true),
{ "/test# code/x", createStringNode("test", true), true }, Arguments.arguments("/.*test.*/", createStringNode("my\rtest", true), false),
{ "/.*test.*/d", createStringNode("my\rtest", true), true }, Arguments.arguments("/.*tEst.*/is", createStringNode("test\ntest", true), true),
{ "/.*test.*/", createStringNode("my\rtest", true), false }, Arguments.arguments("/.*tEst.*/i", createStringNode("test\ntest", true), false),
{ "/.*tEst.*/is", createStringNode("test\ntest", true), true }, Arguments.arguments("/^\\w+$/U", createStringNode("\u00fe", true), true),
{ "/.*tEst.*/i", createStringNode("test\ntest", true), false }, Arguments.arguments("/^\\w+$/", createStringNode("\u00fe", true), false)
{ "/^\\w+$/U", createStringNode("\u00fe", true), true },
{ "/^\\w+$/", createStringNode("\u00fe", true), false },
{ "/^test$\\ntest$/m", createStringNode("test\ntest", true), true }
}
); );
} }

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

@ -1,23 +1,23 @@
package com.jayway.jsonpath.internal.filter; package com.jayway.jsonpath.internal.filter;
import static org.junit.Assert.*; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.After; import org.junit.jupiter.api.Test;
import org.junit.Before;
import org.junit.Test;
import java.util.Locale; import java.util.Locale;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class RelationalOperatorTest { public class RelationalOperatorTest {
Locale locale; Locale locale;
@Before @BeforeEach
public void saveDefaultLocale() { public void saveDefaultLocale() {
locale = Locale.getDefault(); locale = Locale.getDefault();
} }
@After @AfterEach
public void restoreDefaultLocale() { public void restoreDefaultLocale() {
Locale.setDefault(locale); 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.Configuration;
import com.jayway.jsonpath.Configurations; import com.jayway.jsonpath.Configurations;
import com.jayway.jsonpath.JsonPath; 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 java.io.InputStream;
import static org.junit.Assert.assertEquals;
/** /**
* TDD for Issue 191 * TDD for Issue 191
* * <p>
* Shows aggregation across fields rather than within a single entity. * Shows aggregation across fields rather than within a single entity.
*
*/ */
public class Issue191 { public class Issue191 {
@ -23,45 +22,41 @@ public class Issue191 {
public void testResultSetNumericComputation() { public void testResultSetNumericComputation() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json"); InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
Long value = JsonPath.parse(stream).read("$.sum($..timestamp)", Long.class); 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", Assertions.assertEquals(Long.valueOf(35679716813L), value, "Expected the max function to consume the aggregation parameters and calculate the max over the result set");
Long.valueOf(35679716813L), value);
} }
@Test @Test
public void testResultSetNumericComputationTail() { public void testResultSetNumericComputationTail() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json"); InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
Long value = JsonPath.parse(stream).read("$..timestamp.sum()", Long.class); 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", Assertions.assertEquals(Long.valueOf(35679716813L), value, "Expected the max function to consume the aggregation parameters and calculate the max over the result set");
Long.valueOf(35679716813L), value);
} }
@Test @Test
public void testResultSetNumericComputationRecursiveReplacement() { public void testResultSetNumericComputationRecursiveReplacement() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json"); InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
Long value = JsonPath.parse(stream).read("$.max($..timestamp.avg(), $..timestamp.stddev())", Long.class); 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", Assertions.assertEquals(Long.valueOf(1427188672L), value, "Expected the max function to consume the aggregation parameters and calculate the max over the result set");
Long.valueOf(1427188672L), value);
} }
@Test @Test
public void testMultipleResultSetSums() { public void testMultipleResultSetSums() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json"); InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
Long value = JsonPath.parse(stream).read("$.sum($..timestamp, $..cpus)", Long.class); 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", Assertions.assertEquals(Long.valueOf(35679716835L), value, "Expected the max function to consume the aggregation parameters and calculate the max over the result set");
Long.valueOf(35679716835L), value);
} }
@Test @Test
public void testConcatResultSet() { public void testConcatResultSet() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json"); InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
String concatResult = JsonPath.parse(stream).read("$.concat($..state)", String.class); 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 @Test
public void testConcatWithNumericValueAsString() { public void testConcatWithNumericValueAsString() {
InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json"); InputStream stream = ClassLoader.getSystemResourceAsStream("issue_191.json");
String concatResult = JsonPath.parse(stream).read("$.concat($..cpus)", String.class); 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; package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; 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; package com.jayway.jsonpath.internal.function;
import net.minidev.json.JSONArray;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import org.junit.Test; import net.minidev.json.JSONArray;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
public class Issue273 { public class Issue273 {
@Test @Test
public void testGetPropertyFromArray(){ public void testGetPropertyFromArray() {
String json = "[\n" + String json = "[\n" +
" [\n" + " [\n" +
" {\n" + " {\n" +
@ -45,12 +43,12 @@ public class Issue273 {
" }\n" + " }\n" +
"]\n"; "]\n";
JSONArray arr = JsonPath.read(json,"$..[2].author"); JSONArray arr = JsonPath.read(json, "$..[2].author");
assertEquals(arr.get(0), "Herman Melville"); Assertions.assertEquals(arr.get(0), "Herman Melville");
} }
@Test @Test
public void testGetPropertyFromObject(){ public void testGetPropertyFromObject() {
String json = "{\n" + String json = "{\n" +
" \"store\": {\n" + " \"store\": {\n" +
" \"book\": [\n" + " \"book\": [\n" +
@ -89,7 +87,7 @@ public class Issue273 {
" \"expensive\": 10\n" + " \"expensive\": 10\n" +
"}\n" + "}\n" +
" "; " ";
JSONArray arr = JsonPath.read(json,"$..[2].author"); JSONArray arr = JsonPath.read(json, "$..[2].author");
assertEquals(arr.get(0), "Herman Melville"); 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; package com.jayway.jsonpath.internal.function;
import com.fasterxml.jackson.core.JsonProcessingException; import com.jayway.jsonpath.Configuration;
import com.fasterxml.jackson.databind.JsonNode; import com.jayway.jsonpath.DocumentContext;
import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.*; import org.junit.jupiter.api.Assertions;
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider; import org.junit.jupiter.api.Test;
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;
public class Issue612 { public class Issue612 {
@Test @Test
@ -22,16 +16,18 @@ public class Issue612 {
String json = "{\"1\":{\"2\":null}}"; String json = "{\"1\":{\"2\":null}}";
DocumentContext documentContext = JsonPath.using(config).parse(json); DocumentContext documentContext = JsonPath.using(config).parse(json);
JsonPath query = JsonPath.compile("$.1.2.a.b.c"); JsonPath query = JsonPath.compile("$.1.2.a.b.c");
Assert.assertNull(documentContext.read(query)); Assertions.assertNull(documentContext.read(query));
Assert.assertNull(documentContext.map(query, (object, configuration) -> object)); Assertions.assertNull(documentContext.map(query, (object, configuration) -> object));
} }
@Test(expected = Exception.class)
@Test
public void test2() { public void test2() {
Configuration config = Configuration.builder() Configuration config = Configuration.builder()
.build(); .build();
String json = "{\"1\":{\"2\":null}}"; String json = "{\"1\":{\"2\":null}}";
DocumentContext documentContext = JsonPath.using(config).parse(json); DocumentContext documentContext = JsonPath.using(config).parse(json);
JsonPath query = JsonPath.compile("$.1.2.a.b.c"); 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; package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.IOException; import java.io.IOException;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.fail;
public class Issue629 { public class Issue629 {
@ -15,8 +15,7 @@ public class Issue629 {
try { try {
JsonPath jsonPath = JsonPath.compile("$.A.B.C.D("); JsonPath jsonPath = JsonPath.compile("$.A.B.C.D(");
fail("accepted jsonpath with unclosed parentheses"); fail("accepted jsonpath with unclosed parentheses");
} } catch (Exception e) {
catch (Exception e) {
assertTrue(e.getMessage().startsWith("Arguments to function:")); assertTrue(e.getMessage().startsWith("Arguments to function:"));
} }
} }
@ -26,8 +25,7 @@ public class Issue629 {
try { try {
JsonPath jsonPath = JsonPath.compile("$.A.B.C.sum(D()"); JsonPath jsonPath = JsonPath.compile("$.A.B.C.sum(D()");
fail("accepted jsonpath with unclosed parentheses"); fail("accepted jsonpath with unclosed parentheses");
} } catch (Exception e) {
catch (Exception e) {
assertTrue(e.getMessage().startsWith("Arguments to function:")); 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; package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.json.JsonSmartJsonProvider; import org.junit.jupiter.api.Test;
import com.jayway.jsonpath.spi.mapper.JsonSmartMappingProvider;
import org.junit.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; 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.Configuration;
import com.jayway.jsonpath.Configurations; import com.jayway.jsonpath.Configurations;
import net.minidev.json.JSONArray; 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. * 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.Configuration;
import com.jayway.jsonpath.Configurations; import com.jayway.jsonpath.Configurations;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; 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.Configuration;
import com.jayway.jsonpath.Configurations; import com.jayway.jsonpath.Configurations;
import org.junit.Test; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runner.RunWith; import org.junit.jupiter.params.provider.MethodSource;
import org.junit.runners.Parameterized;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static com.jayway.jsonpath.JsonPath.using; 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. * Created by matt@mjgreenwood.net on 12/10/15.
*/ */
@RunWith(Parameterized.class)
public class NestedFunctionTest extends BaseFunctionTest { public class NestedFunctionTest extends BaseFunctionTest {
private static final Logger logger = LoggerFactory.getLogger(NumericPathFunctionTest.class); 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() { public static Iterable<Configuration> configurations() {
return Configurations.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); 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); verifyMathFunction(conf, "$.numbers.avg()", 5.5);
} }
/** /**
* This test calculates the following: * This test calculates the following:
* * <p>
* For each number in $.numbers 1 -> 10 add each number up, * For each number in $.numbers 1 -> 10 add each number up,
* then add 1 (min), 10 (max) * then add 1 (min), 10 (max)
* * <p>
* Alternatively 1+2+3+4+5+6+7+8+9+10+1+10 == 66 * 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); 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); 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(5)", 5.0);
verifyMathFunction(conf, "$.sum(50)", 50.0); verifyMathFunction(conf, "$.sum(50)", 50.0);
} }
@Test
public void testStringConcat() { @ParameterizedTest
@MethodSource("configurations")
public void testStringConcat(Configuration conf) {
verifyTextFunction(conf, "$.text.concat()", "abcdef"); 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"); 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"); 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); verifyMathFunction(conf, "$.numbers.append(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0).avg()", 10.0);
} }
/** /**
* Aggregation function should ignore text values * 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); verifyMathFunction(conf, "$.numbers.append(\"0\", \"11\").sum()", 55.0);
} }
@Test
public void testErrantCloseBraceNegative() { @ParameterizedTest
@MethodSource("configurations")
public void testErrantCloseBraceNegative(Configuration conf) {
try { try {
using(conf).parse(this.NUMBER_SERIES).read("$.numbers.append(0, 1, 2}).avg()"); using(conf).parse(this.NUMBER_SERIES).read("$.numbers.append(0, 1, 2}).avg()");
assert(false); assert (false);
} } catch (Exception e) {
catch (Exception e) {
assertTrue(e.getMessage().startsWith("Unexpected close brace")); assertTrue(e.getMessage().startsWith("Unexpected close brace"));
} }
} }
@Test
public void testErrantCloseBracketNegative() { @ParameterizedTest
@MethodSource("configurations")
public void testErrantCloseBracketNegative(Configuration conf) {
try { try {
using(conf).parse(this.NUMBER_SERIES).read("$.numbers.append(0, 1, 2]).avg()"); using(conf).parse(this.NUMBER_SERIES).read("$.numbers.append(0, 1, 2]).avg()");
assert(false); assert (false);
} } catch (Exception e) {
catch (Exception e) {
assertTrue(e.getMessage().startsWith("Unexpected close bracket")); assertTrue(e.getMessage().startsWith("Unexpected close bracket"));
} }
} }
@Test
public void testUnclosedFunctionCallNegative() { @ParameterizedTest
@MethodSource("configurations")
public void testUnclosedFunctionCallNegative(Configuration conf) {
try { try {
using(conf).parse(this.NUMBER_SERIES).read("$.numbers.append(0, 1, 2"); using(conf).parse(this.NUMBER_SERIES).read("$.numbers.append(0, 1, 2");
assert(false); assert (false);
} } catch (Exception e) {
catch (Exception e) {
assertTrue(e.getMessage().startsWith("Arguments to function: 'append'")); 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.Configuration;
import com.jayway.jsonpath.Configurations; import com.jayway.jsonpath.Configurations;
import com.jayway.jsonpath.JsonPathException; import com.jayway.jsonpath.JsonPathException;
import org.junit.Test; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runner.RunWith; import org.junit.jupiter.params.provider.MethodSource;
import org.junit.runners.Parameterized;
import org.slf4j.Logger; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.runners.Parameterized.Parameters;
/** /**
* Defines functional tests around executing: * Defines functional tests around executing:
* * <p>
* - sum * - sum
* - avg * - avg
* - stddev * - stddev
* * <p>
* for each of the above, executes the test and verifies that the results are as expected based on a static input * for each of the above, executes the test and verifies that the results are as expected based on a static input
* and static output. * and static output.
* * <p>
* Created by mattg on 6/26/15. * Created by mattg on 6/26/15.
*/ */
@RunWith(Parameterized.class)
public class NumericPathFunctionTest extends BaseFunctionTest { 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() { public static Iterable<Configuration> configurations() {
return Configurations.configurations(); return Configurations.configurations();
} }
@Test @ParameterizedTest
public void testAverageOfDoubles() { @MethodSource("configurations")
public void testAverageOfDoubles(Configuration conf) {
verifyMathFunction(conf, "$.numbers.avg()", 5.5); verifyMathFunction(conf, "$.numbers.avg()", 5.5);
} }
@Test @ParameterizedTest
public void testAverageOfEmptyListNegative() { @MethodSource("configurations")
public void testAverageOfEmptyListNegative(Configuration conf) {
try { try {
verifyMathFunction(conf, "$.empty.avg()", null); verifyMathFunction(conf, "$.empty.avg()", null);
} catch (JsonPathException e) { } catch (JsonPathException e) {
@ -56,13 +44,15 @@ public class NumericPathFunctionTest extends BaseFunctionTest {
} }
} }
@Test @ParameterizedTest
public void testSumOfDouble() { @MethodSource("configurations")
public void testSumOfDouble(Configuration conf) {
verifyMathFunction(conf, "$.numbers.sum()", (10d * (10d + 1d)) / 2d); verifyMathFunction(conf, "$.numbers.sum()", (10d * (10d + 1d)) / 2d);
} }
@Test @ParameterizedTest
public void testSumOfEmptyListNegative() { @MethodSource("configurations")
public void testSumOfEmptyListNegative(Configuration conf) {
try { try {
verifyMathFunction(conf, "$.empty.sum()", null); verifyMathFunction(conf, "$.empty.sum()", null);
} catch (JsonPathException e) { } catch (JsonPathException e) {
@ -70,13 +60,15 @@ public class NumericPathFunctionTest extends BaseFunctionTest {
} }
} }
@Test @ParameterizedTest
public void testMaxOfDouble() { @MethodSource("configurations")
public void testMaxOfDouble(Configuration conf) {
verifyMathFunction(conf, "$.numbers.max()", 10d); verifyMathFunction(conf, "$.numbers.max()", 10d);
} }
@Test @ParameterizedTest
public void testMaxOfEmptyListNegative() { @MethodSource("configurations")
public void testMaxOfEmptyListNegative(Configuration conf) {
try { try {
verifyMathFunction(conf, "$.empty.max()", null); verifyMathFunction(conf, "$.empty.max()", null);
} catch (JsonPathException e) { } catch (JsonPathException e) {
@ -84,13 +76,15 @@ public class NumericPathFunctionTest extends BaseFunctionTest {
} }
} }
@Test @ParameterizedTest
public void testMinOfDouble() { @MethodSource("configurations")
public void testMinOfDouble(Configuration conf) {
verifyMathFunction(conf, "$.numbers.min()", 1d); verifyMathFunction(conf, "$.numbers.min()", 1d);
} }
@Test @ParameterizedTest
public void testMinOfEmptyListNegative() { @MethodSource("configurations")
public void testMinOfEmptyListNegative(Configuration conf) {
try { try {
verifyMathFunction(conf, "$.empty.min()", null); verifyMathFunction(conf, "$.empty.min()", null);
} catch (JsonPathException e) { } catch (JsonPathException e) {
@ -99,13 +93,15 @@ public class NumericPathFunctionTest extends BaseFunctionTest {
} }
@Test @ParameterizedTest
public void testStdDevOfDouble() { @MethodSource("configurations")
public void testStdDevOfDouble(Configuration conf) {
verifyMathFunction(conf, "$.numbers.stddev()", 2.8722813232690143d); verifyMathFunction(conf, "$.numbers.stddev()", 2.8722813232690143d);
} }
@Test @ParameterizedTest
public void testStddevOfEmptyListNegative() { @MethodSource("configurations")
public void testStddevOfEmptyListNegative(Configuration conf) {
try { try {
verifyMathFunction(conf, "$.empty.stddev()", null); verifyMathFunction(conf, "$.empty.stddev()", null);
} catch (JsonPathException e) { } 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.Configuration;
import com.jayway.jsonpath.Configurations; import com.jayway.jsonpath.Configurations;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test cases for functions * 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; package com.jayway.jsonpath.internal.path;
import com.jayway.jsonpath.BaseTest; import com.jayway.jsonpath.BaseTest;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;

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

@ -1,6 +1,6 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.time.ZoneOffset; 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 com.jayway.jsonpath.JsonPath;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
*
* If you have a list * If you have a list
* nums = [1, 3, 5, 7, 8, 13, 20] * nums = [1, 3, 5, 7, 8, 13, 20]
* then it is possible to slice by using a notation similar to element retrieval: * then it is possible to slice by using a notation similar to element retrieval:
* * <p>
* nums[3] #equals 7, no slicing * nums[3] #equals 7, no slicing
* nums[:3] #equals [1, 3, 5], from index 0 (inclusive) until index 3 (exclusive) * nums[:3] #equals [1, 3, 5], from index 0 (inclusive) until index 3 (exclusive)
* nums[1:5] #equals [3, 5, 7, 8] * nums[1:5] #equals [3, 5, 7, 8]
* nums[-3:] #equals [8, 13, 20] * nums[-3:] #equals [8, 13, 20]
* 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. * 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: * 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 [7, 8, 13, 20], same as nums[3:]
* nums[::3] #equals [1, 7, 20] (starting at index 0 and getting every third element) * 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) * nums[1:5:2] #equals [3, 7] (from index 1 until index 5 and getting every second element)
*
*/ */
public class ArraySlicingTest { public class ArraySlicingTest {
public static final String JSON_ARRAY = "[1, 3, 5, 7, 8, 13, 20]"; public static final String JSON_ARRAY = "[1, 3, 5, 7, 8, 13, 20]";
@Test @Test
public void get_by_position(){ public void get_by_position() {
Integer result = JsonPath.read(JSON_ARRAY, "$[3]"); Integer result = JsonPath.read(JSON_ARRAY, "$[3]");
assertEquals(7, result.intValue()); assertEquals(7, result.intValue());
} }
@Test @Test
public void get_from_index(){ public void get_from_index() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[:3]"); List<Integer> result = JsonPath.read(JSON_ARRAY, "$[:3]");
assertThat(result, Matchers.contains(1,3,5)); assertThat(result, Matchers.contains(1, 3, 5));
} }
@Test @Test
public void get_between_index(){ public void get_between_index() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[1:5]"); List<Integer> result = JsonPath.read(JSON_ARRAY, "$[1:5]");
assertThat(result, Matchers.contains(3, 5, 7, 8)); assertThat(result, Matchers.contains(3, 5, 7, 8));
} }
@Test @Test
public void get_between_index_2(){ public void get_between_index_2() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[0:1]"); List<Integer> result = JsonPath.read(JSON_ARRAY, "$[0:1]");
assertThat(result, Matchers.contains(1)); assertThat(result, Matchers.contains(1));
} }
@Test @Test
public void get_between_index_3(){ public void get_between_index_3() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[0:2]"); List<Integer> result = JsonPath.read(JSON_ARRAY, "$[0:2]");
assertThat(result, Matchers.contains(1,3)); assertThat(result, Matchers.contains(1, 3));
} }
@Test @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]"); List<Integer> result = JsonPath.read(JSON_ARRAY, "$[1:15]");
assertThat(result, Matchers.contains(3, 5, 7, 8, 13, 20)); assertThat(result, Matchers.contains(3, 5, 7, 8, 13, 20));
} }
@Test @Test
public void get_from_tail_index(){ public void get_from_tail_index() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[-3:]"); List<Integer> result = JsonPath.read(JSON_ARRAY, "$[-3:]");
assertThat(result, Matchers.contains(8, 13, 20)); assertThat(result, Matchers.contains(8, 13, 20));
} }
@Test @Test
public void get_from_tail(){ public void get_from_tail() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[3:]"); List<Integer> result = JsonPath.read(JSON_ARRAY, "$[3:]");
assertThat(result, Matchers.contains(7, 8, 13, 20)); assertThat(result, Matchers.contains(7, 8, 13, 20));
} }
@Test @Test
public void get_indexes(){ public void get_indexes() {
List<Integer> result = JsonPath.read(JSON_ARRAY, "$[0,1,2]"); 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 com.jayway.jsonpath.JsonPath;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.assertTrue;
/** /**
* test defined in http://jsonpath.googlecode.com/svn/trunk/tests/jsonpath-test-js.html * 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.<String>read(json, "$.['c d']"), is(equalTo("e")));
assertThat(JsonPath.<List<String>>read(json, "$[*]"), hasItems("a", "b", "e")); assertThat(JsonPath.<List<String>>read(json, "$[*]"), hasItems("a", "b", "e"));
} }
@Test @Test
public void test_two() throws Exception { public void test_two() throws Exception {
String json = "[ 1, \"2\", 3.14, true, null ]"; String json = "[ 1, \"2\", 3.14, true, null ]";
@ -43,7 +43,7 @@ public class ComplianceTest {
new String("2"), new String("2"),
new Double(3.14), new Double(3.14),
new Boolean(true), new Boolean(true),
(Comparable)null)); (Comparable) null));
List<Object> res = JsonPath.read(json, "$[-1:]"); 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; package com.jayway.jsonpath.old;
import com.jayway.jsonpath.BaseTest; import com.jayway.jsonpath.*;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Filter;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Predicate;
import com.jayway.jsonpath.spi.json.JsonProvider; import com.jayway.jsonpath.spi.json.JsonProvider;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; 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.Criteria.where;
import static com.jayway.jsonpath.Filter.filter; import static com.jayway.jsonpath.Filter.filter;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is; 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 { public class FilterTest extends BaseTest {
@ -75,7 +71,6 @@ public class FilterTest extends BaseTest {
} }
@Test @Test
public void ne_filters_evaluates() throws Exception { public void ne_filters_evaluates() throws Exception {
final Map<String, Object> check = new HashMap<String, Object>(); final Map<String, Object> check = new HashMap<String, Object>();
@ -270,17 +265,17 @@ public class FilterTest extends BaseTest {
Filter filter = filter( Filter filter = filter(
where("first-name").is("Jock") 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>> 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(); JsonPath.parse(json).json();
assertThat((String)JsonPath.read(jocksInTexas1, "$[0].address.state"), is("Texas")); 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].first-name"), is("Jock"));
assertThat((String)JsonPath.read(jocksInTexas1, "$[0].last-name"), is("Ewing")); assertThat((String) JsonPath.read(jocksInTexas1, "$[0].last-name"), is("Ewing"));
} }
@ -308,8 +303,6 @@ public class FilterTest extends BaseTest {
} }
@Test @Test
public void arrays_of_maps_can_be_filtered() throws Exception { 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)); root.put("children", asList(rootChild_A, rootChild_B, rootChild_C));
Predicate customFilter = new Predicate () { Predicate customFilter = new Predicate() {
@Override @Override
public boolean apply(PredicateContext ctx) { public boolean apply(PredicateContext ctx) {
if (ctx.configuration().jsonProvider().getMapValue(ctx.item(), "name").equals("rootGrandChild_A")) { if (ctx.configuration().jsonProvider().getMapValue(ctx.item(), "name").equals("rootGrandChild_A")) {
@ -366,7 +359,7 @@ public class FilterTest extends BaseTest {
Predicate customFilter = new Predicate() { Predicate customFilter = new Predicate() {
@Override @Override
public boolean apply(PredicateContext ctx) { 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.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.jayway.jsonpath.BaseTest; import com.jayway.jsonpath.*;
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.internal.Utils; import com.jayway.jsonpath.internal.Utils;
import com.jayway.jsonpath.spi.cache.LRUCache; import com.jayway.jsonpath.spi.cache.LRUCache;
import com.jayway.jsonpath.spi.json.GsonJsonProvider; import com.jayway.jsonpath.spi.json.GsonJsonProvider;
@ -22,7 +15,7 @@ import net.minidev.json.JSONAware;
import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.JSONParser;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.InputStream; import java.io.InputStream;
import java.util.Collections; 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.Filter.filter;
import static com.jayway.jsonpath.JsonPath.read; import static com.jayway.jsonpath.JsonPath.read;
import static com.jayway.jsonpath.JsonPath.using; 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.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertThat;
public class IssuesTest extends BaseTest { public class IssuesTest extends BaseTest {
@ -51,7 +42,7 @@ public class IssuesTest extends BaseTest {
public void issue_143() { public void issue_143() {
String json = "{ \"foo\": { \"bar\" : \"val\" }, \"moo\": { \"cow\" : \"val\" } }"; 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")); 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"); List<String> result = read(json, "$.p.['s', 't'].u");
assertThat(result).containsExactly("su","tu"); assertThat(result).containsExactly("su", "tu");
} }
@Test @Test
@ -86,9 +77,9 @@ public class IssuesTest extends BaseTest {
assertThat(result).isEmpty(); assertThat(result).isEmpty();
} }
@Test(expected = InvalidPathException.class) @Test
public void issue_114_d() { 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'].*"); List<Integer> result = read(json, "$.datas.selling['3','206'].*");
assertThat(result).containsExactly(26452067,31625950,32381852,32489262); assertThat(result).containsExactly(26452067, 31625950, 32381852, 32489262);
} }
@Test @Test
@ -161,10 +152,10 @@ public class IssuesTest extends BaseTest {
assertTrue(result.isEmpty()); assertTrue(result.isEmpty());
} }
@Test(expected = PathNotFoundException.class) @Test
public void issue_11b() throws Exception { public void issue_11b() throws Exception {
String json = "{ \"foo\" : [] }"; String json = "{ \"foo\" : [] }";
read(json, "$.foo[0].uri"); assertThrows(PathNotFoundException.class, () -> read(json, "$.foo[0].uri"));
} }
@Test @Test
@ -318,13 +309,13 @@ public class IssuesTest extends BaseTest {
} }
@Test(expected = PathNotFoundException.class) @Test
public void issue_22() throws Exception { public void issue_22() throws Exception {
Configuration configuration = Configuration.defaultConfiguration(); Configuration configuration = Configuration.defaultConfiguration();
String json = "{\"a\":{\"b\":1,\"c\":2}}"; 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 @Test
@ -344,10 +335,10 @@ public class IssuesTest extends BaseTest {
assertThat(res).hasSize(1).containsNull(); assertThat(res).hasSize(1).containsNull();
} }
@Test(expected = PathNotFoundException.class) @Test
public void issue_26() throws Exception { public void issue_26() throws Exception {
String json = "[{\"a\":[{\"b\":1,\"c\":2}]}]"; String json = "[{\"a\":[{\"b\":1,\"c\":2}]}]";
Object o = read(json, "$.a"); assertThrows(PathNotFoundException.class, () -> read(json, "$.a"));
} }
@Test @Test
@ -434,7 +425,7 @@ public class IssuesTest extends BaseTest {
assertEquals(Integer.valueOf(1), read(json, "$[0].a")); assertEquals(Integer.valueOf(1), read(json, "$[0].a"));
} }
@Test(expected = PathNotFoundException.class) @Test
public void a_test() { public void a_test() {
String json = "{\n" + String json = "{\n" +
@ -448,7 +439,7 @@ public class IssuesTest extends BaseTest {
" \"version\": 1371160528774\n" + " \"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}"; 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 { try {
read(json, "nonExistingProperty"); read(json, "nonExistingProperty");
@ -498,7 +489,7 @@ public class IssuesTest extends BaseTest {
public void issue_45() { public void issue_45() {
String json = "{\"rootkey\":{\"sub.key\":\"value\"}}"; 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 @Test
@ -508,7 +499,7 @@ public class IssuesTest extends BaseTest {
String json = "{\"a\": {}}"; String json = "{\"a\": {}}";
Configuration configuration = Configuration.defaultConfiguration().setOptions(Option.SUPPRESS_EXCEPTIONS); 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 { try {
read(json, "a.x"); read(json, "a.x");
@ -818,7 +809,7 @@ public class IssuesTest extends BaseTest {
assertThat(parsed.apply(createPredicateContext(noMatch))).isFalse(); 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() { return new PredicateContext() {
@Override @Override
public Object item() { public Object item() {
@ -827,7 +818,7 @@ public class IssuesTest extends BaseTest {
@Override @Override
public <T> T item(Class<T> clazz) throws MappingException { public <T> T item(Class<T> clazz) throws MappingException {
return (T)map; return (T) map;
} }
@Override @Override
@ -951,14 +942,14 @@ public class IssuesTest extends BaseTest {
assertThat(numbers).containsExactly(8.95D, 12.99D, 8.99D, 22.99D); assertThat(numbers).containsExactly(8.95D, 12.99D, 8.99D, 22.99D);
} }
@Test(expected = PathNotFoundException.class) @Test
public void github_89() { public void github_89() {
com.google.gson.JsonObject json = new JsonObject(); com.google.gson.JsonObject json = new JsonObject();
json.addProperty("foo", "bar"); json.addProperty("foo", "bar");
JsonPath path = JsonPath.compile("$.foo"); 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 @Test
public void issue_309(){ public void issue_309() {
String json = "{\n" + String json = "{\n" +
"\"jsonArr\": [\n" + "\"jsonArr\": [\n" +
@ -1018,27 +1009,27 @@ public class IssuesTest extends BaseTest {
DocumentContext doc = JsonPath.parse(json).set("$.jsonArr[1].name", "Jayway"); DocumentContext doc = JsonPath.parse(json).set("$.jsonArr[1].name", "Jayway");
assertThat((String)doc.read("$.jsonArr[0].name")).isEqualTo("nOne"); assertThat((String) doc.read("$.jsonArr[0].name")).isEqualTo("nOne");
assertThat((String)doc.read("$.jsonArr[1].name")).isEqualTo("Jayway"); assertThat((String) doc.read("$.jsonArr[1].name")).isEqualTo("Jayway");
} }
@Test @Test
public void issue_378(){ public void issue_378() {
String json = "{\n" + String json = "{\n" +
" \"nodes\": {\n" + " \"nodes\": {\n" +
" \"unnamed1\": {\n" + " \"unnamed1\": {\n" +
" \"ntpServers\": [\n" + " \"ntpServers\": [\n" +
" \"1.2.3.4\"\n" + " \"1.2.3.4\"\n" +
" ]\n" + " ]\n" +
" }\n" + " }\n" +
" }\n" + " }\n" +
"}"; "}";
Configuration configuration = Configuration.builder() Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider()) .jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider()) .mappingProvider(new JacksonMappingProvider())
.build(); .build();
DocumentContext ctx = JsonPath.using(configuration).parse(json); 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 //CS304 (manually written) Issue link: https://github.com/json-path/JsonPath/issues/620
@Test @Test
public void issue_620_1(){ public void issue_620_1() {
String json = "{\n" + String json = "{\n" +
" \"complexText\": {\n" + " \"complexText\": {\n" +
" \"nestedFields\": [\n" + " \"nestedFields\": [\n" +
@ -1077,12 +1068,13 @@ public class IssuesTest extends BaseTest {
"$.complexText.nestedFields[1].name," + "$.complexText.nestedFields[1].name," +
"$.complexText.nestedFields[0].name)"; "$.complexText.nestedFields[0].name)";
assertThat((String)JsonPath.read(json,path1)).isEqualTo("CBA"); assertThat((String) JsonPath.read(json, path1)).isEqualTo("CBA");
assertThat((String)JsonPath.read(json,path2)).isEqualTo("CBA"); assertThat((String) JsonPath.read(json, path2)).isEqualTo("CBA");
} }
//CS304 (manually written) Issue link: https://github.com/json-path/JsonPath/issues/620 //CS304 (manually written) Issue link: https://github.com/json-path/JsonPath/issues/620
@Test @Test
public void issue_620_2(){ public void issue_620_2() {
String json = "{\n" + String json = "{\n" +
" \"complexText\": {\n" + " \"complexText\": {\n" +
" \"nestedFields\": [\n" + " \"nestedFields\": [\n" +
@ -1109,7 +1101,7 @@ public class IssuesTest extends BaseTest {
boolean thrown = false; boolean thrown = false;
try { try {
Object result = (Object) JsonPath.read(json,path1); Object result = (Object) JsonPath.read(json, path1);
} catch (Exception e) { } catch (Exception e) {
thrown = true; thrown = true;
} }

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

@ -1,21 +1,17 @@
package com.jayway.jsonpath.old; package com.jayway.jsonpath.old;
import com.jayway.jsonpath.BaseTest; import com.jayway.jsonpath.*;
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.internal.path.PathCompiler; import com.jayway.jsonpath.internal.path.PathCompiler;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
public class JsonPathTest extends BaseTest { 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\"}}]]"; 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() { public void missing_prop() {
//Object read = JsonPath.using(Configuration.defaultConfiguration().setOptions(Option.THROW_ON_MISSING_PROPERTY)).parse(DOCUMENT).read("$.store.book[*].fooBar"); assertThrows(PathNotFoundException.class, () -> JsonPath.using(Configuration.defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(DOCUMENT).read("$.store.book[*].fooBar.not"));
//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");
} }
@ -133,7 +127,7 @@ public class JsonPathTest extends BaseTest {
Assertions.fail("Expected PathNotFoundException"); Assertions.fail("Expected PathNotFoundException");
} catch (PathNotFoundException e) { } 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 @Test
@ -296,9 +290,9 @@ public class JsonPathTest extends BaseTest {
List<String> all = JsonPath.read(DOCUMENT, "$..*"); List<String> all = JsonPath.read(DOCUMENT, "$..*");
} }
@Test(expected = PathNotFoundException.class) @Test
public void access_index_out_of_bounds_does_not_throw_exception() throws Exception { 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 @Test
@ -311,21 +305,21 @@ public class JsonPathTest extends BaseTest {
@Test @Test
// see https://code.google.com/p/json-path/issues/detail?id=58 // see https://code.google.com/p/json-path/issues/detail?id=58
public void invalid_paths_throw_invalid_path_exception() throws Exception { public void invalid_paths_throw_invalid_path_exception() throws Exception {
for (String path : new String[]{"$.", "$.results[?"}){ for (String path : new String[]{"$.", "$.results[?"}) {
try{ try {
JsonPath.compile(path); JsonPath.compile(path);
} catch (InvalidPathException e){ } catch (InvalidPathException e) {
// that's expected // that's expected
} catch (Exception e){ } catch (Exception e) {
fail("Expected an InvalidPathException trying to compile '"+path+"', but got a "+e.getClass().getName()); 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 //see https://github.com/json-path/JsonPath/issues/428
public void prevent_stack_overflow_error_when_unclosed_property() { 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; package com.jayway.jsonpath.old;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider; import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class JsonProviderTest { 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.Option;
import com.jayway.jsonpath.PathNotFoundException; import com.jayway.jsonpath.PathNotFoundException;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows;
public class NullHandlingTest { public class NullHandlingTest {
@ -36,9 +36,9 @@ public class NullHandlingTest {
"}"; "}";
@Test(expected = PathNotFoundException.class) @Test
public void not_defined_property_throws_PathNotFoundException() { 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 @Test
public void null_property_returns_null() { public void null_property_returns_null() {
Integer age = JsonPath.read(DOCUMENT, "$.children[1].age"); Integer age = JsonPath.read(DOCUMENT, "$.children[1].age");
assertEquals(null, age); assertNull(age);
} }
@Test @Test

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

@ -1,19 +1,17 @@
package com.jayway.jsonpath.old.internal; package com.jayway.jsonpath.old.internal;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import org.junit.Assert;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ArrayIndexFilterTest { 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 @Test
public void tail_does_not_throw_when_index_out_of_bounds() { public void tail_does_not_throw_when_index_out_of_bounds() {
@ -49,7 +47,7 @@ public class ArrayIndexFilterTest {
@Test @Test
public void can_access_items_from_end_with_negative_index() { public void can_access_items_from_end_with_negative_index() {
int result = JsonPath.parse(JSON).read("$[-3]"); 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; package com.jayway.jsonpath.old.internal;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import java.util.Map; 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.Configuration;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import java.util.Map; 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.JsonPath;
import com.jayway.jsonpath.Option; import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.PathNotFoundException; import com.jayway.jsonpath.PathNotFoundException;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat; 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 { public class PropertyPathTokenTest {
@ -52,21 +53,14 @@ public class PropertyPathTokenTest {
} }
@Test(expected = PathNotFoundException.class) @Test
public void property_not_found_deep() { public void property_not_found_deep() {
assertThrows(PathNotFoundException.class, () -> JsonPath.read(SIMPLE_MAP, "$.foo.not-found"));
String result = JsonPath.read(SIMPLE_MAP, "$.foo.not-found");
assertThat(result).isNull();
} }
@Test(expected = PathNotFoundException.class) @Test
public void property_not_found_option_throw() { public void property_not_found_option_throw() {
assertThrows(PathNotFoundException.class, () -> JsonPath.using(Configuration.defaultConfiguration()).parse(SIMPLE_MAP).read("$.not-found"));
//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();
} }
@Test @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.Configuration;
import com.jayway.jsonpath.internal.path.PathCompiler; import com.jayway.jsonpath.internal.path.PathCompiler;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; 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; package com.jayway.jsonpath.old.internal;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;

Loading…
Cancel
Save