Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for optional marker #40

Merged
merged 7 commits into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
root = true

[*]
end_of_line = lf
insert_final_newline = true
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ There are several markers as followings:
| `#regex STR` | Expects actual (string) value to match the regular-expression 'STR' (see examples below) |
| `#[NUM] EXPR` | Advanced array marker. When NUM is provided, array must has length just NUM. When EXPR is provided, array's element must match the pattern 'EXPR' (see examples below) |

### Optional marker

You can use double hash `##` to mark a field as optional. For example, `##string` means that the field can be a string, null or not present.

### Examples

| Pattern | `{}` | `{ "a": null }` | `{ "a": "abc" }` |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static JsonPatternNode parse(@NotNull JsonNode jsonNode) {
} else if (jsonNode.isArray()) {
return parseArray(jsonNode);
} else {
return parseValue(jsonNode);
return parseSimpleValue(jsonNode);
}
}

Expand Down Expand Up @@ -57,7 +57,7 @@ private static JsonPatternNode parseArray(@NotNull JsonNode jsonNode) {
}

@NotNull
private static JsonPatternNode parseValue(@NotNull JsonNode jsonNode) {
private static JsonPatternNode parseSimpleValue(@NotNull JsonNode jsonNode) {
if (jsonNode.isTextual()) {
JsonPatternNode parsed = parseMarkerOrNull(jsonNode.textValue());
if (parsed != null) {
Expand All @@ -70,21 +70,42 @@ private static JsonPatternNode parseValue(@NotNull JsonNode jsonNode) {

@Nullable
private static JsonPatternNode parseMarkerOrNull(@NotNull String value) {
if (!value.startsWith("#")) {
return null;
}

switch (value) {
case "#ignore":
return IgnoreMarkerPatternNode.getInstance();
case "#null":
return TypeMarkerPatternNode.NULL;
case "#notnull":
return NotNullMarkerPatternNode.getInstance();
case "#present":
return PresentMarkerPatternNode.getInstance();
case "#notpresent":
return NotPresentMarkerPatternNode.getInstance();
}

if (value.startsWith("##")) {
var innerNode = parseValueMarkerOrNull(value.substring(1));
if (innerNode != null) {
return new OptionalPatternNode(JsonUtil.toJsonString(value), innerNode);
} else {
return null;
}
} else {
return parseValueMarkerOrNull(value);
}
}

@Nullable
private static JsonPatternNode parseValueMarkerOrNull(@NotNull String value) {
switch (value) {
case "#array":
return new ArrayMarkerPatternNode(JsonUtil.toJsonString(value));
case "#object":
return new ObjectMarkerPatternNode(JsonUtil.toJsonString(value));
case "#null":
return TypeMarkerPatternNode.NULL;
case "#boolean":
return TypeMarkerPatternNode.BOOLEAN;
case "#number":
Expand All @@ -103,6 +124,11 @@ private static JsonPatternNode parseMarkerOrNull(@NotNull String value) {
return new RegexMarkerPatternNode(JsonUtil.toJsonString(value), value.substring("#regex".length()).trim());
}

return parseArrayMarkerOrNull(value);
}

@Nullable
private static JsonPatternNode parseArrayMarkerOrNull(@NotNull String value) {
Matcher arrayMatcher = ARRAY_PATTERN.matcher(value);
if (arrayMatcher.matches()) {
String length = arrayMatcher.group(1);
Expand All @@ -115,7 +141,6 @@ private static JsonPatternNode parseMarkerOrNull(@NotNull String value) {
return new ArrayMarkerPatternNode(JsonUtil.toJsonString(value), Integer.parseInt(length), childPattern);
}
}

return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,13 @@ public String toString() {
", expected: " + expected +
", reason: " + reason;
}

/**
* Creates a new JSON match error detail with the expected JSON string.
* @param expected The expected JSON string.
* @return A new JSON match error detail.
*/
public @NotNull JsonMatchErrorDetail withExpected(String expected) {
return new JsonMatchErrorDetail(path, actual, expected, reason);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public abstract class JsonPatternNode {
/**
* The string representation of the expected JSON pattern.
*/
private final String expected;
protected final String expected;

/**
* Constructor of the JSON pattern node.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package io.github.orangain.jsonmatch.pattern;

import com.fasterxml.jackson.databind.JsonNode;
import io.github.orangain.jsonmatch.json.JsonPath;
import org.jetbrains.annotations.NotNull;

import java.util.Optional;

/**
* JSON pattern node that matches an optional JSON node. Optional means that the node can be missing or null, but if it
* is present, it must match the inner node.
*/
public class OptionalPatternNode extends JsonPatternNode {
private final JsonPatternNode innerNode;

/**
* Constructor of the optional pattern node.
*
* @param expected The string representation of the expected JSON pattern.
*/
public OptionalPatternNode(@NotNull String expected, @NotNull JsonPatternNode innerNode) {
super(expected);
this.innerNode = innerNode;
}

@NotNull
@Override
public Optional<JsonMatchErrorDetail> matches(@NotNull JsonPath path, @NotNull JsonNode actualNode) {
if (actualNode.isMissingNode() || actualNode.isNull()) {
return Optional.empty();
}

return innerNode.matches(path, actualNode).map(detail -> detail.withExpected(expected));
}

@Override
protected boolean canBeMissing() {
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package io.github.orangain.jsonmatch.marker

import io.github.orangain.jsonmatch.JsonStringAssert
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.Arguments.arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream

class OptionalMarkerTest {
@Test
fun optionalPatternShouldMatchPresentValue() {
// language=JSON
JsonStringAssert.assertThat("""{ "a": "foo" }""")
.jsonMatches("""{ "a": "##string" }""")
}

@Test
fun optionalPatternShouldFailWhenInnerPatternDoesNotMatch() {
Assertions.assertThatThrownBy {
// language=JSON
JsonStringAssert.assertThat("""{ "a": 1 }""")
.jsonMatches("""{ "a": "##string" }""")
}.isInstanceOf(AssertionError::class.java)
.hasMessageContaining("""path: $.a, actual: 1, expected: "##string", reason: not a string""")
}

@ParameterizedTest
@MethodSource("optionalMarkers")
fun optionalPatternShouldMatchEmptyObject(marker: String) {
require(!marker.contains("\"")) { "Please add implementation to escape double quotes." }
val patternJson = """{ "a": "$marker" }"""
// language=JSON
JsonStringAssert.assertThat("""{}""")
.jsonMatches(patternJson)
}

@ParameterizedTest
@MethodSource("optionalMarkers")
fun optionalPatternShouldMatchNull(marker: String) {
require(!marker.contains("\"")) { "Please add implementation to escape double quotes." }
val patternJson = """{ "a": "$marker" }"""
// language=JSON
JsonStringAssert.assertThat("""{"a": null}""")
.jsonMatches(patternJson)
}

companion object {
@JvmStatic
fun optionalMarkers(): Stream<Arguments> {
return Stream.of(
arguments("##null"),
arguments("##array"),
arguments("##object"),
arguments("##boolean"),
arguments("##number"),
arguments("##string"),
arguments("##uuid"),
arguments("##date"),
arguments("##datetime"),
arguments("##regex a+"),
arguments("##[1]"),
)
}
}
}