forked from approvals/go-approval-tests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
approvals.go
346 lines (299 loc) · 9.26 KB
/
approvals.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package approvals
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"github.com/customerio/go-approval-tests/reporters"
"github.com/customerio/go-approval-tests/utils"
)
var (
defaultReporter = reporters.NewDiffReporter()
defaultFrontLoadedReporter = reporters.NewFrontLoadedReporter()
defaultFolder = ""
)
// Failable is an interface wrapper around testing.T
type Failable interface {
Fail()
Fatal(args ...interface{})
Fatalf(format string, args ...interface{})
Name() string
Log(args ...interface{})
Logf(format string, args ...interface{})
Helper()
}
// VerifyWithExtension Example:
//
// VerifyWithExtension(t, strings.NewReader("Hello"), ".json")
//
// Deprecated: Please use Verify with the Options() fluent syntax.
func VerifyWithExtension(t Failable, reader io.Reader, extWithDot string, opts ...verifyOptions) {
t.Helper()
Verify(t, reader, alwaysOption(opts).WithExtension(extWithDot))
}
// Verify Example:
//
// Verify(t, strings.NewReader("Hello"))
func Verify(t Failable, reader io.Reader, opts ...verifyOptions) {
t.Helper()
if len(opts) > 1 {
panic("Please use fluent syntax for options, see documentation for more information")
}
var extWithDot string
if len(opts) == 0 || opts[0].extWithDot == "" {
extWithDot = ".txt"
} else {
extWithDot = opts[0].extWithDot
}
namer := getApprovalName(t)
if len(opts) > 0 {
b, err := io.ReadAll(reader)
if err != nil {
panic(err)
}
result := string(b)
for _, o := range opts {
for _, sb := range o.scrubbers {
result = sb(result)
}
}
reader = strings.NewReader(result)
}
reporter := getReporter()
err := namer.compare(namer.getApprovalFile(extWithDot), namer.getReceivedFile(extWithDot), reader)
if err != nil {
reporter.Report(namer.getApprovalFile(extWithDot), namer.getReceivedFile(extWithDot))
t.Log("Failed Approval: received does not match approved.")
t.Fail()
} else {
_ = os.Remove(namer.getReceivedFile(extWithDot))
}
}
// VerifyString stores the passed string into the received file and confirms
// that it matches the approved local file. On failure, it will launch a reporter.
func VerifyString(t Failable, s string, opts ...verifyOptions) {
t.Helper()
reader := strings.NewReader(s)
Verify(t, reader, opts...)
}
// VerifyXMLStruct Example:
//
// VerifyXMLStruct(t, xml)
func VerifyXMLStruct(t Failable, obj interface{}, opts ...verifyOptions) {
t.Helper()
xmlContent, err := xml.MarshalIndent(obj, "", " ")
if err != nil {
tip := ""
if reflect.TypeOf(obj).Name() == "" {
tip = "when using anonymous types be sure to include\n XMLName xml.Name `xml:\"Your_Name_Here\"`\n"
}
message := fmt.Sprintf("error while pretty printing XML\n%verror:\n %v\nXML:\n %v\n", tip, err, obj)
Verify(t, strings.NewReader(message), alwaysOption(opts).WithExtension(".xml"))
} else {
Verify(t, bytes.NewReader(xmlContent), alwaysOption(opts).WithExtension(".xml"))
}
}
// VerifyXMLBytes Example:
//
// VerifyXMLBytes(t, []byte("<Test/>"))
func VerifyXMLBytes(t Failable, bs []byte, opts ...verifyOptions) {
t.Helper()
type node struct {
Attr []xml.Attr
XMLName xml.Name
Children []node `xml:",any"`
Text string `xml:",chardata"`
}
x := node{}
err := xml.Unmarshal(bs, &x)
if err != nil {
message := fmt.Sprintf("error while parsing XML\nerror:\n %s\nXML:\n %s\n", err, string(bs))
Verify(t, strings.NewReader(message), alwaysOption(opts).WithExtension(".xml"))
} else {
VerifyXMLStruct(t, x, opts...)
}
}
// VerifyJSONStruct Example:
//
// VerifyJSONStruct(t, json)
func VerifyJSONStruct(t Failable, obj interface{}, opts ...verifyOptions) {
t.Helper()
jsonb, err := json.MarshalIndent(obj, "", " ")
if err != nil {
message := fmt.Sprintf("error while pretty printing JSON\nerror:\n %s\nJSON:\n %s\n", err, obj)
Verify(t, strings.NewReader(message), alwaysOption(opts).WithExtension(".json"))
} else {
Verify(t, bytes.NewReader(jsonb), alwaysOption(opts).WithExtension(".json"))
}
}
// VerifyJSONBytes Example:
//
// VerifyJSONBytes(t, []byte("{ \"Greeting\": \"Hello\" }"))
func VerifyJSONBytes(t Failable, bs []byte, opts ...verifyOptions) {
t.Helper()
var obj map[string]interface{}
err := json.Unmarshal(bs, &obj)
if err != nil {
message := fmt.Sprintf("error while parsing JSON\nerror:\n %s\nJSON:\n %s\n", err, string(bs))
Verify(t, strings.NewReader(message), alwaysOption(opts).WithExtension(".json"))
} else {
VerifyJSONStruct(t, obj, opts...)
}
}
// VerifyMap Example:
//
// VerifyMap(t, map[string][string] { "dog": "bark" })
func VerifyMap(t Failable, m interface{}, opts ...verifyOptions) {
t.Helper()
outputText := utils.PrintMap(m)
VerifyString(t, outputText, opts...)
}
// VerifyArray Example:
//
// VerifyArray(t, []string{"dog", "cat"})
func VerifyArray(t Failable, array interface{}, opts ...verifyOptions) {
t.Helper()
outputText := utils.PrintArray(array)
VerifyString(t, outputText, opts...)
}
// VerifyAll Example:
//
// VerifyAll(t, "uppercase", []string("dog", "cat"}, func(x interface{}) string { return strings.ToUpper(x.(string)) })
func VerifyAll(t Failable, header string, collection interface{}, transform func(interface{}) string, opts ...verifyOptions) {
t.Helper()
if len(header) != 0 {
header = fmt.Sprintf("%s\n\n\n", header)
}
outputText := header + strings.Join(utils.MapToString(collection, transform), "\n")
VerifyString(t, outputText, opts...)
}
type reporterCloser struct {
reporter reporters.Reporter
}
func (s *reporterCloser) Close() error {
defaultReporter = s.reporter
return nil
}
type frontLoadedReporterCloser struct {
reporter reporters.Reporter
}
func (s *frontLoadedReporterCloser) Close() error {
defaultFrontLoadedReporter = s.reporter
return nil
}
// UseReporter configures which reporter to use on failure.
// Add at the test or method level to configure your reporter.
//
// The following examples shows how to use a reporter for all of your test cases
// in a package directory through go's setup feature.
//
// func TestMain(m *testing.M) {
// r := approvals.UseReporter(reporters.NewBeyondCompareReporter())
// defer r.Close()
//
// os.Exit(m.Run())
// }
func UseReporter(reporter reporters.Reporter) io.Closer {
closer := &reporterCloser{
reporter: defaultReporter,
}
defaultReporter = reporter
return closer
}
// UseFrontLoadedReporter configures reporters ahead of all other reporters to
// handle situations like CI. These reporters usually prevent reporting in
// scenarios that are headless.
func UseFrontLoadedReporter(reporter reporters.Reporter) io.Closer {
closer := &frontLoadedReporterCloser{
reporter: defaultFrontLoadedReporter,
}
defaultFrontLoadedReporter = reporter
return closer
}
func getReporter() reporters.Reporter {
return reporters.NewFirstWorkingReporter(
defaultFrontLoadedReporter,
defaultReporter,
)
}
// UseFolder configures which folder to use to store approval files.
// By default, the approval files will be stored at the same level as the code.
//
// The following examples shows how to use the idiomatic 'testdata' folder
// for all of your test cases in a package directory.
//
// func TestMain(m *testing.M) {
// approvals.UseFolder("testdata")
//
// os.Exit(m.Run())
// }
func UseFolder(f string) {
defaultFolder = f
}
type scrubber func(s string) string
// verifyOptions can be accessed via the approvals.Options() API enabling configuration of scrubbers
type verifyOptions struct {
scrubbers []scrubber
extWithDot string
}
// Options enables providing individual Verify functions with customisations such as scrubbers
func Options() verifyOptions {
return verifyOptions{}
}
// WithRegexScrubber allows you to 'scrub' dynamic data such as timestamps within your test input
// and replace it with a static placeholder
func (v verifyOptions) WithRegexScrubber(scrubber *regexp.Regexp, replacer string) verifyOptions {
v.scrubbers = append(v.scrubbers, func(s string) string {
return scrubber.ReplaceAllString(s, replacer)
})
return v
}
// WithExtension overrides the default file extension (.txt) for approval files.
func (v verifyOptions) WithExtension(extension string) verifyOptions {
v.extWithDot = extension
return v
}
func alwaysOption(opts []verifyOptions) verifyOptions {
var v verifyOptions
if len(opts) == 0 {
v = Options()
} else {
v = opts[0]
}
return v
}
// AcceptChanges handles renaming `.received` files to `.approved` based on the given flag.
// If `approve` is true, it renames all `.received.*` files and `.received` files in the default folder
// to `.approved.*` and `.approved`, respectively.
func AcceptChanges(approve bool) error {
if !approve {
return nil
}
if defaultFolder == "" {
return fmt.Errorf("default folder is not set; use UseFolder to set the folder")
}
return filepath.Walk(defaultFolder, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip directories
if info.IsDir() {
return nil
}
// Handle `.received.*` files and `.received` files
if strings.Contains(info.Name(), ".received") {
approvedName := strings.Replace(path, ".received", ".approved", 1)
if err := os.Rename(path, approvedName); err != nil {
return fmt.Errorf("failed to rename %s to %s: %w", path, approvedName, err)
}
fmt.Printf("Accepted changes to %s\n", approvedName)
}
return nil
})
}