Skip to content

Commit

Permalink
Improve the diffs when the root element differs
Browse files Browse the repository at this point in the history
  • Loading branch information
trickl committed Oct 18, 2019
1 parent 4d19e43 commit 36e2c9a
Show file tree
Hide file tree
Showing 7 changed files with 89 additions and 37 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.trickl</groupId>
<artifactId>assertj-json</artifactId>
<version>0.2.11-SNAPSHOT</version>
<version>0.2.13-SNAPSHOT</version>
<packaging>jar</packaging>
<developers>
<developer>
Expand Down
26 changes: 15 additions & 11 deletions src/main/java/com/trickl/assertj/core/internal/JsonDiff.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.trickl.assertj.core.api.json.JsonContainer;
import com.trickl.assertj.util.diff.JsonFieldDelta;
import com.trickl.assertj.util.diff.JsonMessageDelta;
import com.trickl.assertj.util.diff.JsonRootDelta;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
Expand Down Expand Up @@ -33,34 +33,38 @@ public class JsonDiff {
public List<Delta<String>> diff(
JsonContainer actual, JsonContainer expected, JSONComparator comparator) throws IOException {
try {
JSONCompareResult result =
JSONCompare.compareJSON(expected.getJson(), actual.getJson(), comparator);
return asDiff(result);
String expectedStr = expected.getJson();
String actualStr = actual.getJson();
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, comparator);
return asDiff(result, expectedStr, actualStr);
} catch (JSONException ex) {
throw new IOException(ex);
}
}

