forked from getsentry/sentry-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSentryTest.kt
More file actions
1718 lines (1454 loc) · 50.4 KB
/
SentryTest.kt
File metadata and controls
1718 lines (1454 loc) · 50.4 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
package io.sentry
import io.sentry.SentryFeedbackOptions.IDialogHandler
import io.sentry.SentryOptions.ProfilesSamplerCallback
import io.sentry.SentryOptions.TracesSamplerCallback
import io.sentry.backpressure.BackpressureMonitor
import io.sentry.backpressure.NoOpBackpressureMonitor
import io.sentry.cache.EnvelopeCache
import io.sentry.cache.IEnvelopeCache
import io.sentry.internal.debugmeta.IDebugMetaLoader
import io.sentry.internal.debugmeta.ResourcesDebugMetaLoader
import io.sentry.internal.modules.CompositeModulesLoader
import io.sentry.internal.modules.IModulesLoader
import io.sentry.internal.modules.NoOpModulesLoader
import io.sentry.protocol.Feedback
import io.sentry.protocol.SdkVersion
import io.sentry.protocol.SentryId
import io.sentry.protocol.SentryThread
import io.sentry.test.ImmediateExecutorService
import io.sentry.test.createSentryClientMock
import io.sentry.test.initForTest
import io.sentry.test.injectForField
import io.sentry.util.PlatformTestManipulator
import io.sentry.util.thread.IThreadChecker
import io.sentry.util.thread.ThreadChecker
import java.io.Closeable
import java.io.File
import java.io.FileReader
import java.nio.file.Files
import java.util.Properties
import java.util.concurrent.CompletableFuture
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNotSame
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
import org.awaitility.kotlin.await
import org.junit.Assert.assertThrows
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.argThat
import org.mockito.kotlin.check
import org.mockito.kotlin.eq
import org.mockito.kotlin.inOrder
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
class SentryTest {
private val dsn = "http://key@localhost/proj"
@get:Rule val tmpDir = TemporaryFolder()
@BeforeTest
@AfterTest
fun beforeTest() {
Sentry.close()
SentryCrashLastRunState.getInstance().reset()
}
@Test
fun `init multiple times calls scopes close with isRestarting true`() {
val scopes = mock<IScopes>()
initForTest { it.dsn = dsn }
Sentry.setCurrentScopes(scopes)
initForTest { it.dsn = dsn }
verify(scopes).close(eq(true))
}
@Test
fun `init multiple times calls close on previous options not new`() {
val profiler1 = mock<ITransactionProfiler>()
val profiler2 = mock<ITransactionProfiler>()
initForTest {
it.dsn = dsn
it.setTransactionProfiler(profiler1)
}
verify(profiler1, never()).close()
initForTest {
it.dsn = dsn
it.setTransactionProfiler(profiler2)
}
verify(profiler2, never()).close()
verify(profiler1).close()
Sentry.close()
verify(profiler2).close()
}
@Test
fun `init multiple times calls close on previous integrations not new`() {
val integration1 = mock<CloseableIntegration>()
val integration2 = mock<CloseableIntegration>()
initForTest {
it.dsn = dsn
it.addIntegration(integration1)
}
verify(integration1, never()).close()
initForTest {
it.dsn = dsn
it.addIntegration(integration2)
}
verify(integration2, never()).close()
verify(integration1).close()
Sentry.close()
verify(integration2).close()
}
@Test
fun `if a single integration crashes, the SDK and other integrations are still initialized`() {
val goodIntegrationInitialized = AtomicBoolean(false)
val goodIntegration = Integration { scopes, options ->
// no-op
goodIntegrationInitialized.set(true)
}
val badIntegration = Integration { scopes, options ->
throw IllegalStateException("bad integration")
}
initForTest {
it.dsn = dsn
it.integrations.clear()
it.integrations.add(badIntegration)
it.integrations.add(goodIntegration)
}
assertTrue(Sentry.isEnabled())
assertTrue(goodIntegrationInitialized.get())
}
interface CloseableIntegration : Integration, Closeable
@Test
fun `global client is enabled after restart`() {
val scopes = mock<IScopes>()
whenever(scopes.close()).then { Sentry.getGlobalScope().client.close() }
whenever(scopes.close(anyOrNull())).then { Sentry.getGlobalScope().client.close() }
initForTest { it.dsn = dsn }
Sentry.setCurrentScopes(scopes)
initForTest { it.dsn = dsn }
verify(scopes).close(eq(true))
assertTrue(Sentry.getGlobalScope().client.isEnabled)
}
@Test
fun `global client is disabled after close`() {
val scopes = mock<IScopes>()
whenever(scopes.close()).then { Sentry.getGlobalScope().client.close() }
whenever(scopes.close(anyOrNull())).then { Sentry.getGlobalScope().client.close() }
initForTest { it.dsn = dsn }
Sentry.setCurrentScopes(scopes)
Sentry.close()
verify(scopes).close(eq(false))
assertFalse(Sentry.getGlobalScope().client.isEnabled)
}
@Test
fun `close calls scopes close with isRestarting false`() {
val scopes = mock<IScopes>()
initForTest { it.dsn = dsn }
Sentry.setCurrentScopes(scopes)
Sentry.close()
verify(scopes).close(eq(false))
}
@Test
fun `outboxPath should be created at initialization`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.cacheDirPath = getTempPath()
sentryOptions = it
}
val file = File(sentryOptions!!.outboxPath!!)
assertTrue(file.exists())
file.deleteOnExit()
}
@Test
fun `cacheDirPath should be created at initialization`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.cacheDirPath = getTempPath()
sentryOptions = it
}
val file = File(sentryOptions!!.cacheDirPath!!)
assertTrue(file.exists())
file.deleteOnExit()
}
@Test
fun `getCacheDirPathWithoutDsn should be created at initialization`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.cacheDirPath = getTempPath()
sentryOptions = it
}
val cacheDirPathWithoutDsn = sentryOptions!!.cacheDirPathWithoutDsn!!
val file = File(cacheDirPathWithoutDsn)
assertTrue(file.exists())
file.deleteOnExit()
}
@Test
fun `Init sets SystemOutLogger if logger is NoOp and debug is enabled`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.cacheDirPath = getTempPath()
sentryOptions = it
it.setDebug(true)
}
assertTrue((sentryOptions!!.logger as DiagnosticLogger).logger is SystemOutLogger)
}
@Test
fun `scope changes are isolated to a thread`() {
initForTest { it.dsn = dsn }
Sentry.configureScope { it.setTag("a", "a") }
CompletableFuture.runAsync {
Sentry.configureScope { it.setTag("b", "b") }
Sentry.configureScope { assertEquals(setOf("a", "b"), it.tags.keys) }
}
.get()
Sentry.configureScope { assertEquals(setOf("a"), it.tags.keys) }
}
@Test
fun `warns about multiple Sentry initializations`() {
val logger = mock<ILogger>()
initForTest { it.dsn = dsn }
initForTest {
it.dsn = dsn
it.setDebug(true)
it.setLogger(logger)
}
verify(logger)
.log(
eq(SentryLevel.WARNING),
eq("Sentry has been already initialized. Previous configuration will be overwritten."),
)
}
@Test
fun `warns about multiple Sentry initializations with string overload`() {
val logger = mock<ILogger>()
initForTest(dsn)
initForTest {
it.dsn = dsn
it.setDebug(true)
it.setLogger(logger)
}
verify(logger)
.log(
eq(SentryLevel.WARNING),
eq("Sentry has been already initialized. Previous configuration will be overwritten."),
)
}
@Test
fun `initializes Sentry using external properties`() {
// create a sentry.properties file in temporary folder
val temporaryFolder = TemporaryFolder()
temporaryFolder.create()
val file = temporaryFolder.newFile("sentry.properties")
file.writeText("dsn=http://key@localhost/proj")
// set location of the sentry.properties file
System.setProperty("sentry.properties.file", file.absolutePath)
try {
// initialize Sentry with empty DSN and enable loading properties from external sources
initForTest { it.isEnableExternalConfiguration = true }
assertTrue(ScopesAdapter.getInstance().isEnabled)
} finally {
temporaryFolder.delete()
}
}
@Test
fun `initializes Sentry with enabled=false, thus disabling Sentry even if dsn is set`() {
initForTest {
it.isEnabled = false
it.dsn = "http://key@localhost/proj"
}
Sentry.setTag("none", "shouldNotExist")
var value: String? = null
Sentry.getCurrentScopes().configureScope { value = it.tags[value] }
assertTrue(Sentry.getCurrentScopes().isNoOp)
assertNull(value)
}
@Test
fun `initializes Sentry with enabled=false, thus disabling Sentry even if dsn is null`() {
initForTest { it.isEnabled = false }
Sentry.setTag("none", "shouldNotExist")
var value: String? = null
Sentry.getCurrentScopes().configureScope { value = it.tags[value] }
assertTrue(Sentry.getCurrentScopes().isNoOp)
assertNull(value)
}
@Test
fun `initializes Sentry with dsn = null, throwing IllegalArgumentException`() {
val exception = assertThrows(java.lang.IllegalArgumentException::class.java) { initForTest() }
assertEquals(
"DSN is required. Use empty string or set enabled to false in SentryOptions to disable SDK.",
exception.message,
)
}
@Test
fun `captureUserFeedback gets forwarded to client`() {
initForTest { it.dsn = dsn }
val client = createSentryClientMock()
Sentry.getCurrentScopes().bindClient(client)
val userFeedback = UserFeedback(SentryId.EMPTY_ID)
Sentry.captureUserFeedback(userFeedback)
verify(client).captureUserFeedback(argThat { eventId == userFeedback.eventId })
}
@Test
fun `startTransaction sets operation and description`() {
initForTest {
it.dsn = dsn
it.tracesSampleRate = 1.0
}
val transaction = Sentry.startTransaction("name", "op", "desc", TransactionOptions())
assertEquals("name", transaction.name)
assertEquals("op", transaction.operation)
assertEquals("desc", transaction.description)
}
@Test
fun `isCrashedLastRun returns true if crashedLastRun is set`() {
initForTest { it.dsn = dsn }
SentryCrashLastRunState.getInstance().setCrashedLastRun(true)
assertTrue(Sentry.isCrashedLastRun()!!)
}
@Test
fun `profilingTracesDirPath should be created and cleared at initialization when profiling is enabled`() {
val tempPath = getTempPath()
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.profilesSampleRate = 1.0
it.cacheDirPath = tempPath
sentryOptions = it
}
assertTrue(File(sentryOptions?.profilingTracesDirPath!!).exists())
assertTrue(File(sentryOptions?.profilingTracesDirPath!!).list()!!.isEmpty())
}
@Test
fun `profilingTracesDirPath should be created and cleared at initialization when continuous profiling is enabled`() {
val tempPath = getTempPath()
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.profileSessionSampleRate = 1.0
it.cacheDirPath = tempPath
sentryOptions = it
}
assertTrue(File(sentryOptions?.profilingTracesDirPath!!).exists())
assertTrue(File(sentryOptions?.profilingTracesDirPath!!).list()!!.isEmpty())
}
@Test
fun `profilingTracesDirPath should not be created when no profiling is enabled`() {
val tempPath = getTempPath()
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.profileSessionSampleRate = 0.0
it.cacheDirPath = tempPath
sentryOptions = it
}
assertFalse(File(sentryOptions?.profilingTracesDirPath!!).exists())
}
@Test
fun `only old profiles in profilingTracesDirPath should be cleared when profiling is enabled`() {
val tempPath = getTempPath()
val options =
SentryOptions().also {
it.dsn = dsn
it.cacheDirPath = tempPath
}
val dir = File(options.profilingTracesDirPath!!)
val oldProfile = File(dir, "oldProfile")
val newProfile = File(dir, "newProfile")
// Create all files
dir.mkdirs()
oldProfile.createNewFile()
newProfile.createNewFile()
// Make the old profile look like it's created earlier
oldProfile.setLastModified(10000)
// Make the new profile look like it's created later
newProfile.setLastModified(System.currentTimeMillis() + 10000)
// Assert both file exist
assertTrue(oldProfile.exists())
assertTrue(newProfile.exists())
initForTest {
it.dsn = dsn
it.profilesSampleRate = 1.0
it.cacheDirPath = tempPath
it.executorService = ImmediateExecutorService()
}
// Assert only the new profile exists
assertFalse(oldProfile.exists())
assertTrue(newProfile.exists())
}
@Test
fun `profilingTracesDirPath should not be created and cleared when profiling is disabled`() {
val tempPath = getTempPath()
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.profilesSampleRate = 0.0
it.cacheDirPath = tempPath
sentryOptions = it
}
assertFalse(File(sentryOptions?.profilingTracesDirPath!!).exists())
}
@Test
fun `using sentry before calling init creates NoOpScopes but after init Sentry uses a new clone`() {
// noop as not yet initialized, caches NoOpScopes in ThreadLocal
Sentry.captureMessage("noop caused")
assertTrue(Sentry.getCurrentScopes().isNoOp)
// init Sentry in another thread
val thread = Thread {
initForTest {
it.dsn = dsn
it.isDebug = true
}
}
thread.start()
thread.join()
Sentry.captureMessage("should work now")
val scopes = Sentry.getCurrentScopes()
assertNotNull(scopes)
assertFalse(scopes.isNoOp)
}
@Test
fun `main scopes can be cloned and does not share scope with current scopes`() {
// noop as not yet initialized, caches NoOpScopes in ThreadLocal
Sentry.addBreadcrumb("breadcrumbNoOp")
Sentry.captureMessage("messageNoOp")
assertTrue(Sentry.getCurrentScopes().isNoOp)
val capturedEvents = mutableListOf<SentryEvent>()
// init Sentry in another thread
val thread = Thread {
initForTest {
it.dsn = dsn
it.isDebug = true
it.beforeSend =
SentryOptions.BeforeSendCallback { event, hint ->
capturedEvents.add(event)
event
}
}
}
thread.start()
thread.join()
Sentry.addBreadcrumb("breadcrumbCurrent")
val scopes = Sentry.getCurrentScopes()
assertNotNull(scopes)
assertFalse(Sentry.getCurrentScopes().isNoOp)
val forkedRootScopes = Sentry.forkedRootScopes("test")
forkedRootScopes.addBreadcrumb("breadcrumbMainClone")
scopes.captureMessage("messageCurrent")
forkedRootScopes.captureMessage("messageMainClone")
assertEquals(2, capturedEvents.size)
val mainCloneEvent = capturedEvents.firstOrNull { it.message?.formatted == "messageMainClone" }
val currentScopesEvent =
capturedEvents.firstOrNull { it.message?.formatted == "messageCurrent" }
assertNotNull(mainCloneEvent)
assertNotNull(mainCloneEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbMainClone" })
assertNull(mainCloneEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbCurrent" })
assertNull(mainCloneEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbNoOp" })
assertNotNull(currentScopesEvent)
assertNull(currentScopesEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbMainClone" })
assertNotNull(currentScopesEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbCurrent" })
assertNull(currentScopesEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbNoOp" })
}
@Test
fun `main scopes is not cloned in global scopes mode and shares scope with current scopes`() {
// noop as not yet initialized, caches NoOpScopes in ThreadLocal
Sentry.addBreadcrumb("breadcrumbNoOp")
Sentry.captureMessage("messageNoOp")
assertTrue(Sentry.getCurrentScopes().isNoOp)
val capturedEvents = mutableListOf<SentryEvent>()
// init Sentry in another thread
val thread = Thread {
initForTest(
{
it.dsn = dsn
it.isDebug = true
it.beforeSend =
SentryOptions.BeforeSendCallback { event, hint ->
capturedEvents.add(event)
event
}
},
true,
)
}
thread.start()
thread.join()
Sentry.addBreadcrumb("breadcrumbCurrent")
val scopes = Sentry.getCurrentScopes()
assertNotNull(scopes)
assertFalse(scopes.isNoOp)
val forkedRootScopes = Sentry.forkedRootScopes("test")
forkedRootScopes.addBreadcrumb("breadcrumbMainClone")
scopes.captureMessage("messageCurrent")
forkedRootScopes.captureMessage("messageMainClone")
assertEquals(2, capturedEvents.size)
val mainCloneEvent = capturedEvents.firstOrNull { it.message?.formatted == "messageMainClone" }
val currentScopesEvent =
capturedEvents.firstOrNull { it.message?.formatted == "messageCurrent" }
assertNotNull(mainCloneEvent)
assertNotNull(mainCloneEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbMainClone" })
assertNotNull(mainCloneEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbCurrent" })
assertNull(mainCloneEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbNoOp" })
assertNotNull(currentScopesEvent)
assertNotNull(
currentScopesEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbMainClone" }
)
assertNotNull(currentScopesEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbCurrent" })
assertNull(currentScopesEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbNoOp" })
}
@Test
fun `when init is called and configure throws an exception then an error is logged`() {
val logger = mock<ILogger>()
val initException = Exception("init")
initForTest(
{
it.dsn = dsn
it.isDebug = true
it.setLogger(logger)
throw initException
},
true,
)
verify(logger).log(eq(SentryLevel.ERROR), any(), eq(initException))
}
@Test
fun `when init with a SentryOptions Subclass is called and configure throws an exception then an error is logged`() {
class ExtendedSentryOptions : SentryOptions()
val logger = mock<ILogger>()
val initException = Exception("init")
Sentry.init(OptionsContainer.create(ExtendedSentryOptions::class.java)) {
options: ExtendedSentryOptions ->
options.dsn = dsn
options.isDebug = true
options.setLogger(logger)
throw initException
}
verify(logger).log(eq(SentryLevel.ERROR), any(), eq(initException))
}
@Test
fun `overrides envelope cache if it's not set`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.cacheDirPath = getTempPath()
sentryOptions = it
}
assertTrue { sentryOptions!!.envelopeDiskCache is EnvelopeCache }
}
@Test
fun `does not override envelope cache if it's already set`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.cacheDirPath = getTempPath()
it.setEnvelopeDiskCache(CustomEnvelopCache())
sentryOptions = it
}
assertTrue { sentryOptions!!.envelopeDiskCache is CustomEnvelopCache }
}
@Test
fun `overrides modules loader if it's not set`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
sentryOptions = it
}
assertTrue { sentryOptions!!.modulesLoader is CompositeModulesLoader }
}
@Test
fun `does not override modules loader if it's already set`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.setModulesLoader(CustomModulesLoader())
sentryOptions = it
}
assertTrue { sentryOptions!!.modulesLoader is CustomModulesLoader }
}
@Test
fun `overrides debug meta loader if it's not set`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
sentryOptions = it
}
assertTrue { sentryOptions!!.debugMetaLoader is ResourcesDebugMetaLoader }
}
@Test
fun `does not override debug meta loader if it's already set`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.setDebugMetaLoader(CustomDebugMetaLoader())
sentryOptions = it
}
assertTrue { sentryOptions!!.debugMetaLoader is CustomDebugMetaLoader }
}
@Test
fun `overrides main thread checker if it's not set`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
sentryOptions = it
}
assertTrue { sentryOptions!!.threadChecker is ThreadChecker }
}
@Test
fun `does not override main thread checker if it's already set`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.threadChecker = CustomThreadChecker()
sentryOptions = it
}
assertTrue { sentryOptions!!.threadChecker is CustomThreadChecker }
}
@Test
fun `overrides collector if it's not set`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
sentryOptions = it
}
assertTrue { sentryOptions!!.performanceCollectors.any { it is JavaMemoryCollector } }
}
@Test
fun `does not override collector if it's already set`() {
var sentryOptions: SentryOptions? = null
initForTest {
it.dsn = dsn
it.addPerformanceCollector(CustomMemoryCollector())
sentryOptions = it
}
assertTrue { sentryOptions!!.performanceCollectors.any { it is CustomMemoryCollector } }
}
@Test
fun `init does not throw on executor shut down`() {
val logger = mock<ILogger>()
initForTest {
it.dsn = dsn
it.profilesSampleRate = 1.0
it.cacheDirPath = getTempPath()
it.setLogger(logger)
it.executorService.close(0)
it.isDebug = true
}
verify(logger)
.log(
eq(SentryLevel.ERROR),
eq(
"Failed to call the executor. Old profiles will not be deleted. Did you call Sentry.close()?"
),
any(),
)
}
@Test
fun `reportFullyDisplayed calls scopes reportFullyDisplayed`() {
val scopes = mock<IScopes>()
initForTest { it.dsn = dsn }
Sentry.setCurrentScopes(scopes)
Sentry.reportFullyDisplayed()
verify(scopes).reportFullyDisplayed()
}
@Test
fun `ignores executorService if it is closed`() {
var sentryOptions: SentryOptions? = null
val executorService = mock<ISentryExecutorService>()
whenever(executorService.isClosed).thenReturn(true)
initForTest {
it.dsn = dsn
it.executorService = executorService
sentryOptions = it
}
assertNotEquals(executorService, sentryOptions!!.executorService)
}
@Test
fun `accept executorService if it is not closed`() {
var sentryOptions: SentryOptions? = null
val executorService = mock<ISentryExecutorService>()
whenever(executorService.isClosed).thenReturn(false)
initForTest {
it.dsn = dsn
it.executorService = executorService
sentryOptions = it
}
assertEquals(executorService, sentryOptions!!.executorService)
}
@Test
fun `init notifies option observers`() {
val optionsObserver = InMemoryOptionsObserver()
initForTest {
it.dsn = dsn
it.executorService = ImmediateExecutorService()
it.addOptionsObserver(optionsObserver)
it.release = "[email protected]+220"
it.proguardUuid = "uuid"
it.dist = "220"
it.sdkVersion = SdkVersion("sentry.java.android", "6.13.0")
it.environment = "debug"
it.setTag("one", "two")
it.sessionReplay.onErrorSampleRate = 0.5
}
assertEquals("[email protected]+220", optionsObserver.release)
assertEquals("debug", optionsObserver.environment)
assertEquals("220", optionsObserver.dist)
assertEquals("uuid", optionsObserver.proguardUuid)
assertEquals(mapOf("one" to "two"), optionsObserver.tags)
assertEquals(SdkVersion("sentry.java.android", "6.13.0"), optionsObserver.sdkVersion)
assertEquals(0.5, optionsObserver.replayErrorSampleRate)
}
@Test
fun `if there is work enqueued, init notifies options observers after that work is done`() {
val optionsObserver =
InMemoryOptionsObserver().apply {
setRelease("[email protected]")
setEnvironment("production")
}
val triggered = AtomicBoolean(false)
initForTest {
it.dsn = dsn
it.addOptionsObserver(optionsObserver)
it.release = "[email protected]+220"
it.environment = "debug"
it.executorService.submit {
// here the values should be still old. Sentry.init will submit another runnable
// to notify the options observers, but because the executor is single-threaded, the
// work will be enqueued and the observers will be notified after current work is
// finished, ensuring that even if something is using the options observer from a
// different thread, it will still use the old values.
Thread.sleep(1000L)
assertEquals("[email protected]", optionsObserver.release)
assertEquals("production", optionsObserver.environment)
triggered.set(true)
}
}
await.untilTrue(triggered)
assertEquals("[email protected]+220", optionsObserver.release)
assertEquals("debug", optionsObserver.environment)
}
@Test
fun `init finalizes previous session`() {
lateinit var previousSessionFile: File
initForTest {
it.dsn = dsn
it.isDebug = true
it.setLogger(SystemOutLogger())
it.release = "[email protected]"
it.cacheDirPath = tmpDir.newFolder().absolutePath
it.executorService = ImmediateExecutorService()
previousSessionFile = EnvelopeCache.getPreviousSessionFile(it.cacheDirPath!!)
previousSessionFile.parentFile.mkdirs()
it.serializer.serialize(
previousSessionFile.bufferedWriter(),
)
assertEquals(
"release",
it.serializer
.deserialize(previousSessionFile.bufferedReader(), Session::class.java)!!
.environment,
)
it.sessionFlushTimeoutMillis = 100
}
assertFalse(previousSessionFile.exists())
}
@Test
fun `if there is work enqueued, init finalizes previous session after that work is done`() {
lateinit var previousSessionFile: File
val triggered = AtomicBoolean(false)
initForTest {
it.dsn = dsn
it.release = "[email protected]"
it.cacheDirPath = tmpDir.newFolder().absolutePath
previousSessionFile = EnvelopeCache.getPreviousSessionFile(it.cacheDirPath!!)
previousSessionFile.parentFile.mkdirs()
it.serializer.serialize(
previousSessionFile.bufferedWriter(),
)
it.executorService.submit {
// here the previous session should still exist. Sentry.init will submit another runnable
// to finalize the previous session, but because the executor is single-threaded, the
// work will be enqueued and the previous session will be finalized after current work is
// finished, ensuring that even if something is using the previous session from a
// different thread, it will still be able to access it.
Thread.sleep(1000L)
val session =
it.serializer.deserialize(previousSessionFile.bufferedReader(), Session::class.java)
assertEquals("[email protected]", session!!.release)
assertEquals("release", session.environment)
triggered.set(true)
}
}
await.untilTrue(triggered)
assertFalse(previousSessionFile.exists())
}
@Test
fun `captureFeedback gets forwarded to client`() {
initForTest { it.dsn = dsn }
val client = createSentryClientMock()
Sentry.getCurrentScopes().bindClient(client)
val feedback = Feedback("message")
val hint = Hint()
Sentry.captureFeedback(feedback)
Sentry.captureFeedback(feedback, hint)
Sentry.captureFeedback(feedback, hint) { it.setTag("testKey", "testValue") }
verify(client).captureFeedback(eq(feedback), eq(null), anyOrNull())
verify(client)
.captureFeedback(
eq(feedback),
eq(hint),
check { assertFalse(it.tags.containsKey("testKey")) },
)
verify(client)
.captureFeedback(
eq(feedback),
eq(hint),
check { assertEquals("testValue", it.tags["testKey"]) },
)
}
@Test
fun `captureCheckIn gets forwarded to client`() {
initForTest { it.dsn = dsn }
val client = createSentryClientMock()
Sentry.getCurrentScopes().bindClient(client)
val checkIn = CheckIn("some_slug", CheckInStatus.OK)