-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
assert.go
353 lines (318 loc) · 10.6 KB
/
assert.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
347
348
349
350
351
352
353
// Package assert provides type-safe assertions with clean error messages.
package assert
import (
"bytes"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"testing"
"github.com/alecthomas/repr"
"github.com/hexops/gotextdiff"
"github.com/hexops/gotextdiff/myers"
)
// A CompareOption modifies how object comparisons behave.
type CompareOption func() []repr.Option
// Exclude fields of the given type from comparison.
func Exclude[T any]() CompareOption {
return func() []repr.Option {
return []repr.Option{repr.Hide[T]()}
}
}
// OmitEmpty fields from comparison.
func OmitEmpty() CompareOption {
return func() []repr.Option {
return []repr.Option{repr.OmitEmpty(true)}
}
}
// IgnoreGoStringer ignores GoStringer implementations when comparing.
func IgnoreGoStringer() CompareOption {
return func() []repr.Option {
return []repr.Option{repr.IgnoreGoStringer()}
}
}
// Compare two values for equality and return true or false.
func Compare[T any](t testing.TB, x, y T, options ...CompareOption) bool {
return objectsAreEqual(x, y, options...)
}
func extractCompareOptions(msgAndArgs ...any) ([]any, []CompareOption) {
compareOptions := []CompareOption{}
out := []any{}
for _, arg := range msgAndArgs {
if opt, ok := arg.(CompareOption); ok {
compareOptions = append(compareOptions, opt)
} else {
out = append(out, arg)
}
}
return out, compareOptions
}
// HasPrefix asserts that the string s starts with prefix.
func HasPrefix(t testing.TB, s, prefix string, msgAndArgs ...any) {
if strings.HasPrefix(s, prefix) {
return
}
t.Helper()
msg := formatMsgAndArgs("Expected string to have prefix:", msgAndArgs...)
t.Fatalf("%s\nPrefix: %q\nString: %q\n", msg, prefix, s)
}
// HasSuffix asserts that the string s ends with suffix.
func HasSuffix(t testing.TB, s, suffix string, msgAndArgs ...any) {
if strings.HasSuffix(s, suffix) {
return
}
t.Helper()
msg := formatMsgAndArgs("Expected string to have suffix:", msgAndArgs...)
t.Fatalf("%s\nSuffix: %q\nString: %q\n", msg, suffix, s)
}
// Equal asserts that "expected" and "actual" are equal.
//
// If they are not, a diff of the Go representation of the values will be displayed.
func Equal[T any](t testing.TB, expected, actual T, msgArgsAndCompareOptions ...any) {
msgArgsAndCompareOptions, compareOptions := extractCompareOptions(msgArgsAndCompareOptions...)
if objectsAreEqual(expected, actual, compareOptions...) {
return
}
t.Helper()
msg := formatMsgAndArgs("Expected values to be equal:", msgArgsAndCompareOptions...)
t.Fatalf("%s\n%s", msg, Diff(expected, actual, compareOptions...))
}
// NotEqual asserts that "expected" is not equal to "actual".
//
// If they are equal the expected value will be displayed.
func NotEqual[T any](t testing.TB, expected, actual T, msgArgsAndCompareOptions ...any) {
msgArgsAndCompareOptions, compareOptions := extractCompareOptions(msgArgsAndCompareOptions...)
if !objectsAreEqual(expected, actual, compareOptions...) {
return
}
t.Helper()
msg := formatMsgAndArgs("Expected values to not be equal but both were:", msgArgsAndCompareOptions...)
t.Fatalf("%s\n%s", msg, repr.String(expected, repr.Indent(" ")))
}
// Contains asserts that "haystack" contains "needle".
func Contains(t testing.TB, haystack string, needle string, msgAndArgs ...any) {
if strings.Contains(haystack, needle) {
return
}
t.Helper()
msg := formatMsgAndArgs("Haystack does not contain needle.", msgAndArgs...)
t.Fatalf("%s\nNeedle: %q\nHaystack: %q\n", msg, needle, haystack)
}
// NotContains asserts that "haystack" does not contain "needle".
func NotContains(t testing.TB, haystack string, needle string, msgAndArgs ...any) {
if !strings.Contains(haystack, needle) {
return
}
t.Helper()
msg := formatMsgAndArgs("Haystack should not contain needle.", msgAndArgs...)
quotedHaystack, quotedNeedle, positions := needlePosition(haystack, needle)
t.Fatalf("%s\nNeedle: %s\nHaystack: %s\n %s\n", msg, quotedNeedle, quotedHaystack, positions)
}
// SliceContains asserts that "haystack" contains "needle".
func SliceContains[T any](t testing.TB, haystack []T, needle T, msgAndArgs ...interface{}) {
t.Helper()
for _, item := range haystack {
if objectsAreEqual(item, needle) {
return
}
}
msg := formatMsgAndArgs("Haystack does not contain needle.", msgAndArgs...)
needleRepr := repr.String(needle, repr.Indent(" "))
haystackRepr := repr.String(haystack, repr.Indent(" "))
t.Fatalf("%s\nNeedle: %s\nHaystack: %s\n", msg, needleRepr, haystackRepr)
}
// NotSliceContains asserts that "haystack" does not contain "needle".
func NotSliceContains[T any](t testing.TB, haystack []T, needle T, msgAndArgs ...interface{}) {
t.Helper()
for _, item := range haystack {
if objectsAreEqual(item, needle) {
msg := formatMsgAndArgs("Haystack should not contain needle.", msgAndArgs...)
needleRepr := repr.String(needle, repr.Indent(" "))
haystackRepr := repr.String(haystack, repr.Indent(" "))
t.Fatalf("%s\nNeedle: %s\nHaystack: %s\n", msg, needleRepr, haystackRepr)
}
}
}
// Zero asserts that a value is its zero value.
func Zero[T any](t testing.TB, value T, msgAndArgs ...any) {
var zero T
if objectsAreEqual(value, zero) {
return
}
val := reflect.ValueOf(value)
if (val.Kind() == reflect.Slice || val.Kind() == reflect.Map || val.Kind() == reflect.Array) && val.Len() == 0 {
return
}
t.Helper()
msg := formatMsgAndArgs("Expected a zero value but got:", msgAndArgs...)
t.Fatalf("%s\n%s", msg, repr.String(value, repr.Indent(" ")))
}
// NotZero asserts that a value is not its zero value.
func NotZero[T any](t testing.TB, value T, msgAndArgs ...any) {
var zero T
if !objectsAreEqual(value, zero) {
val := reflect.ValueOf(value)
if !((val.Kind() == reflect.Slice || val.Kind() == reflect.Map || val.Kind() == reflect.Array) && val.Len() == 0) {
return
}
}
t.Helper()
msg := formatMsgAndArgs("Did not expect the zero value:", msgAndArgs...)
t.Fatalf("%s\n%s", msg, repr.String(value))
}
// EqualError asserts that either an error is non-nil and that its message is what is expected,
// or that error is nil if the expected message is empty.
func EqualError(t testing.TB, err error, errString string, msgAndArgs ...any) {
if err == nil && errString == "" {
return
}
t.Helper()
if err == nil {
t.Fatal(formatMsgAndArgs("Expected an error", msgAndArgs...))
}
if err.Error() != errString {
msg := formatMsgAndArgs("Error message not as expected:", msgAndArgs...)
t.Fatalf("%s\n%s", msg, Diff(errString, err.Error()))
}
}
// IsError asserts than any error in "err"'s tree matches "target".
func IsError(t testing.TB, err, target error, msgAndArgs ...any) {
if errors.Is(err, target) {
return
}
t.Helper()
t.Fatal(formatMsgAndArgs(fmt.Sprintf("Error tree %+v should contain error %q", err, target), msgAndArgs...))
}
// NotIsError asserts than no error in "err"'s tree matches "target".
func NotIsError(t testing.TB, err, target error, msgAndArgs ...any) {
if !errors.Is(err, target) {
return
}
t.Helper()
t.Fatal(formatMsgAndArgs(fmt.Sprintf("Error tree %+v should NOT contain error %q", err, target), msgAndArgs...))
}
// Error asserts that an error is not nil.
func Error(t testing.TB, err error, msgAndArgs ...any) {
if err != nil {
return
}
t.Helper()
t.Fatal(formatMsgAndArgs("Expected an error", msgAndArgs...))
}
// NoError asserts that an error is nil.
func NoError(t testing.TB, err error, msgAndArgs ...any) {
if err == nil {
return
}
t.Helper()
msg := formatMsgAndArgs("Did not expect an error but got:", msgAndArgs...)
t.Fatalf("%s\n%+v", msg, err)
}
// True asserts that an expression is true.
func True(t testing.TB, ok bool, msgAndArgs ...any) {
if ok {
return
}
t.Helper()
t.Fatal(formatMsgAndArgs("Expected expression to be true", msgAndArgs...))
}
// False asserts that an expression is false.
func False(t testing.TB, ok bool, msgAndArgs ...any) {
if !ok {
return
}
t.Helper()
t.Fatal(formatMsgAndArgs("Expected expression to be false", msgAndArgs...))
}
// Panics asserts that the given function panics.
func Panics(t testing.TB, fn func(), msgAndArgs ...any) {
t.Helper()
defer func() {
if recover() == nil {
msg := formatMsgAndArgs("Expected function to panic", msgAndArgs...)
t.Fatal(msg)
}
}()
fn()
}
// NotPanics asserts that the given function does not panic.
func NotPanics(t testing.TB, fn func(), msgAndArgs ...any) {
t.Helper()
defer func() {
if err := recover(); err != nil {
msg := formatMsgAndArgs("Expected function not to panic", msgAndArgs...)
t.Fatalf("%s\nPanic: %v", msg, err)
}
}()
fn()
}
// Diff returns a unified diff of the string representation of two values.
func Diff[T any](before, after T, compareOptions ...CompareOption) string {
var lhss, rhss string
// Special case strings so we get nice diffs.
if l, ok := any(before).(string); ok {
lhss = l + "\n"
rhss = any(after).(string) + "\n"
} else {
ropts := expandCompareOptions(compareOptions...)
lhss = repr.String(before, ropts...) + "\n"
rhss = repr.String(after, ropts...) + "\n"
}
edits := myers.ComputeEdits("a.txt", lhss, rhss)
lines := strings.Split(fmt.Sprint(gotextdiff.ToUnified("expected.txt", "actual.txt", lhss, edits)), "\n")
if len(lines) < 3 {
return ""
}
return strings.Join(lines[3:], "\n")
}
func formatMsgAndArgs(dflt string, msgAndArgs ...any) string {
if len(msgAndArgs) == 0 {
return dflt
}
format, ok := msgAndArgs[0].(string)
if !ok {
panic("message argument to assert function must be a fmt string")
}
return fmt.Sprintf(format, msgAndArgs[1:]...)
}
func needlePosition(haystack, needle string) (quotedHaystack, quotedNeedle, positions string) {
quotedNeedle = strconv.Quote(needle)
quotedNeedle = quotedNeedle[1 : len(quotedNeedle)-1]
quotedHaystack = strconv.Quote(haystack)
rawPositions := strings.ReplaceAll(quotedHaystack, quotedNeedle, strings.Repeat("^", len(quotedNeedle)))
for _, rn := range rawPositions {
if rn != '^' {
positions += " "
} else {
positions += "^"
}
}
return
}
func expandCompareOptions(options ...CompareOption) []repr.Option {
ropts := []repr.Option{repr.Indent(" ")}
for _, option := range options {
ropts = append(ropts, option()...)
}
return ropts
}
func objectsAreEqual(expected, actual any, options ...CompareOption) bool {
if expected == nil || actual == nil {
return expected == actual
}
if exp, eok := expected.([]byte); eok {
if act, aok := actual.([]byte); aok {
return bytes.Equal(exp, act)
}
}
if exp, eok := expected.(string); eok {
if act, aok := actual.(string); aok {
return exp == act
}
}
ropts := expandCompareOptions(options...)
expectedStr := repr.String(expected, ropts...)
actualStr := repr.String(actual, ropts...)
return expectedStr == actualStr
}