-
Notifications
You must be signed in to change notification settings - Fork 84
/
helpers_test.go
67 lines (58 loc) · 1.5 KB
/
helpers_test.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
package main
import (
"bytes"
"flag"
"fmt"
"os"
"strings"
"testing"
"github.com/go-test/deep"
)
// Helpers to tests. By including t.Helper(), the right failing line in the test
// itself is reported.
var (
update = flag.Bool("update", false, "update the golden files of this test")
)
// writeGolden - write golden file that to be used for later tests
func writeGolden(t *testing.T, goldenAssetPath string, data []byte) error {
t.Helper()
fd, err := os.Create(goldenAssetPath)
if err != nil {
return err
}
_, err = fd.Write(data)
if err != nil {
return err
}
return nil
}
// compareOrUpdateGolden - compare generated data with golden dump or update it with -update flag set
func compareOrUpdateGolden(t *testing.T, genData []byte, path string) (err error) {
t.Helper()
if *update { // Generate golden dump file
err = writeGolden(t, path, genData)
if err != nil {
t.Error(err)
}
return nil
}
// Compare with golden dump file
golden, err := os.ReadFile(path)
if err != nil {
t.Error(err)
}
if strings.HasSuffix(path, ".txt") || strings.HasSuffix(path, ".scc") {
// Replace \r\n with \n to handle accidental Windows line endings
golden = bytes.ReplaceAll(golden, []byte{13, 10}, []byte{10})
}
diff := deep.Equal(golden, genData)
if diff != nil {
return fmt.Errorf("Generated data different from %s", path)
}
return nil
}
// TestMain is to set flags for tests. In particular, the update flag to update golden files.
func TestMain(m *testing.M) {
flag.Parse()
os.Exit(m.Run())
}