-
Notifications
You must be signed in to change notification settings - Fork 14
/
errors_test.go
618 lines (556 loc) · 17 KB
/
errors_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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
package terrors
import (
"errors"
"fmt"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/monzo/terrors/stack"
)
type newError func(code, message string, params map[string]string) *Error
func TestLogParams(t *testing.T) {
err := New("service.foo", "Some message", map[string]string{"public": "value"})
assert.Equal(t, "value", err.LogMetadata()["public"])
}
func TestErrorConstructors(t *testing.T) {
testCases := []struct {
constructor newError
code string
message string
params map[string]string
expectedCode string
}{
{
BadRequest, "service.foo", "bad_request.service.foo", nil, ErrBadRequest,
},
{
BadResponse, "service.foo", "bad_response.service.foo", nil, ErrBadResponse,
},
{
Timeout, "service.foo", "timeout.service.foo", nil, ErrTimeout,
},
{
NotFound, "service.foo", "not_found.service.foo", nil, ErrNotFound,
},
{
Forbidden, "service.foo", "forbidden.service.foo", nil, ErrForbidden,
},
{
Unauthorized, "service.foo", "unauthorized.service.foo", nil, ErrUnauthorized,
},
{
Unauthorized, "service.foo", "test params", map[string]string{
"some key": "some value",
"another key": "another value",
}, ErrUnauthorized,
},
{
PreconditionFailed, "service.foo", "precondition_failed.service.foo", nil, ErrPreconditionFailed,
},
{
RateLimited, "service.foo", "rate_limited.service.foo", nil, ErrRateLimited,
},
}
for _, tc := range testCases {
err := tc.constructor(tc.code, tc.message, tc.params)
assert.Equal(t, fmt.Sprintf("%s.%s", tc.expectedCode, tc.code), err.Code)
assert.Equal(t, fmt.Sprintf("%s: %s", err.Code, tc.message), err.Error())
if len(tc.params) > 0 {
assert.Equal(t, tc.params, err.Params)
}
}
}
func TestNew(t *testing.T) {
err := New("service.foo", "Some message", map[string]string{
"public": "value",
})
assert.Equal(t, "service.foo", err.Code)
assert.Equal(t, "Some message", err.Message)
assert.Equal(t, map[string]string{
"public": "value",
}, err.Params)
}
func TestWrapWithWrappedErr(t *testing.T) {
err := &Error{
Code: ErrForbidden,
Message: "Some message",
StackFrames: stack.BuildStack(0),
Params: map[string]string{
"something old": "caesar",
},
}
wrappedErr := Wrap(err, map[string]string{
"something new": "a computer",
}).(*Error)
assert.Equal(t, err.Code, wrappedErr.Code)
assert.Equal(t, err.StackFrames, wrappedErr.StackFrames)
assert.Equal(t, err.Message, wrappedErr.Message)
assert.Equal(t, wrappedErr.Params, map[string]string{
"something old": "caesar",
"something new": "a computer",
})
}
func TestWrap(t *testing.T) {
err := fmt.Errorf("Look here, an error")
wrappedErr := Wrap(err, map[string]string{
"blub": "dub",
}).(*Error)
assert.Equal(t, "internal_service: Look here, an error", wrappedErr.Error())
assert.Equal(t, "Look here, an error", wrappedErr.Message)
assert.Equal(t, ErrInternalService, wrappedErr.Code)
assert.Equal(t, wrappedErr.Params, map[string]string{
"blub": "dub",
})
}
func getNilErr() error {
return Wrap(nil, nil)
}
func TestNilError(t *testing.T) {
assert.Equal(t, getNilErr(), nil)
assert.Nil(t, getNilErr())
assert.Nil(t, Wrap(nil, nil))
}
func TestMatchesMethod(t *testing.T) {
err := &Error{
Code: "bad_request.missing_param.foo",
Message: "You need to pass a value for foo; try passing foo=bar",
}
assert.True(t, err.Matches(ErrBadRequest))
assert.True(t, err.Matches(ErrBadRequest+".missing_param"))
assert.False(t, err.Matches(ErrInternalService))
assert.False(t, err.Matches(ErrBadRequest+".missing_param.foo1"))
assert.True(t, err.Matches("You need to pass a value for foo"))
}
func TestMatches(t *testing.T) {
err := &Error{
Code: "bad_request.missing_param.foo",
Message: "You need to pass a value for foo; try passing foo=bar",
}
assert.True(t, Matches(err, ErrBadRequest))
assert.True(t, Matches(err, ErrBadRequest+".missing_param"))
assert.False(t, Matches(err, ErrInternalService))
assert.False(t, Matches(err, ErrBadRequest+".missing_param.foo1"))
assert.True(t, Matches(err, "You need to pass a value for foo"))
assert.False(t, Matches(nil, ErrBadRequest))
}
func TestPrefixMatchesMethod(t *testing.T) {
err := &Error{
Code: "bad_request.missing_param.foo",
Message: "You need to pass a value for foo; try passing foo=bar",
}
assert.True(t, err.PrefixMatches(ErrBadRequest))
assert.True(t, err.PrefixMatches(ErrBadRequest+".missing_param"))
assert.True(t, err.PrefixMatches(ErrBadRequest, "missing_param"))
assert.False(t, err.PrefixMatches(ErrInternalService))
assert.False(t, err.PrefixMatches(ErrBadRequest+".missing_param.foo1"))
assert.False(t, err.PrefixMatches(ErrBadRequest, "missing_param", "foo1"))
assert.False(t, err.PrefixMatches("You need to pass a value for foo"))
assert.False(t, err.PrefixMatches("missing_param"))
}
func TestPrefixMatches(t *testing.T) {
err := &Error{
Code: "bad_request.missing_param.foo",
Message: "You need to pass a value for foo; try passing foo=bar",
}
assert.True(t, PrefixMatches(err, ErrBadRequest))
assert.True(t, PrefixMatches(err, ErrBadRequest+".missing_param"))
assert.True(t, PrefixMatches(err, ErrBadRequest, "missing_param"))
assert.False(t, PrefixMatches(err, ErrInternalService))
assert.False(t, PrefixMatches(err, ErrBadRequest+".missing_param.foo1"))
assert.False(t, PrefixMatches(err, ErrBadRequest, "missing_param", "foo1"))
assert.False(t, PrefixMatches(err, "You need to pass a value for foo"))
assert.False(t, PrefixMatches(err, "missing_param"))
assert.False(t, PrefixMatches(nil, ErrBadRequest))
}
func TestIsRetryable(t *testing.T) {
assert.False(t, IsRetryable(BadRequest("", "", nil)))
assert.False(t, IsRetryable(BadResponse("", "", nil)))
assert.False(t, IsRetryable(NotFound("", "", nil)))
assert.False(t, IsRetryable(PreconditionFailed("", "", nil)))
assert.False(t, IsRetryable(NonRetryableInternalService("", "", nil)))
assert.True(t, IsRetryable(InternalService("", "", nil)))
assert.True(t, IsRetryable(RateLimited("", "", nil)))
assert.True(t, IsRetryable(errors.New("")))
assert.True(t, IsRetryable(Augment(errors.New(""), "", nil)))
assert.True(t, IsRetryable(Wrap(errors.New(""), nil)))
assert.False(t, IsRetryable(WrapWithCode(errors.New(""), nil, ErrBadRequest)))
// Check that IsRetryable honors errors that implement terrors.retryableError
// (after already being converted to a terror)
assert.False(t, IsRetryable(Augment(&testRetryableError{false}, "", nil)))
assert.False(t, IsRetryable(Propagate(&testRetryableError{false})))
assert.True(t, IsRetryable(Augment(&testRetryableError{true}, "", nil)))
assert.True(t, IsRetryable(Propagate(&testRetryableError{true})))
// Check that IsRetryable honors errors that implement terrors.retryableError
// (without having been converted to a terror yet)
assert.False(t, IsRetryable(&testRetryableError{false}))
assert.False(t, IsRetryable(&testRetryableError{false}))
assert.True(t, IsRetryable(&testRetryableError{true}))
assert.True(t, IsRetryable(&testRetryableError{true}))
}
type testRetryableError struct {
retryable bool
}
func (e *testRetryableError) Retryable() bool {
return e.retryable
}
func (*testRetryableError) Error() string {
return ""
}
func ExampleWrapWithCode() {
fn := "not/a/file"
_, err := os.Open(fn)
if err != nil {
errParams := map[string]string{
"filename": fn,
}
err = WrapWithCode(err, errParams, ErrNotFound)
terr := err.(*Error)
fmt.Println(terr.Error())
// Output: not_found: open not/a/file: no such file or directory
}
}
func ExampleMatches() {
err := NotFound("handler_missing", "Handler not found", nil)
fmt.Println(Matches(err, "not_found.handler_missing"))
// Output: true
}
func TestAugmentError(t *testing.T) {
newErr := Augment(assert.AnError, "added context", map[string]string{
"meta": "data",
})
terr := newErr.(*Error)
assert.Equal(t, "internal_service", terr.Code)
assert.Equal(t, "added context", terr.Message)
assert.Equal(t, "internal_service: added context: assert.AnError general error for testing", terr.Error())
assert.Equal(t, "data", terr.Params["meta"])
assert.Equal(t, assert.AnError, terr.cause)
}
func TestAugmentTerror(t *testing.T) {
base := NotFound("foo", "failed to find foo", map[string]string{
"base": "meta",
})
newErr := Augment(base, "added context", map[string]string{
"new": "meta",
})
terr := newErr.(*Error)
assert.Equal(t, "not_found.foo", terr.Code)
assert.Equal(t, "added context", terr.Message)
assert.Empty(t, terr.StackFrames)
assert.Equal(t, "not_found.foo: added context: failed to find foo", terr.Error())
assert.Equal(t, base, terr.cause)
}
func TestAugmentTerrorWithWrap(t *testing.T) {
base := NotFound("foo", "failed to find foo", map[string]string{"base": "meta"})
augmentedErr := Augment(base, "added context", map[string]string{"new": "meta"})
assert.Equal(t, "not_found.foo: added context: failed to find foo", augmentedErr.Error())
wrappedErr := Wrap(augmentedErr, map[string]string{"wrap": "meta"})
assert.Equal(t, "not_found.foo: added context: failed to find foo", wrappedErr.Error())
}
func TestAugmentNil(t *testing.T) {
assert.Nil(t, Augment(nil, "added context", map[string]string{
"new": "meta",
}))
}
func TestIsError(t *testing.T) {
cases := []struct {
desc string
errCreator func() error
code []string
expectedMatch bool
}{
{
desc: "non-terror",
errCreator: func() error {
return assert.AnError
},
code: []string{ErrInternalService},
expectedMatch: false,
},
{
desc: "simple wrapped go error",
errCreator: func() error {
return Augment(assert.AnError, "added context", map[string]string{
"meta": "data",
})
},
code: []string{ErrInternalService},
expectedMatch: true,
},
{
desc: "non-wrapped terror",
errCreator: func() error {
return NotFound("foo", "bar", nil)
},
code: []string{ErrNotFound},
expectedMatch: true,
},
{
desc: "single-wrapped terror Augmentd",
errCreator: func() error {
base := NotFound("foo", "bar", nil)
return Augment(base, "added context", nil)
},
code: []string{ErrNotFound},
expectedMatch: true,
},
{
desc: "multi-wrapped terror Augmentd",
errCreator: func() error {
base := NotFound("foo", "bar", nil)
next := Augment(base, "added context", nil)
return Augment(next, "more context", nil)
},
code: []string{ErrNotFound},
expectedMatch: true,
},
{
desc: "multiple code parts match",
errCreator: func() error {
base := NotFound("foo", "bar", nil)
return Augment(base, "added context", nil)
},
code: []string{ErrNotFound, "foo"},
expectedMatch: true,
},
{
desc: "multiple code parts mismatch",
errCreator: func() error {
base := NotFound("foo", "bar", nil)
return Augment(base, "added context", nil)
},
code: []string{ErrNotFound, "notfoo"},
expectedMatch: false,
},
{
desc: "created NewInternalWithCause",
errCreator: func() error {
base := NotFound("foo", "bar", nil)
return NewInternalWithCause(base, "added context", nil, "")
},
code: []string{ErrNotFound},
expectedMatch: true,
},
{
desc: "created NewInternalWithCause wrong code",
errCreator: func() error {
base := NotFound("foo", "bar", nil)
return NewInternalWithCause(base, "added context", nil, "")
},
code: []string{ErrForbidden},
expectedMatch: false,
},
{
desc: "created NewInternalWithCause with subcode",
errCreator: func() error {
base := NotFound("foo", "bar", nil)
return NewInternalWithCause(base, "added context", nil, "downstream")
},
code: []string{ErrInternalService, "downstream"},
expectedMatch: true,
},
{
desc: "created NewInternalWithCause with subcode mismatch",
errCreator: func() error {
base := NotFound("foo", "bar", nil)
return NewInternalWithCause(base, "added context", nil, "downstream")
},
code: []string{ErrInternalService, "mismatch"},
expectedMatch: false,
},
}
for _, tc := range cases {
t.Run(tc.desc, func(t *testing.T) {
assert.Equal(t, tc.expectedMatch, Is(tc.errCreator(), tc.code...))
})
}
}
func TestNewInternalWithCauseStack(t *testing.T) {
err := NewInternalWithCause(assert.AnError, "test", nil, "")
// Ensure that the first callsite is this method rather than the terrors internals
assert.Contains(t, err.StackFrames[0].Method, "TestNewInternalWithCauseStack")
}
func TestNewInternalWithCauseMessageChain(t *testing.T) {
// Check non-terrors Errors are included at the base of the MessageChain
innerTerror := NewInternalWithCause(errors.New("wrapped error"), "inner terror", nil, "")
// Check that the message is included when the cause is a terrors Error too
outerTerror := NewInternalWithCause(innerTerror, "outer terror", nil, "")
assert.Equal(t, []string{"inner terror", "wrapped error"}, outerTerror.MessageChain)
}
func TestPropagate(t *testing.T) {
t.Run("terror", func(t *testing.T) {
terr := &Error{Code: "foo"}
out := Propagate(terr)
assert.Equal(t, terr, out)
})
t.Run("non-terror", func(t *testing.T) {
out := Propagate(assert.AnError)
assert.IsType(t, &Error{}, out)
terr := out.(*Error)
assert.Equal(t, ErrInternalService, terr.Code)
assert.Equal(t, assert.AnError, terr.cause)
assert.Equal(t, assert.AnError.Error(), terr.Message)
assert.Greater(t, len(terr.StackFrames), 0)
})
t.Run("nil", func(t *testing.T) {
assert.Nil(t, Propagate(nil))
})
}
func TestStackTrace(t *testing.T) {
t.Run("nil stack", func(t *testing.T) {
terr := &Error{}
res := terr.StackTrace()
assert.Len(t, res, 0)
})
t.Run("non-nil stack", func(t *testing.T) {
terr := InternalService("foo", "bar", nil)
res := terr.StackTrace()
// Don't assert on content because it changes
assert.NotEmpty(t, res)
})
}
func TestErrorMessage(t *testing.T) {
cases := []struct {
desc string
terr Error
expected string
}{
{
desc: "plain terror",
terr: Error{Code: "code", Message: "message"},
expected: "message",
},
{
desc: "terror with cause",
terr: Error{Code: "code", Message: "message", cause: &Error{
Code: "code_inner", Message: "message_inner",
}},
expected: "message: message_inner",
},
}
for _, tc := range cases {
t.Run(tc.desc, func(t *testing.T) {
msg := tc.terr.ErrorMessage()
assert.Equal(t, tc.expected, msg)
})
}
}
func TestRetryable(t *testing.T) {
cases := []struct {
desc string
terr Error
expected bool
}{
{
desc: "by value, positive",
terr: Error{
IsRetryable: &retryable,
},
expected: true,
},
{
desc: "by value, negative",
terr: Error{
IsRetryable: ¬Retryable,
},
expected: false,
},
{
desc: "by code, positive",
terr: Error{
Code: ErrInternalService,
IsRetryable: nil,
},
expected: true,
},
{
desc: "by code, negative",
terr: Error{
Code: ErrNotFound,
IsRetryable: nil,
},
expected: false,
},
}
for _, tc := range cases {
t.Run("By code - positive", func(t *testing.T) {
assert.Equal(t, tc.expected, tc.terr.Retryable())
})
}
}
func TestUnexpected(t *testing.T) {
cases := []struct {
name string
terr Error
expect bool
}{
{
name: "default",
terr: Error{},
expect: false,
},
{
name: "unexpected",
terr: Error{
IsUnexpected: &unexpected,
},
expect: true,
},
{
name: "not unexpected",
terr: Error{
IsUnexpected: ¬Unexpected,
},
expect: false,
},
}
for _, tc := range cases {
t.Run(t.Name(), func(t *testing.T) {
assert.Equal(t, tc.expect, tc.terr.Unexpected())
})
}
}
func TestSetIsRetryable(t *testing.T) {
err := New("code", "message", nil)
assert.False(t, *err.IsRetryable)
err.SetIsRetryable(true)
assert.True(t, *err.IsRetryable)
err.SetIsRetryable(false)
assert.False(t, *err.IsRetryable)
}
func TestSetIsUnexpected(t *testing.T) {
err := New("code", "message", nil)
assert.Nil(t, err.IsUnexpected)
err.SetIsUnexpected(true)
assert.True(t, *err.IsUnexpected)
err.SetIsUnexpected(false)
assert.False(t, *err.IsUnexpected)
}
func failyFunction() error {
return InternalService("halp", "I'm in trouble", nil)
}
func TestStackStringChasesCausalChain(t *testing.T) {
err := Augment(failyFunction(), "something may be up", nil)
terr := err.(*Error)
ss := terr.StackString()
t.Log(ss)
assert.Contains(t, ss, "failyFunction")
}
func TestCircularErrorProducesFiniteOutputWithStackFrames(t *testing.T) {
orig := failyFunction()
err := Augment(orig, "something may be up", nil)
terr := err.(*Error)
terr.cause = terr
terr.StackFrames = orig.(*Error).StackFrames
ss := terr.StackString()
// The default field size limit used in elastic-slog. It's kind of arbitrary, but it'll do for now.
assert.Less(t, len(ss), 32000)
assert.GreaterOrEqual(t, len(ss), 32000-1000)
}
func TestCircularErrorProducesFiniteOutputWithoutStackFrames(t *testing.T) {
err := Augment(failyFunction(), "something may be up", nil)
terr := err.(*Error)
terr.cause = terr
ss := terr.StackString()
// There's no actual stack in the causal cycle, so we don't render anything here.
assert.Empty(t, ss)
}