-
Notifications
You must be signed in to change notification settings - Fork 0
/
match_snapshot.go
98 lines (80 loc) · 2.34 KB
/
match_snapshot.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package snapshotmacther
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/sergi/go-diff/diffmatchpatch"
)
var snapshotDir = "__snapshots__"
var EnvKeyUpdateSnapshot = "UPDATE_SNAPSHOT"
func MatchSnapshot(names ...string) *SnapshotMatcher {
filename := filepath.Join(names...)
updateSnapShot := os.Getenv(EnvKeyUpdateSnapshot)
return &SnapshotMatcher{
filename: filename,
forceUpdate: updateSnapShot == "all" || updateSnapShot == filename,
}
}
type SnapshotMatcher struct {
filename string
forceUpdate bool
actualData []byte
expectedData []byte
}
func (matcher *SnapshotMatcher) Match(actual interface{}) (success bool, err error) {
f := filepath.Join(snapshotDir, matcher.filename)
switch v := actual.(type) {
case []byte:
matcher.actualData = v
case string:
matcher.actualData = []byte(v)
default:
return false, fmt.Errorf("snapshot not support %T", actual)
}
if matcher.forceUpdate {
if err := snapshot(f, matcher.actualData); err != nil {
return false, err
}
return true, nil
}
data, err := ioutil.ReadFile(f)
if err != nil {
if os.IsNotExist(err) {
if err := snapshot(f, matcher.actualData); err != nil {
return false, err
}
return true, nil
}
return false, err
}
matcher.expectedData = data
return bytes.Equal(matcher.actualData, matcher.expectedData), nil
}
func (matcher *SnapshotMatcher) FailureMessage(actual interface{}) (message string) {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(string(matcher.expectedData), string(matcher.actualData), true)
return dmp.DiffPrettyText(diffs) + matcher.helper()
}
func (matcher *SnapshotMatcher) NegatedFailureMessage(actual interface{}) (message string) {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(string(matcher.expectedData), string(matcher.actualData), true)
return dmp.DiffPrettyText(diffs) + matcher.helper()
}
func (matcher *SnapshotMatcher) helper() string {
return fmt.Sprintf(`
-----------
run with "%s=%s" for updating the snapshot or "%s=all" for updating all snapshot
`, EnvKeyUpdateSnapshot, matcher.filename, EnvKeyUpdateSnapshot)
}
func snapshot(filename string, input []byte) error {
dirname := filepath.Dir(filename)
if err := os.MkdirAll(dirname, os.ModePerm); err != nil {
return err
}
if err := ioutil.WriteFile(filename, input, os.ModePerm); err != nil {
return err
}
return nil
}