private List<Delta<String>> asDiff(JSONCompareResult result) {
private List<Delta<String>> asDiff(JSONCompareResult result, String expectedStr, String actualStr)
throws JSONException {
if (result.passed()) {
return Collections.EMPTY_LIST;
return Collections.emptyList();
}

List<Delta<String>> diffs = new LinkedList<>();
for (FieldComparisonFailure missingField : result.getFieldMissing()) {
diffs.add(new JsonFieldDelta(missingField, Delta.TYPE.DELETE));
diffs.add(new JsonFieldDelta<>(missingField, Delta.TYPE.DELETE));
}

for (FieldComparisonFailure changedField : result.getFieldFailures()) {
diffs.add(new JsonFieldDelta(changedField, Delta.TYPE.CHANGE));
diffs.add(new JsonFieldDelta<>(changedField, Delta.TYPE.CHANGE));
}

for (FieldComparisonFailure unexpectedField : result.getFieldUnexpected()) {
diffs.add(new JsonFieldDelta(unexpectedField, Delta.TYPE.INSERT));
diffs.add(new JsonFieldDelta<>(unexpectedField, Delta.TYPE.INSERT));
}

if (diffs.isEmpty()) {
diffs.add(new JsonMessageDelta(result.getMessage()));
String expectedNoFormat = expectedStr.replace("\n", "").replace("\r", "");
String actualNoFormat = actualStr.replace("\n", "").replace("\r", "");
diffs.add(new JsonRootDelta<>(expectedNoFormat, actualNoFormat, result.getMessage()));
}

return diffs;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,39 @@ public String formatUnexpected(FieldComparisonFailure failure) {
return formatUnexpected(failure.getActual());
}

private String formatUnexpected(Object actual) {
protected String formatUnexpected(Object actual) {
return "Unexpected: " + describe(actual);
}

public String formatMissing(FieldComparisonFailure failure) {
return formatMissing(failure.getExpected());
}

private String formatMissing(Object expected) {
protected String formatMissing(Object expected) {
return "Expected: " + describe(expected) + " but none found";
}

public String formatRootFailureMessage(Object expected, Object actual) {
return formatFailureMessage(null, expected, actual);
}

public String formatFailureMessage(FieldComparisonFailure failure) {
return FieldComparisonFailureFormatter.this.formatFailureMessage(
return formatFailureMessage(
failure.getField(), failure.getActual(), failure.getExpected());
}

private String formatFailureMessage(String field, Object expected, Object actual) {
return quote(field) + " - Expected: " + describe(expected) + " got: " + describe(actual);
protected String formatFailureMessage(String field, Object expected, Object actual) {
StringBuilder messageBuilder = new StringBuilder();
if (field != null && field.length() > 0) {
messageBuilder.append(quote(field));
messageBuilder.append(" - ");
}
messageBuilder.append("Expected: ");
messageBuilder.append(describe(expected));
messageBuilder.append(" ");
messageBuilder.append("got: ");
messageBuilder.append(describe(actual));
return messageBuilder.toString();
}

private static String quote(String value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,23 @@ public class WriteOnFailureComparator implements JSONComparator {
private final Path actualOutputPath;
private final boolean writeExpected;
private final Path expectedOutputPath;
private final int indentation = 2;

private static final int INDENTATION = 2;

@Override
public JSONCompareResult compareJSON(JSONObject expected, JSONObject actual)
throws JSONException {
JSONCompareResult result = comparator.compareJSON(expected, actual);

writeOnFailure(result, expected.toString(), actual.toString(indentation));
writeOnFailure(result, expected.toString(), actual.toString(INDENTATION));

return result;
}

@Override
public JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException {
JSONCompareResult result = comparator.compareJSON(expected, actual);
writeOnFailure(result, expected.toString(), actual.toString(indentation));
writeOnFailure(result, expected.toString(), actual.toString(INDENTATION));
return result;
}

Expand All @@ -49,7 +50,7 @@ public void compareJSON(
String str, JSONObject expected, JSONObject actual, JSONCompareResult result)
throws JSONException {
comparator.compareJSON(str, expected, actual, result);
writeOnFailure(result, expected.toString(), actual.toString(indentation));
writeOnFailure(result, expected.toString(), actual.toString(INDENTATION));
}

@Override
Expand All @@ -64,7 +65,7 @@ public void compareJSONArray(
String str, JSONArray expected, JSONArray actual, JSONCompareResult result)
throws JSONException {
comparator.compareJSONArray(str, expected, actual, result);
writeOnFailure(result, expected.toString(indentation), actual.toString(indentation));
writeOnFailure(result, expected.toString(INDENTATION), actual.toString(INDENTATION));
}

private void writeOnFailure(JSONCompareResult result, String expected, String actual) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.trickl.assertj.util.diff;

import com.trickl.assertj.core.presentation.FieldComparisonFailureFormatter;
import java.util.Collections;
import java.util.List;
import lombok.Getter;
Expand All @@ -13,20 +14,23 @@
*
* @param <T> The type of the compared elements in the 'lines'.
*/
public class JsonMessageDelta<T> extends Delta<T> {
public class JsonRootDelta<T> extends Delta<T> {

@Getter private final String expected;

@Getter private final String actual;

@Getter private final String message;

@Getter private final TYPE type = TYPE.CHANGE;

/**
* Create a delta for a JSON document.
* @param message details of the difference
*/
public JsonMessageDelta(String message) {

/** Create a delta for a JSON document. */
public JsonRootDelta(String expected, String actual, String message) {
super(new Chunk(0, Collections.EMPTY_LIST), new Chunk(0, Collections.EMPTY_LIST));
this.expected = expected;
this.actual = actual;
this.message = message;
}
}

@Override
public void applyTo(List<T> target) throws IllegalStateException {}
Expand All @@ -36,6 +40,10 @@ public void verify(List<T> target) throws IllegalStateException {}

@Override
public String toString() {
return message;
FieldComparisonFailureFormatter formatter = new FieldComparisonFailureFormatter();
if (message != null && message.length() > 0) {
return message;
}
return formatter.formatRootFailureMessage(expected, actual);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
import static com.trickl.assertj.core.api.JsonAssertions.assertThat;
import static com.trickl.assertj.core.api.JsonAssertions.json;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;

import org.junit.BeforeClass;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import org.skyscreamer.jsonassert.comparator.JSONComparator;

/**
Expand Down Expand Up @@ -84,6 +84,7 @@ public void should_assert_if_root_string_different() {
assertThatThrownBy(() -> assertThat(json("\"test1\""))
.isSameJsonAs("\"test2\""))
.isInstanceOf(AssertionError.class)
.hasMessage("\nInputStream does not have same content as String:\n\n");
.hasMessage("\nInputStream does not have same content as String:" +
"\n\nExpected: '\"test2\"' got: '\"test1\"'");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@

import static com.trickl.assertj.core.api.JsonAssertions.json;
import static java.lang.String.format;
import static java.nio.charset.Charset.defaultCharset;
import static org.assertj.core.api.Assertions.assertThat;
import static org.skyscreamer.jsonassert.JSONCompareMode.NON_EXTENSIBLE;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.assertj.core.util.Files;
import org.assertj.core.util.TextFileWriter;
import org.assertj.core.util.diff.Delta;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.skyscreamer.jsonassert.JSONCompareMode.NON_EXTENSIBLE;
import org.skyscreamer.jsonassert.comparator.DefaultComparator;

/**
Expand Down Expand Up @@ -54,6 +54,16 @@ public void should_return_empty_diff_list_if_files_have_equal_content() throws I
assertThat(diffs).isEmpty();
}

@Test
public void should_return_empty_diff_on_identical_primitives() throws IOException {
writer.write(actual, "\"original\"");
writer.write(expected, "\"original\"");
List<Delta<String>> diffs =
diff.diff(
json(actual), json(expected), new DefaultComparator(NON_EXTENSIBLE));
assertThat(diffs).isEmpty();
}

@Test
public void should_return_diffs_if_files_have_different_fields() throws IOException {
writer.write(actual, "{\"id\": 3}");
Expand All @@ -67,6 +77,20 @@ public void should_return_diffs_if_files_have_different_fields() throws IOExcept
format("\"id\" - Expected: '3' got: '5'"));
}


@Test
public void should_return_diffs_on_different_primitives() throws IOException {
writer.write(actual, "\"actual\"");
writer.write(expected, "\"expected\"");
List<Delta<String>> diffs =
diff.diff(
json(actual), json(expected), new DefaultComparator(NON_EXTENSIBLE));
assertThat(diffs).hasSize(1);
assertThat(diffs.get(0))
.hasToString(
format("Expected: '\"expected\"' got: '\"actual\"'"));
}

@Test
public void should_return_diffs_if_files_have_missing_fields() throws IOException {
writer.write(actual, "{\"id\": 3}");
Expand Down

0 comments on commit 36e2c9a

Please sign in to comment.