forked from mongodb/mongo-java-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKotlinSerializerCodecTest.kt
886 lines (786 loc) · 37.2 KB
/
KotlinSerializerCodecTest.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
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bson.codecs.kotlinx
import java.util.stream.Stream
import kotlin.test.assertEquals
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.MissingFieldException
import kotlinx.serialization.SerializationException
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.plus
import kotlinx.serialization.modules.polymorphic
import kotlinx.serialization.modules.subclass
import org.bson.BsonBoolean
import org.bson.BsonDocument
import org.bson.BsonDocumentReader
import org.bson.BsonDocumentWriter
import org.bson.BsonDouble
import org.bson.BsonInt32
import org.bson.BsonInt64
import org.bson.BsonInvalidOperationException
import org.bson.BsonMaxKey
import org.bson.BsonMinKey
import org.bson.BsonString
import org.bson.BsonUndefined
import org.bson.codecs.DecoderContext
import org.bson.codecs.EncoderContext
import org.bson.codecs.configuration.CodecConfigurationException
import org.bson.codecs.kotlinx.samples.Box
import org.bson.codecs.kotlinx.samples.DataClassBsonValues
import org.bson.codecs.kotlinx.samples.DataClassContainsOpen
import org.bson.codecs.kotlinx.samples.DataClassContainsValueClass
import org.bson.codecs.kotlinx.samples.DataClassEmbedded
import org.bson.codecs.kotlinx.samples.DataClassKey
import org.bson.codecs.kotlinx.samples.DataClassLastItemDefaultsToNull
import org.bson.codecs.kotlinx.samples.DataClassListOfDataClasses
import org.bson.codecs.kotlinx.samples.DataClassListOfListOfDataClasses
import org.bson.codecs.kotlinx.samples.DataClassListOfSealed
import org.bson.codecs.kotlinx.samples.DataClassMapOfDataClasses
import org.bson.codecs.kotlinx.samples.DataClassMapOfListOfDataClasses
import org.bson.codecs.kotlinx.samples.DataClassNestedParameterizedTypes
import org.bson.codecs.kotlinx.samples.DataClassOpen
import org.bson.codecs.kotlinx.samples.DataClassOpenA
import org.bson.codecs.kotlinx.samples.DataClassOpenB
import org.bson.codecs.kotlinx.samples.DataClassOptionalBsonValues
import org.bson.codecs.kotlinx.samples.DataClassParameterized
import org.bson.codecs.kotlinx.samples.DataClassSealed
import org.bson.codecs.kotlinx.samples.DataClassSealedA
import org.bson.codecs.kotlinx.samples.DataClassSealedB
import org.bson.codecs.kotlinx.samples.DataClassSealedC
import org.bson.codecs.kotlinx.samples.DataClassSelfReferential
import org.bson.codecs.kotlinx.samples.DataClassWithAnnotations
import org.bson.codecs.kotlinx.samples.DataClassWithBooleanMapKey
import org.bson.codecs.kotlinx.samples.DataClassWithBsonConstructor
import org.bson.codecs.kotlinx.samples.DataClassWithBsonDiscriminator
import org.bson.codecs.kotlinx.samples.DataClassWithBsonExtraElements
import org.bson.codecs.kotlinx.samples.DataClassWithBsonId
import org.bson.codecs.kotlinx.samples.DataClassWithBsonIgnore
import org.bson.codecs.kotlinx.samples.DataClassWithBsonProperty
import org.bson.codecs.kotlinx.samples.DataClassWithBsonRepresentation
import org.bson.codecs.kotlinx.samples.DataClassWithCollections
import org.bson.codecs.kotlinx.samples.DataClassWithDataClassMapKey
import org.bson.codecs.kotlinx.samples.DataClassWithDefaults
import org.bson.codecs.kotlinx.samples.DataClassWithEmbedded
import org.bson.codecs.kotlinx.samples.DataClassWithEncodeDefault
import org.bson.codecs.kotlinx.samples.DataClassWithEnum
import org.bson.codecs.kotlinx.samples.DataClassWithEnumMapKey
import org.bson.codecs.kotlinx.samples.DataClassWithFailingInit
import org.bson.codecs.kotlinx.samples.DataClassWithListThatLastItemDefaultsToNull
import org.bson.codecs.kotlinx.samples.DataClassWithMutableList
import org.bson.codecs.kotlinx.samples.DataClassWithMutableMap
import org.bson.codecs.kotlinx.samples.DataClassWithMutableSet
import org.bson.codecs.kotlinx.samples.DataClassWithNestedParameterized
import org.bson.codecs.kotlinx.samples.DataClassWithNestedParameterizedDataClass
import org.bson.codecs.kotlinx.samples.DataClassWithNullableGeneric
import org.bson.codecs.kotlinx.samples.DataClassWithNulls
import org.bson.codecs.kotlinx.samples.DataClassWithPair
import org.bson.codecs.kotlinx.samples.DataClassWithParameterizedDataClass
import org.bson.codecs.kotlinx.samples.DataClassWithRequired
import org.bson.codecs.kotlinx.samples.DataClassWithSequence
import org.bson.codecs.kotlinx.samples.DataClassWithSimpleValues
import org.bson.codecs.kotlinx.samples.DataClassWithTriple
import org.bson.codecs.kotlinx.samples.Key
import org.bson.codecs.kotlinx.samples.SealedInterface
import org.bson.codecs.kotlinx.samples.ValueClass
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
@OptIn(ExperimentalSerializationApi::class)
@Suppress("LargeClass")
class KotlinSerializerCodecTest {
private val oid = "\$oid"
private val emptyDocument = "{}"
private val altConfiguration =
BsonConfiguration(encodeDefaults = false, classDiscriminator = "_t", explicitNulls = true)
private val allBsonTypesJson =
"""{
| "id": {"$oid": "111111111111111111111111"},
| "arrayEmpty": [],
| "arraySimple": [{"${'$'}numberInt": "1"}, {"${'$'}numberInt": "2"}, {"${'$'}numberInt": "3"}],
| "arrayComplex": [{"a": {"${'$'}numberInt": "1"}}, {"a": {"${'$'}numberInt": "2"}}],
| "arrayMixedTypes": [{"${'$'}numberInt": "1"}, {"${'$'}numberInt": "2"}, true,
| [{"${'$'}numberInt": "1"}, {"${'$'}numberInt": "2"}, {"${'$'}numberInt": "3"}],
| {"a": {"${'$'}numberInt": "2"}}],
| "arrayComplexMixedTypes": [{"a": {"${'$'}numberInt": "1"}}, {"a": "a"}],
| "binary": {"${'$'}binary": {"base64": "S2Fma2Egcm9ja3Mh", "subType": "00"}},
| "boolean": true,
| "code": {"${'$'}code": "int i = 0;"},
| "codeWithScope": {"${'$'}code": "int x = y", "${'$'}scope": {"y": {"${'$'}numberInt": "1"}}},
| "dateTime": {"${'$'}date": {"${'$'}numberLong": "1577836801000"}},
| "decimal128": {"${'$'}numberDecimal": "1.0"},
| "documentEmpty": {},
| "document": {"a": {"${'$'}numberInt": "1"}},
| "double": {"${'$'}numberDouble": "62.0"},
| "int32": {"${'$'}numberInt": "42"},
| "int64": {"${'$'}numberLong": "52"},
| "maxKey": {"${'$'}maxKey": 1},
| "minKey": {"${'$'}minKey": 1},
| "objectId": {"${'$'}oid": "211111111111111111111112"},
| "regex": {"${'$'}regularExpression": {"pattern": "^test.*regex.*xyz$", "options": "i"}},
| "string": "the fox ...",
| "symbol": {"${'$'}symbol": "ruby stuff"},
| "timestamp": {"${'$'}timestamp": {"t": 305419896, "i": 5}},
| "undefined": {"${'$'}undefined": true}
| }"""
.trimMargin()
private val allBsonTypesDocument = BsonDocument.parse(allBsonTypesJson)
companion object {
@JvmStatic
fun testTypesCastingDataClassWithSimpleValues(): Stream<BsonDocument> {
return Stream.of(
BsonDocument()
.append("char", BsonString("c"))
.append("byte", BsonInt32(1))
.append("short", BsonInt32(2))
.append("int", BsonInt32(10))
.append("long", BsonInt32(10))
.append("float", BsonInt32(2))
.append("double", BsonInt32(3))
.append("boolean", BsonBoolean.TRUE)
.append("string", BsonString("String")),
BsonDocument()
.append("char", BsonString("c"))
.append("byte", BsonDouble(1.0))
.append("short", BsonDouble(2.0))
.append("int", BsonDouble(9.9999999999999992))
.append("long", BsonDouble(9.9999999999999992))
.append("float", BsonDouble(2.0))
.append("double", BsonDouble(3.0))
.append("boolean", BsonBoolean.TRUE)
.append("string", BsonString("String")),
BsonDocument()
.append("char", BsonString("c"))
.append("byte", BsonDouble(1.0))
.append("short", BsonDouble(2.0))
.append("int", BsonDouble(10.0))
.append("long", BsonDouble(10.0))
.append("float", BsonDouble(2.0))
.append("double", BsonDouble(3.0))
.append("boolean", BsonBoolean.TRUE)
.append("string", BsonString("String")),
BsonDocument()
.append("char", BsonString("c"))
.append("byte", BsonInt64(1))
.append("short", BsonInt64(2))
.append("int", BsonInt64(10))
.append("long", BsonInt64(10))
.append("float", BsonInt64(2))
.append("double", BsonInt64(3))
.append("boolean", BsonBoolean.TRUE)
.append("string", BsonString("String")))
}
}
@ParameterizedTest
@MethodSource("testTypesCastingDataClassWithSimpleValues")
fun testTypesCastingDataClassWithSimpleValues(data: BsonDocument) {
val expectedDataClass = DataClassWithSimpleValues('c', 1, 2, 10, 10L, 2.0f, 3.0, true, "String")
assertDecodesTo(data, expectedDataClass)
}
@Test
fun testDataClassWithComplexTypes() {
val expected =
"""{
| "listSimple": ["a", "b", "c", "d"],
| "listList": [["a", "b"], [], ["c", "d"]],
| "listMap": [{"a": 1, "b": 2}, {}, {"c": 3, "d": 4}],
| "mapSimple": {"a": 1, "b": 2, "c": 3, "d": 4},
| "mapList": {"a": ["a", "b"], "b": [], "c": ["c", "d"]},
| "mapMap" : {"a": {"a": 1, "b": 2}, "b": {}, "c": {"c": 3, "d": 4}}
|}"""
.trimMargin()
val dataClass =
DataClassWithCollections(
listOf("a", "b", "c", "d"),
listOf(listOf("a", "b"), emptyList(), listOf("c", "d")),
listOf(mapOf("a" to 1, "b" to 2), emptyMap(), mapOf("c" to 3, "d" to 4)),
mapOf("a" to 1, "b" to 2, "c" to 3, "d" to 4),
mapOf("a" to listOf("a", "b"), "b" to emptyList(), "c" to listOf("c", "d")),
mapOf("a" to mapOf("a" to 1, "b" to 2), "b" to emptyMap(), "c" to mapOf("c" to 3, "d" to 4)))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithDefaults() {
val expectedDefault =
"""{
| "boolean": false,
| "string": "String",
| "listSimple": ["a", "b", "c"]
|}"""
.trimMargin()
val defaultDataClass = DataClassWithDefaults()
assertRoundTrips(expectedDefault, defaultDataClass)
assertRoundTrips(emptyDocument, defaultDataClass, altConfiguration)
val expectedSomeOverrides = """{"boolean": true, "listSimple": ["a"]}"""
val someOverridesDataClass = DataClassWithDefaults(boolean = true, listSimple = listOf("a"))
assertRoundTrips(expectedSomeOverrides, someOverridesDataClass, altConfiguration)
}
@Test
fun testDataClassWithNulls() {
val expectedNulls =
"""{
| "boolean": null,
| "string": null,
| "listSimple": null
|}"""
.trimMargin()
val dataClass = DataClassWithNulls(null, null, null)
assertRoundTrips(emptyDocument, dataClass)
assertRoundTrips(expectedNulls, dataClass, altConfiguration)
}
@Test
fun testDataClassWithListThatLastItemDefaultsToNull() {
val expectedWithOutNulls =
"""{
| "elements": [{"required": "required"}, {"required": "required"}],
|}"""
.trimMargin()
val dataClass =
DataClassWithListThatLastItemDefaultsToNull(
listOf(DataClassLastItemDefaultsToNull("required"), DataClassLastItemDefaultsToNull("required")))
assertRoundTrips(expectedWithOutNulls, dataClass)
val expectedWithNulls =
"""{
| "elements": [{"required": "required", "optional": null}, {"required": "required", "optional": null}],
|}"""
.trimMargin()
assertRoundTrips(expectedWithNulls, dataClass, BsonConfiguration(explicitNulls = true))
}
@Test
fun testDataClassWithNullableGenericsNotNull() {
val expected =
"""{
| "box": {"boxed": "String"}
|}"""
.trimMargin()
val dataClass = DataClassWithNullableGeneric(Box("String"))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithNullableGenericsNull() {
val expectedDefault = """{"box": {}}"""
val dataClass = DataClassWithNullableGeneric(Box(null))
assertRoundTrips(expectedDefault, dataClass)
val expectedNull = """{"box": {"boxed": null}}"""
assertRoundTrips(expectedNull, dataClass, altConfiguration)
}
@Test
fun testDataClassSelfReferential() {
val expected =
"""{"name": "tree",
| "left": {"name": "L", "left": {"name": "LL"}, "right": {"name": "LR"}},
| "right": {"name": "R",
| "left": {"name": "RL",
| "left": {"name": "RLL"},
| "right": {"name": "RLR"}},
| "right": {"name": "RR"}}
|}"""
.trimMargin()
val dataClass =
DataClassSelfReferential(
"tree",
DataClassSelfReferential("L", DataClassSelfReferential("LL"), DataClassSelfReferential("LR")),
DataClassSelfReferential(
"R",
DataClassSelfReferential("RL", DataClassSelfReferential("RLL"), DataClassSelfReferential("RLR")),
DataClassSelfReferential("RR")))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithEmbedded() {
val expected = """{"id": "myId", "embedded": {"name": "embedded1"}}"""
val dataClass = DataClassWithEmbedded("myId", DataClassEmbedded("embedded1"))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassListOfDataClasses() {
val expected = """{"id": "myId", "nested": [{"name": "embedded1"}, {"name": "embedded2"}]}"""
val dataClass =
DataClassListOfDataClasses("myId", listOf(DataClassEmbedded("embedded1"), DataClassEmbedded("embedded2")))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassListOfListOfDataClasses() {
val expected = """{"id": "myId", "nested": [[{"name": "embedded1"}], [{"name": "embedded2"}]]}"""
val dataClass =
DataClassListOfListOfDataClasses(
"myId", listOf(listOf(DataClassEmbedded("embedded1")), listOf(DataClassEmbedded("embedded2"))))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassMapOfDataClasses() {
val expected = """{"id": "myId", "nested": {"first": {"name": "embedded1"}, "second": {"name": "embedded2"}}}"""
val dataClass =
DataClassMapOfDataClasses(
"myId", mapOf("first" to DataClassEmbedded("embedded1"), "second" to DataClassEmbedded("embedded2")))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassMapOfListOfDataClasses() {
val expected =
"""{"id": "myId", "nested": {"first": [{"name": "embedded1"}], "second": [{"name": "embedded2"}]}}"""
val dataClass =
DataClassMapOfListOfDataClasses(
"myId",
mapOf(
"first" to listOf(DataClassEmbedded("embedded1")),
"second" to listOf(DataClassEmbedded("embedded2"))))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithParameterizedDataClass() {
val expected =
"""{"id": "myId",
| "parameterizedDataClass": {"number": 2.0, "string": "myString",
| "parameterizedList": [{"name": "embedded1"}]}
|}"""
.trimMargin()
val dataClass =
DataClassWithParameterizedDataClass(
"myId", DataClassParameterized(2.0, "myString", listOf(DataClassEmbedded("embedded1"))))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithNestedParameterizedDataClass() {
val expected =
"""{"id": "myId",
|"nestedParameterized": {
| "parameterizedDataClass":
| {"number": 4.2, "string": "myString", "parameterizedList": [{"name": "embedded1"}]},
| "other": "myOtherString", "optionalOther": "myOptionalOtherString"
| }
|}"""
.trimMargin()
val dataClass =
DataClassWithNestedParameterizedDataClass(
"myId",
DataClassWithNestedParameterized(
DataClassParameterized(4.2, "myString", listOf(DataClassEmbedded("embedded1"))),
"myOtherString",
"myOptionalOtherString"))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithPair() {
val expected = """{"pair": {"first": "a", "second": 1}}"""
val dataClass = DataClassWithPair("a" to 1)
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithTriple() {
val expected = """{"triple": {"first": "a", "second": 1, "third": 2.1}}"""
val dataClass = DataClassWithTriple(Triple("a", 1, 2.1))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassNestedParameterizedTypes() {
val expected =
"""{
|"triple": {
| "first": "0",
| "second": {"first": 1, "second": {"first": 1.2, "second": {"first": "1.3", "second": 1.3}}},
| "third": {"first": 2, "second": {"first": 2.1, "second": "two dot two"},
| "third": {"first": "3.1", "second": {"first": 3.2, "second": "three dot two" },
| "third": 3.3 }}
| }
|}"""
.trimMargin()
val dataClass =
DataClassNestedParameterizedTypes(
Triple(
"0",
Pair(1, Pair(1.2, Pair("1.3", 1.3))),
Triple(2, Pair(2.1, "two dot two"), Triple("3.1", Pair(3.2, "three dot two"), 3.3))))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithMutableList() {
val expected = """{"value": ["A", "B", "C"]}"""
val dataClass = DataClassWithMutableList(mutableListOf("A", "B", "C"))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithMutableSet() {
val expected = """{"value": ["A", "B", "C"]}"""
val dataClass = DataClassWithMutableSet(mutableSetOf("A", "B", "C"))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithMutableMap() {
val expected = """{"value": {"a": "A", "b": "B", "c": "C"}}"""
val dataClass = DataClassWithMutableMap(mutableMapOf("a" to "A", "b" to "B", "c" to "C"))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithAnnotations() {
val expected = """{"_id": "id", "nom": "name", "string": "string"}"""
val dataClass = DataClassWithAnnotations("id", "name", "string")
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithEncodeDefault() {
val expectedDefault =
"""{
| "boolean": false,
| "listSimple": ["a", "b", "c"]
|}"""
.trimMargin()
val defaultDataClass = DataClassWithEncodeDefault()
assertRoundTrips(expectedDefault, defaultDataClass)
assertRoundTrips("""{"listSimple": ["a", "b", "c"]}""", defaultDataClass, altConfiguration)
val expectedSomeOverrides = """{"string": "STRING", "listSimple": ["a"]}"""
val someOverridesDataClass = DataClassWithEncodeDefault(string = "STRING", listSimple = listOf("a"))
assertRoundTrips(expectedSomeOverrides, someOverridesDataClass, altConfiguration)
}
@Test
fun testDataClassWithRequired() {
val expectedDefault =
"""{
| "boolean": false,
| "string": "String",
| "listSimple": ["a", "b", "c"]
|}"""
.trimMargin()
val defaultDataClass = DataClassWithRequired()
assertRoundTrips(expectedDefault, defaultDataClass)
assertThrows<MissingFieldException> { deserialize<DataClassWithRequired>(BsonDocument()) }
}
@Test
fun testDataClassWithEnum() {
val expected = """{"value": "A"}"""
val dataClass = DataClassWithEnum(Key.A)
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithEnumKeyMap() {
val expected = """{"map": {"A": true, "B": false}}"""
val dataClass = DataClassWithEnumMapKey(mapOf(Key.A to true, Key.B to false))
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataClassWithSequence() {
val dataClass = DataClassWithSequence(listOf("A", "B", "C").asSequence())
assertThrows<SerializationException> { serialize(dataClass) }
}
@Test
fun testDataClassWithBooleanKeyMap() {
val dataClass = DataClassWithBooleanMapKey(mapOf(true to true, false to false))
assertThrows<SerializationException> { serialize(dataClass) }
assertThrows<SerializationException> {
deserialize<DataClassWithBooleanMapKey>(BsonDocument.parse("""{"map": {"true": true}}"""))
}
}
@Test
fun testDataClassWithDataClassKeyMap() {
val dataClass = DataClassWithDataClassMapKey(mapOf(DataClassKey("A") to true, DataClassKey("A") to false))
assertThrows<SerializationException> { serialize(dataClass) }
assertThrows<SerializationException> {
deserialize<DataClassWithDataClassMapKey>(BsonDocument.parse("""{"map": {"A": true}}"""))
}
}
@Test
fun testDataClassEmbeddedWithExtraData() {
val expected =
"""{
| "extraA": "extraA",
| "name": "NAME",
| "extraB": "extraB"
|}"""
.trimMargin()
val dataClass = DataClassEmbedded("NAME")
assertDecodesTo(BsonDocument.parse(expected), dataClass)
}
@Test
fun testDataClassBsonValues() {
val dataClass =
DataClassBsonValues(
allBsonTypesDocument["id"]!!.asObjectId().value,
allBsonTypesDocument["arrayEmpty"]!!.asArray(),
allBsonTypesDocument["arraySimple"]!!.asArray(),
allBsonTypesDocument["arrayComplex"]!!.asArray(),
allBsonTypesDocument["arrayMixedTypes"]!!.asArray(),
allBsonTypesDocument["arrayComplexMixedTypes"]!!.asArray(),
allBsonTypesDocument["binary"]!!.asBinary(),
allBsonTypesDocument["boolean"]!!.asBoolean(),
allBsonTypesDocument["code"]!!.asJavaScript(),
allBsonTypesDocument["codeWithScope"]!!.asJavaScriptWithScope(),
allBsonTypesDocument["dateTime"]!!.asDateTime(),
allBsonTypesDocument["decimal128"]!!.asDecimal128(),
allBsonTypesDocument["documentEmpty"]!!.asDocument(),
allBsonTypesDocument["document"]!!.asDocument(),
allBsonTypesDocument["double"]!!.asDouble(),
allBsonTypesDocument["int32"]!!.asInt32(),
allBsonTypesDocument["int64"]!!.asInt64(),
allBsonTypesDocument["maxKey"]!! as BsonMaxKey,
allBsonTypesDocument["minKey"]!! as BsonMinKey,
allBsonTypesDocument["objectId"]!!.asObjectId(),
allBsonTypesDocument["regex"]!!.asRegularExpression(),
allBsonTypesDocument["string"]!!.asString(),
allBsonTypesDocument["symbol"]!!.asSymbol(),
allBsonTypesDocument["timestamp"]!!.asTimestamp(),
allBsonTypesDocument["undefined"]!! as BsonUndefined)
assertRoundTrips(allBsonTypesJson, dataClass)
}
@Test
fun testDataClassOptionalBsonValues() {
val dataClass =
DataClassOptionalBsonValues(
allBsonTypesDocument["id"]!!.asObjectId().value,
allBsonTypesDocument["arrayEmpty"]!!.asArray(),
allBsonTypesDocument["arraySimple"]!!.asArray(),
allBsonTypesDocument["arrayComplex"]!!.asArray(),
allBsonTypesDocument["arrayMixedTypes"]!!.asArray(),
allBsonTypesDocument["arrayComplexMixedTypes"]!!.asArray(),
allBsonTypesDocument["binary"]!!.asBinary(),
allBsonTypesDocument["boolean"]!!.asBoolean(),
allBsonTypesDocument["code"]!!.asJavaScript(),
allBsonTypesDocument["codeWithScope"]!!.asJavaScriptWithScope(),
allBsonTypesDocument["dateTime"]!!.asDateTime(),
allBsonTypesDocument["decimal128"]!!.asDecimal128(),
allBsonTypesDocument["documentEmpty"]!!.asDocument(),
allBsonTypesDocument["document"]!!.asDocument(),
allBsonTypesDocument["double"]!!.asDouble(),
allBsonTypesDocument["int32"]!!.asInt32(),
allBsonTypesDocument["int64"]!!.asInt64(),
allBsonTypesDocument["maxKey"]!! as BsonMaxKey,
allBsonTypesDocument["minKey"]!! as BsonMinKey,
allBsonTypesDocument["objectId"]!!.asObjectId(),
allBsonTypesDocument["regex"]!!.asRegularExpression(),
allBsonTypesDocument["string"]!!.asString(),
allBsonTypesDocument["symbol"]!!.asSymbol(),
allBsonTypesDocument["timestamp"]!!.asTimestamp(),
allBsonTypesDocument["undefined"]!! as BsonUndefined)
assertRoundTrips(allBsonTypesJson, dataClass)
val emptyDataClass =
DataClassOptionalBsonValues(
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null)
assertRoundTrips("{}", emptyDataClass)
assertRoundTrips(
"""{ "id": null, "arrayEmpty": null, "arraySimple": null, "arrayComplex": null, "arrayMixedTypes": null,
| "arrayComplexMixedTypes": null, "binary": null, "boolean": null, "code": null, "codeWithScope": null,
| "dateTime": null, "decimal128": null, "documentEmpty": null, "document": null, "double": null,
| "int32": null, "int64": null, "maxKey": null, "minKey": null, "objectId": null, "regex": null,
| "string": null, "symbol": null, "timestamp": null, "undefined": null }"""
.trimMargin(),
emptyDataClass,
BsonConfiguration(explicitNulls = true))
}
@Test
fun testDataClassSealed() {
val expectedA = """{"a": "string"}"""
val dataClassA = DataClassSealedA("string")
assertRoundTrips(expectedA, dataClassA)
val expectedB = """{"b": 1}"""
val dataClassB = DataClassSealedB(1)
assertRoundTrips(expectedB, dataClassB)
val expectedC = """{"c": "String"}"""
val dataClassC = DataClassSealedC("String")
assertRoundTrips(expectedC, dataClassC)
val expectedDataClassSealedA = """{"_t": "org.bson.codecs.kotlinx.samples.DataClassSealedA", "a": "string"}"""
val dataClassSealedA = DataClassSealedA("string") as DataClassSealed
assertRoundTrips(expectedDataClassSealedA, dataClassSealedA)
val expectedDataClassSealedB = """{"_t": "org.bson.codecs.kotlinx.samples.DataClassSealedB", "b": 1}"""
val dataClassSealedB = DataClassSealedB(1) as DataClassSealed
assertRoundTrips(expectedDataClassSealedB, dataClassSealedB)
val expectedDataClassSealedC = """{"_t": "C", "c": "String"}"""
val dataClassSealedC = DataClassSealedC("String") as DataClassSealed
assertRoundTrips(expectedDataClassSealedC, dataClassSealedC)
val dataClassListOfSealed = DataClassListOfSealed(listOf(dataClassA, dataClassB, dataClassC))
val expectedListOfSealed =
"""{"items": [$expectedDataClassSealedA, $expectedDataClassSealedB, $expectedDataClassSealedC]}"""
assertRoundTrips(expectedListOfSealed, dataClassListOfSealed)
val expectedListOfSealedDiscriminator = expectedListOfSealed.replace("_t", "#class")
assertRoundTrips(
expectedListOfSealedDiscriminator, dataClassListOfSealed, BsonConfiguration(classDiscriminator = "#class"))
}
@Test
fun testDataClassOpen() {
val expectedA = """{"a": "string"}"""
val dataClassA = DataClassOpenA("string")
assertRoundTrips(expectedA, dataClassA)
val expectedB = """{"b": 1}"""
val dataClassB = DataClassOpenB(1)
assertRoundTrips(expectedB, dataClassB)
val serializersModule =
SerializersModule {
this.polymorphic(DataClassOpen::class) {
this.subclass(DataClassOpenA::class)
this.subclass(DataClassOpenB::class)
}
} + defaultSerializersModule
val dataClassContainsOpenA = DataClassContainsOpen(dataClassA)
val expectedOpenA = """{"open": {"_t": "org.bson.codecs.kotlinx.samples.DataClassOpenA", "a": "string"}}"""
assertRoundTrips(expectedOpenA, dataClassContainsOpenA, serializersModule = serializersModule)
val dataClassContainsOpenB = DataClassContainsOpen(dataClassB)
val expectedOpenB = """{"open": {"#class": "org.bson.codecs.kotlinx.samples.DataClassOpenB", "b": 1}}"""
assertRoundTrips(
expectedOpenB,
dataClassContainsOpenB,
configuration = BsonConfiguration(classDiscriminator = "#class"),
serializersModule = serializersModule)
}
@Test
fun testValueClasses() {
val expected = """{"value": "valueString"}"""
val valueClass = ValueClass("valueString")
val dataClass = DataClassContainsValueClass(valueClass)
assertThrows<BsonInvalidOperationException>() { serialize(valueClass) }
assertRoundTrips(expected, dataClass)
}
@Test
fun testDataFailures() {
assertThrows<MissingFieldException>("Missing data") {
val codec = KotlinSerializerCodec.create(DataClassWithSimpleValues::class)
codec?.decode(BsonDocumentReader(BsonDocument()), DecoderContext.builder().build())
}
assertThrows<BsonInvalidOperationException>("Invalid types") {
val data =
BsonDocument.parse(
"""{"char": 123, "short": "2", "int": 22, "long": "ok", "float": true, "double": false,
| "boolean": "true", "string": 99}"""
.trimMargin())
val codec = KotlinSerializerCodec.create<DataClassWithSimpleValues>()
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}
assertThrows<IllegalArgumentException>("Failing init") {
val data = BsonDocument.parse("""{"id": "myId"}""")
val codec = KotlinSerializerCodec.create<DataClassWithFailingInit>()
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}
var exception =
assertThrows<SerializationException>("Invalid complex types - document") {
val data = BsonDocument.parse("""{"_id": "myId", "embedded": 123}""")
val codec = KotlinSerializerCodec.create<DataClassWithEmbedded>()
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}
assertEquals(
"Invalid data for `org.bson.codecs.kotlinx.samples.DataClassEmbedded` " +
"expected a bson document found: INT32",
exception.message)
exception =
assertThrows<SerializationException>("Invalid complex types - list") {
val data = BsonDocument.parse("""{"_id": "myId", "nested": 123}""")
val codec = KotlinSerializerCodec.create<DataClassListOfDataClasses>()
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}
assertEquals("Invalid data for `LIST` expected a bson array found: INT32", exception.message)
exception =
assertThrows<SerializationException>("Invalid complex types - map") {
val data = BsonDocument.parse("""{"_id": "myId", "nested": 123}""")
val codec = KotlinSerializerCodec.create<DataClassMapOfDataClasses>()
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}
assertEquals("Invalid data for `MAP` expected a bson document found: INT32", exception.message)
exception =
assertThrows<SerializationException>("Missing discriminator") {
val data = BsonDocument.parse("""{"_id": {"$oid": "111111111111111111111111"}, "name": "string"}""")
val codec = KotlinSerializerCodec.create<SealedInterface>()
codec?.decode(BsonDocumentReader(data), DecoderContext.builder().build())
}
assertEquals(
"Missing required discriminator field `_t` for polymorphic class: " +
"`org.bson.codecs.kotlinx.samples.SealedInterface`.",
exception.message)
}
@Test
fun testInvalidAnnotations() {
assertThrows<CodecConfigurationException> { KotlinSerializerCodec.create(DataClassWithBsonId::class) }
assertThrows<CodecConfigurationException> { KotlinSerializerCodec.create(DataClassWithBsonProperty::class) }
assertThrows<CodecConfigurationException> {
KotlinSerializerCodec.create(DataClassWithBsonDiscriminator::class)
}
assertThrows<CodecConfigurationException> { KotlinSerializerCodec.create(DataClassWithBsonConstructor::class) }
assertThrows<CodecConfigurationException> { KotlinSerializerCodec.create(DataClassWithBsonIgnore::class) }
assertThrows<CodecConfigurationException> {
KotlinSerializerCodec.create(DataClassWithBsonExtraElements::class)
}
assertThrows<CodecConfigurationException> {
KotlinSerializerCodec.create(DataClassWithBsonRepresentation::class)
}
}
private inline fun <reified T : Any> assertRoundTrips(
expected: String,
value: T,
configuration: BsonConfiguration = BsonConfiguration(),
serializersModule: SerializersModule = defaultSerializersModule
) {
assertDecodesTo(
assertEncodesTo(expected, value, serializersModule, configuration), value, serializersModule, configuration)
}
private inline fun <reified T : Any> assertEncodesTo(
json: String,
value: T,
serializersModule: SerializersModule = defaultSerializersModule,
configuration: BsonConfiguration = BsonConfiguration()
): BsonDocument {
val expected = BsonDocument.parse(json)
val actual = serialize(value, serializersModule, configuration)
assertEquals(expected, actual)
return actual
}
private inline fun <reified T : Any> serialize(
value: T,
serializersModule: SerializersModule = defaultSerializersModule,
configuration: BsonConfiguration = BsonConfiguration()
): BsonDocument {
val document = BsonDocument()
val writer = BsonDocumentWriter(document)
val codec = KotlinSerializerCodec.create(T::class, serializersModule, configuration)!!
codec.encode(writer, value, EncoderContext.builder().build())
writer.flush()
return document
}
private inline fun <reified T : Any> assertDecodesTo(
value: BsonDocument,
expected: T,
serializersModule: SerializersModule = defaultSerializersModule,
configuration: BsonConfiguration = BsonConfiguration()
) {
assertEquals(expected, deserialize(value, serializersModule, configuration))
}
private inline fun <reified T : Any> deserialize(
value: BsonDocument,
serializersModule: SerializersModule = defaultSerializersModule,
configuration: BsonConfiguration = BsonConfiguration()
): T {
val codec = KotlinSerializerCodec.create(T::class, serializersModule, configuration)!!
return codec.decode(BsonDocumentReader(value), DecoderContext.builder().build())
}
}