Skip to content

Commit

Permalink
fix: improve snapshot diff with newlines (#71)
Browse files Browse the repository at this point in the history
remove extraneous newlines from snap diff
  • Loading branch information
gkampitakis authored Jul 9, 2023
1 parent 31d53b8 commit 09d3a05
Show file tree
Hide file tree
Showing 10 changed files with 158 additions and 29 deletions.
3 changes: 0 additions & 3 deletions golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,11 @@ linters:
- gofumpt
- revive
- unconvert
- gocognit

disable:
- errcheck

linters-settings:
gocognit:
min-complexity: 45
lll:
line-length: 130
gofumpt:
Expand Down
99 changes: 91 additions & 8 deletions snaps/__snapshots__/diff_test.snap
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
- Snapshot - 20
+ Received + 10000

mock-diff[2m
at snap/path:10
mock-diff
[2mat snap/path:10

---

Expand All @@ -14,8 +14,8 @@ at snap/path:10
- Snapshot - 10000
+ Received + 20

mock-diff[2m
at snap/path:20
mock-diff
[2mat snap/path:20

---

Expand All @@ -24,8 +24,10 @@ at snap/path:20
- Snapshot - 20
+ Received + 20

- abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd+ abcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcf
at snap/path:10
- abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd
+ abcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcfabcf

at snap/path:10

---

Expand Down Expand Up @@ -54,8 +56,8 @@ at snap/path:10
+ Sed lorem felis, condimentum eget vehicula non, sagittis sit amet diam. 
+ Vivamus ut sapien at erat imperdiet suscipit id a lectus.
+ Another Line added.
[2m
at snap/path:10

[2mat snap/path:10

---

Expand Down Expand Up @@ -107,4 +109,85 @@ at snap/path:20
+ Received + 10

there is a diff here

---

[TestDiff/should_print_newline_diffs/multiline - 1]

- Snapshot - 0
+ Received + 3

snapshot
+ 
 with multiple lines
+ 
+ diff


at snap/path:10

---

[TestDiff/should_print_newline_diffs/multiline - 2]

- Snapshot - 3
+ Received + 0

snapshot
- 
 with multiple lines
- 
- diff


at snap/path:10

---

[TestDiff/should_print_newline_diffs/singleline - 1]

- Snapshot - 0
+ Received + 1

- single line snap
+ single line snap ↵

at snap/path:10

---

[TestDiff/should_print_newline_diffs/singleline - 2]

- Snapshot - 0
+ Received + 1

- single line snap
+ single line snap ↵

at snap/path:10

---

[TestDiff/should_print_newline_diffs/singleline - 3]

- Snapshot - 0
+ Received + 1

- single line snap
+ single line snap↵

at snap/path:10

---

[TestDiff/should_print_newline_diffs/singleline - 4]

- Snapshot - 1
+ Received + 0

- single line snap↵
+ single line snap

at snap/path:10

---
30 changes: 25 additions & 5 deletions snaps/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ func isSingleline(s string) bool {
return i == len(s)-1 || i == -1
}

func hasNewLine(b []byte) bool {
return b[len(b)-1] == '\n'
}

// shouldPrintHighlights checks if the two strings are going to be presented with
// inline highlights
func shouldPrintHighlights(a, b string) bool {
Expand Down Expand Up @@ -165,16 +169,31 @@ func singlelineDiff(expected, received string) (string, int, int) {
switch diff.Type {
case diffDelete:
deleted++
colors.FprintDeleteBold(a, diff.Text)
if strings.HasSuffix(diff.Text, "\n") {
colors.FprintDeleteBold(a, diff.Text[:len(diff.Text)-1]+newLineSymbol)
} else {
colors.FprintDeleteBold(a, diff.Text)
}
case diffInsert:
inserted++
colors.FprintInsertBold(b, diff.Text)
if strings.HasSuffix(diff.Text, "\n") {
colors.FprintInsertBold(b, diff.Text[:len(diff.Text)-1]+newLineSymbol)
} else {
colors.FprintInsertBold(b, diff.Text)
}
case diffEqual:
colors.FprintBg(a, colors.RedBg, colors.Reddiff, diff.Text)
colors.FprintBg(b, colors.GreenBG, colors.Greendiff, diff.Text)
}
}

if !hasNewLine(a.Bytes()) {
a.WriteByte('\n')
}
if !hasNewLine(b.Bytes()) {
b.WriteByte('\n')
}

a.Write(b.Bytes())

return a.String(), inserted, deleted
Expand Down Expand Up @@ -204,15 +223,16 @@ func buildDiffReport(inserted, deleted int, diff, name string, line int) string

iPadding, dPadding := intPadding(inserted, deleted)

s.WriteString("\n")
s.WriteByte('\n')
colors.FprintDelete(&s, fmt.Sprintf("Snapshot %s- %d\n", dPadding, deleted))
colors.FprintInsert(&s, fmt.Sprintf("Received %s+ %d\n", iPadding, inserted))
s.WriteString("\n")
s.WriteByte('\n')

s.WriteString(diff)
s.WriteByte('\n')

if name != "" {
colors.Fprint(&s, colors.Dim, fmt.Sprintf("\nat %s:%d\n", name, line))
colors.Fprint(&s, colors.Dim, fmt.Sprintf("at %s:%d\n", name, line))
}

return s.String()
Expand Down
28 changes: 28 additions & 0 deletions snaps/diff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,32 @@ func TestDiff(t *testing.T) {
MatchSnapshot(t, prettyDiff(a, b, "snap/path", 20))
})
})

t.Run("should print newline diffs", func(t *testing.T) {
t.Run("multiline", func(t *testing.T) {
a := `snapshot
with multiple lines
`
b := `snapshot
with multiple lines
diff
`

MatchSnapshot(t, prettyDiff(a, b, "snap/path", 10))
MatchSnapshot(t, prettyDiff(b, a, "snap/path", 10))
})

t.Run("singleline", func(t *testing.T) {
a := "single line snap"
b := "single line snap \n"
c := "single line snap\n"

MatchSnapshot(t, prettyDiff(a, b, "snap/path", 10))
MatchSnapshot(t, prettyDiff(a, b, "snap/path", 10))
MatchSnapshot(t, prettyDiff(a, c, "snap/path", 10))
MatchSnapshot(t, prettyDiff(c, a, "snap/path", 10))
})
})
}
2 changes: 1 addition & 1 deletion snaps/matchJSON.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ func validateJSON(input interface{}) ([]byte, error) {
}

func takeJSONSnapshot(b []byte) string {
return string(pretty.PrettyOptions(b, jsonOptions))
return strings.TrimSuffix(string(pretty.PrettyOptions(b, jsonOptions)), "\n")
}

func applyJSONMatchers(b []byte, matchers ...match.JSONMatcher) ([]byte, []match.MatcherError) {
Expand Down
3 changes: 1 addition & 2 deletions snaps/matchJSON_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ func TestMatchJSON(t *testing.T) {
4
],
"user": "mock-name"
}
`
}`

for _, tc := range []struct {
name string
Expand Down
3 changes: 2 additions & 1 deletion snaps/matchSnapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package snaps

import (
"errors"
"strings"

"github.com/gkampitakis/go-snaps/internal/colors"
"github.com/kr/pretty"
Expand Down Expand Up @@ -110,5 +111,5 @@ func takeSnapshot(objects []interface{}) string {
snapshot += pretty.Sprint(objects[i]) + "\n"
}

return escapeEndChars(snapshot)
return strings.TrimSuffix(escapeEndChars(snapshot), "\n")
}
4 changes: 2 additions & 2 deletions snaps/matchSnapshot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ func TestMatchSnapshot(t *testing.T) {
expected := "\n\x1b[38;5;52m\x1b[48;5;225m- Snapshot - 2\x1b[0m\n\x1b[38;5;22m\x1b[48;5;159m" +
"+ Received + 2\x1b[0m\n\n\x1b[38;5;52m\x1b[48;5;225m- int(10)\x1b[0m\n\x1b[38;5;52m\x1b[48;5;225m" +
"- hello world\x1b[0m\n\x1b[38;5;22m\x1b[48;5;159m+ int(100)\x1b[0m\n\x1b[38;5;22m\x1b[48;5;159m" +
"+ bye world\x1b[0m\n \x1b[2m↵\n\x1b[0m\x1b[2m\nat " + filepath.FromSlash(
"+ bye world\x1b[0m\n\n\x1b[2mat " + filepath.FromSlash(
"../__snapshots__/matchSnapshot_test.snap:2",
) +
"\n\x1b[0m"
Expand Down Expand Up @@ -221,7 +221,7 @@ func TestMatchSnapshot(t *testing.T) {
"+ Received + 3\x1b[0m\n\n\x1b[38;5;52m\x1b[48;5;225m- int(10)\x1b[0m\n\x1b[38;5;52m\x1b[48;5;225m" +
"- hello world----\x1b[0m\n\x1b[38;5;52m\x1b[48;5;225m- ---\x1b[0m\n\x1b[38;5;22m\x1b[48;5;159m" +
"+ int(100)\x1b[0m\n\x1b[38;5;22m\x1b[48;5;159m+ bye world----\x1b[0m\n\x1b[38;5;22m\x1b[48;5;159m" +
"+ --\x1b[0m\n \x1b[2m↵\n\x1b[0m\x1b[2m\nat " + filepath.FromSlash(
"+ --\x1b[0m\n\n\x1b[2mat " + filepath.FromSlash(
"../__snapshots__/matchSnapshot_test.snap:2",
) +
"\n\x1b[0m"
Expand Down
5 changes: 3 additions & 2 deletions snaps/snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func getPrevSnapshot(testID, snapPath string) (string, int, error) {
line := s.Bytes()

if bytes.Equal(line, endSequenceByteSlice) {
return snapshot.String(), lineNumber, nil
return strings.TrimSuffix(snapshot.String(), "\n"), lineNumber, nil
}
snapshot.Write(line)
snapshot.WriteByte('\n')
Expand All @@ -150,7 +150,7 @@ func addNewSnapshot(testID, snapshot, snapPath string) error {
}
defer f.Close()

_, err = fmt.Fprintf(f, "\n%s\n%s---\n", testID, snapshot)
_, err = fmt.Fprintf(f, "\n%s\n%s\n---\n", testID, snapshot)
return err
}

Expand Down Expand Up @@ -185,6 +185,7 @@ func updateSnapshot(testID, snapshot, snapPath string) error {

// add new snapshot
updatedSnapFile.WriteString(snapshot)
updatedSnapFile.WriteByte('\n')
updatedSnapFile.Write(endSequenceByteSlice)
updatedSnapFile.WriteByte('\n')
}
Expand Down
10 changes: 5 additions & 5 deletions snaps/snapshot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,21 +76,21 @@ func TestGetPrevSnapshot(t *testing.T) {
description: "should return match",
testID: "[my-test - 1]",
fileData: "[my-test - 1]\nmysnapshot\n---\n",
snap: "mysnapshot\n",
snap: "mysnapshot",
line: 1,
},
{
description: "should ignore regex in testID and match correct snap",
testID: "[.*]",
fileData: "\n[my-test]\nwrong snap\n---\n\n[.*]\nmysnapshot\n---\n",
snap: "mysnapshot\n",
snap: "mysnapshot",
line: 6,
},
{
description: "should ignore end chars (---) inside snapshot",
testID: "[mock-test 1]",
fileData: "\n[mock-test 1]\nmysnapshot\n---moredata\n---\n",
snap: "mysnapshot\n---moredata\n",
snap: "mysnapshot\n---moredata",
line: 2,
},
} {
Expand All @@ -111,7 +111,7 @@ func TestGetPrevSnapshot(t *testing.T) {
func TestAddNewSnapshot(t *testing.T) {
snapPath := filepath.Join(t.TempDir(), "__snapshots__/mock-test.snap")

test.NoError(t, addNewSnapshot("[mock-id]", "my-snap\n", snapPath))
test.NoError(t, addNewSnapshot("[mock-id]", "my-snap", snapPath))
test.Equal(t, "\n[mock-id]\nmy-snap\n---\n", test.GetFileContent(t, snapPath))
}

Expand Down Expand Up @@ -198,7 +198,7 @@ string hello world 1 3 2
`
snapPath := test.CreateTempFile(t, mockSnap)
newSnapshot := "int(1250)\nstring new value\n"
newSnapshot := "int(1250)\nstring new value"

test.NoError(t, updateSnapshot("[Test_3/TestSimple - 1]", newSnapshot, snapPath))
test.Equal(t, updatedSnap, test.GetFileContent(t, snapPath))
Expand Down

0 comments on commit 09d3a05

Please sign in to comment.