-
Notifications
You must be signed in to change notification settings - Fork 206
/
error_test.go
571 lines (535 loc) · 15.6 KB
/
error_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
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package dig
import (
"errors"
"fmt"
"io"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"go.uber.org/dig/internal/digreflect"
)
// assertErrorMatches matches error messages against the provided list of
// strings.
//
// The error must match each string in-order. That is, the following is valid,
//
// assertErrorMatches(t, errors.New("foo bar baz"), "foo", "baz")
//
// But not,
//
// assertErrorMatches(t, errors.New("foo bar baz"), "foo", "baz", "bar")
//
// Because "bar" is not after "baz" in the error message.
//
// Messages will be treated as regular expressions.
func AssertErrorMatches(t *testing.T, err error, msg string, msgs ...string) {
t.Helper()
// We have one positional argument in addition to the variadic argument to
// ensure that there's at least one string to match against.
if err == nil {
t.Errorf("expected error but got nil")
return
}
var finders []consumingFinder
for _, m := range append([]string{msg}, msgs...) {
if r, err := regexp.Compile(m); err == nil {
finders = append(finders, regexpFinder{r})
} else {
finders = append(finders, stringFinder(m))
}
}
t.Run("single line", func(t *testing.T) {
original := err.Error()
assert.NoError(t, runFinders(original, finders))
})
// Intersperse "\n" finders between each message for the "%+v" check.
plusFinders := make([]consumingFinder, 0, len(finders)*2-1)
for i, f := range finders {
if i > 0 {
plusFinders = append(plusFinders, stringFinder("\n"))
}
plusFinders = append(plusFinders, f)
}
t.Run("multi line", func(t *testing.T) {
original := fmt.Sprintf("%+v", err)
assert.NoError(t, runFinders(original, plusFinders))
})
}
// consumingFinder matches a string and returns the rest of the string *after*
// the match.
type consumingFinder interface {
// Attempt to match against the given string and return false if a match
// could not be found.
//
// If a match was found, return the remaining string after the entire
// match. So if the finder matches "oo" in "foobar", the returned string
// must be just "bar".
Find(got string) (rest string, ok bool)
}
func runFinders(original string, finders []consumingFinder) error {
remaining := original
for _, f := range finders {
if newRemaining, ok := f.Find(remaining); ok {
remaining = newRemaining
continue
}
// Match not found. Check if the order was wrong.
if _, ok := f.Find(original); ok {
// We won't use %q for the error message itself
// because we want it to be printed to the console as
// it would actually show.
return fmt.Errorf(`"%v" contains %v in the wrong place`, original, f)
}
return fmt.Errorf(`"%v" does not contain %v`, original, f)
}
return nil
}
type regexpFinder struct{ r *regexp.Regexp }
func (r regexpFinder) String() string {
return "`" + r.r.String() + "`"
}
func (r regexpFinder) Find(got string) (rest string, ok bool) {
loc := r.r.FindStringIndex(got)
if len(loc) == 0 {
return got, false
}
return got[loc[1]:], true
}
type stringFinder string
func (s stringFinder) String() string { return strconv.Quote(string(s)) }
func (s stringFinder) Find(got string) (rest string, ok bool) {
i := strings.Index(got, string(s))
if i < 0 {
return got, false
}
return got[i+len(s):], true
}
func TestRootCause(t *testing.T) {
tests := []struct {
desc string
give error
wantAsDigError bool
wantRootCause error
wantRootCauseAsDigError bool
}{
{
desc: "random unformatted error",
give: errors.New("This non-Dig error is not formatted"),
wantAsDigError: false,
wantRootCause: errors.New("This non-Dig error is not formatted"),
wantRootCauseAsDigError: false,
},
{
desc: "random formatted error",
give: fmt.Errorf("This non-Dig error is %v", "formatted"),
wantAsDigError: false,
wantRootCause: fmt.Errorf("This non-Dig error is %v", "formatted"),
wantRootCauseAsDigError: false,
},
{
desc: "simple errInvalidInput",
give: errInvalidInput{Message: "baz", Cause: nil},
wantAsDigError: true,
wantRootCause: errInvalidInput{Message: "baz", Cause: nil},
wantRootCauseAsDigError: true,
},
{
desc: "errInvalidInput wrapping errInvalidInput",
give: errInvalidInput{Message: "foo", Cause: errInvalidInput{Message: "bar", Cause: nil}},
wantAsDigError: true,
wantRootCause: errInvalidInput{Message: "bar", Cause: nil},
wantRootCauseAsDigError: true,
},
{
desc: "errInvalidInput wrapping non-dig.Error",
give: errInvalidInput{Message: "foo", Cause: errors.New("bar")},
wantAsDigError: true,
wantRootCause: errors.New("bar"),
wantRootCauseAsDigError: false,
},
{
desc: "nil",
give: nil,
wantAsDigError: false,
wantRootCause: nil,
wantRootCauseAsDigError: false,
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
var de Error
assert.Equal(t, tt.wantAsDigError, errors.As(tt.give, &de))
gotRootCause := RootCause(tt.give)
assert.Equal(t, gotRootCause, tt.wantRootCause)
assert.Equal(t, tt.wantRootCause, gotRootCause, "incorrect root cause")
assert.Equal(t, tt.wantRootCauseAsDigError, errors.As(gotRootCause, &de))
})
}
}
type MyNonDigError struct {
msg string
}
func (e MyNonDigError) Error() string {
return e.msg
}
func TestRootCauseEndToEnd(t *testing.T) {
tests := []struct {
desc string
setup func(c *Container)
invoke interface{}
wantAsDigError bool
wantRootCauseMessage string
wantRootCauseAsDigError bool
}{
{
desc: "error thrown in constructor",
setup: func(c *Container) {
assert.NoError(t, c.Provide(func() (string, error) {
return "hello", MyNonDigError{msg: "great sadness"}
}))
},
invoke: func(s string) {
fmt.Println(s)
},
wantAsDigError: true,
wantRootCauseMessage: "great sadness",
wantRootCauseAsDigError: false,
},
{
desc: "parameter not available in container",
setup: func(c *Container) {
assert.NoError(t, c.Provide(func() int { return 5 }))
},
invoke: func(s string) {
fmt.Println(s)
},
wantAsDigError: true,
wantRootCauseMessage: "missing type: string",
wantRootCauseAsDigError: true,
},
{
desc: "error in invoke",
setup: func(c *Container) {
assert.NoError(t, c.Provide(func() (string, error) {
return "hello", nil
}))
},
invoke: func(s string) error {
return errors.New("terrible unhappiness")
},
wantAsDigError: false,
wantRootCauseMessage: "terrible unhappiness",
wantRootCauseAsDigError: false,
},
}
for _, tt := range tests {
c := New()
tt.setup(c)
var de Error
err := c.Invoke(tt.invoke)
assert.Equal(t, tt.wantAsDigError, errors.As(err, &de),
fmt.Sprintf("expected errors.As() to return %v", tt.wantAsDigError))
rcErr := RootCause(err)
assert.Equal(t, tt.wantRootCauseMessage, rcErr.Error())
assert.Equal(t, tt.wantRootCauseAsDigError, errors.As(rcErr, &de),
fmt.Sprintf("expected errors.As() on the root cause to return %v", tt.wantRootCauseAsDigError))
}
}
func joinLines(ls ...string) string { return strings.Join(ls, "\n") }
// Simple error fake that provides control of %v and %+v representations.
type errFormatted struct {
v string // output for %v
plusV string // output for %+v
}
var (
_ error = errFormatted{}
_ fmt.Formatter = errFormatted{}
)
func (e errFormatted) Error() string { return e.v }
func (e errFormatted) Format(w fmt.State, c rune) {
if w.Flag('+') && c == 'v' {
io.WriteString(w, e.plusV)
} else {
io.WriteString(w, e.v)
}
}
func TestMissingTypeFormatting(t *testing.T) {
type type1 struct{}
type someInterface interface{ stuff() }
tests := []struct {
desc string
give missingType
wantV string
wantPlusV string
}{
{
desc: "no suggestions",
give: missingType{
Key: key{t: reflect.TypeOf(type1{})},
},
wantV: "dig.type1",
wantPlusV: "dig.type1 (did you mean to Provide it?)",
},
{
desc: "one suggestion",
give: missingType{
Key: key{t: reflect.TypeOf(type1{})},
suggestions: []key{
{t: reflect.TypeOf(&type1{})},
},
},
wantV: "dig.type1 (did you mean *dig.type1?)",
wantPlusV: "dig.type1 (did you mean to use *dig.type1?)",
},
{
desc: "many suggestions",
give: missingType{
Key: key{t: reflect.TypeOf(type1{})},
suggestions: []key{
{t: reflect.TypeOf(&type1{})},
{t: reflect.TypeOf(new(someInterface)).Elem()},
},
},
wantV: "dig.type1 (did you mean *dig.type1, or dig.someInterface?)",
wantPlusV: "dig.type1 (did you mean to use one of *dig.type1, or dig.someInterface?)",
},
{
desc: "one suggestion for a slice of elements",
give: missingType{
Key: key{t: reflect.TypeOf([]type1{})},
suggestions: []key{
{t: reflect.TypeOf([]*type1{})},
},
},
wantV: "[]dig.type1 (did you mean []*dig.type1?)",
wantPlusV: "[]dig.type1 (did you mean to use []*dig.type1?)",
},
{
desc: "one suggestion for an array of elements",
give: missingType{
Key: key{t: reflect.TypeOf([4]type1{})},
suggestions: []key{
{t: reflect.TypeOf([4]*type1{})},
},
},
wantV: "[4]dig.type1 (did you mean [4]*dig.type1?)",
wantPlusV: "[4]dig.type1 (did you mean to use [4]*dig.type1?)",
},
{
desc: "one suggestion for a slice of pointers",
give: missingType{
Key: key{t: reflect.TypeOf([]*type1{})},
suggestions: []key{
{t: reflect.TypeOf([]type1{})},
},
},
wantV: "[]*dig.type1 (did you mean []dig.type1?)",
wantPlusV: "[]*dig.type1 (did you mean to use []dig.type1?)",
},
{
desc: "one suggestion for an array of pointers",
give: missingType{
Key: key{t: reflect.TypeOf([4]*type1{})},
suggestions: []key{
{t: reflect.TypeOf([4]type1{})},
},
},
wantV: "[4]*dig.type1 (did you mean [4]dig.type1?)",
wantPlusV: "[4]*dig.type1 (did you mean to use [4]dig.type1?)",
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
assert.Equal(t, tt.wantV, fmt.Sprint(tt.give), "%v did not match")
assert.Equal(t, tt.wantPlusV, fmt.Sprintf("%+v", tt.give), "%+v did not match")
})
}
}
func TestErrorFormatting(t *testing.T) {
type someType struct{}
type anotherType struct{}
simpleErr := errors.New("great sadness")
richError := errFormatted{
v: "great sadness",
plusV: joinLines(
"sadness so great",
"it needs multiple",
"lines",
),
}
someFunc := &digreflect.Func{
Package: "foo",
Name: "Bar",
File: "foo/bar.go",
Line: 42,
}
tests := []struct {
desc string
give error
wantString string
wantPlusV string
}{
{
desc: "wrapped error/simple",
give: errInvalidInput{
Message: "something went wrong",
Cause: simpleErr,
},
wantString: "something went wrong: great sadness",
wantPlusV: joinLines(
"something went wrong:",
"great sadness",
),
},
{
desc: "wrapped error/rich",
give: errInvalidInput{
Message: "something went wrong",
Cause: richError,
},
wantString: "something went wrong: great sadness",
wantPlusV: joinLines(
"something went wrong:",
"sadness so great",
"it needs multiple",
"lines",
),
},
{
desc: "errProvide",
give: errProvide{
Func: someFunc,
Reason: simpleErr,
},
wantString: `cannot provide function "foo".Bar (foo/bar.go:42): great sadness`,
wantPlusV: joinLines(
`cannot provide function "foo".Bar`,
" foo/bar.go:42:",
"great sadness",
),
},
{
desc: "errConstructorFailed",
give: errConstructorFailed{
Func: someFunc,
Reason: richError,
},
wantString: `received non-nil error from function "foo".Bar (foo/bar.go:42): great sadness`,
wantPlusV: joinLines(
`received non-nil error from function "foo".Bar`,
" foo/bar.go:42:",
"sadness so great",
"it needs multiple",
"lines",
),
},
{
desc: "errArgumentsFailed",
give: errArgumentsFailed{
Func: someFunc,
Reason: simpleErr,
},
wantString: `could not build arguments for function "foo".Bar (foo/bar.go:42): great sadness`,
wantPlusV: joinLines(
`could not build arguments for function "foo".Bar`,
" foo/bar.go:42:",
"great sadness",
),
},
{
desc: "errMissingDependencies",
give: errMissingDependencies{
Func: someFunc,
Reason: richError,
},
wantString: `missing dependencies for function "foo".Bar (foo/bar.go:42): great sadness`,
wantPlusV: joinLines(
`missing dependencies for function "foo".Bar`,
" foo/bar.go:42:",
"sadness so great",
"it needs multiple",
"lines",
),
},
{
desc: "errParamSingleFailed",
give: errParamSingleFailed{
Key: key{t: reflect.TypeOf(someType{})},
Reason: richError,
},
wantString: `failed to build dig.someType: great sadness`,
wantPlusV: joinLines(
`failed to build dig.someType:`,
"sadness so great",
"it needs multiple",
"lines",
),
},
{
desc: "errParamGroupFailed",
give: errParamGroupFailed{
Key: key{t: reflect.TypeOf(someType{}), group: "items"},
Reason: richError,
},
wantString: `could not build value group dig.someType[group="items"]: great sadness`,
wantPlusV: joinLines(
`could not build value group dig.someType[group="items"]:`,
"sadness so great",
"it needs multiple",
"lines",
),
},
{
desc: "errMissingTypes/single",
give: errMissingTypes{
{Key: key{t: reflect.TypeOf(someType{})}},
},
wantString: "missing type: dig.someType",
wantPlusV: joinLines(
"missing type:",
" - dig.someType (did you mean to Provide it?)",
),
},
{
desc: "errMissingTypes/multiple",
give: errMissingTypes{
{Key: key{t: reflect.TypeOf(someType{})}},
{Key: key{t: reflect.TypeOf(&anotherType{})}},
},
wantString: "missing types: dig.someType; *dig.anotherType",
wantPlusV: joinLines(
"missing types:",
" - dig.someType (did you mean to Provide it?)",
" - *dig.anotherType (did you mean to Provide it?)",
),
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
assert.Equal(t, tt.wantString, tt.give.Error(), "%v did not match")
assert.Equal(t, tt.wantPlusV, fmt.Sprintf("%+v", tt.give), "%+v did not match")
})
}
}