Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
fslev committed Oct 4, 2022
1 parent 2397114 commit f57df24
Show file tree
Hide file tree
Showing 11 changed files with 247 additions and 30 deletions.
17 changes: 9 additions & 8 deletions src/main/java/io/json/compare/JSONCompare.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

public class JSONCompare {

private static final String ASSERTION_ERROR_HINT_MESSAGE = "Json matching by default uses regular expressions.\n" +
private static final String ASSERTION_ERROR_HINT_MESSAGE = "Json matching by default uses regular expressions." + System.lineSeparator() +
"In case expected json contains any unintentional regexes, then quote them between \\Q and \\E delimiters or use a custom comparator.";

public static void assertMatches(Object expected, Object actual) {
Expand Down Expand Up @@ -65,13 +65,14 @@ public static void assertMatches(Object expected, Object actual, JsonComparator
List<String> diffs = new JsonMatcher(expectedJson, actualJson,
comparator == null ? new DefaultJsonComparator() : comparator, compareModes).match();
if (!diffs.isEmpty()) {
String defaultMessage = String.format("FOUND %s DIFFERENCE(S):\n%s\n",
String defaultMessage = String.format("FOUND %s DIFFERENCE(S):" + System.lineSeparator() + "%s" + System.lineSeparator(),
diffs.size(), diffs.stream().map(diff ->
"\n\n_________________________DIFF__________________________\n" + diff).reduce(String::concat).get());
System.lineSeparator() + System.lineSeparator() + "_________________________DIFF__________________________" +
System.lineSeparator() + diff).reduce(String::concat).get());
if (comparator == null || comparator.getClass().equals(DefaultJsonComparator.class)) {
defaultMessage += "\n\n" + ASSERTION_ERROR_HINT_MESSAGE + "\n";
defaultMessage += System.lineSeparator() + System.lineSeparator() + ASSERTION_ERROR_HINT_MESSAGE + System.lineSeparator();
}
AssertionFailureBuilder.assertionFailure().message(message == null ? defaultMessage : defaultMessage + "\n" + message)
AssertionFailureBuilder.assertionFailure().message(message == null ? defaultMessage : defaultMessage + System.lineSeparator() + message)
.expected(prettyPrint(expectedJson)).actual(prettyPrint(actualJson)).buildAndThrow();
}
}
Expand All @@ -84,8 +85,8 @@ public static void assertNotMatches(Object expected, Object actual, JsonComparat
if (!diffs.isEmpty()) {
return;
}
String defaultMessage = "\nJSONs are equal";
AssertionFailureBuilder.assertionFailure().message(message == null ? defaultMessage : defaultMessage + "\n" + message)
String defaultMessage = System.lineSeparator() + "JSONs are equal";
AssertionFailureBuilder.assertionFailure().message(message == null ? defaultMessage : defaultMessage + System.lineSeparator() + message)
.expected(prettyPrint(expectedJson)).actual(prettyPrint(actualJson))
.includeValuesInMessage(false).buildAndThrow();
}
Expand All @@ -102,7 +103,7 @@ private static JsonNode toJson(Object obj) {
try {
return JsonUtils.toJson(obj);
} catch (IOException e) {
throw new RuntimeException(String.format("Invalid JSON\n%s\n", e));
throw new RuntimeException(String.format("Invalid JSON" + System.lineSeparator() + "%s" + System.lineSeparator(), e));
}
}
}
11 changes: 7 additions & 4 deletions src/main/java/io/json/compare/matcher/JsonArrayMatcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,11 @@ private List<String> matchWithJsonArray(int expPosition, JsonNode expElement, Js
return Collections.emptyList();
} else {
if (compareModes.contains(CompareMode.JSON_ARRAY_STRICT_ORDER)) {
diffs.add(String.format("JSON ARRAY elements differ at position %s:\n%s\n________diffs________\n%s", expPosition + 1,
MessageUtil.cropL(JSONCompare.prettyPrint(expElement)), String.join("\n_____________________\n", elementDiffs)));
diffs.add(String.format("JSON ARRAY elements differ at position %s:" +
System.lineSeparator() + "%s" + System.lineSeparator() +
"________diffs________" + System.lineSeparator() + "%s", expPosition + 1,
MessageUtil.cropL(JSONCompare.prettyPrint(expElement)), String.join(
System.lineSeparator() + "_____________________" + System.lineSeparator(), elementDiffs)));
return diffs;
}
}
Expand All @@ -70,7 +73,7 @@ private List<String> matchWithJsonArray(int expPosition, JsonNode expElement, Js
elementDiffs = new JsonMatcher(expElement, actElement, comparator, compareModes).match();
if (!elementDiffs.isEmpty()) {
diffs.add("Expected element from position " + (expPosition + 1)
+ " was FOUND:\n" + MessageUtil.cropL(JSONCompare.prettyPrint(expElement)));
+ " was FOUND:" + System.lineSeparator() + MessageUtil.cropL(JSONCompare.prettyPrint(expElement)));
return diffs;
}
}
Expand All @@ -83,7 +86,7 @@ private List<String> matchWithJsonArray(int expPosition, JsonNode expElement, Js
}
}
if (useCase == UseCase.MATCH) {
diffs.add("\nExpected element from position " + (expPosition + 1) + " was NOT FOUND:\n"
diffs.add(System.lineSeparator() + "Expected element from position " + (expPosition + 1) + " was NOT FOUND:" + System.lineSeparator()
+ MessageUtil.cropL(JSONCompare.prettyPrint(expElement)));
} else if (useCase == UseCase.MATCH_ANY) {
diffs.add(String.format("Expected condition %s from position %s was not met." +
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/io/json/compare/matcher/JsonObjectMatcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,31 +36,31 @@ public List<String> match() {
case MATCH:
if (!jsonPathExpression.isPresent()) {
if (candidateEntries.isEmpty()) {
diffs.add(String.format("Field '%s' was not found", expectedField));
diffs.add(String.format("Field '%s' was NOT FOUND", expectedField));
} else {
diffs.addAll(matchWithCandidates(expectedSanitizedField, expectedValue, candidateEntries));
}
} else {
try {
diffs.addAll(new JsonPathMatcher(jsonPathExpression.get(), expectedValue, actual, comparator, compareModes).match());
} catch (PathNotFoundException e) {
diffs.add(String.format("json path ('%s') -> %s", jsonPathExpression.get(), e.getMessage()));
diffs.add(String.format("json path '%s' -> %s", jsonPathExpression.get(), e.getMessage()));
}
}
break;
case DO_NOT_MATCH_ANY:
case DO_NOT_MATCH:
if (!jsonPathExpression.isPresent()) {
if (!candidateEntries.isEmpty()) {
diffs.add(String.format("Field '%s' was found", expectedField));
diffs.add(String.format("Field '%s' was FOUND", expectedField));
}
} else {
try {
new JsonPathMatcher(jsonPathExpression.get(), expectedValue, actual, comparator, compareModes).match();
} catch (PathNotFoundException e) {
break;
}
diffs.add(String.format("Json path '%s' was found", expectedField));
diffs.add(String.format("Json path '%s' was FOUND", expectedField));
}
break;
}
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/io/json/compare/matcher/JsonPathMatcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ public List<String> match() {
List<String> diffs = new ArrayList<>();
JsonNode result = MAPPER.convertValue(PARSE_CONTEXT.parse(actual).read(jsonPath), JsonNode.class);
List<String> jsonPathDiffs = new JsonMatcher(expected, result, comparator, compareModes).match();
jsonPathDiffs.forEach(diff -> diffs.add(String.format("Json path ('%s') -> Expected json path result:\n%s\nBut got:\n%s\n\n%s",
jsonPathDiffs.forEach(diff -> diffs.add(String.format("Json path ('%s') -> Expected json path result:" +
System.lineSeparator() + "%s" + System.lineSeparator() +
"But got:" + System.lineSeparator() + "%s" + System.lineSeparator() + System.lineSeparator() + "%s",
jsonPath, expected, result, diff)));
return diffs;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class JsonValueMatcher extends AbstractJsonMatcher {
@Override
public List<String> match() {
List<String> diffs = new ArrayList<>();
String diff = "Expected %s: %s But got: %s";
String diff = System.lineSeparator() + "Expected %s: %s But got: %s";

if (expected.isNull() && !actual.isNull()) {
diffs.add(String.format(diff, "null", "", actual));
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/io/json/compare/util/MessageUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ public static String cropL(String msg) {

private static String crop(String msg, int limit) {
if (msg != null && msg.length() > limit) {
String start = msg.substring(0, AFTER_CROP_SIZE / 2) + "\n\n<...cropped content...>\n\n";
String start = msg.substring(0, AFTER_CROP_SIZE / 2) + System.lineSeparator() + System.lineSeparator() +
"<...cropped content...>" + System.lineSeparator() + System.lineSeparator();
String end = msg.substring(msg.length() - AFTER_CROP_SIZE / 2);
return start + end;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public void checkNullMessageFromJSONObjectFailedCompare() {
try {
JSONCompare.assertMatches(expected, actual, new HashSet<>(Arrays.asList(CompareMode.JSON_OBJECT_NON_EXTENSIBLE)));
} catch (AssertionError e) {
assertTrue(e.getMessage().contains("Field 'a' was not found"));
assertTrue(e.getMessage().contains("Field 'a' was NOT FOUND"));
}
}

Expand Down Expand Up @@ -104,7 +104,7 @@ public void checkMessageFromFailedMatchingBetweenHighDepthJsons() {
try {
JSONCompare.assertMatches(expected, actual, new HashSet<>(Arrays.asList(CompareMode.JSON_OBJECT_NON_EXTENSIBLE)));
} catch (AssertionError e) {
assertTrue(e.getMessage().contains("Field 'version' was not found or cannot be matched <- @"));
assertTrue(e.getMessage().contains("Field 'version' was NOT FOUND or cannot be matched <- @"));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ public void checkInvalidOrNotFoundJsonPathErrorMessage() {
} catch (AssertionError e) {
assertTrue(e.getMessage().matches("(?s).*FOUND 1 DIFFERENCE.*" +
"_________________________DIFF__________________________.*" +
"\\Qa -> a1 -> a11 -> json path ('$.idontexist') -> No results for path: $['idontexist']\\E.*"));
"\\Qa -> a1 -> a11 -> json path '$.idontexist' -> No results for path: $['idontexist']\\E.*"));
return;
}
fail("No error thrown");
Expand Down Expand Up @@ -271,7 +271,7 @@ public void matchJsonObjectWithJsonPath_do_not_match_use_case_on_field_negative(
try {
JSONCompare.assertMatches(expected, actual);
} catch (AssertionError e) {
assertTrue(e.getMessage().contains("Json path") && e.getMessage().contains("was found"));
assertTrue(e.getMessage().contains("Json path") && e.getMessage().contains("was FOUND"));
return;
}
fail("JSONs match");
Expand Down Expand Up @@ -355,7 +355,7 @@ public void matchJsonObjectWithMultipleJsonPaths() {
actual = "{\"b\":false,\"a\":{\"a2\":290.11,\"a1\":{\"b11\":null,\"a11\":{\"a\":\"lorem\"}}}}";
JSONCompare.assertNotMatches(expected, actual);

expected = "{\"#($.b)\":false,\"a\":{\"#($.a1)\":{\"b11\":null,\"a11\":{\"a\":\"not found\"}},\"#($.a2)\":290.11}}";
expected = "{\"#($.b)\":false,\"a\":{\"#($.a1)\":{\"b11\":null,\"a11\":{\"a\":\"NOT FOUND\"}},\"#($.a2)\":290.11}}";
actual = "{\"b\":false,\"a\":{\"a2\":290.11,\"a1\":{\"b11\":null,\"a11\":{\"a\":\"lorem\"}}}}";
JSONCompare.assertNotMatches(expected, actual);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public void compareJsonArraysAndCheckForJsonStrictOrderDifferences() {
"Expected condition \"\\Q!.*\\E\" from position 2 was not met. Actual JSON array has extra elements.*" +
"JSON ARRAY elements differ at position 4:.*lorem2.*ipsum2.*lorem3.*ipsum3.*diffs.*" +
"lorem2 ->.*Expected value: \"ipsum2\" But got: \"ipsum-updated\".*" +
"Field 'lorem3' was not found.*"));
"Field 'lorem3' was NOT FOUND.*"));
JSONCompare.assertNotMatches(expected, actual);
}

Expand Down
Loading

0 comments on commit f57df24

Please sign in to comment.