Debian Codegraph @

v2/goldie.go

raw symbols SCIP
1 // Package goldie provides test assertions based on golden files. It's
2 // typically used for testing responses with larger data bodies.
3 //
4 // The concept is straight forward. Valid response data is stored in a "golden
5 // file". The actual response data will be byte compared with the golden file
6 // and the test will fail if there is a difference.
7 //
8 // Updating the golden file can be done by running `go test -update ./...`.
9 package goldie
10
11 import (
12 "flag"
13 "fmt"
14 "io/ioutil"
15 "os"
16 "path/filepath"
17 "strings"
18 "testing"
19 "time"
20
21 "github.com/pmezard/go-difflib/difflib"
22 "github.com/sergi/go-diff/diffmatchpatch"
23 )
24
25 const (
26 // defaultFixtureDir is the folder name for where the fixtures are stored.
27 // It's relative to the "go test" path.
28 defaultFixtureDir = "testdata"
29
30 // defaultFileNameSuffix is the suffix appended to the fixtures. Set to
31 // empty string to disable file name suffixes.
32 defaultFileNameSuffix = ".golden"
33
34 // defaultFilePerms is used to set the permissions on the golden fixture
35 // files.
36 defaultFilePerms os.FileMode = 0644
37
38 // defaultDirPerms is used to set the permissions on the golden fixture
39 // folder.
40 defaultDirPerms os.FileMode = 0755
41
42 // defaultDiffEngine sets which diff engine to use if not defined.
43 defaultDiffEngine = ClassicDiff
44
45 // defaultIgnoreTemplateErrors sets the default value for the
46 // WithIgnoreTemplateErrors option.
47 defaultIgnoreTemplateErrors = false
48
49 // defaultUseTestNameForDir sets the default value for the
50 // WithTestNameForDir option.
51 defaultUseTestNameForDir = false
52
53 // defaultUseSubTestNameForDir sets the default value for the
54 // WithSubTestNameForDir option.
55 defaultUseSubTestNameForDir = false
56 )
57
58 var (
59 // update determines if the actual received data should be written to the
60 // golden files or not. This should be true when you need to update the
61 // data, but false when actually running the tests.
62 update = flag.Bool("update", false, "Update golden test file fixture")
63
64 // clean determines if we should remove old golden test files in the output
65 // directory or not. This only takes effect if we are updating the golden
66 // test files.
67 clean = flag.Bool("clean", false, "Clean old golden test files before writing new olds")
68
69 // ts saves the timestamp of the test run, we use ts to mark the
70 // modification time of golden file dirs, for cleaning if required by
71 // `-clean` flag.
72 ts = time.Now()
73 )
74
75 // Goldie is the root structure for the test runner. It provides test assertions based on golden files. It's
76 // typically used for testing responses with larger data bodies.
77 type Goldie struct {
78 fixtureDir string
79 fileNameSuffix string
80 filePerms os.FileMode
81 dirPerms os.FileMode
82
83 diffEngine DiffEngine
84 diffFn DiffFn
85 ignoreTemplateErrors bool
86 useTestNameForDir bool
87 useSubTestNameForDir bool
88 }
89
90 // === Create new testers ==================================
91
92 // New creates a new golden file tester. If there is an issue with applying any
93 // of the options, an error will be reported and t.FailNow() will be called.
94 func New(t *testing.T, options ...Option) *Goldie {
95 g := Goldie{
96 fixtureDir: defaultFixtureDir,
97 fileNameSuffix: defaultFileNameSuffix,
98 filePerms: defaultFilePerms,
99 dirPerms: defaultDirPerms,
100 diffEngine: defaultDiffEngine,
101 ignoreTemplateErrors: defaultIgnoreTemplateErrors,
102 useTestNameForDir: defaultUseTestNameForDir,
103 useSubTestNameForDir: defaultUseSubTestNameForDir,
104 }
105
106 var err error
107 for _, option := range options {
108 err = option(&g)
109 if err != nil {
110 t.Error(fmt.Errorf("could not apply option: %w", err))
111 t.FailNow()
112 }
113 }
114
115 return &g
116 }
117
118 // Diff generates a string that shows the difference between the actual and the
119 // expected. This method could be called in your own DiffFn in case you want
120 // to leverage any of the engines defined.
121 func Diff(engine DiffEngine, actual string, expected string) (diff string) {
122 switch engine {
123 case Simple:
124 diff = fmt.Sprintf("Expected: %s\nGot: %s", expected, actual)
125
126 case ClassicDiff:
127 diff, _ = difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
128 A: difflib.SplitLines(expected),
129 B: difflib.SplitLines(actual),
130 FromFile: "Expected",
131 FromDate: "",
132 ToFile: "Actual",
133 ToDate: "",
134 Context: 1,
135 })
136
137 case ColoredDiff:
138 dmp := diffmatchpatch.New()
139 diffs := dmp.DiffMain(actual, expected, false)
140 diff = dmp.DiffPrettyText(diffs)
141 }
142
143 return diff
144 }
145
146 // Update will update the golden fixtures with the received actual data.
147 //
148 // This method does not need to be called from code, but it's exposed so that
149 // it can be explicitly called if needed. The more common approach would be to
150 // update using `go test -update ./...`.
151 func (g *Goldie) Update(t *testing.T, name string, actualData []byte) error {
152 goldenFile := g.GoldenFileName(t, name)
153 goldenFileDir := filepath.Dir(goldenFile)
154 if err := g.ensureDir(goldenFileDir); err != nil {
155 return err
156 }
157
158 if err := ioutil.WriteFile(goldenFile, actualData, g.filePerms); err != nil {
159 return err
160 }
161
162 if err := os.Chtimes(goldenFileDir, ts, ts); err != nil {
163 return err
164 }
165
166 return nil
167 }
168
169 // ensureDir will create the fixture folder if it does not already exist.
170 func (g *Goldie) ensureDir(loc string) error {
171 s, err := os.Stat(loc)
172
173 switch {
174 case err != nil && os.IsNotExist(err):
175 // the location does not exist, so make directories to there
176 return os.MkdirAll(loc, g.dirPerms)
177
178 case err == nil && s.IsDir() && *clean && s.ModTime().UnixNano() != ts.UnixNano():
179 if err := os.RemoveAll(loc); err != nil {
180 return err
181 }
182 return os.MkdirAll(loc, g.dirPerms)
183
184 case err == nil && !s.IsDir():
185 return newErrFixtureDirectoryIsFile(loc)
186 }
187
188 return err
189 }
190
191 // GoldenFileName simply returns the file name of the golden file fixture.
192 func (g *Goldie) GoldenFileName(t *testing.T, name string) string {
193 dir := g.fixtureDir
194
195 if g.useTestNameForDir {
196 dir = filepath.Join(dir, strings.Split(t.Name(), "/")[0])
197 }
198
199 if g.useSubTestNameForDir {
200 n := strings.Split(t.Name(), "/")
201 if len(n) > 1 {
202 dir = filepath.Join(dir, n[1])
203 }
204 }
205
206 return filepath.Join(dir, fmt.Sprintf("%s%s", name, g.fileNameSuffix))
207 }