-
Notifications
You must be signed in to change notification settings - Fork 18
/
trace_test.go
619 lines (528 loc) · 16.2 KB
/
trace_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
619
/*
Copyright 2015-2019 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package trace
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestEmpty(t *testing.T) {
assert.Equal(t, "", DebugReport(nil))
assert.Equal(t, "", UserMessage(nil))
assert.Equal(t, "", UserMessageWithFields(nil))
assert.Equal(t, map[string]interface{}{}, GetFields(nil))
}
func TestWrap(t *testing.T) {
testErr := &testError{Param: "param"}
err := Wrap(Wrap(testErr))
assert.Regexp(t, ".*trace_test.go.*", line(DebugReport(err)))
assert.NotRegexp(t, ".*trace.go.*", line(DebugReport(err)))
assert.NotRegexp(t, ".*trace_test.go.*", line(UserMessage(err)))
assert.Regexp(t, ".*param.*", line(UserMessage(err)))
}
func TestOrigError(t *testing.T) {
testErr := fmt.Errorf("some error")
err := Wrap(Wrap(testErr))
assert.Equal(t, testErr, err.OrigError())
}
func TestIsEOF(t *testing.T) {
assert.True(t, IsEOF(io.EOF))
assert.True(t, IsEOF(Wrap(io.EOF)))
}
func TestWrapUserMessage(t *testing.T) {
testErr := fmt.Errorf("description")
err := Wrap(testErr, "user message")
assert.Regexp(t, ".*trace_test.go.*", line(DebugReport(err)))
assert.NotRegexp(t, ".*trace.go.*", line(DebugReport(err)))
assert.Equal(t, "user message\tdescription", line(UserMessage(err)))
err = Wrap(err, "user message 2")
assert.Equal(t, "user message 2\tuser message\t\tdescription", line(UserMessage(err)))
}
func TestWrapWithMessage(t *testing.T) {
testErr := fmt.Errorf("description")
err := WrapWithMessage(testErr, "user message")
assert.Equal(t, "user message\tdescription", line(UserMessage(err)))
assert.Regexp(t, ".*trace_test.go.*", line(DebugReport(err)))
assert.NotRegexp(t, ".*trace.go.*", line(DebugReport(err)))
}
func TestUserMessageWithFields(t *testing.T) {
testErr := fmt.Errorf("description")
assert.Equal(t, testErr.Error(), UserMessageWithFields(testErr))
err := Wrap(testErr, "user message")
assert.Equal(t, "user message\tdescription", line(UserMessageWithFields(err)))
err = WithField(err, "test_key", "test_value")
assert.Equal(t, "test_key=\"test_value\" user message\tdescription", line(UserMessageWithFields(err)))
}
func TestGetFields(t *testing.T) {
testErr := fmt.Errorf("description")
assert.Equal(t, map[string]interface{}{}, GetFields(testErr))
fields := map[string]interface{}{
"test_key": "test_value",
}
err := WithFields(Wrap(testErr), fields)
assert.Equal(t, fields, GetFields(err))
// ensure that you can get fields from a proxyError
e := roundtripError(err)
assert.Equal(t, fields, GetFields(e))
}
func roundtripError(err error) error {
w := newTestWriter()
WriteError(w, err)
outErr := ReadError(w.StatusCode, w.Body)
return outErr
}
func TestWrapNil(t *testing.T) {
err1 := Wrap(nil, "message: %v", "extra")
assert.Nil(t, err1)
var err2 error
err2 = nil
err3 := Wrap(err2)
assert.Nil(t, err3)
err4 := Wrap(err3)
assert.Nil(t, err4)
}
func TestRaceErrorWrap(t *testing.T) {
baseErr := BadParameter("foo")
iters := 100_000
wg := sync.WaitGroup{}
wg.Add(3)
// trace.Wrap with format arguments
go func() {
for i := 0; i < iters; i++ {
_ = Wrap(baseErr, "foo bar %q", "baz")
}
wg.Done()
}()
// trace.WrapWithMessage
go func() {
for i := 0; i < iters; i++ {
_ = WrapWithMessage(baseErr, "foo bar %q", "baz")
}
wg.Done()
}()
// plain Error() call
go func() {
for i := 0; i < iters; i++ {
_ = baseErr.Error()
}
wg.Done()
}()
wg.Wait()
}
func TestWrapStdlibErrors(t *testing.T) {
assert.True(t, IsNotFound(os.ErrNotExist))
}
func TestGenericErrors(t *testing.T) {
testCases := []struct {
Err Error
Predicate func(error) bool
StatusCode int
comment string
}{
{
Err: NotFound("not found"),
Predicate: IsNotFound,
StatusCode: http.StatusNotFound,
comment: "not found error",
},
{
Err: AlreadyExists("already exists"),
Predicate: IsAlreadyExists,
StatusCode: http.StatusConflict,
comment: "already exists error",
},
{
Err: BadParameter("is bad"),
Predicate: IsBadParameter,
StatusCode: http.StatusBadRequest,
comment: "bad parameter error",
},
{
Err: CompareFailed("is bad"),
Predicate: IsCompareFailed,
StatusCode: http.StatusPreconditionFailed,
comment: "comparison failed error",
},
{
Err: AccessDenied("denied"),
Predicate: IsAccessDenied,
StatusCode: http.StatusForbidden,
comment: "access denied error",
},
{
Err: ConnectionProblem(nil, "prob"),
Predicate: IsConnectionProblem,
StatusCode: http.StatusRequestTimeout,
comment: "connection error",
},
{
Err: LimitExceeded("limit exceeded"),
Predicate: IsLimitExceeded,
StatusCode: http.StatusTooManyRequests,
comment: "limit exceeded error",
},
{
Err: NotImplemented("not implemented"),
Predicate: IsNotImplemented,
StatusCode: http.StatusNotImplemented,
comment: "not implemented error",
},
}
for _, testCase := range testCases {
SetDebug(true)
err := testCase.Err
var traceErr *TraceErr
var ok bool
if traceErr, ok = err.(*TraceErr); !ok {
t.Fatalf("Expected error to be of type *TraceErr: %#v", err)
}
assert.NotEmpty(t, traceErr.Traces, testCase.comment)
assert.Regexp(t, ".*.trace_test\\.go.*", line(DebugReport(err)), testCase.comment)
assert.NotRegexp(t, ".*.errors\\.go.*", line(DebugReport(err)), testCase.comment)
assert.NotRegexp(t, ".*.trace\\.go.*", line(DebugReport(err)), testCase.comment)
assert.True(t, testCase.Predicate(err), testCase.comment)
w := newTestWriter()
WriteError(w, err)
outErr := ReadError(w.StatusCode, w.Body)
if _, ok := outErr.(proxyError); !ok {
t.Fatalf("Expected error to be of type proxyError: %#v", outErr)
}
assert.True(t, testCase.Predicate(outErr), testCase.comment)
SetDebug(false)
w = newTestWriter()
WriteError(w, err)
outErr = ReadError(w.StatusCode, w.Body)
assert.True(t, testCase.Predicate(outErr), testCase.comment)
}
}
// Make sure we write some output produced by standard errors
func TestWriteExternalErrors(t *testing.T) {
err := Wrap(fmt.Errorf("snap!"))
SetDebug(true)
w := newTestWriter()
WriteError(w, err)
extErr := ReadError(w.StatusCode, w.Body)
assert.Equal(t, http.StatusInternalServerError, w.StatusCode)
assert.Regexp(t, ".*.snap.*", strings.Replace(string(w.Body), "\n", "", -1))
require.NotNil(t, extErr)
assert.EqualError(t, err, extErr.Error())
SetDebug(false)
w = newTestWriter()
WriteError(w, err)
extErr = ReadError(w.StatusCode, w.Body)
assert.Equal(t, http.StatusInternalServerError, w.StatusCode)
assert.Regexp(t, ".*.snap.*", strings.Replace(string(w.Body), "\n", "", -1))
require.NotNil(t, extErr)
assert.EqualError(t, err, extErr.Error())
}
type netError struct{}
func (e *netError) Error() string { return "net" }
func (e *netError) Timeout() bool { return true }
func (e *netError) Temporary() bool { return true }
func TestConvert(t *testing.T) {
err := ConvertSystemError(&netError{})
assert.True(t, IsConnectionProblem(err), "failed to detect network error")
dir := t.TempDir()
err = os.Mkdir(dir, 0o770)
err = ConvertSystemError(err)
assert.True(t, IsAlreadyExists(err), "expected AlreadyExists error, got %T", err)
}
func TestAggregates(t *testing.T) {
err1 := Errorf("failed one")
err2 := Errorf("failed two")
err := NewAggregate(err1, err2)
assert.True(t, IsAggregate(err))
agg := Unwrap(err).(Aggregate)
assert.Equal(t, []error{err1, err2}, agg.Errors())
assert.Equal(t, "failed one, failed two", err.Error())
}
func TestErrorf(t *testing.T) {
err := Errorf("error")
assert.Regexp(t, ".*.trace_test.go.*", line(DebugReport(err)))
assert.NotRegexp(t, ".*.Fields.*", line(DebugReport(err)))
assert.Equal(t, []string(nil), err.(*TraceErr).Messages)
}
func TestWithField(t *testing.T) {
err := WithField(Wrap(Errorf("error")), "testfield", true)
assert.Regexp(t, ".*.testfield.*", line(DebugReport(err)))
}
func TestWithFields(t *testing.T) {
err := WithFields(Wrap(Errorf("error")), map[string]interface{}{
"testfield1": true,
"testfield2": "value2",
})
assert.Regexp(t, ".*.Fields.*", line(DebugReport(err)))
assert.Regexp(t, ".*.testfield1: true.*", line(DebugReport(err)))
assert.Regexp(t, ".*.testfield2: value2.*", line(DebugReport(err)))
}
func TestAggregateConvertsToCommonErrors(t *testing.T) {
testCases := []struct {
Err error
Predicate func(error) bool
RoundtripPredicate func(error) bool
StatusCode int
comment string
}{
{
comment: "Aggregate unwraps to first aggregated error",
Err: NewAggregate(
BadParameter("invalid value of foo"),
LimitExceeded("limit exceeded"),
),
Predicate: IsAggregate,
RoundtripPredicate: IsBadParameter,
StatusCode: http.StatusBadRequest,
},
{
comment: "Nested aggregate unwraps recursively",
Err: NewAggregate(
NewAggregate(
BadParameter("invalid value of foo"),
LimitExceeded("limit exceeded"),
),
),
Predicate: IsAggregate,
RoundtripPredicate: IsBadParameter,
StatusCode: http.StatusBadRequest,
},
}
for _, testCase := range testCases {
SetDebug(true)
err := testCase.Err
assert.Regexp(t, ".*.trace_test.go.*", line(DebugReport(err)), testCase.comment)
assert.True(t, testCase.Predicate(err), testCase.comment)
w := newTestWriter()
WriteError(w, err)
outErr := ReadError(w.StatusCode, w.Body)
assert.True(t, testCase.RoundtripPredicate(outErr), testCase.comment)
SetDebug(false)
w = newTestWriter()
WriteError(w, err)
outErr = ReadError(w.StatusCode, w.Body)
assert.True(t, testCase.RoundtripPredicate(outErr), testCase.comment)
}
}
func TestAggregateThrowAwayNils(t *testing.T) {
err := NewAggregate(fmt.Errorf("error1"), nil, fmt.Errorf("error2"))
require.NotNil(t, err)
assert.NotRegexp(t, ".*nil.*", err.Error())
}
func TestAggregateAllNils(t *testing.T) {
assert.Nil(t, NewAggregate(nil, nil, nil))
}
func TestAggregateFromChannel(t *testing.T) {
errCh := make(chan error, 3)
errCh <- fmt.Errorf("Snap!")
errCh <- fmt.Errorf("BAM")
errCh <- fmt.Errorf("omg")
close(errCh)
err := NewAggregateFromChannel(errCh, context.Background())
require.NotNil(t, err)
assert.Regexp(t, ".*Snap!.*", err.Error())
assert.Regexp(t, ".*BAM.*", err.Error())
assert.Regexp(t, ".*omg.*", err.Error())
}
func TestAggregateFromChannelCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
errCh := make(chan error)
outCh := make(chan error)
go func() {
outCh <- NewAggregateFromChannel(errCh, ctx)
}()
errCh <- fmt.Errorf("Snap!")
errCh <- fmt.Errorf("BAM")
errCh <- fmt.Errorf("omg")
// we never closed the channel, so we just need to make sure
// the function exits when we cancel it
cancel()
err := <-outCh
assert.Error(t, err)
}
func TestCompositeErrorsCanProperlyUnwrap(t *testing.T) {
testCases := []struct {
err error
message string
wrappedMessage string
}{
{
err: ConnectionProblem(fmt.Errorf("internal error"), "failed to connect"),
message: "failed to connect",
wrappedMessage: "internal error",
},
{
err: Retry(fmt.Errorf("transient error"), "connection refused"),
message: "connection refused",
wrappedMessage: "transient error",
},
{
err: Trust(fmt.Errorf("access denied"), "failed to validate"),
message: "failed to validate",
wrappedMessage: "access denied",
},
}
var wrapper ErrorWrapper
for _, tt := range testCases {
assert.Equal(t, tt.message, tt.err.Error())
assert.Implements(t, &wrapper, Unwrap(tt.err))
assert.Equal(t, tt.wrappedMessage, Unwrap(tt.err).(ErrorWrapper).OrigError().Error())
}
}
type testError struct {
Param string
}
func (n *testError) Error() string {
return fmt.Sprintf("TestError(param=%v)", n.Param)
}
func (n *testError) OrigError() error {
return n
}
func newTestWriter() *testWriter {
return &testWriter{
H: make(http.Header),
}
}
type testWriter struct {
H http.Header
Body []byte
StatusCode int
}
func (tw *testWriter) Header() http.Header {
return tw.H
}
func (tw *testWriter) Write(body []byte) (int, error) {
tw.Body = body
return len(tw.Body), nil
}
func (tw *testWriter) WriteHeader(code int) {
tw.StatusCode = code
}
func line(s string) string {
return strings.ReplaceAll(s, "\n", "")
}
func TestStdlibCompat(t *testing.T) {
rootErr := BadParameter("root error")
var err error = rootErr
for i := 0; i < 10; i++ {
err = Wrap(err)
}
for i := 0; i < 10; i++ {
err = WrapWithMessage(err, "wrap message %d", i)
}
if !errors.Is(err, rootErr) {
t.Error("trace.Is(err, rootErr): got false, want true")
}
otherErr := CompareFailed("other error")
if errors.Is(err, otherErr) {
t.Error("trace.Is(err, otherErr): got true, want false")
}
var bpErr *BadParameterError
if !errors.As(err, &bpErr) {
t.Error("trace.As(err, BadParameterEror): got false, want true")
}
var cpErr *ConnectionProblemError
if errors.As(err, &cpErr) {
t.Error("trace.As(err, ConnectivityProblemError): got true, want false")
}
expectedErr := errors.New("wrapped error message")
err = &ConnectionProblemError{Err: expectedErr, Message: "error message"}
wrappedErr := errors.Unwrap(err)
if wrappedErr == nil {
t.Errorf("trace.Unwrap(err): got nil, want %v", expectedErr)
}
wrappedErrorMessage := wrappedErr.Error()
if wrappedErrorMessage != expectedErr.Error() {
t.Errorf("got %q, want %q", wrappedErrorMessage, expectedErr.Error())
}
}
// TestAggregate_StdLibCompat runs through a scenario which ensures that
// Aggregate behaves well with errors.Is/errors.As in cases with trace wrapped
// errors and stdlib errors
func TestAggregate_StdlibCompat(t *testing.T) {
randomErr := errors.New("random")
bpMsg := "bad param"
bpErr := BadParameter(bpMsg)
fooErr := errors.New("foo")
agg := Wrap(NewAggregate(Wrap(bpErr), fooErr))
assert.ErrorIs(t, agg, bpErr)
assert.ErrorIs(t, agg, fooErr)
assert.NotErrorIs(t, agg, randomErr)
var badParamErrTarget *BadParameterError
require.ErrorAs(t, agg, &badParamErrTarget)
assert.Equal(t, bpMsg, badParamErrTarget.Message, "BadParameter message mismatch")
var notFoundTarget *NotFoundError
require.False(t, errors.As(agg, ¬FoundTarget), "Aggregate does not contain a NotFoundError")
}
func TestIsAggregate(t *testing.T) {
err1 := errors.New("foo")
err2 := errors.New("bar")
errAggregate := Wrap(NewAggregate(err1, err2))
errGo := fmt.Errorf("go wrap: %w", errAggregate)
tests := []struct {
name string
err error
want bool
}{
{
name: "plain Go error is not aggregate",
err: err1,
},
{
name: "Aggregate returns true",
err: errAggregate,
want: true,
},
{
name: "Aggregate unwrapped returns true",
err: Unwrap(errAggregate),
want: true,
},
{
name: "Aggregate Go-wrapped returns true",
err: errGo,
want: true,
},
{
name: "unrelated wrapped error is not aggregate",
err: Wrap(err1),
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := IsAggregate(test.err); got != test.want {
t.Errorf("IsAggregate = %v, want %v", got, test.want)
}
})
}
}
func TestAggregate_IsError(t *testing.T) {
err1 := BadParameter("bad")
err2 := NotFound("not found")
err3 := errors.New("some other error")
errAggregate := NewAggregate(err1, err2, err3)
errUnrelated := errors.New("unrelated error")
assert.True(t, IsBadParameter(errAggregate), "IsBadParameter aggregate mismatch")
assert.True(t, IsNotFound(errAggregate), "IsNotFound aggregate mismatch")
assert.False(t, IsConnectionProblem(errAggregate), "IsConnectionProblem aggregate mismatch")
assert.ErrorIs(t, errAggregate, err1)
assert.ErrorIs(t, errAggregate, err2)
assert.ErrorIs(t, errAggregate, err3)
assert.NotErrorIs(t, errAggregate, errUnrelated)
}