-
-
Notifications
You must be signed in to change notification settings - Fork 427
/
JsonSerializerTest.kt
1135 lines (973 loc) · 46.9 KB
/
JsonSerializerTest.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 io.sentry.exception.SentryEnvelopeException
import io.sentry.profilemeasurements.ProfileMeasurement
import io.sentry.profilemeasurements.ProfileMeasurementValue
import io.sentry.protocol.Device
import io.sentry.protocol.Request
import io.sentry.protocol.SdkVersion
import io.sentry.protocol.SentryId
import io.sentry.protocol.SentrySpan
import io.sentry.protocol.SentryTransaction
import org.mockito.kotlin.any
import org.mockito.kotlin.check
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import java.io.BufferedWriter
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.io.StringReader
import java.io.StringWriter
import java.nio.file.Files
import java.util.Date
import java.util.TimeZone
import java.util.UUID
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
class JsonSerializerTest {
private class Fixture {
val logger: ILogger = mock()
val serializer: ISerializer
val hub = mock<IHub>()
val traceFile = Files.createTempFile("test", "here").toFile()
init {
val options = SentryOptions()
options.dsn = "https://key@sentry.io/proj"
options.setLogger(logger)
options.setDebug(true)
whenever(hub.options).thenReturn(options)
serializer = JsonSerializer(options)
options.setEnvelopeReader(EnvelopeReader(serializer))
}
}
private lateinit var fixture: Fixture
@BeforeTest
fun before() {
fixture = Fixture()
}
private fun <T> serializeToString(ev: T): String {
return this.serializeToString { wrt -> fixture.serializer.serialize(ev!!, wrt) }
}
private fun serializeToString(serialize: (StringWriter) -> Unit): String {
val wrt = StringWriter()
serialize(wrt)
return wrt.toString()
}
private fun serializeToString(envelope: SentryEnvelope): String {
val outputStream = ByteArrayOutputStream()
BufferedWriter(OutputStreamWriter(outputStream))
fixture.serializer.serialize(envelope, outputStream)
return outputStream.toString()
}
@Test
fun `when serializing SentryEvent-SentryId object, it should become a event_id json without dashes`() {
val dateIsoFormat = "2000-12-31T23:59:58.000Z"
val sentryEvent = generateEmptySentryEvent(DateUtils.getDateTime(dateIsoFormat))
val actual = serializeToString(sentryEvent)
val expected = "{\"timestamp\":\"$dateIsoFormat\",\"event_id\":\"${sentryEvent.eventId}\",\"contexts\":{}}"
assertEquals(actual, expected)
}
@Test
fun `when deserializing event_id, it should become a SentryEvent-SentryId uuid`() {
val expected = UUID.randomUUID().toString().replace("-", "")
val jsonEvent = "{\"event_id\":\"$expected\"}"
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), SentryEvent::class.java)
assertEquals(expected, actual!!.eventId.toString())
}
@Test
fun `when serializing SentryEvent-Date, it should become a timestamp json ISO format`() {
val dateIsoFormat = "2000-12-31T23:59:58.000Z"
val sentryEvent = generateEmptySentryEvent(DateUtils.getDateTime(dateIsoFormat))
sentryEvent.eventId = null
val expected = "{\"timestamp\":\"$dateIsoFormat\",\"contexts\":{}}"
val actual = serializeToString(sentryEvent)
assertEquals(expected, actual)
}
@Test
fun `when deserializing timestamp, it should become a SentryEvent-Date`() {
val dateIsoFormat = "2000-12-31T23:59:58.000Z"
val expected = DateUtils.getDateTime(dateIsoFormat)
val jsonEvent = "{\"timestamp\":\"$dateIsoFormat\"}"
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), SentryEvent::class.java)
assertEquals(expected, actual!!.timestamp)
}
@Test
fun `when deserializing millis timestamp, it should become a SentryEvent-Date`() {
val dateIsoFormat = "1581410911"
val expected = DateUtils.getDateTimeWithMillisPrecision(dateIsoFormat)
val jsonEvent = "{\"timestamp\":\"$dateIsoFormat\"}"
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), SentryEvent::class.java)
assertEquals(expected, actual!!.timestamp)
}
@Test
fun `when deserializing millis timestamp with mills precision, it should become a SentryEvent-Date`() {
val dateIsoFormat = "1581410911.988"
val expected = DateUtils.getDateTimeWithMillisPrecision(dateIsoFormat)
val jsonEvent = "{\"timestamp\":\"$dateIsoFormat\"}"
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), SentryEvent::class.java)
assertEquals(expected, actual!!.timestamp)
}
@Test
fun `when deserializing unknown properties, it should be added to unknown field`() {
val jsonEvent = "{\"string\":\"test\",\"int\":1,\"boolean\":true}"
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), SentryEvent::class.java)
assertEquals("test", actual!!.unknown!!["string"] as String)
assertEquals(1, actual.unknown!!["int"] as Int)
assertEquals(true, actual.unknown!!["boolean"] as Boolean)
}
@Test
fun `when deserializing unknown properties with nested objects, it should be added to unknown field`() {
val sentryEvent = generateEmptySentryEvent()
sentryEvent.eventId = null
val objects = hashMapOf<String, Any>()
objects["int"] = 1
objects["boolean"] = true
val unknown = hashMapOf<String, Any>()
unknown["object"] = objects
sentryEvent.setUnknown(unknown)
val jsonEvent = "{\"object\":{\"int\":1,\"boolean\":true}}"
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), SentryEvent::class.java)
val hashMapActual = actual!!.unknown!!["object"] as Map<*, *> // gson creates it as JsonObject
assertEquals(true, hashMapActual.get("boolean") as Boolean)
assertEquals(1, hashMapActual.get("int") as Int)
}
@Test
fun `when serializing unknown field, its keys should becom part of json`() {
val dateIsoFormat = "2000-12-31T23:59:58.000Z"
val sentryEvent = generateEmptySentryEvent(DateUtils.getDateTime(dateIsoFormat))
sentryEvent.eventId = null
val objects = hashMapOf<String, Any>()
objects["int"] = 1
objects["boolean"] = true
val unknown = hashMapOf<String, Any>()
unknown["object"] = objects
sentryEvent.setUnknown(unknown)
val actual = serializeToString(sentryEvent)
val expected = "{\"timestamp\":\"2000-12-31T23:59:58.000Z\",\"contexts\":{},\"object\":{\"boolean\":true,\"int\":1}}"
assertEquals(actual, expected)
}
@Test
fun `when serializing a TimeZone, it should become a timezone ID string`() {
val dateIsoFormat = "2000-12-31T23:59:58.000Z"
val sentryEvent = generateEmptySentryEvent(DateUtils.getDateTime(dateIsoFormat))
sentryEvent.eventId = null
val device = Device()
device.timezone = TimeZone.getTimeZone("Europe/Vienna")
sentryEvent.contexts.setDevice(device)
val expected = "{\"timestamp\":\"2000-12-31T23:59:58.000Z\",\"contexts\":{\"device\":{\"timezone\":\"Europe/Vienna\"}}}"
val actual = serializeToString(sentryEvent)
assertEquals(actual, expected)
}
@Test
fun `when deserializing a timezone ID string, it should become a Device-TimeZone`() {
val sentryEvent = generateEmptySentryEvent()
sentryEvent.eventId = null
val jsonEvent = "{\"contexts\":{\"device\":{\"timezone\":\"Europe/Vienna\"}}}"
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), SentryEvent::class.java)
assertEquals("Europe/Vienna", actual!!.contexts.device!!.timezone!!.id)
}
@Test
fun `when serializing a DeviceOrientation, it should become an orientation string`() {
val dateIsoFormat = "2000-12-31T23:59:58.000Z"
val sentryEvent = generateEmptySentryEvent(DateUtils.getDateTime(dateIsoFormat))
sentryEvent.eventId = null
val device = Device()
device.orientation = Device.DeviceOrientation.LANDSCAPE
sentryEvent.contexts.setDevice(device)
val expected = "{\"timestamp\":\"2000-12-31T23:59:58.000Z\",\"contexts\":{\"device\":{\"orientation\":\"landscape\"}}}"
val actual = serializeToString(sentryEvent)
assertEquals(actual, expected)
}
@Test
fun `when deserializing an orientation string, it should become a DeviceOrientation`() {
val sentryEvent = generateEmptySentryEvent()
sentryEvent.eventId = null
val jsonEvent = "{\"contexts\":{\"device\":{\"orientation\":\"landscape\"}}}"
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), SentryEvent::class.java)
assertEquals(Device.DeviceOrientation.LANDSCAPE, actual!!.contexts.device!!.orientation)
}
@Test
fun `when serializing a SentryLevel, it should become a sentry level string`() {
val dateIsoFormat = "2000-12-31T23:59:58.000Z"
val sentryEvent = generateEmptySentryEvent(DateUtils.getDateTime(dateIsoFormat))
sentryEvent.eventId = null
sentryEvent.level = SentryLevel.DEBUG
val expected = "{\"timestamp\":\"2000-12-31T23:59:58.000Z\",\"level\":\"debug\",\"contexts\":{}}"
val actual = serializeToString(sentryEvent)
assertEquals(actual, expected)
}
@Test
fun `when deserializing a sentry level string, it should become a SentryLevel`() {
val sentryEvent = generateEmptySentryEvent()
sentryEvent.eventId = null
val jsonEvent = "{\"level\":\"debug\"}"
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), SentryEvent::class.java)
assertEquals(SentryLevel.DEBUG, actual!!.level)
}
@Test
fun `when deserializing a event with breadcrumbs containing data, it should become have breadcrumbs`() {
val jsonEvent = FileFromResources.invoke("event_breadcrumb_data.json")
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), SentryEvent::class.java)
assertNotNull(actual) { event ->
assertNotNull(event.breadcrumbs) {
assertEquals(2, it.size)
}
}
}
@Test
fun `when deserializing a event with custom contexts, they should be set in the event contexts`() {
val jsonEvent = FileFromResources.invoke("event_with_contexts.json")
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), SentryEvent::class.java)
val obj = actual!!.contexts["object"] as Map<*, *>
val number = actual.contexts["number"] as Int
val list = actual.contexts["list"] as List<*>
val listObjects = actual.contexts["list_objects"] as List<*>
assertTrue(obj["boolean"] as Boolean)
assertEquals("hi", obj["string"] as String)
assertEquals(9, obj["number"] as Int)
assertEquals(50, number)
assertEquals(1, list[0])
assertEquals(2, list[1])
val listObjectsFirst = listObjects[0] as Map<*, *>
assertTrue(listObjectsFirst["boolean"] as Boolean)
assertEquals("hi", listObjectsFirst["string"] as String)
assertEquals(9, listObjectsFirst["number"] as Int)
val listObjectsSecond = listObjects[1] as Map<*, *>
assertFalse(listObjectsSecond["boolean"] as Boolean)
assertEquals("ciao", listObjectsSecond["string"] as String)
assertEquals(10, listObjectsSecond["number"] as Int)
}
@Test
fun `when theres a null value, gson wont blow up`() {
val json = FileFromResources.invoke("event.json")
val event = fixture.serializer.deserialize(StringReader(json), SentryEvent::class.java)
assertNotNull(event)
assertNull(event.user)
}
@Test
fun `When deserializing a Session all the values should be set to the Session object`() {
val jsonEvent = FileFromResources.invoke("session.json")
val actual = fixture.serializer.deserialize(StringReader(jsonEvent), Session::class.java)
assertSessionData(actual)
}
@Test
fun `When deserializing an Envelope and reader throws IOException it should return null `() {
val inputStream = mock<InputStream>()
whenever(inputStream.read(any())).thenThrow(IOException())
val envelope = fixture.serializer.deserializeEnvelope(inputStream)
assertNull(envelope)
}
@Test
fun `When serializing a Session all the values should be set to the JSON string`() {
val session = createSessionMockData()
val jsonSession = serializeToString(session)
// reversing, so we can assert values and not a json string
val expectedSession = fixture.serializer.deserialize(StringReader(jsonSession), Session::class.java)
assertSessionData(expectedSession)
}
@Test
fun `When deserializing an Envelope, all the values should be set to the SentryEnvelope object`() {
val jsonEnvelope = FileFromResources.invoke("envelope_session.txt")
val envelope = fixture.serializer.deserializeEnvelope(ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)))
assertEnvelopeData(envelope)
}
@Test
fun `When deserializing an Envelope, SdkVersion should be set`() {
val jsonEnvelope = FileFromResources.invoke("envelope_session_sdkversion.txt")
val envelope = fixture.serializer.deserializeEnvelope(ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)))!!
assertNotNull(envelope.header.sdkVersion)
val sdkInfo = envelope.header.sdkVersion!!
assertEquals("test", sdkInfo.name)
assertEquals("1.2.3", sdkInfo.version)
assertNotNull(sdkInfo.integrations)
assertTrue(sdkInfo.integrations!!.any { it == "NdkIntegration" })
assertNotNull(sdkInfo.packages)
assertTrue(
sdkInfo.packages!!.any {
it.name == "io.sentry:maven:sentry-android-core" && it.version == "4.5.6"
}
)
}
@Test
fun `When serializing an envelope, all the values should be set`() {
val session = createSessionMockData()
val sentryEnvelope = SentryEnvelope.from(fixture.serializer, session, null)
val jsonEnvelope = serializeToString(sentryEnvelope)
// reversing it so we can assert the values
val envelope = fixture.serializer.deserializeEnvelope(ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)))
assertEnvelopeData(envelope)
}
@Test
fun `When serializing an envelope, SdkVersion should be set`() {
val session = createSessionMockData()
val version = SdkVersion("test", "1.2.3").apply {
addIntegration("TestIntegration")
addPackage("abc", "4.5.6")
}
val sentryEnvelope = SentryEnvelope.from(fixture.serializer, session, version)
val jsonEnvelope = serializeToString(sentryEnvelope)
// reversing it so we can assert the values
val envelope = fixture.serializer.deserializeEnvelope(ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)))!!
assertNotNull(envelope.header.sdkVersion)
val sdkVersion = envelope.header.sdkVersion!!
assertEquals(version.name, sdkVersion.name)
assertEquals(version.version, sdkVersion.version)
assertNotNull(sdkVersion.integrations)
assertTrue(sdkVersion.integrations!!.any { it == "TestIntegration" })
assertNotNull(sdkVersion.packages)
assertTrue(
sdkVersion.packages!!.any {
it.name == "abc" && it.version == "4.5.6"
}
)
}
@Test
fun `when serializing a data map, data should be stringfied`() {
val data = mapOf("a" to "b")
val expected = "{\"a\":\"b\"}"
val dataJson = fixture.serializer.serialize(data)
assertEquals(expected, dataJson)
}
@Test
fun `serializes trace context`() {
val traceContext = SentryEnvelopeHeader(null, null, TraceContext(SentryId("3367f5196c494acaae85bbbd535379ac"), "key", "release", "environment", "userId", "segment", "transaction", "0.5"))
val expected = """{"trace":{"trace_id":"3367f5196c494acaae85bbbd535379ac","public_key":"key","release":"release","environment":"environment","user_id":"userId","user_segment":"segment","transaction":"transaction","sample_rate":"0.5"}}"""
val json = serializeToString(traceContext)
assertEquals(expected, json)
}
@Test
fun `serializes trace context with user having null id and segment`() {
val traceContext = SentryEnvelopeHeader(null, null, TraceContext(SentryId("3367f5196c494acaae85bbbd535379ac"), "key", "release", "environment", null, null, "transaction", "0.6"))
val expected = """{"trace":{"trace_id":"3367f5196c494acaae85bbbd535379ac","public_key":"key","release":"release","environment":"environment","transaction":"transaction","sample_rate":"0.6"}}"""
val json = serializeToString(traceContext)
assertEquals(expected, json)
}
@Test
fun `deserializes trace context`() {
val json = """{"trace":{"trace_id":"3367f5196c494acaae85bbbd535379ac","public_key":"key","release":"release","environment":"environment","user_id":"userId","user_segment":"segment","transaction":"transaction"}}"""
val actual = fixture.serializer.deserialize(StringReader(json), SentryEnvelopeHeader::class.java)
assertNotNull(actual) {
assertNotNull(it.traceContext) {
assertEquals(SentryId("3367f5196c494acaae85bbbd535379ac"), it.traceId)
assertEquals("key", it.publicKey)
assertEquals("release", it.release)
assertEquals("environment", it.environment)
assertEquals("userId", it.userId)
assertEquals("segment", it.userSegment)
}
}
}
@Test
fun `deserializes trace context without user`() {
val json = """{"trace":{"trace_id":"3367f5196c494acaae85bbbd535379ac","public_key":"key","release":"release","environment":"environment","transaction":"transaction"}}"""
val actual = fixture.serializer.deserialize(StringReader(json), SentryEnvelopeHeader::class.java)
assertNotNull(actual) {
assertNotNull(it.traceContext) {
assertEquals(SentryId("3367f5196c494acaae85bbbd535379ac"), it.traceId)
assertEquals("key", it.publicKey)
assertEquals("release", it.release)
assertEquals("environment", it.environment)
assertNull(it.userId)
assertNull(it.userSegment)
}
}
}
@Test
fun `serializes profilingTraceData`() {
val profilingTraceData = ProfilingTraceData(fixture.traceFile, NoOpTransaction.getInstance())
profilingTraceData.androidApiLevel = 21
profilingTraceData.deviceLocale = "deviceLocale"
profilingTraceData.deviceManufacturer = "deviceManufacturer"
profilingTraceData.deviceModel = "deviceModel"
profilingTraceData.deviceOsBuildNumber = "deviceOsBuildNumber"
profilingTraceData.deviceOsVersion = "11"
profilingTraceData.isDeviceIsEmulator = true
profilingTraceData.cpuArchitecture = "cpuArchitecture"
profilingTraceData.deviceCpuFrequencies = listOf(1, 2, 3, 4)
profilingTraceData.devicePhysicalMemoryBytes = "2000000"
profilingTraceData.buildId = "buildId"
profilingTraceData.transactions = listOf(
ProfilingTransactionData(NoOpTransaction.getInstance(), 1, 2),
ProfilingTransactionData(NoOpTransaction.getInstance(), 2, 3)
)
profilingTraceData.transactionName = "transactionName"
profilingTraceData.durationNs = "100"
profilingTraceData.release = "release"
profilingTraceData.transactionId = "transactionId"
profilingTraceData.traceId = "traceId"
profilingTraceData.profileId = "profileId"
profilingTraceData.environment = "environment"
profilingTraceData.truncationReason = "truncationReason"
profilingTraceData.measurementsMap.putAll(
hashMapOf(
ProfileMeasurement.ID_SCREEN_FRAME_RATES to
ProfileMeasurement(
ProfileMeasurement.UNIT_HZ,
listOf(ProfileMeasurementValue(1, 60.1F))
)
)
)
profilingTraceData.sampledProfile = "sampled profile in base 64"
val actual = serializeToString(profilingTraceData)
val reader = StringReader(actual)
val objectReader = JsonObjectReader(reader)
val element = JsonObjectDeserializer().deserialize(objectReader) as Map<*, *>
assertEquals(21, element["android_api_level"] as Int)
assertEquals("deviceLocale", element["device_locale"] as String)
assertEquals("deviceManufacturer", element["device_manufacturer"] as String)
assertEquals("deviceModel", element["device_model"] as String)
assertEquals("deviceOsBuildNumber", element["device_os_build_number"] as String)
assertEquals("android", element["device_os_name"] as String)
assertEquals("11", element["device_os_version"] as String)
assertEquals(true, element["device_is_emulator"] as Boolean)
assertEquals("cpuArchitecture", element["architecture"] as String)
assertEquals(listOf(1, 2, 3, 4), element["device_cpu_frequencies"] as List<Int>)
assertEquals("2000000", element["device_physical_memory_bytes"] as String)
assertEquals("android", element["platform"] as String)
assertEquals("buildId", element["build_id"] as String)
assertEquals(
listOf(
mapOf(
"trace_id" to "00000000000000000000000000000000",
"relative_cpu_end_ms" to null,
"name" to "",
"relative_start_ns" to 1,
"relative_end_ns" to null,
"id" to "00000000000000000000000000000000",
"relative_cpu_start_ms" to 2
),
mapOf(
"trace_id" to "00000000000000000000000000000000",
"relative_cpu_end_ms" to null,
"name" to "",
"relative_start_ns" to 2,
"relative_end_ns" to null,
"id" to "00000000000000000000000000000000",
"relative_cpu_start_ms" to 3
)
),
element["transactions"]
)
assertEquals(
mapOf(
ProfileMeasurement.ID_SCREEN_FRAME_RATES to
mapOf(
"unit" to ProfileMeasurement.UNIT_HZ,
"values" to listOf(
mapOf(
"value" to "60.1",
"elapsed_since_start_ns" to 1
)
)
)
),
element["measurements"]
)
assertEquals("transactionName", element["transaction_name"] as String)
assertEquals("100", element["duration_ns"] as String)
assertEquals("release", element["version_name"] as String)
assertEquals("", element["version_code"] as String)
assertEquals("transactionId", element["transaction_id"] as String)
assertEquals("traceId", element["trace_id"] as String)
assertEquals("profileId", element["profile_id"] as String)
assertEquals("environment", element["environment"] as String)
assertEquals("truncationReason", element["truncation_reason"] as String)
assertEquals("sampled profile in base 64", element["sampled_profile"] as String)
}
@Test
fun `deserializes profilingTraceData`() {
val json = """{
"android_api_level":21,
"device_locale":"deviceLocale",
"device_manufacturer":"deviceManufacturer",
"device_model":"deviceModel",
"device_os_build_number":"deviceOsBuildNumber",
"device_os_name":"android",
"device_os_version":"11",
"device_is_emulator":true,
"architecture":"arm64-v8a",
"device_cpu_frequencies":[1, 2, 3, 4],
"device_physical_memory_bytes":"2000000",
"platform":"android",
"build_id":"buildId",
"transactions":[
{
"id":"id",
"trace_id":"traceId",
"name":"name",
"relative_start_ns":0,
"relative_end_ns":10
},
{
"id":"id2",
"trace_id":"traceId2",
"name":"name 2",
"relative_start_ns":4,
"relative_end_ns":21
}
],
"measurements":{
"screen_frame_rates": {
"unit":"hz",
"values":[
{"value":"60.1","elapsed_since_start_ns":"1"}
]
},
"frozen_frame_renders": {
"unit":"nanosecond",
"values":[
{"value":"100","elapsed_since_start_ns":"2"}
]
}
},
"transaction_name":"transactionName",
"duration_ns":"100",
"version_name":"release",
"version_code":"",
"transaction_id":"transactionId",
"trace_id":"traceId",
"profile_id":"profileId",
"environment":"environment",
"truncation_reason":"truncationReason",
"sampled_profile":"sampled profile in base 64"
}"""
val profilingTraceData = fixture.serializer.deserialize(StringReader(json), ProfilingTraceData::class.java)
assertNotNull(profilingTraceData)
assertEquals(21, profilingTraceData.androidApiLevel)
assertEquals("deviceLocale", profilingTraceData.deviceLocale)
assertEquals("deviceManufacturer", profilingTraceData.deviceManufacturer)
assertEquals("deviceModel", profilingTraceData.deviceModel)
assertEquals("deviceOsBuildNumber", profilingTraceData.deviceOsBuildNumber)
assertEquals("android", profilingTraceData.deviceOsName)
assertEquals("11", profilingTraceData.deviceOsVersion)
assertEquals(true, profilingTraceData.isDeviceIsEmulator)
assertEquals("arm64-v8a", profilingTraceData.cpuArchitecture)
assertEquals(listOf(1, 2, 3, 4), profilingTraceData.deviceCpuFrequencies)
assertEquals("2000000", profilingTraceData.devicePhysicalMemoryBytes)
assertEquals("android", profilingTraceData.platform)
assertEquals("buildId", profilingTraceData.buildId)
val expectedTransactions = listOf(
ProfilingTransactionData().apply {
id = "id"
traceId = "traceId"
name = "name"
relativeStartNs = 0
relativeEndNs = 10
},
ProfilingTransactionData().apply {
id = "id2"
traceId = "traceId2"
name = "name 2"
relativeStartNs = 4
relativeEndNs = 21
}
)
assertEquals(expectedTransactions, profilingTraceData.transactions)
val expectedMeasurements = mapOf(
ProfileMeasurement.ID_SCREEN_FRAME_RATES to ProfileMeasurement(
ProfileMeasurement.UNIT_HZ,
listOf(ProfileMeasurementValue(1, 60.1))
),
ProfileMeasurement.ID_FROZEN_FRAME_RENDERS to ProfileMeasurement(
ProfileMeasurement.UNIT_NANOSECONDS,
listOf(ProfileMeasurementValue(2, 100))
)
)
assertEquals(expectedMeasurements, profilingTraceData.measurementsMap)
assertEquals("transactionName", profilingTraceData.transactionName)
assertEquals("100", profilingTraceData.durationNs)
assertEquals("release", profilingTraceData.release)
assertEquals("transactionId", profilingTraceData.transactionId)
assertEquals("traceId", profilingTraceData.traceId)
assertEquals("profileId", profilingTraceData.profileId)
assertEquals("environment", profilingTraceData.environment)
assertEquals("truncationReason", profilingTraceData.truncationReason)
assertEquals("sampled profile in base 64", profilingTraceData.sampledProfile)
}
@Test
fun `serializes profileMeasurement`() {
val measurementValues = listOf(ProfileMeasurementValue(1, 2), ProfileMeasurementValue(3, 4))
val profileMeasurement = ProfileMeasurement(ProfileMeasurement.UNIT_NANOSECONDS, measurementValues)
val actual = serializeToString(profileMeasurement)
val expected = "{\"unit\":\"nanosecond\",\"values\":[{\"value\":\"2\",\"elapsed_since_start_ns\":1},{\"value\":\"4\",\"elapsed_since_start_ns\":3}]}"
assertEquals(expected, actual)
}
@Test
fun `deserializes profileMeasurement`() {
val json = """{
"unit":"hz",
"values":[
{"value":"60.1","elapsed_since_start_ns":"1"},{"value":"100","elapsed_since_start_ns":"2"}
]
}"""
val profileMeasurement = fixture.serializer.deserialize(StringReader(json), ProfileMeasurement::class.java)
val expected = ProfileMeasurement(
ProfileMeasurement.UNIT_HZ,
listOf(ProfileMeasurementValue(1, 60.1), ProfileMeasurementValue(2, 100))
)
assertEquals(expected, profileMeasurement)
}
@Test
fun `serializes profileMeasurementValue`() {
val profileMeasurementValue = ProfileMeasurementValue(1, 2)
val actual = serializeToString(profileMeasurementValue)
val expected = "{\"value\":\"2\",\"elapsed_since_start_ns\":1}"
assertEquals(expected, actual)
}
@Test
fun `deserializes profileMeasurementValue`() {
val json = """{"value":"60.1","elapsed_since_start_ns":"1"}"""
val profileMeasurementValue = fixture.serializer.deserialize(StringReader(json), ProfileMeasurementValue::class.java)
val expected = ProfileMeasurementValue(1, 60.1)
assertEquals(expected, profileMeasurementValue)
}
@Test
fun `serializes transaction`() {
val trace = TransactionContext("transaction-name", "http")
trace.description = "some request"
trace.status = SpanStatus.OK
trace.setTag("myTag", "myValue")
trace.sampled = true
val tracer = SentryTracer(trace, fixture.hub)
tracer.setData("dataKey", "dataValue")
val span = tracer.startChild("child")
span.finish(SpanStatus.OK)
tracer.finish()
val stringWriter = StringWriter()
fixture.serializer.serialize(SentryTransaction(tracer), stringWriter)
val reader = StringReader(stringWriter.toString())
val objectReader = JsonObjectReader(reader)
val element = JsonObjectDeserializer().deserialize(objectReader) as Map<*, *>
assertEquals("transaction-name", element["transaction"] as String)
assertEquals("transaction", element["type"] as String)
assertNotNull(element["start_timestamp"] as Number)
assertNotNull(element["event_id"] as String)
assertNotNull(element["spans"] as List<*>)
assertEquals("myValue", (element["tags"] as Map<*, *>)["myTag"] as String)
assertEquals("dataValue", (element["extra"] as Map<*, *>)["dataKey"] as String)
val jsonSpan = (element["spans"] as List<*>)[0] as Map<*, *>
assertNotNull(jsonSpan["trace_id"])
assertNotNull(jsonSpan["span_id"])
assertNotNull(jsonSpan["parent_span_id"])
assertEquals("child", jsonSpan["op"] as String)
assertNotNull("ok", jsonSpan["status"] as String)
assertNotNull(jsonSpan["timestamp"])
assertNotNull(jsonSpan["start_timestamp"])
val jsonTrace = (element["contexts"] as Map<*, *>)["trace"] as Map<*, *>
assertNotNull(jsonTrace["trace_id"] as String)
assertNotNull(jsonTrace["span_id"] as String)
assertEquals("http", jsonTrace["op"] as String)
assertEquals("some request", jsonTrace["description"] as String)
assertEquals("ok", jsonTrace["status"] as String)
}
@Test
fun `deserializes transaction`() {
val json = """{
"transaction": "a-transaction",
"type": "transaction",
"start_timestamp": 1632395079.503000,
"timestamp": 1632395079.807321,
"event_id": "3367f5196c494acaae85bbbd535379ac",
"contexts": {
"trace": {
"trace_id": "b156a475de54423d9c1571df97ec7eb6",
"span_id": "0a53026963414893",
"op": "http",
"status": "ok"
},
"custom": {
"some-key": "some-value"
}
},
"extra": {
"extraKey": "extraValue"
},
"spans": [
{
"start_timestamp": 1632395079.840000,
"timestamp": 1632395079.884043,
"trace_id": "2b099185293344a5bfdd7ad89ebf9416",
"span_id": "5b95c29a5ded4281",
"parent_span_id": "a3b2d1d58b344b07",
"op": "PersonService.create",
"description": "desc",
"status": "aborted",
"tags": {
"name": "value"
},
"data": {
"key": "value"
}
}
]
}"""
val transaction = fixture.serializer.deserialize(StringReader(json), SentryTransaction::class.java)
assertNotNull(transaction)
assertEquals("a-transaction", transaction.transaction)
assertNotNull(transaction.startTimestamp)
assertNotNull(transaction.timestamp)
assertNotNull(transaction.contexts)
assertNotNull(transaction.contexts.trace)
assertEquals(SpanStatus.OK, transaction.status)
assertEquals("transaction", transaction.type)
assertEquals("b156a475de54423d9c1571df97ec7eb6", transaction.contexts.trace!!.traceId.toString())
assertEquals("0a53026963414893", transaction.contexts.trace!!.spanId.toString())
assertEquals("http", transaction.contexts.trace!!.operation)
assertNotNull(transaction.contexts["custom"])
assertEquals("some-value", (transaction.contexts["custom"] as Map<*, *>)["some-key"])
assertEquals("extraValue", transaction.getExtra("extraKey"))
assertNotNull(transaction.spans)
assertEquals(1, transaction.spans.size)
val span = transaction.spans[0]
assertNotNull(span.startTimestamp)
assertNotNull(span.timestamp)
assertNotNull(span.data) {
assertEquals("value", it["key"])
}
assertEquals("2b099185293344a5bfdd7ad89ebf9416", span.traceId.toString())
assertEquals("5b95c29a5ded4281", span.spanId.toString())
assertEquals("a3b2d1d58b344b07", span.parentSpanId.toString())
assertEquals("PersonService.create", span.op)
assertEquals(SpanStatus.ABORTED, span.status)
assertEquals("desc", span.description)
assertEquals(mapOf("name" to "value"), span.tags)
}
@Test
fun `deserializes legacy timestamp format in spans and transactions`() {
val json = """{
"transaction": "a-transaction",
"type": "transaction",
"start_timestamp": "2020-10-23T10:24:01.791Z",
"timestamp": "2020-10-23T10:24:02.791Z",
"event_id": "3367f5196c494acaae85bbbd535379ac",
"contexts": {
"trace": {
"trace_id": "b156a475de54423d9c1571df97ec7eb6",
"span_id": "0a53026963414893",
"op": "http",
"status": "ok"
}
},
"spans": [
{
"start_timestamp": "2021-03-05T08:51:12.838Z",
"timestamp": "2021-03-05T08:51:12.949Z",
"trace_id": "2b099185293344a5bfdd7ad89ebf9416",
"span_id": "5b95c29a5ded4281",
"parent_span_id": "a3b2d1d58b344b07",
"op": "PersonService.create",
"description": "desc",
"status": "aborted"
}
]
}"""
val transaction = fixture.serializer.deserialize(StringReader(json), SentryTransaction::class.java)
assertNotNull(transaction) {
assertNotNull(it.startTimestamp)
assertNotNull(it.timestamp)
}
}
@Test
fun `serializes span data`() {
val sentrySpan = SentrySpan(createSpan() as Span, mapOf("data1" to "value1"))
val serialized = serializeToString(sentrySpan)
val deserialized = fixture.serializer.deserialize(StringReader(serialized), SentrySpan::class.java)
assertNotNull(deserialized?.data) {
assertNotNull(it["data1"]) {
assertEquals("value1", it)
}
}
}
@Test
fun `serializing user feedback`() {
val actual = serializeToString(userFeedback)
val expected = "{\"event_id\":\"${userFeedback.eventId}\",\"name\":\"${userFeedback.name}\"," +
"\"email\":\"${userFeedback.email}\",\"comments\":\"${userFeedback.comments}\"}"
assertEquals(expected, actual)
}
@Test
fun `deserializing user feedback`() {
val jsonUserFeedback = "{\"event_id\":\"c2fb8fee2e2b49758bcb67cda0f713c7\"," +
"\"name\":\"John\",\"email\":\"john@me.com\",\"comments\":\"comment\"}"
val actual = fixture.serializer.deserialize(StringReader(jsonUserFeedback), UserFeedback::class.java)
assertNotNull(actual)
assertEquals(userFeedback.eventId, actual.eventId)
assertEquals(userFeedback.name, actual.name)
assertEquals(userFeedback.email, actual.email)
assertEquals(userFeedback.comments, actual.comments)
}
@Test
fun `serialize envelope with item throwing`() {
val eventID = SentryId()
val header = SentryEnvelopeHeader(eventID)
val message = "hello"
val attachment = Attachment(message.toByteArray(), "bytes.txt")
val validAttachmentItem = SentryEnvelopeItem.fromAttachment(attachment, 5)
val invalidAttachmentItem = SentryEnvelopeItem.fromAttachment(Attachment("no"), 5)
val envelope = SentryEnvelope(header, listOf(invalidAttachmentItem, validAttachmentItem))
val actualJson = serializeToString(envelope)
val expectedJson = "{\"event_id\":\"${eventID}\"}\n" +
"{\"filename\":\"${attachment.filename}\"," +
"\"type\":\"attachment\"," +
"\"attachment_type\":\"event.attachment\"," +
"\"length\":${attachment.bytes?.size}}\n" +
"$message\n"
assertEquals(expectedJson, actualJson)
verify(fixture.logger)
.log(
eq(SentryLevel.ERROR),
eq("Failed to create envelope item. Dropping it."),
any<SentryEnvelopeException>()
)
}
@Test
fun `empty maps are serialized to null`() {
val event = SentryEvent()
event.tags = emptyMap()
val serialized = serializeToString(event)
val deserialized = fixture.serializer.deserialize(StringReader(serialized), SentryEvent::class.java)
assertNull(deserialized?.tags)
}
@Test
fun `empty lists are serialized to null`() {
val event = generateEmptySentryEvent()
event.threads = listOf()
val serialized = serializeToString(event)
val deserialized = fixture.serializer.deserialize(StringReader(serialized), SentryEvent::class.java)
assertNull(deserialized?.threads)
}
@Test
fun `Long can be serialized inside request data`() {
val request = Request()
data class LongContainer(val longValue: Long)