forked from getsentry/sentry-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
734 lines (658 loc) · 17.7 KB
/
client_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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
package sentry
import (
"context"
"encoding/json"
"errors"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
pkgErrors "github.com/pkg/errors"
"github.com/stretchr/testify/require"
)
func TestNewClientAllowsEmptyDSN(t *testing.T) {
transport := &TransportMock{}
client, err := NewClient(ClientOptions{
Transport: transport,
})
if err != nil {
t.Fatalf("expected no error when creating client without a DNS but got %v", err)
}
client.CaptureException(errors.New("custom error"), nil, &ScopeMock{})
assertEqual(t, transport.lastEvent.Exception[0].Value, "custom error")
}
type customComplexError struct {
Message string
}
func (e customComplexError) Error() string {
return "customComplexError: " + e.Message
}
func (e customComplexError) AnswerToLife() string {
return "42"
}
func setupClientTest() (*Client, *ScopeMock, *TransportMock) {
scope := &ScopeMock{}
transport := &TransportMock{}
client, _ := NewClient(ClientOptions{
Dsn: "http://[email protected]/1337",
Transport: transport,
Integrations: func(i []Integration) []Integration {
return []Integration{}
},
})
return client, scope, transport
}
func TestCaptureMessageShouldSendEventWithProvidedMessage(t *testing.T) {
client, scope, transport := setupClientTest()
client.CaptureMessage("foo", nil, scope)
assertEqual(t, transport.lastEvent.Message, "foo")
}
func TestCaptureMessageShouldSucceedWithoutNilScope(t *testing.T) {
client, _, transport := setupClientTest()
client.CaptureMessage("foo", nil, nil)
assertEqual(t, transport.lastEvent.Message, "foo")
}
func TestCaptureMessageEmptyString(t *testing.T) {
client, scope, transport := setupClientTest()
client.CaptureMessage("", nil, scope)
want := &Event{
Exception: []Exception{
{
Type: "sentry.usageError",
Value: "CaptureMessage called with empty message",
Stacktrace: &Stacktrace{Frames: []Frame{}},
},
},
}
got := transport.lastEvent
opts := cmp.Options{
cmpopts.IgnoreFields(Event{}, "sdkMetaData", "attachments"),
cmp.Transformer("SimplifiedEvent", func(e *Event) *Event {
return &Event{
Exception: e.Exception,
}
}),
}
if diff := cmp.Diff(want, got, opts); diff != "" {
t.Errorf("(-want +got):\n%s", diff)
}
}
type customErr struct{}
func (e *customErr) Error() string {
return "wat"
}
type customErrWithCause struct{ cause error }
func (e *customErrWithCause) Error() string {
return "err"
}
func (e *customErrWithCause) Cause() error {
return e.cause
}
type wrappedError struct{ original error }
func (e wrappedError) Error() string {
return "wrapped: " + e.original.Error()
}
func (e wrappedError) Unwrap() error {
return e.original
}
type captureExceptionTestGroup struct {
name string
tests []captureExceptionTest
}
type captureExceptionTest struct {
name string
err error
want []Exception
}
func TestCaptureException(t *testing.T) {
basicTests := []captureExceptionTest{
{
name: "NilError",
err: nil,
want: []Exception{
{
Type: "sentry.usageError",
Value: "CaptureException called with nil error",
Stacktrace: &Stacktrace{Frames: []Frame{}},
},
},
},
{
name: "SimpleError",
err: errors.New("custom error"),
want: []Exception{
{
Type: "*errors.errorString",
Value: "custom error",
Stacktrace: &Stacktrace{Frames: []Frame{}},
},
},
},
}
errorChainTests := []captureExceptionTest{
{
name: "MostRecentErrorHasStack",
err: pkgErrors.WithStack(&customErr{}),
want: []Exception{
{
Type: "*sentry.customErr",
Value: "wat",
// No Stacktrace, because we can't tell where the error came
// from and because we have a stack trace in the most recent
// error in the chain.
},
{
Type: "*errors.withStack",
Value: "wat",
Stacktrace: &Stacktrace{Frames: []Frame{}},
},
},
},
{
name: "ChainWithNilCause",
err: &customErrWithCause{cause: nil},
want: []Exception{
{
Type: "*sentry.customErrWithCause",
Value: "err",
Stacktrace: &Stacktrace{Frames: []Frame{}},
},
},
},
{
name: "ChainWithoutStacktrace",
err: &customErrWithCause{cause: &customErr{}},
want: []Exception{
{
Type: "*sentry.customErr",
Value: "wat",
},
{
Type: "*sentry.customErrWithCause",
Value: "err",
Stacktrace: &Stacktrace{Frames: []Frame{}},
},
},
},
{
name: "Go113Unwrap",
err: wrappedError{original: errors.New("original")},
want: []Exception{
{
Type: "*errors.errorString",
Value: "original",
},
{
Type: "sentry.wrappedError",
Value: "wrapped: original",
Stacktrace: &Stacktrace{Frames: []Frame{}},
},
},
},
}
tests := []captureExceptionTestGroup{
{
name: "Basic",
tests: basicTests,
},
{
name: "ErrorChain",
tests: errorChainTests,
},
}
for _, grp := range tests {
for _, tt := range grp.tests {
tt := tt
t.Run(grp.name+"/"+tt.name, func(t *testing.T) {
client, _, transport := setupClientTest()
client.CaptureException(tt.err, nil, nil)
if transport.lastEvent == nil {
t.Fatal("missing event")
}
got := transport.lastEvent.Exception
if diff := cmp.Diff(tt.want, got); diff != "" {
t.Errorf("Event mismatch (-want +got):\n%s", diff)
}
})
}
}
}
func TestCaptureEvent(t *testing.T) {
client, _, transport := setupClientTest()
eventID := EventID("0123456789abcdef")
timestamp := time.Now().UTC()
serverName := "testServer"
client.CaptureEvent(&Event{
EventID: eventID,
Timestamp: timestamp,
ServerName: serverName,
}, nil, nil)
if transport.lastEvent == nil {
t.Fatal("missing event")
}
want := &Event{
EventID: eventID,
Timestamp: timestamp,
ServerName: serverName,
Level: LevelInfo,
Platform: "go",
Sdk: SdkInfo{
Name: "sentry.go",
Version: SDKVersion,
Integrations: []string{},
Packages: []SdkPackage{
{
// FIXME: name format doesn't follow spec in
// https://docs.sentry.io/development/sdk-dev/event-payloads/sdk/
Name: "sentry-go",
Version: SDKVersion,
},
// TODO: perhaps the list of packages is incomplete or there
// should not be any package at all. We may include references
// to used integrations like http, echo, gin, etc.
},
},
}
got := transport.lastEvent
opts := cmp.Options{cmpopts.IgnoreFields(Event{}, "Release", "sdkMetaData", "attachments")}
if diff := cmp.Diff(want, got, opts); diff != "" {
t.Errorf("Event mismatch (-want +got):\n%s", diff)
}
}
func TestCaptureEventShouldSendEventWithMessage(t *testing.T) {
client, scope, transport := setupClientTest()
event := NewEvent()
event.Message = "event message"
client.CaptureEvent(event, nil, scope)
assertEqual(t, transport.lastEvent.Message, "event message")
}
func TestCaptureEventNil(t *testing.T) {
client, scope, transport := setupClientTest()
client.CaptureEvent(nil, nil, scope)
want := &Event{
Exception: []Exception{
{
Type: "sentry.usageError",
Value: "CaptureEvent called with nil event",
Stacktrace: &Stacktrace{Frames: []Frame{}},
},
},
}
got := transport.lastEvent
opts := cmp.Options{
cmpopts.IgnoreFields(Event{}, "sdkMetaData", "attachments"),
cmp.Transformer("SimplifiedEvent", func(e *Event) *Event {
return &Event{
Exception: e.Exception,
}
}),
}
if diff := cmp.Diff(want, got, opts); diff != "" {
t.Errorf("(-want +got):\n%s", diff)
}
}
func TestCaptureCheckIn(t *testing.T) {
tests := []struct {
name string
checkIn *CheckIn
monitorConfig *MonitorConfig
expectNilEvent bool
}{
{
name: "Nil CheckIn",
checkIn: nil,
monitorConfig: nil,
expectNilEvent: true,
},
{
name: "Nil MonitorConfig",
checkIn: &CheckIn{
ID: "66e1a05b182346f2aee5fd7f0dc9b44e",
MonitorSlug: "cron",
Status: CheckInStatusOK,
Duration: time.Second * 10,
},
monitorConfig: nil,
},
{
name: "IntervalSchedule",
checkIn: &CheckIn{
ID: "66e1a05b182346f2aee5fd7f0dc9b44e",
MonitorSlug: "cron",
Status: CheckInStatusInProgress,
Duration: time.Second * 10,
},
monitorConfig: &MonitorConfig{
Schedule: IntervalSchedule(1, MonitorScheduleUnitHour),
CheckInMargin: 10,
MaxRuntime: 5000,
Timezone: "Asia/Singapore",
},
},
{
name: "CronSchedule",
checkIn: &CheckIn{
ID: "66e1a05b182346f2aee5fd7f0dc9b44e",
MonitorSlug: "cron",
Status: CheckInStatusInProgress,
Duration: time.Second * 10,
},
monitorConfig: &MonitorConfig{
Schedule: CrontabSchedule("40 * * * *"),
CheckInMargin: 10,
MaxRuntime: 5000,
Timezone: "Asia/Singapore",
},
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
client, _, transport := setupClientTest()
client.CaptureCheckIn(tt.checkIn, tt.monitorConfig, nil)
capturedEvent := transport.lastEvent
if tt.expectNilEvent && capturedEvent == nil {
// Event is nil as expected, nothing else to check
return
}
if capturedEvent == nil {
t.Fatal("missing event")
}
if capturedEvent.Type != checkInType {
t.Errorf("Event type mismatch: want %s, got %s", checkInType, capturedEvent.Type)
}
if diff := cmp.Diff(capturedEvent.CheckIn, tt.checkIn); diff != "" {
t.Errorf("CheckIn mismatch (-want +got):\n%s", diff)
}
if diff := cmp.Diff(capturedEvent.MonitorConfig, tt.monitorConfig); diff != "" {
t.Errorf("CheckIn mismatch (-want +got):\n%s", diff)
}
})
}
}
func TestCaptureCheckInExistingID(t *testing.T) {
client, _, _ := setupClientTest()
monitorConfig := &MonitorConfig{
Schedule: IntervalSchedule(1, MonitorScheduleUnitDay),
CheckInMargin: 30,
MaxRuntime: 30,
Timezone: "UTC",
}
checkInID := client.CaptureCheckIn(&CheckIn{
MonitorSlug: "cron",
Status: CheckInStatusInProgress,
Duration: time.Second,
}, monitorConfig, nil)
checkInID2 := client.CaptureCheckIn(&CheckIn{
ID: *checkInID,
MonitorSlug: "cron",
Status: CheckInStatusOK,
Duration: time.Minute,
}, monitorConfig, nil)
if *checkInID != *checkInID2 {
t.Errorf("Expecting equivalent CheckInID: %s and %s", *checkInID, *checkInID2)
}
}
func TestSampleRateCanDropEvent(t *testing.T) {
client, scope, transport := setupClientTest()
client.options.SampleRate = 0.000000000000001
client.CaptureMessage("Foo", nil, scope)
if transport.lastEvent != nil {
t.Error("expected event to be dropped")
}
}
func TestApplyToScopeCanDropEvent(t *testing.T) {
client, scope, transport := setupClientTest()
scope.shouldDropEvent = true
client.AddEventProcessor(func(event *Event, hint *EventHint) *Event {
if event == nil {
t.Errorf("EventProcessor received nil Event")
}
return event
})
client.CaptureMessage("Foo", nil, scope)
if transport.lastEvent != nil {
t.Error("expected event to be dropped")
}
}
func TestBeforeSendCanDropEvent(t *testing.T) {
client, scope, transport := setupClientTest()
client.options.BeforeSend = func(event *Event, hint *EventHint) *Event {
return nil
}
client.CaptureMessage("Foo", nil, scope)
if transport.lastEvent != nil {
t.Error("expected event to be dropped")
}
}
func TestBeforeSendGetAccessToEventHint(t *testing.T) {
client, scope, transport := setupClientTest()
client.options.BeforeSend = func(event *Event, hint *EventHint) *Event {
if ex, ok := hint.OriginalException.(customComplexError); ok {
event.Message = event.Exception[0].Value + " " + ex.AnswerToLife()
}
return event
}
ex := customComplexError{Message: "Foo"}
client.CaptureException(ex, &EventHint{OriginalException: ex}, scope)
assertEqual(t, transport.lastEvent.Message, "customComplexError: Foo 42")
}
func TestBeforeSendTransactionCanDropTransaction(t *testing.T) {
transport := &TransportMock{}
ctx := NewTestContext(ClientOptions{
EnableTracing: true,
TracesSampleRate: 1.0,
Transport: transport,
BeforeSend: func(event *Event, hint *EventHint) *Event {
t.Error("beforeSend should not be called")
return event
},
BeforeSendTransaction: func(event *Event, hint *EventHint) *Event {
assertEqual(t, event.Transaction, "Foo")
return nil
},
})
transaction := StartTransaction(ctx,
"Foo",
)
transaction.Finish()
if transport.lastEvent != nil {
t.Error("expected event to be dropped")
}
}
func TestBeforeSendTransactionIsCalled(t *testing.T) {
transport := &TransportMock{}
ctx := NewTestContext(ClientOptions{
EnableTracing: true,
TracesSampleRate: 1.0,
Transport: transport,
BeforeSend: func(event *Event, hint *EventHint) *Event {
t.Error("beforeSend should not be called")
return event
},
BeforeSendTransaction: func(event *Event, hint *EventHint) *Event {
assertEqual(t, event.Transaction, "Foo")
event.Transaction = "Bar"
return event
},
})
transaction := StartTransaction(ctx,
"Foo",
)
transaction.Finish()
lastEvent := transport.lastEvent
assertEqual(t, lastEvent.Transaction, "Bar")
// Make sure it's the same span
assertEqual(t, lastEvent.Contexts["trace"]["span_id"], transaction.SpanID)
}
func TestSampleRate(t *testing.T) {
tests := []struct {
SampleRate float64
// tolerated range is [SampleRate-MaxDelta, SampleRate+MaxDelta]
MaxDelta float64
}{
{0.00, 0.0},
{0.25, 0.2},
{0.50, 0.2},
{0.75, 0.2},
{1.00, 0.0},
}
for _, tt := range tests {
tt := tt
t.Run(fmt.Sprint(tt.SampleRate), func(t *testing.T) {
var (
total uint64
sampled uint64
)
// Call sample from multiple goroutines just like multiple hubs
// sharing a client would. This should help uncover data races.
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 10000; j++ {
atomic.AddUint64(&total, 1)
s := sample(tt.SampleRate)
switch tt.SampleRate {
case 0:
if s {
panic("sampled true when rate is 0")
}
case 1:
if !s {
panic("sampled false when rate is 1")
}
}
if s {
atomic.AddUint64(&sampled, 1)
}
}
}()
}
wg.Wait()
rate := float64(sampled) / float64(total)
if !(tt.SampleRate-tt.MaxDelta <= rate && rate <= tt.SampleRate+tt.MaxDelta) {
t.Errorf("effective sample rate was %f, want %f±%f", rate, tt.SampleRate, tt.MaxDelta)
}
})
}
}
func BenchmarkProcessEvent(b *testing.B) {
c, err := NewClient(ClientOptions{
SampleRate: 0.25,
Transport: &TransportMock{},
})
if err != nil {
b.Fatal(err)
}
for i := 0; i < b.N; i++ {
c.processEvent(&Event{}, nil, nil)
}
}
func TestRecover(t *testing.T) {
tests := []struct {
v interface{} // for panic(v)
want *Event
}{
{
errors.New("panic error"),
&Event{
Exception: []Exception{
{
Type: "*errors.errorString",
Value: "panic error",
Stacktrace: &Stacktrace{Frames: []Frame{}},
},
},
},
},
{"panic string", &Event{Message: "panic string"}},
// Arbitrary types should be converted to string:
{101010, &Event{Message: "101010"}},
{[]string{"", "", "hello"}, &Event{Message: `[]string{"", "", "hello"}`}},
{&struct{ Field string }{"test"}, &Event{Message: `&struct { Field string }{Field:"test"}`}},
}
checkEvent := func(t *testing.T, events []*Event, want *Event) {
t.Helper()
if len(events) != 1 {
b, err := json.MarshalIndent(events, "", " ")
if err != nil {
t.Fatal(err)
}
t.Fatalf("events = %s\ngot %d events, want 1", b, len(events))
}
got := events[0]
opts := cmp.Options{
cmpopts.IgnoreFields(Event{}, "sdkMetaData", "attachments"),
cmp.Transformer("SimplifiedEvent", func(e *Event) *Event {
return &Event{
Message: e.Message,
Exception: e.Exception,
Level: e.Level,
}
}),
}
if diff := cmp.Diff(want, got, opts); diff != "" {
t.Errorf("(-want +got):\n%s", diff)
}
}
for _, tt := range tests {
tt := tt
t.Run(fmt.Sprintf("Recover/%v", tt.v), func(t *testing.T) {
client, scope, transport := setupClientTest()
func() {
defer client.Recover(nil, nil, scope)
panic(tt.v)
}()
tt.want.Level = LevelFatal
checkEvent(t, transport.Events(), tt.want)
})
t.Run(fmt.Sprintf("RecoverWithContext/%v", tt.v), func(t *testing.T) {
client, scope, transport := setupClientTest()
var called bool
client.AddEventProcessor(func(event *Event, hint *EventHint) *Event {
called = true
if hint.Context != context.TODO() {
t.Fatal("unexpected context value")
}
return event
})
func() {
defer client.RecoverWithContext(context.TODO(), nil, nil, scope)
panic(tt.v)
}()
tt.want.Level = LevelFatal
checkEvent(t, transport.Events(), tt.want)
if !called {
t.Error("event processor not called, could not test that hint has context")
}
})
}
}
func TestCustomMaxSpansProperty(t *testing.T) {
client, _, _ := setupClientTest()
assertEqual(t, client.Options().MaxSpans, defaultMaxSpans)
client.options.MaxSpans = 2000
assertEqual(t, client.Options().MaxSpans, 2000)
properClient, _ := NewClient(ClientOptions{
MaxSpans: 3000,
Transport: &TransportMock{},
})
assertEqual(t, properClient.Options().MaxSpans, 3000)
}
func TestSDKIdentifier(t *testing.T) {
client, _, _ := setupClientTest()
assertEqual(t, client.GetSDKIdentifier(), "sentry.go")
client.SetSDKIdentifier("sentry.go.test")
assertEqual(t, client.GetSDKIdentifier(), "sentry.go.test")
}
func TestClientSetsUpTransport(t *testing.T) {
client, _ := NewClient(ClientOptions{Dsn: testDsn})
require.IsType(t, &HTTPTransport{}, client.Transport)
client, _ = NewClient(ClientOptions{})
require.IsType(t, &noopTransport{}, client.Transport)
}