forked from gkampitakis/go-snaps
/
matchSnapshot.go
84 lines (69 loc) 路 1.69 KB
/
matchSnapshot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package snaps
import (
"errors"
"github.com/NicklasWallgren/go-snaps/snaps/internal/formatter"
"github.com/NicklasWallgren/go-snaps/snaps/internal/colors"
)
// MatchSnapshot verifies the values match the most recent snap file
//
// You can pass multiple values
//
// MatchSnapshot(t, 10, "hello world")
//
// or call MatchSnapshot multiples times inside a test
//
// MatchSnapshot(t, 10)
// MatchSnapshot(t, "hello world")
//
// The difference is the latter will create multiple entries.
func MatchSnapshot(t testingT, values ...interface{}) {
t.Helper()
if len(values) == 0 {
t.Log(colors.Sprint(colors.Yellow, "[warning] MatchSnapshot call without params\n"))
return
}
dir, snapPath := snapDirAndName()
testID := testsRegistry.getTestID(t.Name(), snapPath)
snapshot := takeSnapshot(values)
prevSnapshot, err := getPrevSnapshot(testID, snapPath)
if errors.Is(err, errSnapNotFound) {
if isCI {
handleError(t, err)
return
}
err := addNewSnapshot(testID, snapshot, dir, snapPath)
if err != nil {
handleError(t, err)
return
}
t.Log(addedMsg)
testEvents.register(added)
return
}
if err != nil {
handleError(t, err)
return
}
diff := prettyDiff(unescapeEndChars(prevSnapshot), unescapeEndChars(snapshot))
if diff == "" {
testEvents.register(passed)
return
}
if !shouldUpdate {
handleError(t, diff)
return
}
if err = updateSnapshot(testID, snapshot, snapPath); err != nil {
handleError(t, err)
return
}
t.Log(updatedMsg)
testEvents.register(updated)
}
func takeSnapshot(objects []interface{}) string {
var snapshot string
for i := 0; i < len(objects); i++ {
snapshot += formatter.Sprint(objects[i]) + "\n"
}
return escapeEndChars(snapshot)
}