Skip to content

✨ Add Snapshot.ignore(String... jsonPaths) method #10

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
7 changes: 6 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@
<artifactId>slf4j-api</artifactId>
<version>1.8.0-beta2</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any way to do this without an extra dependency?
Jackson already uses JsonPointers, maybe that could be used to specify ignored elements as well?

</dependency>
</dependencies>

<build>
Expand Down Expand Up @@ -224,4 +229,4 @@
</plugin>
</plugins>
</build>
</project>
</project>
54 changes: 46 additions & 8 deletions src/main/java/io/github/jsonSnapshot/Snapshot.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
package io.github.jsonSnapshot;

import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import org.assertj.core.util.diff.DiffUtils;
import org.assertj.core.util.diff.Patch;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.assertj.core.util.diff.DiffUtils;
import org.assertj.core.util.diff.Patch;
import static io.github.jsonSnapshot.SnapshotMatcher.defaultJsonFunction;

public class Snapshot {

Expand All @@ -19,6 +27,8 @@ public class Snapshot {

private Function<Object, String> jsonFunction;

private final List<String> pathsToIgnore = new ArrayList<>();

private Object[] current;

Snapshot(
Expand Down Expand Up @@ -65,11 +75,11 @@ private SnapshotMatchException generateDiffError(String rawSnapshot, String curr
+ currentObject.trim()
+ "\n\n"
+ patch
.getDeltas()
.stream()
.map(delta -> delta.toString() + "\n")
.reduce(String::concat)
.get();
.getDeltas()
.stream()
.map(delta -> delta.toString() + "\n")
.reduce(String::concat)
.get();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid formatting-only changes

return new SnapshotMatchException(error);
}

Expand All @@ -83,11 +93,39 @@ private String getRawSnapshot(Collection<String> rawSnapshots) {
return null;
}

private Object ignorePaths(Object input) {
DocumentContext context = JsonPath.using(new JacksonJsonProvider()).parse(defaultJsonFunction().apply(input));
this.pathsToIgnore.forEach(path -> context.delete(path));
String root = "$";
return context.read(root);
}

private Object[] getCurrentWithoutIgnoredPaths() {
if (pathsToIgnore.isEmpty() || current == null) {
return current;
}

return Arrays.asList(current).stream()
.map(this::ignorePaths)
.collect(Collectors.toList())
.toArray();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stream#toArray(Object[]::new)?

}

private String takeSnapshot() {
return getSnapshotName() + jsonFunction.apply(current);
return getSnapshotName() + jsonFunction.apply(getCurrentWithoutIgnoredPaths());
}

public String getSnapshotName() {
return clazz.getName() + "." + method.getName() + "=";
}

/**
* Ignore fields when comparing object and snapshot.
*
* @param jsonPathsToIgnore A list of paths to ignore in <a href="https://github.com/json-path/JsonPath">JsonPath</a> syntax.
*/
public Snapshot ignoring(String... jsonPathsToIgnore) {
this.pathsToIgnore.addAll(Arrays.asList(jsonPathsToIgnore));
return this;
}
}
24 changes: 24 additions & 0 deletions src/test/java/io/github/jsonSnapshot/SnapshotIntegrationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,28 @@ void shouldThrowStackOverflowError() {

assertThrows(SnapshotMatchException.class, () -> expect(fakeObject1).toMatchSnapshot());
}

@Test
public void shouldMatchSnapshotAndIgnoreTopLevelFieldMethod() {
expect(FakeObject.builder().id("anyId6").value(6).name("anyName6").build())
.ignoring("value")
.toMatchSnapshot();
}

@Test
public void shouldMatchSnapshotAndIgnoreSeveralNestedFieldsMethod() {
FakeObject grandChild = FakeObject.builder().id("grandChild7").value(7).build();
FakeObject child = FakeObject.builder().id("child7").value(7).fakeObject(grandChild).build();
expect(FakeObject.builder().id("anyId7").value(7).name("anyName7").fakeObject(child).build())
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd extract creation of test data into a variable, maybe something like:

FakeObject testObject = FakeObject.builder()
    .id("anyId7").value(7)
    .name("anyName7").fakeObject(FakeObject.builder()
            .id("child7").value(7)
            .fakeObject(FakeObject.builder()
                    .id("grandChild7").value(7)
                    .build()
            ).build()
    ).build().

.ignoring("value", "fakeObject.id", "fakeObject.fakeObject")
.toMatchSnapshot();
}

@Test
public void shouldMatchSnapshotAndIgnoreEverythingMethod() {
FakeObject child = FakeObject.builder().id("child8").value(8).build();
expect(FakeObject.builder().id("anyId8").value(8).name("anyName8").fakeObject(child).build())
.ignoring("$..*")
.toMatchSnapshot();
}
}
24 changes: 24 additions & 0 deletions src/test/java/io/github/jsonSnapshot/SnapshotIntegrationTest.snap
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
io.github.jsonSnapshot.SnapshotIntegrationTest.shouldMatchSnapshotAndIgnoreEverythingMethod=[
{ }
]


io.github.jsonSnapshot.SnapshotIntegrationTest.shouldMatchSnapshotAndIgnoreSeveralNestedFieldsMethod=[
{
"fakeObject": {
"value": 7
},
"id": "anyId7",
"name": "anyName7"
}
]


io.github.jsonSnapshot.SnapshotIntegrationTest.shouldMatchSnapshotAndIgnoreTopLevelFieldMethod=[
{
"id": "anyId6",
"name": "anyName6"
}
]


io.github.jsonSnapshot.SnapshotIntegrationTest.shouldMatchSnapshotFour=[
{
"id": "anyId4",
Expand Down
57 changes: 50 additions & 7 deletions src/test/java/io/github/jsonSnapshot/SnapshotTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.PathNotFoundException;
import org.junit.Before;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand All @@ -31,20 +36,23 @@ class SnapshotTest {
@BeforeEach
void setUp() throws NoSuchMethodException, IOException {
snapshotFile = new SnapshotFile(DEFAULT_CONFIG.getFilePath(), "anyFilePath");
snapshot =
new Snapshot(
snapshotFile,
String.class,
String.class.getDeclaredMethod("toString"),
SnapshotMatcher.defaultJsonFunction(),
"anyObject");
snapshot = createSnapshot("anyObject");
}

@AfterEach
void tearDown() throws IOException {
Files.delete(Paths.get(FILE_PATH));
}

private Snapshot createSnapshot(Object... current) throws NoSuchMethodException {
return new Snapshot(
snapshotFile,
String.class,
String.class.getDeclaredMethod("toString"),
SnapshotMatcher.defaultJsonFunction(),
current);
}

@Test
void shouldGetSnapshotNameSuccessfully() {
String snapshotName = snapshot.getSnapshotName();
Expand All @@ -64,4 +72,39 @@ void shouldMatchSnapshotWithException() {

assertThrows(SnapshotMatchException.class, snapshot::toMatchSnapshot);
}

@Test
public void shouldNotFailOnEmptyIgnoredPathList() {
snapshot.ignoring().toMatchSnapshot();
assertThat(snapshotFile.getRawSnapshots()).isEqualTo(Stream.of(SNAPSHOT).collect(Collectors.toCollection(TreeSet::new)));
}

@Test
public void shouldFailWhenTryingToIgnoreChildOfPrimitiveJsonObject() {
assertThrows(PathNotFoundException.class, () -> snapshot.ignoring("anyObject_is_a_json_string_and_can_not_have_children").toMatchSnapshot());
}

@Test
public void shouldIgnoreTopLevelAndNestedFields() throws NoSuchMethodException, IOException {
Object object = new ObjectMapper().readTree("{\n" +
" \"notIgnored\": \"notIgnored\",\n" +
" \"ignoredInParent\": \"ignored\",\n" +
" \"child\": {\n" +
" \"ignoredInParent\": \"notIgnored\",\n" +
" \"ignoredInChild\": \"ignored\"\n" +
" }\n" +
"}");
Snapshot snapshot = createSnapshot(object);

snapshot.ignoring("ignoredInParent", "child.ignoredInChild").toMatchSnapshot();
String expectedSnapshot = "java.lang.String.toString=[\n" +
" {\n" +
" \"child\": {\n" +
" \"ignoredInParent\": \"notIgnored\"\n" +
" },\n" +
" \"notIgnored\": \"notIgnored\"\n" +
" }\n" +
"]";
assertThat(snapshotFile.getRawSnapshots()).isEqualTo(Collections.singleton(expectedSnapshot));
}
}