From 2dcee1036482c240b775403d6ff153f9a4f791c8 Mon Sep 17 00:00:00 2001 From: orangain Date: Sun, 5 Feb 2023 23:38:50 +0900 Subject: [PATCH] Fix match of empty object literal --- .../pattern/ObjectLiteralPatternNode.java | 4 ++ .../jsonmatch/EmptyObjectLiteralTest.kt | 50 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 src/test/kotlin/io/github/orangain/jsonmatch/EmptyObjectLiteralTest.kt diff --git a/src/main/java/io/github/orangain/jsonmatch/pattern/ObjectLiteralPatternNode.java b/src/main/java/io/github/orangain/jsonmatch/pattern/ObjectLiteralPatternNode.java index 5dfd8ba..d79c377 100644 --- a/src/main/java/io/github/orangain/jsonmatch/pattern/ObjectLiteralPatternNode.java +++ b/src/main/java/io/github/orangain/jsonmatch/pattern/ObjectLiteralPatternNode.java @@ -23,6 +23,10 @@ public ObjectLiteralPatternNode(@NotNull String expected, @NotNull Map matches(@NotNull JsonPath path, @NotNull JsonNode actualNode) { + if (!actualNode.isObject()) { + String reason = "not a json object"; + return Optional.of(error(path, actualNode, reason)); + } Set actualFieldNames = new HashSet<>(); actualNode.fieldNames().forEachRemaining(actualFieldNames::add); diff --git a/src/test/kotlin/io/github/orangain/jsonmatch/EmptyObjectLiteralTest.kt b/src/test/kotlin/io/github/orangain/jsonmatch/EmptyObjectLiteralTest.kt new file mode 100644 index 0000000..9cedafe --- /dev/null +++ b/src/test/kotlin/io/github/orangain/jsonmatch/EmptyObjectLiteralTest.kt @@ -0,0 +1,50 @@ +package io.github.orangain.jsonmatch + +import org.assertj.core.api.Assertions +import org.junit.Test + +class EmptyObjectLiteralTest { + val patternJson = "{}" + + @Test + fun matchEmptyObject() { + // language=JSON + JsonStringAssert.assertThat("{}").jsonMatches(patternJson) + } + + @Test + fun doesNotMatchArray() { + Assertions.assertThatThrownBy { + // language=JSON + JsonStringAssert.assertThat("[]").jsonMatches(patternJson) + }.isInstanceOf(AssertionError::class.java) + .hasMessageContaining("""path: $, actual: [], expected: {}, reason: not a json object""") + } + + @Test + fun doesNotMatchNumber() { + Assertions.assertThatThrownBy { + // language=JSON + JsonStringAssert.assertThat("0").jsonMatches(patternJson) + }.isInstanceOf(AssertionError::class.java) + .hasMessageContaining("""path: $, actual: 0, expected: {}, reason: not a json object""") + } + + @Test + fun doesNotMatchString() { + Assertions.assertThatThrownBy { + // language=JSON + JsonStringAssert.assertThat("\"foo\"").jsonMatches(patternJson) + }.isInstanceOf(AssertionError::class.java) + .hasMessageContaining("""path: $, actual: "foo", expected: {}, reason: not a json object""") + } + + @Test + fun doesNotMatchNull() { + Assertions.assertThatThrownBy { + // language=JSON + JsonStringAssert.assertThat("null").jsonMatches(patternJson) + }.isInstanceOf(AssertionError::class.java) + .hasMessageContaining("""path: $, actual: null, expected: {}, reason: not a json object""") + } +} \ No newline at end of file