-
-
Notifications
You must be signed in to change notification settings - Fork 427
/
SentryClientTest.kt
1350 lines (1157 loc) · 46.6 KB
/
SentryClientTest.kt
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
package io.sentry
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.check
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.isNull
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.mockingDetails
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.nhaarman.mockitokotlin2.whenever
import io.sentry.exception.SentryEnvelopeException
import io.sentry.hints.ApplyScopeData
import io.sentry.hints.Cached
import io.sentry.hints.DiskFlushNotification
import io.sentry.protocol.Mechanism
import io.sentry.protocol.Request
import io.sentry.protocol.SdkVersion
import io.sentry.protocol.SentryException
import io.sentry.protocol.SentryId
import io.sentry.protocol.SentryTransaction
import io.sentry.protocol.User
import io.sentry.test.callMethod
import io.sentry.transport.ITransport
import io.sentry.transport.ITransportGate
import org.junit.Assert.assertArrayEquals
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.io.InputStreamReader
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
import java.nio.charset.Charset
import java.nio.file.Files
import java.util.Arrays
import java.util.UUID
import kotlin.test.Ignore
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
class SentryClientTest {
class Fixture {
var transport = mock<ITransport>()
var factory = mock<ITransportFactory>()
val maxAttachmentSize: Long = 5 * 1024 * 1024
val hub = mock<IHub>()
val sentryTracer = SentryTracer(TransactionContext("a-transaction", "op"), hub)
var sentryOptions: SentryOptions = SentryOptions().apply {
dsn = dsnString
sdkVersion = SdkVersion("test", "1.2.3")
setDebug(true)
setDiagnosticLevel(SentryLevel.DEBUG)
setSerializer(GsonSerializer(this))
setLogger(mock())
maxAttachmentSize = this@Fixture.maxAttachmentSize
setTransportFactory(factory)
release = "0.0.1"
isTraceSampling = true
}
init {
whenever(factory.create(any(), any())).thenReturn(transport)
whenever(hub.options).thenReturn(sentryOptions)
}
var attachment = Attachment("hello".toByteArray(), "hello.txt", "text/plain", true)
val profilingTraceFile = Files.createTempFile("trace", ".trace").toFile()
var profilingTraceData = ProfilingTraceData(profilingTraceFile, sentryTracer, "1", 0, { emptyList() }, "", "", "", false, "", "", "", "", "")
var profilingNonExistingTraceData = ProfilingTraceData(File("non_existent.trace"), sentryTracer, "1", 0, { emptyList() }, "", "", "", false, "", "", "", "", "")
fun getSut() = SentryClient(sentryOptions)
}
private val fixture = Fixture()
@Test
fun `when fixture is unchanged, client is enabled`() {
val sut = fixture.getSut()
assertTrue(sut.isEnabled)
}
@Test
@Ignore("Not implemented")
fun `when dsn is an invalid string, client is disabled`() {
fixture.sentryOptions.dsn = "invalid-dsn"
val sut = fixture.getSut()
assertFalse(sut.isEnabled)
}
@Test
fun `when dsn is an invalid string, client throws`() {
fixture.sentryOptions.setTransportFactory(NoOpTransportFactory.getInstance())
fixture.sentryOptions.dsn = "invalid-dsn"
assertFailsWith<IllegalArgumentException> { fixture.getSut() }
}
@Test
@Ignore("Not implemented")
fun `when dsn is null, client is disabled`() {
fixture.sentryOptions.dsn = null
val sut = fixture.getSut()
assertFalse(sut.isEnabled)
}
@Test
fun `when dsn without private key is valid, client is enabled`() {
fixture.sentryOptions.dsn = dsnString
val sut = fixture.getSut()
assertTrue(sut.isEnabled)
}
@Test
fun `when dsn with secret is valid, client is enabled`() {
fixture.sentryOptions.dsn = dsnStringLegacy
val sut = fixture.getSut()
assertTrue(sut.isEnabled)
}
@Test
fun `when client is closed, client gets disabled`() {
val sut = fixture.getSut()
assertTrue(sut.isEnabled)
sut.close()
assertFalse(sut.isEnabled)
}
@Test
fun `when client is closed, hostname cache is closed`() {
val sut = fixture.getSut()
assertTrue(sut.isEnabled)
sut.close()
val mainEventProcessor = fixture.sentryOptions.eventProcessors
.filterIsInstance<MainEventProcessor>()
.first()
assertTrue(mainEventProcessor.isClosed)
}
@Test
fun `when beforeSend is set, callback is invoked`() {
var invoked = false
fixture.sentryOptions.setBeforeSend { e, _ -> invoked = true; e }
val sut = fixture.getSut()
sut.captureEvent(SentryEvent())
assertTrue(invoked)
}
@Test
fun `when beforeSend is returns null, event is dropped`() {
fixture.sentryOptions.setBeforeSend { _: SentryEvent, _: Any? -> null }
val sut = fixture.getSut()
val event = SentryEvent()
sut.captureEvent(event)
verify(fixture.transport, never()).send(any(), anyOrNull())
}
@Test
fun `when beforeSend is returns new instance, new instance is sent`() {
val expected = SentryEvent().apply {
setTag("test", "test")
}
fixture.sentryOptions.setBeforeSend { _, _ -> expected }
val sut = fixture.getSut()
val actual = SentryEvent()
sut.captureEvent(actual)
verify(fixture.transport).send(
check {
val event = getEventFromData(it.items.first().data)
assertEquals("test", event.tags!!["test"])
},
anyOrNull()
)
verifyNoMoreInteractions(fixture.transport)
}
@Test
fun `when beforeSend throws an exception, breadcrumb is added and event is sent`() {
val exception = Exception("test")
exception.stackTrace.toString()
fixture.sentryOptions.setBeforeSend { _, _ -> throw exception }
val sut = fixture.getSut()
val actual = SentryEvent()
sut.captureEvent(actual)
assertNotNull(actual.breadcrumbs) {
assertEquals("test", it.first().data["sentry:message"])
assertEquals("SentryClient", it.first().category)
assertEquals(SentryLevel.ERROR, it.first().level)
assertEquals("BeforeSend callback failed.", it.first().message)
}
}
@Test
fun `when event captured with hint, hint passed to connection`() {
val event = SentryEvent()
fixture.sentryOptions.environment = "not to be applied"
val sut = fixture.getSut()
val expectedHint = Object()
sut.captureEvent(event, expectedHint)
verify(fixture.transport).send(any(), eq(expectedHint))
}
@Test
fun `when captureMessage is called, sentry event contains formatted message`() {
var sentEvent: SentryEvent? = null
fixture.sentryOptions.setBeforeSend { e, _ -> sentEvent = e; e }
val sut = fixture.getSut()
val actual = "actual message"
sut.callMethod(
"captureMessage",
parameterTypes = arrayOf(
String::class.java,
SentryLevel::class.java,
Scope::class.java
),
actual,
null,
null
)
assertEquals(actual, sentEvent!!.message!!.formatted)
}
@Test
fun `when captureMessage is called, sentry event contains level`() {
var sentEvent: SentryEvent? = null
fixture.sentryOptions.setBeforeSend { e, _ -> sentEvent = e; e }
val sut = fixture.getSut()
sut.callMethod(
"captureMessage",
parameterTypes = arrayOf(String::class.java, SentryLevel::class.java),
null,
SentryLevel.DEBUG
)
assertEquals(SentryLevel.DEBUG, sentEvent!!.level)
}
@Test
fun `when event has release, value from options not applied`() {
val event = SentryEvent()
val expected = "original"
fixture.sentryOptions.environment = "not to be applied"
event.release = expected
val sut = fixture.getSut()
sut.captureEvent(event)
assertEquals(expected, event.release)
}
@Test
fun `when event doesn't have release, value from options applied`() {
val event = SentryEvent()
val expected = "original"
fixture.sentryOptions.release = expected
val sut = fixture.getSut()
sut.captureEvent(event)
assertEquals(expected, event.release)
}
@Test
fun `when event has environment, value from options not applied`() {
val event = SentryEvent()
val expected = "original"
fixture.sentryOptions.environment = "not to be applied"
event.environment = expected
val sut = fixture.getSut()
sut.captureEvent(event)
assertEquals(expected, event.environment)
}
@Test
fun `when event doesn't have environment, value from options applied`() {
val event = SentryEvent()
val expected = "original"
fixture.sentryOptions.environment = expected
val sut = fixture.getSut()
sut.captureEvent(event)
assertEquals(expected, event.environment)
}
@Test
fun `when captureEvent with scope, event should have its data if not set`() {
val event = SentryEvent()
val scope = createScope()
val sut = fixture.getSut()
sut.captureEvent(event, scope)
assertEquals("message", event.breadcrumbs!![0].message)
assertNotNull(event.extras) {
assertEquals("extra", it["extra"])
}
assertEquals("tags", event.tags!!["tags"])
assertNotNull(event.fingerprints) {
assertEquals("fp", it[0])
}
assertNotNull(event.user) {
assertEquals("id", it.id)
}
assertEquals(SentryLevel.FATAL, event.level)
assertNotNull(event.request) {
assertEquals("post", it.method)
}
}
@Test
fun `when breadcrumbs are not empty, sort them out by date`() {
val b1 = Breadcrumb(DateUtils.getDateTime("2020-03-27T08:52:58.001Z"))
val b2 = Breadcrumb(DateUtils.getDateTime("2020-03-27T08:52:58.002Z"))
val scope = Scope(SentryOptions()).apply {
addBreadcrumb(b2)
addBreadcrumb(b1)
}
val sut = fixture.getSut()
val b3 = Breadcrumb(DateUtils.getDateTime("2020-03-27T08:52:58.003Z"))
val event = SentryEvent().apply {
breadcrumbs = mutableListOf(b3)
}
sut.captureEvent(event, scope)
assertNotNull(event.breadcrumbs) {
assertSame(b1, it[0])
assertSame(b2, it[1])
assertSame(b3, it[2])
}
}
@Test
fun `when captureEvent with scope, event data has priority over scope but level and it should append extras, tags and breadcrumbs`() {
val event = createEvent()
val scope = createScope()
val sut = fixture.getSut()
sut.captureEvent(event, scope)
// breadcrumbs are appending
assertNotNull(event.breadcrumbs) {
assertEquals("eventMessage", it[0].message)
assertEquals("message", it[1].message)
}
// extras are appending
assertNotNull(event.extras) {
assertEquals("eventExtra", it["eventExtra"])
assertEquals("extra", it["extra"])
}
// tags are appending
assertNotNull(event.tags) {
assertEquals("eventTag", it["eventTag"])
assertEquals("tags", it["tags"])
}
// fingerprint is replaced
assertNotNull(event.fingerprints) {
assertEquals("eventFp", it[0])
assertEquals(1, it.size)
}
assertEquals("eventTransaction", event.transaction)
assertNotNull(event.user) {
assertEquals("eventId", it.id)
}
assertEquals(SentryLevel.FATAL, event.level)
}
@Test
fun `when captureEvent with scope, event extras and tags are only append if key is absent`() {
val event = createEvent()
val scope = createScope()
scope.setExtra("eventExtra", "extra")
scope.setTag("eventTag", "tags")
val sut = fixture.getSut()
sut.captureEvent(event, scope)
// extras are appending
assertNotNull(event.extras) {
assertEquals("eventExtra", it["eventExtra"])
}
// tags are appending
assertNotNull(event.tags) {
assertEquals("eventTag", it["eventTag"])
}
}
@Test
fun `when captureEvent with scope, event should have its level if set`() {
val event = SentryEvent()
event.level = SentryLevel.DEBUG
val scope = createScope()
val sut = fixture.getSut()
sut.captureEvent(event, scope)
assertEquals(SentryLevel.FATAL, event.level)
}
@Test
fun `when captureEvent with sampling, some events not captured`() {
fixture.sentryOptions.sampleRate = 0.000000001
val sut = fixture.getSut()
val allEvents = 10
(0..allEvents).forEach { _ -> sut.captureEvent(SentryEvent()) }
assertTrue(allEvents > mockingDetails(fixture.transport).invocations.size)
}
@Test
fun `when captureEvent without sampling, all events are captured`() {
fixture.sentryOptions.sampleRate = null
val sut = fixture.getSut()
val allEvents = 10
(0..allEvents).forEach { _ -> sut.captureEvent(SentryEvent()) }
assertEquals(
allEvents,
mockingDetails(fixture.transport).invocations.size - 1
) // 1 extra invocation outside .send()
}
@Test
fun `when captureEvent with attachments`() {
val event = createEvent()
fixture.getSut().captureEvent(event, createScopeWithAttachments())
verifyAttachmentsInEnvelope(event.eventId)
}
@Test
fun `when captureUserFeedback with empty id, envelope is not sent`() {
val sut = fixture.getSut()
sut.captureUserFeedback(UserFeedback(SentryId.EMPTY_ID))
verify(fixture.transport, never()).send(any(), anyOrNull())
}
@Test
fun `when captureUserFeedback, envelope is sent`() {
val sut = fixture.getSut()
sut.captureUserFeedback(userFeedback)
verify(fixture.transport).send(
check { actual ->
assertEquals(userFeedback.eventId, actual.header.eventId)
assertEquals(fixture.sentryOptions.sdkVersion, actual.header.sdkVersion)
assertEquals(1, actual.items.count())
val item = actual.items.first()
assertEquals(SentryItemType.UserFeedback, item.header.type)
assertEquals("application/json", item.header.contentType)
assertEnvelopeItemDataForUserFeedback(item)
}
)
}
private fun assertEnvelopeItemDataForUserFeedback(item: SentryEnvelopeItem) {
val stream = ByteArrayOutputStream()
val writer = stream.bufferedWriter(Charset.forName("UTF-8"))
fixture.sentryOptions.serializer.serialize(userFeedback, writer)
val expectedData = stream.toByteArray()
assertTrue(Arrays.equals(expectedData, item.data))
}
@Test
fun `when captureUserFeedback and connection throws, log exception`() {
val sut = fixture.getSut()
val exception = IOException("No connection")
whenever(fixture.transport.send(any())).thenThrow(exception)
val logger = mock<ILogger>()
fixture.sentryOptions.setLogger(logger)
sut.captureUserFeedback(userFeedback)
verify(logger)
.log(
SentryLevel.WARNING, exception,
"Capturing user feedback %s failed.", userFeedback.eventId
)
}
@Test
fun `when hint is Cached, scope is not applied`() {
val sut = fixture.getSut()
val event = SentryEvent()
val scope = Scope(SentryOptions())
scope.level = SentryLevel.FATAL
sut.captureEvent(event, scope, mock<Cached>())
assertNotEquals(scope.level, event.level)
}
@Test
fun `when hint is not Cached, scope is applied`() {
val sut = fixture.getSut()
val event = SentryEvent()
val scope = Scope(SentryOptions())
scope.level = SentryLevel.FATAL
sut.captureEvent(event, scope, Object())
assertEquals(scope.level, event.level)
}
@Test
fun `when hint is ApplyScopeData, scope is applied`() {
val sut = fixture.getSut()
val event = SentryEvent()
val scope = Scope(SentryOptions())
scope.level = SentryLevel.FATAL
sut.captureEvent(event, scope, mock<ApplyScopeData>())
assertEquals(scope.level, event.level)
}
@Test
fun `when hint is Cached but also ApplyScopeData, scope is applied`() {
val sut = fixture.getSut()
val event = SentryEvent()
val scope = Scope(SentryOptions())
scope.level = SentryLevel.FATAL
sut.captureEvent(event, scope, mock<CustomCachedApplyScopeDataHint>())
assertEquals(scope.level, event.level)
}
@Test
fun `when transport factory is NoOp, it should initialize it`() {
fixture.sentryOptions.setTransportFactory(NoOpTransportFactory.getInstance())
fixture.getSut()
assertTrue(fixture.sentryOptions.transportFactory is AsyncHttpTransportFactory)
}
@Test
fun `when transport factory is set on options, it should use the custom transport factory`() {
val sentryOptions: SentryOptions = SentryOptions().apply {
dsn = dsnString
}
val transportFactory = mock<ITransportFactory>()
sentryOptions.setTransportFactory(transportFactory)
SentryClient(sentryOptions)
assertEquals(transportFactory, sentryOptions.transportFactory)
}
@Test
fun `when transport gate is set on options, it should use the custom transport gate`() {
val sentryOptions: SentryOptions = SentryOptions().apply {
dsn = dsnString
}
val transportGate = CustomTransportGate()
sentryOptions.setTransportGate(transportGate)
SentryClient(sentryOptions)
assertEquals(transportGate, sentryOptions.transportGate)
}
@Test
fun `when transport gate is null, it should init an always on transport gate`() {
val sentryOptions: SentryOptions = SentryOptions().apply {
dsn = dsnString
}
SentryClient(sentryOptions)
assertNotNull(sentryOptions.transportGate)
assertTrue(sentryOptions.transportGate.isConnected)
}
@Test
fun `when scope has event processors, they should be applied`() {
val event = SentryEvent()
val scope = createScope()
val processor = mock<EventProcessor>()
whenever(processor.process(any<SentryEvent>(), anyOrNull())).thenReturn(event)
scope.addEventProcessor(processor)
val sut = fixture.getSut()
sut.captureEvent(event, scope)
verify(processor).process(eq(event), anyOrNull())
}
@Test
fun `when scope has event processors, apply for transactions`() {
val transaction = SentryTransaction(fixture.sentryTracer)
val scope = createScope()
val processor = mock<EventProcessor>()
whenever(processor.process(any<SentryTransaction>(), anyOrNull())).thenReturn(transaction)
scope.addEventProcessor(processor)
val sut = fixture.getSut()
sut.captureTransaction(transaction, scope, null)
verify(processor).process(eq(transaction), anyOrNull())
}
@Test
fun `when options have event processors, they should be applied`() {
val processor = mock<EventProcessor>()
fixture.sentryOptions.addEventProcessor(processor)
val event = SentryEvent()
fixture.getSut().captureEvent(event)
verify(processor).process(eq(event), anyOrNull())
}
@Test
fun `when options have event processors, apply for transactions`() {
val processor = mock<EventProcessor>()
fixture.sentryOptions.addEventProcessor(processor)
val transaction = SentryTransaction(fixture.sentryTracer)
fixture.getSut().captureTransaction(transaction, fixture.sentryTracer.traceState())
verify(processor).process(eq(transaction), anyOrNull())
}
@Test
fun `when captureSession and no release is set, do nothing`() {
fixture.getSut().captureSession(createSession(""))
verify(fixture.transport, never()).send(any(), anyOrNull())
}
@Test
fun `when captureSession and release is set, send an envelope`() {
fixture.getSut().captureSession(createSession())
verify(fixture.transport).send(any(), anyOrNull())
}
@Test
fun `when captureSession, sdkInfo should be in the envelope header`() {
fixture.getSut().captureSession(createSession())
verify(fixture.transport).send(
check {
assertNotNull(it.header.sdkVersion)
},
anyOrNull()
)
}
@Test
fun `when captureEnvelope and thres an exception, returns empty sentryId`() {
whenever(fixture.transport.send(any(), anyOrNull())).thenThrow(IOException())
val envelope = SentryEnvelope(SentryId(UUID.randomUUID()), null, setOf())
val sentryId = fixture.getSut().captureEnvelope(envelope)
assertEquals(SentryId.EMPTY_ID, sentryId)
}
@Test
fun `when captureEnvelope and theres no exception, returns envelope header id`() {
val expectedSentryId = SentryId(UUID.randomUUID())
val envelope = SentryEnvelope(expectedSentryId, null, setOf())
val sentryId = fixture.getSut().captureEnvelope(envelope)
assertEquals(expectedSentryId, sentryId)
}
@Test
fun `When event is non handled, mark session as Crashed`() {
val scope = Scope(fixture.sentryOptions)
scope.startSession()
val event = SentryEvent().apply {
exceptions = createNonHandledException()
}
fixture.getSut().updateSessionData(event, null, scope)
scope.withSession {
assertEquals(Session.State.Crashed, it!!.status)
}
}
@Test
fun `When event is handled, keep level as it is`() {
val scope = Scope(fixture.sentryOptions)
val sessionPair = scope.startSession()
assertNotNull(sessionPair) {
val session = it.current
val level = session.status
val event = SentryEvent()
fixture.getSut().updateSessionData(event, null, scope)
assertEquals(level, session.status)
}
}
@Test
fun `When event is non handled, increase errorCount`() {
val scope = Scope(fixture.sentryOptions)
scope.startSession()
val event = SentryEvent().apply {
exceptions = createNonHandledException()
}
fixture.getSut().updateSessionData(event, null, scope)
scope.withSession {
assertEquals(1, it!!.errorCount())
}
}
@Test
fun `When event is Errored, increase errorCount`() {
val scope = Scope(fixture.sentryOptions)
scope.startSession()
val exceptions = mutableListOf<SentryException>()
exceptions.add(SentryException())
val event = SentryEvent().apply {
setExceptions(exceptions)
}
fixture.getSut().updateSessionData(event, null, scope)
scope.withSession {
assertEquals(1, it!!.errorCount())
}
}
@Test
fun `When event is handled and not errored, do not increase errorsCount`() {
val scope = Scope(fixture.sentryOptions)
val sessionPair = scope.startSession()
assertNotNull(sessionPair) {
val session = it.current
val errorCount = session.errorCount()
val event = SentryEvent()
fixture.getSut().updateSessionData(event, null, scope)
assertEquals(errorCount, session.errorCount())
}
}
@Test
fun `When event has userAgent, set it into session`() {
val scope = Scope(fixture.sentryOptions)
val sessionPair = scope.startSession()
assertNotNull(sessionPair) {
val event = SentryEvent().apply {
request = Request().apply {
headers = mutableMapOf("user-agent" to "jamesBond")
}
}
fixture.getSut().updateSessionData(event, null, scope)
scope.withSession {
assertEquals("jamesBond", it!!.userAgent)
}
}
}
@Test
fun `When event has no userAgent, keep as it is`() {
val scope = Scope(fixture.sentryOptions)
val sessionPair = scope.startSession()
assertNotNull(sessionPair) {
val session = it.current
val userAgent = session.userAgent
val event = SentryEvent().apply {
request = Request().apply {
headers = mutableMapOf()
}
}
fixture.getSut().updateSessionData(event, null, scope)
assertEquals(userAgent, session.userAgent)
}
}
@Test
fun `When capture an event and there's no session, do nothing`() {
val scope = Scope(fixture.sentryOptions)
val event = SentryEvent()
fixture.getSut().updateSessionData(event, null, scope)
scope.withSession {
assertNull(it)
}
}
@Test
fun `when captureEvent with sampling, session is still updated`() {
fixture.sentryOptions.sampleRate = 1.0
val sut = fixture.getSut()
val event = SentryEvent().apply {
exceptions = createNonHandledException()
}
val scope = Scope(fixture.sentryOptions)
val sessionPair = scope.startSession()
assertNotNull(sessionPair) {
sut.captureEvent(event, scope, null)
scope.withSession {
assertEquals(Session.State.Crashed, it!!.status)
assertEquals(1, it.errorCount())
}
}
}
@Test
fun `when context property is missing on the event, property from scope contexts is applied`() {
val sut = fixture.getSut()
val scope = Scope(fixture.sentryOptions)
scope.setContexts("key", "abc")
val sessionPair = scope.startSession()
assertNotNull(sessionPair) {
sut.captureEvent(SentryEvent(), scope, null)
verify(fixture.transport).send(
check {
val event = getEventFromData(it.items.first().data)
val map = event.contexts["key"] as Map<*, *>
assertEquals("abc", map["value"])
},
anyOrNull()
)
}
}
@Test
fun `when contexts property is set on the event, property from scope contexts is not applied`() {
val sut = fixture.getSut()
val event = SentryEvent()
event.contexts["key"] = "event value"
val scope = Scope(fixture.sentryOptions)
scope.setContexts("key", "scope value")
val sessionPair = scope.startSession()
assertNotNull(sessionPair) {
sut.captureEvent(event, scope, null)
verify(fixture.transport).send(
check {
val eventFromData = getEventFromData(it.items.first().data)
assertEquals("event value", eventFromData.contexts["key"])
},
anyOrNull()
)
}
}
@Test
fun `when contexts are not objects, wrap it up within a value object`() {
val sut = fixture.getSut()
val event = SentryEvent()
val scope = Scope(fixture.sentryOptions)
scope.setContexts("boolean", true)
scope.setContexts("string", "test")
scope.setContexts("number", 1.0)
scope.setContexts("collection", listOf("a", "b"))
scope.setContexts("array", arrayOf("a", "b"))
scope.setContexts("char", 'a')
sut.captureEvent(event, scope, null)
verify(fixture.transport).send(
check {
val contexts = getEventFromData(it.items.first().data).contexts
val bolKey = contexts["boolean"] as Map<*, *>
assertTrue(bolKey["value"] as Boolean)
val strKey = contexts["string"] as Map<*, *>
assertEquals("test", strKey["value"])
val numKey = contexts["number"] as Map<*, *>
assertEquals(1.0, numKey["value"])
val listKey = contexts["collection"] as Map<*, *>
assertEquals("a", (listKey["value"] as List<*>)[0])
assertEquals("b", (listKey["value"] as List<*>)[1])
val arrKey = contexts["array"] as Map<*, *>
assertEquals("a", (arrKey["value"] as List<*>)[0])
assertEquals("b", (arrKey["value"] as List<*>)[1])
val charKey = contexts["char"] as Map<*, *>
assertEquals("a", charKey["value"])
},
anyOrNull()
)
}
@Test
fun `exception thrown by an event processor is handled gracefully`() {
fixture.sentryOptions.addEventProcessor(eventProcessorThrows())
val sut = fixture.getSut()
sut.captureEvent(SentryEvent())
}
@Test
fun `transactions are sent using connection`() {
val sut = fixture.getSut()
sut.captureTransaction(
SentryTransaction(fixture.sentryTracer),
Scope(fixture.sentryOptions),
null
)
verify(fixture.transport).send(
check {
val transaction = it.items.first().getTransaction(fixture.sentryOptions.serializer)
assertNotNull(transaction)
assertEquals("a-transaction", transaction.transaction)
},
eq(null)
)
}
@Test
fun `when captureTransaction with attachments`() {
val transaction = SentryTransaction(fixture.sentryTracer)
fixture.getSut().captureTransaction(transaction, createScopeWithAttachments(), null)
verifyAttachmentsInEnvelope(transaction.eventId)
assertFails { verifyProfilingTraceInEnvelope(transaction.eventId) }
}
@Test
fun `when captureTransaction with attachments and profiling data`() {
val transaction = SentryTransaction(fixture.sentryTracer)
fixture.getSut().captureTransaction(transaction, null, createScopeWithAttachments(), null, fixture.profilingTraceData)
verifyAttachmentsInEnvelope(transaction.eventId)
verifyProfilingTraceInEnvelope(transaction.eventId)
}
@Test
fun `when captureTransaction with profiling data`() {
val transaction = SentryTransaction(fixture.sentryTracer)
fixture.getSut().captureTransaction(transaction, null, null, null, fixture.profilingTraceData)
assertFails { verifyAttachmentsInEnvelope(transaction.eventId) }
verifyProfilingTraceInEnvelope(transaction.eventId)
}
@Test
fun `when captureTransaction with non existing profiling trace file, profiling trace data is not sent`() {
val transaction = SentryTransaction(fixture.sentryTracer)
fixture.getSut().captureTransaction(transaction, null, createScopeWithAttachments(), null, fixture.profilingNonExistingTraceData)
verifyAttachmentsInEnvelope(transaction.eventId)
assertFails { verifyProfilingTraceInEnvelope(transaction.eventId) }
}
@Test
fun `when captureTransaction with attachments not added to transaction`() {
val transaction = SentryTransaction(fixture.sentryTracer)
val scope = createScopeWithAttachments()
scope.addAttachment(Attachment("hello".toByteArray(), "application/octet-stream"))
fixture.getSut().captureTransaction(transaction, scope, null)
verifyAttachmentsInEnvelope(transaction.eventId)
}
@Test
fun `when captureTransaction scope is applied to transaction`() {
val sut = fixture.getSut()
val scope = Scope(fixture.sentryOptions)
scope.setTag("tag1", "value1")
scope.setContexts("context-key", "context-value")
scope.request = Request().apply {
url = "/url"
}
scope.addBreadcrumb(Breadcrumb("message"))
scope.setExtra("a", "b")
sut.captureTransaction(SentryTransaction(fixture.sentryTracer), scope, null)
verify(fixture.transport).send(
check { envelope ->
val transaction =
envelope.items.first().getTransaction(fixture.sentryOptions.serializer)
assertNotNull(transaction) {
assertEquals("value1", it.getTag("tag1"))
assertEquals(mapOf("value" to "context-value"), it.contexts["context-key"])
assertNotNull(it.request) { request ->
assertEquals("/url", request.url)
}
assertNotNull(it.breadcrumbs) { breadcrumbs ->
assertEquals("message", breadcrumbs.first().message)
}
assertEquals("b", it.getExtra("a"))