-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathapprovals.go
More file actions
253 lines (222 loc) · 6.97 KB
/
approvals.go
File metadata and controls
253 lines (222 loc) · 6.97 KB
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
package approvals
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"os"
"reflect"
"strings"
"github.com/approvals/go-approval-tests/core"
"github.com/approvals/go-approval-tests/internal/log"
"github.com/approvals/go-approval-tests/reporters"
"github.com/approvals/go-approval-tests/utils"
)
var (
defaultReporter = reporters.NewDiffReporter()
defaultFrontLoadedReporter = reporters.NewFrontLoadedReporter()
defaultFolder = ""
)
// VerifyWithExtension Example:
//
// VerifyWithExtension(t, strings.NewReader("Hello"), ".json")
//
// Deprecated: Please use Verify with the Options() fluent syntax.
func VerifyWithExtension(t core.Failable, reader io.Reader, extWithDot string, opts ...VerifyOptions) {
t.Helper()
Verify(t, reader, alwaysOption(opts).ForFile().WithExtension(extWithDot))
}
// Verify Example:
//
// Verify(t, strings.NewReader("Hello"))
func Verify(t core.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 opt VerifyOptions
if len(opts) > 0 {
opt = opts[0]
}
reader, err := opt.Scrub(reader)
if err != nil {
panic(err)
}
extWithDot := opt.ForFile().GetExtension()
namer := opt.ForFile().GetNamer()(t)
approvalFile := namer.GetApprovalFile(extWithDot)
receivedFile := namer.GetReceivedFile(extWithDot)
reporter := getReporter()
err = core.Compare(namer.GetName(), approvalFile, receivedFile, reader)
if err != nil {
log.GetFailedFileLoggerInstance().Log(receivedFile, approvalFile)
reporter.Report(approvalFile, receivedFile)
t.Error("Failed Approval: received does not match approved.")
} else {
_ = os.Remove(receivedFile)
}
}
// 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 core.Failable, s string, opts ...VerifyOptions) {
t.Helper()
reader := strings.NewReader(s)
Verify(t, reader, opts...)
}
// VerifyXMLStruct Example:
//
// VerifyXMLStruct(t, xml)
func VerifyXMLStruct(t core.Failable, obj interface{}, opts ...VerifyOptions) {
t.Helper()
options := alwaysOption(opts).ForFile().WithExtension(".xml")
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), options)
} else {
Verify(t, bytes.NewReader(xmlContent), options)
}
}
// VerifyXMLBytes Example:
//
// VerifyXMLBytes(t, []byte("<Test/>"))
func VerifyXMLBytes(t core.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).ForFile().WithExtension(".xml"))
} else {
VerifyXMLStruct(t, x, opts...)
}
}
// VerifyJSONStruct Example:
//
// VerifyJSONStruct(t, json)
func VerifyJSONStruct(t core.Failable, obj interface{}, opts ...VerifyOptions) {
t.Helper()
options := alwaysOption(opts).ForFile().WithExtension(".json")
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), options)
} else {
Verify(t, bytes.NewReader(jsonb), options)
}
}
// VerifyJSONBytes Example:
//
// VerifyJSONBytes(t, []byte("{ \"Greeting\": \"Hello\" }"))
func VerifyJSONBytes(t core.Failable, bs []byte, opts ...VerifyOptions) {
t.Helper()
var obj 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).ForFile().WithExtension(".json"))
} else {
VerifyJSONStruct(t, obj, opts...)
}
}
// VerifyMap Example:
//
// VerifyMap(t, map[string][string] { "dog": "bark" })
func VerifyMap(t core.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 core.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 core.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
}