-
-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathSentryClientTests.cs
More file actions
1772 lines (1456 loc) · 57.1 KB
/
SentryClientTests.cs
File metadata and controls
1772 lines (1456 loc) · 57.1 KB
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using NSubstitute.ReceivedExtensions;
using Sentry.Internal.Http;
using BackgroundWorker = Sentry.Internal.BackgroundWorker;
namespace Sentry.Tests;
public partial class SentryClientTests : IDisposable
{
private class Fixture : IDisposable
{
public SentryOptions SentryOptions { get; set; } = new()
{
Dsn = ValidDsn,
AttachStacktrace = false,
AutoSessionTracking = false
};
public IBackgroundWorker BackgroundWorker { get; set; } = Substitute.For<IBackgroundWorker, IDisposable>();
public IClientReportRecorder ClientReportRecorder { get; } = Substitute.For<IClientReportRecorder>();
public RandomValuesFactory RandomValuesFactory { get; set; } = null;
public ISessionManager SessionManager { get; set; } = Substitute.For<ISessionManager>();
public BackpressureMonitor BackpressureMonitor { get; set; }
public Fixture()
{
SentryOptions.ClientReportRecorder = ClientReportRecorder;
BackgroundWorker.EnqueueEnvelope(Arg.Any<Envelope>()).Returns(true);
}
public SentryClient GetSut()
{
var randomValuesFactory = RandomValuesFactory ?? new IsolatedRandomValuesFactory();
return new SentryClient(SentryOptions, BackgroundWorker, randomValuesFactory, SessionManager, BackpressureMonitor);
}
public void Dispose()
{
BackpressureMonitor?.Dispose();
}
}
public void Dispose()
{
_fixture.Dispose();
}
private readonly Fixture _fixture = new();
private readonly ITestOutputHelper _output;
public SentryClientTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void Ctor_DebugTrue_CreatesConsoleDiagnosticLogger()
{
// Arrange
_fixture.SentryOptions.Debug = true;
_fixture.SentryOptions.DiagnosticLogger = null;
// Act
_ = _fixture.GetSut();
// Assert
Assert.NotNull(_fixture.SentryOptions.DiagnosticLogger);
Assert.IsType<ConsoleDiagnosticLogger>(_fixture.SentryOptions.DiagnosticLogger);
}
[Fact]
public void Ctor_DebugFalseButLoggerSet_SetsLoggerToNull()
{
// Arrange
_fixture.SentryOptions.Debug = false;
_fixture.SentryOptions.DiagnosticLogger = Substitute.For<IDiagnosticLogger>();
// Act
_ = _fixture.GetSut();
// Assert
Assert.Null(_fixture.SentryOptions.DiagnosticLogger);
}
[Fact]
public void Ctor_DebugTrueAndLoggerSet_KeepsExistingLogger()
{
// Arrange
var existingLogger = Substitute.For<IDiagnosticLogger>();
_fixture.SentryOptions.Debug = true;
_fixture.SentryOptions.DiagnosticLogger = existingLogger;
// Act
_ = _fixture.GetSut();
// Assert
Assert.Same(existingLogger, _fixture.SentryOptions.DiagnosticLogger);
}
[Theory]
[MemberData(nameof(GetExceptionFilterTestCases))]
public void CaptureEvent_ExceptionFilteredForType(bool shouldFilter, Exception exception, params IExceptionFilter[] filters)
{
foreach (var filter in filters)
{
_fixture.SentryOptions.AddExceptionFilter(filter);
}
var sut = _fixture.GetSut();
var result = sut.CaptureException(exception);
Assert.Equal(shouldFilter, result == default);
_fixture.BackgroundWorker.Received(result == default ? 0 : 1).EnqueueEnvelope(Arg.Any<Envelope>());
}
public static IEnumerable<object[]> GetExceptionFilterTestCases()
{
var systemExceptionFilter = new ExceptionTypeFilter<SystemException>();
var applicationExceptionFilter = new ExceptionTypeFilter<ApplicationException>();
var aggregateExceptionFilter = new ExceptionTypeFilter<AggregateException>();
// Filtered out for it's the exact filtered type
yield return new object[]
{
true,
new SystemException(),
systemExceptionFilter
};
// Filtered for it's a derived type
yield return new object[]
{
true,
new ArithmeticException(),
systemExceptionFilter
};
// Not filtered since it's not in the inheritance chain
yield return new object[]
{
false,
new Exception(),
systemExceptionFilter
};
// Filtered because it's the only exception under an aggregate exception
yield return new object[]
{
true,
new AggregateException(new SystemException()),
systemExceptionFilter
};
// Filtered because all exceptions under the aggregate exception are the filtered or derived type
yield return new object[]
{
true,
new AggregateException(new SystemException(), new ArithmeticException()),
systemExceptionFilter
};
// Filtered because all exceptions under the aggregate exception are covered by all of the filters
yield return new object[]
{
true,
new AggregateException(new SystemException(), new ApplicationException()),
systemExceptionFilter,
applicationExceptionFilter
};
// Not filtered because there's an exception under the aggregate not covered by the filters
yield return new object[]
{
false,
new AggregateException(new SystemException(), new Exception()),
systemExceptionFilter
};
// Filtered because we're specifically filtering out aggregate exceptions (strange, but should work)
yield return new object[]
{
true,
new AggregateException(),
aggregateExceptionFilter
};
}
[Fact]
public void CaptureEvent_IdReturnedToString_NoDashes()
{
var sut = _fixture.GetSut();
var evt = new SentryEvent(new Exception());
var actual = sut.CaptureEvent(evt);
var hasDashes = actual.ToString().Contains('-');
Assert.False(hasDashes);
}
[Fact]
public void CaptureEvent_ExceptionProcessorsOnOptions_Invoked()
{
var exceptionProcessor = Substitute.For<ISentryEventExceptionProcessor>();
_fixture.SentryOptions.AddExceptionProcessorProvider(() => new[] { exceptionProcessor });
var sut = _fixture.GetSut();
var evt = new SentryEvent(new Exception());
_ = sut.CaptureEvent(evt);
exceptionProcessor.Received(1).Process(evt.Exception!, evt);
}
[Fact]
public void CaptureEvent_ExceptionProcessorsOnScope_Invoked()
{
var exceptionProcessor = Substitute.For<ISentryEventExceptionProcessor>();
var scope = new Scope();
scope.AddExceptionProcessor(exceptionProcessor);
var sut = _fixture.GetSut();
var evt = new SentryEvent(new Exception());
_ = sut.CaptureEvent(evt, scope);
exceptionProcessor.Received(1).Process(evt.Exception!, evt);
}
[Fact]
public void CaptureEvent_NullEventWithScope_EmptyGuid()
{
var sut = _fixture.GetSut();
Assert.Equal(default, sut.CaptureEvent(null, new Scope(_fixture.SentryOptions)));
}
[Fact]
public void CaptureEvent_NullEvent_EmptyGuid()
{
var sut = _fixture.GetSut();
Assert.Equal(default, sut.CaptureEvent(null));
}
[Fact]
public void CaptureEvent_NullScope_QueuesEvent()
{
var expectedId = Guid.NewGuid();
var expectedEvent = new SentryEvent(eventId: expectedId);
var sut = _fixture.GetSut();
var actualId = sut.CaptureEvent(expectedEvent);
Assert.Equal(expectedId, (Guid)actualId);
}
[Fact]
public void CaptureEvent_EventAndScope_QueuesEvent()
{
var expectedId = Guid.NewGuid();
var expectedEvent = new SentryEvent(eventId: expectedId);
var sut = _fixture.GetSut();
var actualId = sut.CaptureEvent(expectedEvent, new Scope(_fixture.SentryOptions));
Assert.Equal(expectedId, (Guid)actualId);
}
[Fact]
public void CaptureEvent_EventAndScope_EvaluatesScope()
{
var scope = new Scope(_fixture.SentryOptions);
var sut = _fixture.GetSut();
var evaluated = false;
object actualSender = null;
object actualScope = null;
scope.OnEvaluating += (sender, activeScope) =>
{
actualSender = sender;
actualScope = activeScope;
evaluated = true;
};
_ = sut.CaptureEvent(new SentryEvent(), scope);
Assert.True(evaluated);
Assert.Same(scope, actualSender);
Assert.Same(scope, actualScope);
}
[Fact]
public void CaptureEvent_EventAndScope_CopyScopeIntoEvent()
{
const string expectedBreadcrumb = "test";
var scope = new Scope(_fixture.SentryOptions);
scope.AddBreadcrumb(expectedBreadcrumb);
var @event = new SentryEvent();
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(@event, scope);
Assert.Equal(scope.Breadcrumbs, @event.Breadcrumbs);
}
[Fact]
public void CaptureEvent_UserIsNull_SetsFallbackUserId()
{
// Arrange
var scope = new Scope(_fixture.SentryOptions);
var @event = new SentryEvent();
var sut = _fixture.GetSut();
// Act
_ = sut.CaptureEvent(@event, scope);
// Assert
@event.User.Id.Should().NotBeNullOrWhiteSpace();
}
[Fact]
public void CaptureEvent_Redact_Breadcrumbs()
{
// Act
var scope = new Scope(_fixture.SentryOptions);
scope.AddBreadcrumb("Visited https://user@sentry.io in session");
var @event = new SentryEvent();
// Act
Envelope envelope = null;
var sut = _fixture.GetSut();
sut.Worker.EnqueueEnvelope(Arg.Do<Envelope>(e => envelope = e));
_ = sut.CaptureEvent(@event, scope);
// Assert
envelope.Should().NotBeNull();
envelope.Items.Count.Should().Be(1);
var actual = (SentryEvent)(envelope.Items[0].Payload as JsonSerializable)?.Source;
actual.Should().NotBeNull();
actual?.Breadcrumbs.Count.Should().Be(1);
actual?.Breadcrumbs.ToArray()[0].Message.Should().Be($"Visited https://{PiiExtensions.RedactedText}@sentry.io in session");
}
[Fact]
public void CaptureEvent_BeforeEvent_RejectEvent()
{
_fixture.SentryOptions.SetBeforeSend((_, _) => null);
var expectedEvent = new SentryEvent();
var sut = _fixture.GetSut();
var actualId = sut.CaptureEvent(expectedEvent, new Scope(_fixture.SentryOptions));
Assert.Equal(default, actualId);
_ = _fixture.BackgroundWorker.DidNotReceive().EnqueueEnvelope(Arg.Any<Envelope>());
}
[Fact]
public void CaptureEvent_BeforeEvent_RejectEvent_RecordsDiscard()
{
_fixture.SentryOptions.SetBeforeSend((_, _) => null);
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(new SentryEvent());
_fixture.ClientReportRecorder.Received(1)
.RecordDiscardedEvent(DiscardReason.BeforeSend, DataCategory.Error);
}
[Fact]
public void CaptureEvent_EventProcessor_RejectEvent_RecordsDiscard()
{
var processor = Substitute.For<ISentryEventProcessor>();
processor.Process(Arg.Any<SentryEvent>()).ReturnsNull();
_fixture.SentryOptions.AddEventProcessor(processor);
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(new SentryEvent());
_fixture.ClientReportRecorder.Received(1)
.RecordDiscardedEvent(DiscardReason.EventProcessor, DataCategory.Error);
}
[Fact]
public void CaptureEvent_ExceptionFilter_RecordsDiscard()
{
var filter = Substitute.For<IExceptionFilter>();
filter.Filter(Arg.Any<Exception>()).Returns(true);
_fixture.SentryOptions.AddExceptionFilter(filter);
var sut = _fixture.GetSut();
_ = sut.CaptureException(new Exception());
_fixture.ClientReportRecorder.Received(1)
.RecordDiscardedEvent(DiscardReason.EventProcessor, DataCategory.Error);
}
[Fact]
public void CaptureEvent_BeforeSend_GetsHint()
{
SentryHint received = null;
_fixture.SentryOptions.SetBeforeSend((e, h) =>
{
received = h;
return e;
});
var @event = new SentryEvent();
var hint = new SentryHint();
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(@event, hint: hint);
Assert.Same(hint, received);
}
[Fact]
public void CaptureEvent_BeforeSend_Gets_ScopeAttachments()
{
// Arrange
SentryHint hint = null;
_fixture.SentryOptions.SetBeforeSend((e, h) =>
{
hint = h;
return e;
});
var scope = new Scope(_fixture.SentryOptions);
scope.AddAttachment(AttachmentHelper.FakeAttachment("foo.txt"));
scope.AddAttachment(AttachmentHelper.FakeAttachment("bar.txt"));
var sut = _fixture.GetSut();
// Act
_ = sut.CaptureEvent(new SentryEvent(), scope);
// Assert
hint.Should().NotBeNull();
hint.Attachments.Should().Contain(scope.Attachments);
}
[Fact]
public void CaptureEvent_BeforeSendAddsAttachment_EnvelopeContainsAttachment()
{
// Arrange
_fixture.SentryOptions.SetBeforeSend((e, h) =>
{
h.Attachments.Add(AttachmentHelper.FakeAttachment("foo.txt"));
return e;
});
var sut = _fixture.GetSut();
Envelope envelope = null;
sut.Worker.EnqueueEnvelope(Arg.Do<Envelope>(e => envelope = e));
// Act
_ = sut.CaptureEvent(new SentryEvent());
// Assert
envelope.Should().NotBeNull();
envelope.Items.Count.Should().Be(2);
Assert.True(envelope.Items[1].Header.ContainsKey("filename"));
Assert.True((string)envelope.Items[1].Header["filename"] == "foo.txt");
}
[Fact]
public void CaptureEvent_EventProcessor_Gets_Hint()
{
// Arrange
var processor = Substitute.For<ISentryEventProcessorWithHint>();
processor.Process(Arg.Any<SentryEvent>(), Arg.Any<SentryHint>()).Returns(new SentryEvent());
_fixture.SentryOptions.AddEventProcessor(processor);
// Act
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(new SentryEvent());
// Assert
processor.Received(1).Process(Arg.Any<SentryEvent>(), Arg.Any<SentryHint>());
}
[Fact]
public void CaptureEvent_EventProcessor_Gets_ScopeAttachments()
{
// Arrange
var processor = Substitute.For<ISentryEventProcessorWithHint>();
SentryHint hint = null;
processor.Process(Arg.Any<SentryEvent>(), Arg.Do<SentryHint>(h => hint = h)).Returns(new SentryEvent());
_fixture.SentryOptions.AddEventProcessor(processor);
var scope = new Scope(_fixture.SentryOptions);
scope.AddAttachment(AttachmentHelper.FakeAttachment("foo.txt"));
// Act
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(new SentryEvent(), scope);
// Assert
hint.Should().NotBeNull();
hint.Attachments.Should().Contain(scope.Attachments);
}
[Fact]
public void CaptureEvent_Gets_ScopeAttachments()
{
// Arrange
var scope = new Scope(_fixture.SentryOptions);
scope.AddAttachment(AttachmentHelper.FakeAttachment("foo.txt"));
scope.AddAttachment(AttachmentHelper.FakeAttachment("bar.txt"));
var sut = _fixture.GetSut();
// Act
sut.CaptureEvent(new SentryEvent(), scope);
// Assert
sut.Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(envelope =>
envelope.Items.Count(item => item.TryGetType() == "attachment") == 2));
}
[Fact]
public void CaptureEvent_Gets_HintAttachments()
{
// Arrange
var scope = new Scope(_fixture.SentryOptions);
_fixture.SentryOptions.SetBeforeSend((e, h) =>
{
h.Attachments.Add(AttachmentHelper.FakeAttachment("foo.txt"));
h.Attachments.Add(AttachmentHelper.FakeAttachment("bar.txt"));
return e;
});
var sut = _fixture.GetSut();
// Act
sut.CaptureEvent(new SentryEvent(), scope);
// Assert
sut.Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(envelope =>
envelope.Items.Count(item => item.TryGetType() == "attachment") == 2));
}
[Fact]
public void CaptureEvent_Gets_ScopeAndHintAttachments()
{
// Arrange
var scope = new Scope(_fixture.SentryOptions);
scope.AddAttachment(AttachmentHelper.FakeAttachment("foo.txt"));
_fixture.SentryOptions.SetBeforeSend((e, h) =>
{
h.Attachments.Add(AttachmentHelper.FakeAttachment("bar.txt"));
return e;
});
var sut = _fixture.GetSut();
// Act
sut.CaptureEvent(new SentryEvent(), scope);
// Assert
sut.Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(envelope =>
envelope.Items.Count(item => item.TryGetType() == "attachment") == 2));
}
[Fact]
public void CaptureEvent_CanRemove_ScopetAttachment()
{
// Arrange
var scope = new Scope(_fixture.SentryOptions);
scope.AddAttachment(AttachmentHelper.FakeAttachment("foo.txt"));
scope.AddAttachment(AttachmentHelper.FakeAttachment("bar.txt"));
_fixture.SentryOptions.SetBeforeSend((e, h) =>
{
var attachment = h.Attachments.FirstOrDefault(a => a.FileName == "bar.txt");
h.Attachments.Remove(attachment);
return e;
});
var sut = _fixture.GetSut();
// Act
sut.CaptureEvent(new SentryEvent(), scope);
// Assert
sut.Worker.Received(1).EnqueueEnvelope(Arg.Is<Envelope>(envelope =>
envelope.Items.Count(item => item.TryGetType() == "attachment") == 1));
}
[Fact]
public void CaptureEvent_BeforeSend_ModifyEvent()
{
SentryEvent received = null;
_fixture.SentryOptions.SetBeforeSend((e, _) => received = e);
var @event = new SentryEvent();
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(@event);
Assert.Same(@event, received);
}
[Fact]
public void CaptureEvent_LevelOnScope_OverridesLevelOnEvent()
{
const SentryLevel expected = SentryLevel.Fatal;
var @event = new SentryEvent
{
Level = SentryLevel.Fatal
};
var scope = new Scope
{
Level = expected
};
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(@event, scope);
Assert.Equal(expected, @event.Level);
}
[Fact]
public void CaptureEvent_SamplingLowest_DropsEvent()
{
// Smallest value allowed. Should always drop
_fixture.SentryOptions.SampleRate = float.Epsilon;
var @event = new SentryEvent();
var sut = _fixture.GetSut();
Assert.Equal(default, sut.CaptureEvent(@event));
}
[Fact]
public void CaptureEvent_SampleDrop_RecordsDiscard()
{
_fixture.SentryOptions.SampleRate = float.Epsilon;
var @event = new SentryEvent();
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(@event);
_fixture.ClientReportRecorder.Received(1)
.RecordDiscardedEvent(DiscardReason.SampleRate, DataCategory.Error);
}
[Theory]
[InlineData(0.6f, "sample_rate")] // Sample rand is greater than the sample rate
[InlineData(0.4f, "backpressure")] // Sample is dropped due to downsampling
public void CaptureEvent_SampleDrop_RecordsCorrectDiscardReason(double sampleRand, string discardReason)
{
// Arrange
_fixture.RandomValuesFactory = Substitute.For<RandomValuesFactory>();
_fixture.RandomValuesFactory.NextDouble().Returns(sampleRand);
_fixture.SentryOptions.SampleRate = 0.5f;
var logger = Substitute.For<IDiagnosticLogger>();
_fixture.BackpressureMonitor = new BackpressureMonitor(logger, null, false);
_fixture.BackpressureMonitor.SetDownsampleLevel(1);
var sut = _fixture.GetSut();
// Act
var @event = new SentryEvent();
_ = sut.CaptureEvent(@event);
// Assert
var expectedReason = new DiscardReason(discardReason);
_fixture.ClientReportRecorder.Received(1).RecordDiscardedEvent(expectedReason, DataCategory.Error);
}
[Fact]
public void CaptureEvent_SamplingHighest_SendsEvent()
{
// Largest value allowed. Should always send
_fixture.SentryOptions.SampleRate = 1;
SentryEvent received = null;
_fixture.SentryOptions.SetBeforeSend((e, _) => received = e);
var @event = new SentryEvent();
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(@event);
Assert.Same(@event, received);
}
[Fact]
public void CaptureEvent_SamplingNull_DropsEvent()
{
_fixture.SentryOptions.SampleRate = null;
SentryEvent received = null;
_fixture.SentryOptions.SetBeforeSend((e, _) => received = e);
var @event = new SentryEvent();
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(@event);
Assert.Same(@event, received);
}
[Theory]
[InlineData(0.25f, 0)]
[InlineData(0.50f, 0)]
[InlineData(0.75f, 0)]
[InlineData(0.25f, 1)]
[InlineData(0.50f, 1)]
[InlineData(0.75f, 1)]
[InlineData(0.25f, 3)]
[InlineData(0.50f, 3)]
[InlineData(0.75f, 3)]
public void CaptureEvent_WithSampleRate_AppropriateDistribution(float sampleRate, int downsampleLevel)
{
// Arrange
var now = DateTimeOffset.UtcNow;
var clock = new MockClock(now);
_fixture.BackpressureMonitor = new BackpressureMonitor(null, clock, enablePeriodicHealthCheck: false);
_fixture.BackpressureMonitor.SetDownsampleLevel(downsampleLevel);
_fixture.SentryOptions.SampleRate = sampleRate;
const int numEvents = 1000;
const double allowedRelativeDeviation = 0.15;
const uint allowedDeviation = (uint)(allowedRelativeDeviation * numEvents);
var expectedSampled = (int)(numEvents * sampleRate * _fixture.BackpressureMonitor.DownsampleFactor);
// This test expects an approximate uniform distribution of random numbers, so we'll retry a few times.
TestHelpers.RetryTest(maxAttempts: 3, _output, () =>
{
// Act
var client = _fixture.GetSut();
var countSampled = 0;
for (var i = 0; i < numEvents; i++)
{
var id = client.CaptureMessage($"Test[{i}]");
if (id != SentryId.Empty)
{
countSampled++;
}
}
// Assert
countSampled.Should().BeCloseTo(expectedSampled, allowedDeviation);
});
}
[Fact]
public void CaptureEvent_Processing_Order()
{
// Arrange
var @event = new SentryEvent(new Exception());
var processingOrder = new List<string>();
var exceptionFilter = Substitute.For<IExceptionFilter>();
exceptionFilter.Filter(Arg.Do<Exception>(_ =>
processingOrder.Add("exceptionFilter")
)).Returns(false);
_fixture.SentryOptions.ExceptionFilters.Add(exceptionFilter);
var exceptionProcessor = Substitute.For<ISentryEventExceptionProcessor>();
exceptionProcessor
.When(x => x.Process(Arg.Any<Exception>(), Arg.Any<SentryEvent>()))
.Do(_ => processingOrder.Add("exceptionProcessor"));
var scope = new Scope(_fixture.SentryOptions);
scope.ExceptionProcessors.Add(exceptionProcessor);
var eventProcessor = Substitute.For<ISentryEventProcessor>();
eventProcessor.Process(default).ReturnsForAnyArgs(_ =>
{
processingOrder.Add("eventProcessor");
return @event;
});
_fixture.SentryOptions.AddEventProcessor(eventProcessor);
_fixture.SentryOptions.SetBeforeSend((e, _) =>
{
processingOrder.Add("SetBeforeSend");
return e;
});
_fixture.SessionManager.When(x => x.ReportError())
.Do(_ => processingOrder.Add("UpdateSession"));
var logger = Substitute.For<IDiagnosticLogger>();
logger.IsEnabled(Arg.Any<SentryLevel>()).Returns(true);
logger.When(x => x.Log(Arg.Any<SentryLevel>(), Arg.Is("Event sampled in.")))
.Do(_ => processingOrder.Add("SampleRate"));
_fixture.SentryOptions.DiagnosticLogger = logger;
_fixture.SentryOptions.Debug = true;
// Act
var client = _fixture.GetSut();
client.CaptureEvent(@event, scope);
// Assert
// See https://github.com/getsentry/sentry-dotnet/issues/1599
var expectedOrder = new List<string>()
{
"exceptionFilter",
"exceptionProcessor",
"eventProcessor",
"SetBeforeSend",
"UpdateSession",
"SampleRate"
};
processingOrder.Should().Equal(expectedOrder);
}
[Fact]
public void CaptureEvent_SessionRunningAndHasException_ReportsErrorButDoesNotEndSession()
{
_fixture.BackgroundWorker.EnqueueEnvelope(Arg.Do<Envelope>(envelope =>
{
var sessionItems = envelope.Items.Where(x => x.TryGetType() == "session");
foreach (var item in sessionItems)
{
var session = (SessionUpdate)((JsonSerializable)item.Payload).Source;
Assert.Equal(1, session.ErrorCount);
Assert.Null(session.EndStatus);
}
}));
_fixture.SessionManager = new GlobalSessionManager(_fixture.SentryOptions);
_fixture.SessionManager.StartSession();
_fixture.GetSut().CaptureEvent(new SentryEvent(new Exception("test exception")));
}
[Fact]
public void CaptureEvent_SessionRunningAndHasTerminalException_ReportsErrorAndEndsSessionAsCrashed()
{
_fixture.BackgroundWorker.EnqueueEnvelope(Arg.Do<Envelope>(envelope =>
{
var sessionItems = envelope.Items.Where(x => x.TryGetType() == "session");
foreach (var item in sessionItems)
{
var session = (SessionUpdate)((JsonSerializable)item.Payload).Source;
Assert.Equal(1, session.ErrorCount);
Assert.NotNull(session.EndStatus);
Assert.Equal(SessionEndStatus.Crashed, session.EndStatus);
}
}));
_fixture.SessionManager = new GlobalSessionManager(_fixture.SentryOptions);
_fixture.SessionManager.StartSession();
var exception = new Exception("test exception");
exception.SetSentryMechanism("test mechanism", handled: false);
_fixture.GetSut().CaptureEvent(new SentryEvent(exception));
}
[Fact]
public void CaptureEvent_Release_SetFromOptions()
{
const string expectedRelease = "release number";
_fixture.SentryOptions.Release = expectedRelease;
var @event = new SentryEvent();
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(@event);
Assert.Equal(expectedRelease, @event.Release);
}
[Fact]
public void CaptureEvent_Distribution_SetFromOptions()
{
const string expectedDistribution = "some distribution";
_fixture.SentryOptions.Distribution = expectedDistribution;
var @event = new SentryEvent();
var sut = _fixture.GetSut();
_ = sut.CaptureEvent(@event);
Assert.Equal(expectedDistribution, @event.Distribution);
}
[Fact]
public void CaptureEvent_DisposedClient_DoesNotThrow()
{
var sut = _fixture.GetSut();
sut.Dispose();
var @event = new SentryEvent();
sut.CaptureEvent(@event);
}
[Fact]
public void Dispose_should_only_flush()
{
// Arrange
var client = _fixture.GetSut();
// Act
client.Dispose();
//Assert is still usable
client.CaptureEvent(new SentryEvent { Message = "Test" });
}
[Fact]
public void CaptureFeedback_DisposedClient_DoesNotThrow()
{
// Arrange
var feedback = new SentryFeedback("Everything is great!");
var sut = _fixture.GetSut();
sut.Dispose();
// Act
var id = sut.CaptureFeedback(feedback, out var result);
// Assert
result.Should().Be(CaptureFeedbackResult.Success);
id.Should().NotBe(SentryId.Empty);
}
[Fact]
public void CaptureFeedback_NoMessage_FeedbackIgnored()
{
//Arrange
var sut = _fixture.GetSut();
var feedback = new SentryFeedback(string.Empty);
//Act
var id = sut.CaptureFeedback(feedback, out var result);
//Assert
_ = sut.Worker.DidNotReceive().EnqueueEnvelope(Arg.Any<Envelope>());
result.Should().Be(CaptureFeedbackResult.EmptyMessage);
id.Should().Be(SentryId.Empty);
}
[Fact]
public void CaptureFeedback_ValidUserFeedback_FeedbackRegistered()
{
//Arrange
var sut = _fixture.GetSut();
var feedback = new SentryFeedback("Everything is great!");
//Act
var result = sut.CaptureFeedback(feedback);
//Assert
_ = sut.Worker.Received(1).EnqueueEnvelope(Arg.Any<Envelope>());
result.Should().NotBe(SentryId.Empty);
}
[Fact]
public void CaptureFeedback_WithScope_ScopeCopiedToEvent()
{
//Arrange
const string expectedBreadcrumb = "test";
var scope = new Scope(_fixture.SentryOptions);
scope.AddBreadcrumb(expectedBreadcrumb);
scope.Level = SentryLevel.Warning;
var feedback = new SentryFeedback("Everything is great!");
var sut = _fixture.GetSut();
Envelope envelope = null;
sut.Worker.When(w => w.EnqueueEnvelope(Arg.Any<Envelope>()))
.Do(callback => envelope = callback.Arg<Envelope>());
//Act
var result = sut.CaptureFeedback(feedback, scope);
//Assert
result.Should().NotBe(SentryId.Empty);
_ = sut.Worker.Received(1).EnqueueEnvelope(Arg.Any<Envelope>());
envelope.Should().NotBeNull();
envelope.Items.Should().Contain(item => item.TryGetType() == EnvelopeItem.TypeValueFeedback);
var item = envelope.Items.First(x => x.TryGetType() == EnvelopeItem.TypeValueFeedback);
var @event = (SentryEvent)((JsonSerializable)item.Payload).Source;
@event.Level.Should().Be(scope.Level);
Assert.Equal(scope.Breadcrumbs, @event.Breadcrumbs);
}
[Fact]
public void CaptureFeedback_EventProcessorApplied()
{
//Arrange
var feedback = new SentryFeedback("Everything is great!");
var eventProcessor = Substitute.For<ISentryEventProcessor>();
eventProcessor.Process(Arg.Any<SentryEvent>()).Returns(e =>
{
var evt = (SentryEvent)e[0];
evt.Environment = "testing 123";
return evt;
});
_fixture.SentryOptions.AddEventProcessor(eventProcessor);
var sut = _fixture.GetSut();
Envelope envelope = null;
sut.Worker.When(w => w.EnqueueEnvelope(Arg.Any<Envelope>()))
.Do(callback => envelope = callback.Arg<Envelope>());
//Act
var result = sut.CaptureFeedback(feedback);