Skip to content
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

fix: handle crlf sequences in snaps #65

Merged
merged 2 commits into from
Jun 9, 2023
Merged
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
18 changes: 0 additions & 18 deletions internal/test/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,24 +68,6 @@ func NotCalled(t *testing.T) {
t.Errorf("function was not expected to be called")
}

// NOTE: this was added at 1.17
func SetEnv(t *testing.T, key, value string) {
t.Helper()

prevVal, exists := os.LookupEnv(key)
os.Setenv(key, value)

if exists {
t.Cleanup(func() {
os.Setenv(key, prevVal)
})
} else {
t.Cleanup(func() {
os.Unsetenv(key)
})
}
}

func CreateTempFile(t *testing.T, data string) string {
dir := t.TempDir()
path := filepath.Join(dir, "mock.file")
Expand Down
62 changes: 27 additions & 35 deletions snaps/clean.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package snaps

import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
Expand Down Expand Up @@ -143,24 +144,29 @@ func examineSnaps(
obsoleteTests := []string{}

for _, snapPath := range used {
var updatedFile strings.Builder
hasDiffs := false

f, err := os.Open(snapPath)
f, err := os.OpenFile(snapPath, os.O_RDWR, os.ModePerm)
if err != nil {
return nil, err
}
defer f.Close()

var updatedFile bytes.Buffer
if i, err := f.Stat(); err == nil {
updatedFile.Grow(int(i.Size()))
}
var hasDiffs bool

registeredTests := occurrences(registry[snapPath])
s := bufio.NewScanner(f)

for s.Scan() {
b := s.Bytes()
// Check if line is a test id
match := testIDRegexp.FindStringSubmatch(s.Text())
match := testIDRegexp.FindSubmatch(b)
if len(match) <= 1 {
continue
}
testID := match[1]
testID := string(match[1])

if !registeredTests.Has(testID) && !testSkipped(testID, runOnly) {
obsoleteTests = append(obsoleteTests, testID)
Expand All @@ -171,47 +177,33 @@ func examineSnaps(
continue
}

fmt.Fprintf(&updatedFile, "\n[%s]\n%s---\n", testID, scanSnapshot(s))
updatedFile.WriteByte('\n')
updatedFile.Write(b)
updatedFile.WriteByte('\n')

for s.Scan() {
line := s.Bytes()
updatedFile.Write(line)
updatedFile.WriteByte('\n')

if bytes.Equal(line, endSequenceByteSlice) {
break
}
}
}

f.Close()
if !hasDiffs || !shouldUpdate {
continue
}

if err = stringToSnapshotFile(updatedFile.String(), snapPath); err != nil {
if err = overwriteFile(f, updatedFile.Bytes()); err != nil {
fmt.Println(err)
}
}

return obsoleteTests, nil
}

func removeSnapshot(s *bufio.Scanner) {
for s.Scan() {
// skip until ---
if s.Text() == "---" {
break
}
}
}

func scanSnapshot(s *bufio.Scanner) string {
var snapshot strings.Builder

for s.Scan() {
line := s.Text()
// reached end char
if s.Text() == "---" {
break
}

snapshot.WriteString(line + "\n")
}

return snapshot.String()
}

func summary(
obsoleteFiles, obsoleteTests []string, NOskippedTests int,
testEvents map[uint8]int,
Expand Down Expand Up @@ -322,7 +314,7 @@ e.g
as it means there are 3 snapshots created inside TestAdd
*/
func occurrences(tests map[string]int) set {
result := make(set)
result := make(set, len(tests))
for testID, counter := range tests {
if counter > 1 {
for i := 1; i <= counter; i++ {
Expand Down
17 changes: 8 additions & 9 deletions snaps/matchJSON_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ const jsonFilename = "matchJSON_test.snap"

func TestMatchJSON(t *testing.T) {
t.Run("should create json snapshot", func(t *testing.T) {
expected := `
{
expected := `{
"items": [
5,
1,
Expand Down Expand Up @@ -63,7 +62,7 @@ func TestMatchJSON(t *testing.T) {

MatchJSON(mockT, tc.input)

snap, err := getPrevSnapshot("mock-name - 1", snapPath)
snap, err := getPrevSnapshot("[mock-name - 1]", snapPath)
test.Nil(t, err)
test.Equal(t, expected, snap)
test.Equal(t, 1, testEvents.items[added])
Expand Down Expand Up @@ -181,7 +180,7 @@ func TestMatchJSON(t *testing.T) {
})

t.Run("if it's running on ci should skip creating snapshot", func(t *testing.T) {
snapPath := setupSnapshot(t, jsonFilename, true)
setupSnapshot(t, jsonFilename, true)

mockT := test.MockTestingT{
MockHelper: func() {},
Expand All @@ -198,8 +197,6 @@ func TestMatchJSON(t *testing.T) {

MatchJSON(mockT, "{}")

_, err := snapshotFileToString(snapPath)
test.Equal(t, errSnapNotFound, err)
test.Equal(t, 1, testEvents.items[erred])
})

Expand Down Expand Up @@ -236,9 +233,11 @@ func TestMatchJSON(t *testing.T) {
// Second call with different params
MatchJSON(mockT, "{\"value\":\"bye world\"}")

snap, err := snapshotFileToString(snapPath)
test.Nil(t, err)
test.Equal(t, "\n[mock-name - 1]\n{\n \"value\": \"bye world\"\n}\n---\n", snap)
test.Equal(
t,
"\n[mock-name - 1]\n{\n \"value\": \"bye world\"\n}\n---\n",
snapshotFile(t, snapPath),
)
test.Equal(t, 1, testEvents.items[updated])
})
}
14 changes: 4 additions & 10 deletions snaps/matchSnapshot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,12 @@ func TestMatchSnapshot(t *testing.T) {

MatchSnapshot(mockT, 10, "hello world")

snap, err := snapshotFileToString(snapPath)
test.Nil(t, err)
test.Equal(t, "\n[mock-name - 1]\nint(10)\nhello world\n---\n", snap)
test.Equal(t, "\n[mock-name - 1]\nint(10)\nhello world\n---\n", snapshotFile(t, snapPath))
test.Equal(t, 1, testEvents.items[added])
})

t.Run("if it's running on ci should skip", func(t *testing.T) {
snapPath := setupSnapshot(t, fileName, true)
setupSnapshot(t, fileName, true)

mockT := test.MockTestingT{
MockHelper: func() {},
Expand All @@ -100,8 +98,6 @@ func TestMatchSnapshot(t *testing.T) {

MatchSnapshot(mockT, 10, "hello world")

_, err := snapshotFileToString(snapPath)
test.Equal(t, errSnapNotFound, err)
test.Equal(t, 1, testEvents.items[erred])
})

Expand Down Expand Up @@ -178,9 +174,7 @@ func TestMatchSnapshot(t *testing.T) {
// Second call with different params
MatchSnapshot(mockT, 100, "bye world")

snap, err := snapshotFileToString(snapPath)
test.Nil(t, err)
test.Equal(t, "\n[mock-name - 1]\nint(100)\nbye world\n---\n", snap)
test.Equal(t, "\n[mock-name - 1]\nint(100)\nbye world\n---\n", snapshotFile(t, snapPath))
test.Equal(t, 1, testEvents.items[updated])
})

Expand Down Expand Up @@ -229,7 +223,7 @@ func TestMatchSnapshot(t *testing.T) {
}

// First call for creating the snapshot ( adding ending chars inside the diff )
MatchSnapshot(mockT, 10, "hello world----", "---")
MatchSnapshot(mockT, 10, "hello world----", endSequence)

// Resetting registry to emulate the same MatchSnapshot call
testsRegistry = newRegistry()
Expand Down
1 change: 0 additions & 1 deletion snaps/skip.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ func isFileSkipped(dir, filename, runOnly string) bool {

for _, decls := range file.Decls {
funcDecl, ok := decls.(*ast.FuncDecl)

if !ok {
continue
}
Expand Down
Loading