-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
MappingMongoConverterUnitTests.java
4534 lines (3281 loc) · 137 KB
/
MappingMongoConverterUnitTests.java
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
/*
* Copyright 2011-2024 the original author or authors.
*
* 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
*
* https://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.springframework.data.mongodb.core.convert;
import static java.time.ZoneId.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.data.mongodb.core.DocumentTestUtils.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.nio.ByteBuffer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
import org.assertj.core.data.Percentage;
import org.bson.BsonUndefined;
import org.bson.types.Binary;
import org.bson.types.Code;
import org.bson.types.Decimal128;
import org.bson.types.ObjectId;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.annotation.Transient;
import org.springframework.data.annotation.TypeAlias;
import org.springframework.data.convert.ConverterBuilder;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.convert.PropertyValueConverter;
import org.springframework.data.convert.PropertyValueConverterFactory;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.ValueConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Polygon;
import org.springframework.data.geo.Shape;
import org.springframework.data.mapping.MappingException;
import org.springframework.data.mapping.callback.EntityCallbacks;
import org.springframework.data.mapping.model.MappingInstantiationException;
import org.springframework.data.mongodb.core.DocumentTestUtils;
import org.springframework.data.mongodb.core.convert.DocumentAccessorUnitTests.NestedType;
import org.springframework.data.mongodb.core.convert.DocumentAccessorUnitTests.ProjectingType;
import org.springframework.data.mongodb.core.convert.MappingMongoConverterUnitTests.ClassWithMapUsingEnumAsKey.FooBarEnum;
import org.springframework.data.mongodb.core.geo.Sphere;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.FieldName.Type;
import org.springframework.data.mongodb.core.mapping.FieldType;
import org.springframework.data.mongodb.core.mapping.MongoField;
import org.springframework.data.mongodb.core.mapping.MongoId;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.PersonPojoStringId;
import org.springframework.data.mongodb.core.mapping.TextScore;
import org.springframework.data.mongodb.core.mapping.Unwrapped;
import org.springframework.data.mongodb.core.mapping.event.AfterConvertCallback;
import org.springframework.data.projection.EntityProjection;
import org.springframework.data.projection.EntityProjectionIntrospector;
import org.springframework.data.util.ClassTypeInformation;
import org.springframework.data.util.TypeInformation;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.test.util.ReflectionTestUtils;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
/**
* Unit tests for {@link MappingMongoConverter}.
*
* @author Oliver Gierke
* @author Patrik Wasik
* @author Christoph Strobl
* @author Mark Paluch
* @author Roman Puchkovskiy
* @author Heesu Jung
* @author Julia Lee
*/
@ExtendWith(MockitoExtension.class)
class MappingMongoConverterUnitTests {
private MappingMongoConverter converter;
private MongoMappingContext mappingContext;
@Mock ApplicationContext context;
@Mock DbRefResolver resolver;
@BeforeEach
void beforeEach() {
MongoCustomConversions conversions = new MongoCustomConversions(
Arrays.asList(new ByteBufferToDoubleHolderConverter()));
mappingContext = new MongoMappingContext();
mappingContext.setApplicationContext(context);
mappingContext.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
mappingContext.afterPropertiesSet();
mappingContext.getPersistentEntity(Address.class);
converter = new MappingMongoConverter(resolver, mappingContext);
converter.setCustomConversions(conversions);
converter.afterPropertiesSet();
}
@Test
void convertsAddressCorrectly() {
Address address = new Address();
address.city = "New York";
address.street = "Broadway";
org.bson.Document document = new org.bson.Document();
converter.write(address, document);
assertThat(document.get("city").toString()).isEqualTo("New York");
assertThat(document.get("s").toString()).isEqualTo("Broadway");
}
@Test // DATAMONGO-130
void writesMapTypeCorrectly() {
Map<Locale, String> map = Collections.singletonMap(Locale.US, "Foo");
org.bson.Document document = new org.bson.Document();
converter.write(map, document);
assertThat(document.get(Locale.US.toString()).toString()).isEqualTo("Foo");
}
@Test // DATAMONGO-130
void readsMapWithCustomKeyTypeCorrectly() {
org.bson.Document mapObject = new org.bson.Document(Locale.US.toString(), "Value");
org.bson.Document document = new org.bson.Document("map", mapObject);
ClassWithMapProperty result = converter.read(ClassWithMapProperty.class, document);
assertThat(result.map.get(Locale.US)).isEqualTo("Value");
}
@Test // DATAMONGO-128
void usesDocumentsStoredTypeIfSubtypeOfRequest() {
org.bson.Document document = new org.bson.Document();
document.put("birthDate", new Date());
document.put(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, Person.class.getName());
assertThat(converter.read(Contact.class, document)).isInstanceOf(Person.class);
}
@Test // DATAMONGO-128
void ignoresDocumentsStoredTypeIfCompletelyDifferentTypeRequested() {
org.bson.Document document = new org.bson.Document();
document.put("birthDate", new Date());
document.put(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, Person.class.getName());
assertThat(converter.read(BirthDateContainer.class, document)).isInstanceOf(BirthDateContainer.class);
}
@Test
void writesTypeDiscriminatorIntoRootObject() {
Person person = new Person();
org.bson.Document result = new org.bson.Document();
converter.write(person, result);
assertThat(result.containsKey(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY)).isTrue();
assertThat(result.get(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY).toString()).isEqualTo(Person.class.getName());
}
@Test // DATAMONGO-136
void writesEnumsCorrectly() {
ClassWithEnumProperty value = new ClassWithEnumProperty();
value.sampleEnum = SampleEnum.FIRST;
org.bson.Document result = new org.bson.Document();
converter.write(value, result);
assertThat(result.get("sampleEnum")).isInstanceOf(String.class);
assertThat(result.get("sampleEnum").toString()).isEqualTo("FIRST");
}
@Test // DATAMONGO-209
void writesEnumCollectionCorrectly() {
ClassWithEnumProperty value = new ClassWithEnumProperty();
value.enums = Arrays.asList(SampleEnum.FIRST);
org.bson.Document result = new org.bson.Document();
converter.write(value, result);
assertThat(result.get("enums")).isInstanceOf(List.class);
List<Object> enums = (List<Object>) result.get("enums");
assertThat(enums.size()).isEqualTo(1);
assertThat(enums.get(0)).isEqualTo("FIRST");
}
@Test // DATAMONGO-136
void readsEnumsCorrectly() {
org.bson.Document document = new org.bson.Document("sampleEnum", "FIRST");
ClassWithEnumProperty result = converter.read(ClassWithEnumProperty.class, document);
assertThat(result.sampleEnum).isEqualTo(SampleEnum.FIRST);
}
@Test // DATAMONGO-209
void readsEnumCollectionsCorrectly() {
BasicDBList enums = new BasicDBList();
enums.add("FIRST");
org.bson.Document document = new org.bson.Document("enums", enums);
ClassWithEnumProperty result = converter.read(ClassWithEnumProperty.class, document);
assertThat(result.enums).isInstanceOf(List.class);
assertThat(result.enums.size()).isEqualTo(1);
assertThat(result.enums).contains(SampleEnum.FIRST);
}
@Test // DATAMONGO-144
void considersFieldNameWhenWriting() {
Person person = new Person();
person.firstname = "Oliver";
org.bson.Document result = new org.bson.Document();
converter.write(person, result);
assertThat(result.containsKey("foo")).isTrue();
assertThat(result.containsKey("firstname")).isFalse();
}
@Test // DATAMONGO-144
void considersFieldNameWhenReading() {
org.bson.Document document = new org.bson.Document("foo", "Oliver");
Person result = converter.read(Person.class, document);
assertThat(result.firstname).isEqualTo("Oliver");
}
@Test
void resolvesNestedComplexTypeForConstructorCorrectly() {
org.bson.Document address = new org.bson.Document("street", "110 Southwark Street");
address.put("city", "London");
BasicDBList addresses = new BasicDBList();
addresses.add(address);
org.bson.Document person = new org.bson.Document("firstname", "Oliver");
person.put("addresses", addresses);
Person result = converter.read(Person.class, person);
assertThat(result.addresses).isNotNull();
}
@Test // DATAMONGO-145
void writesCollectionWithInterfaceCorrectly() {
Person person = new Person();
person.firstname = "Oliver";
CollectionWrapper wrapper = new CollectionWrapper();
wrapper.contacts = Arrays.asList((Contact) person);
org.bson.Document document = new org.bson.Document();
converter.write(wrapper, document);
Object result = document.get("contacts");
assertThat(result).isInstanceOf(List.class);
List<Object> contacts = (List<Object>) result;
org.bson.Document personDocument = (org.bson.Document) contacts.get(0);
assertThat(personDocument.get("foo").toString()).isEqualTo("Oliver");
assertThat((String) personDocument.get(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY)).isEqualTo(Person.class.getName());
}
@Test // DATAMONGO-145
void readsCollectionWithInterfaceCorrectly() {
org.bson.Document person = new org.bson.Document(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, Person.class.getName());
person.put("foo", "Oliver");
BasicDBList contacts = new BasicDBList();
contacts.add(person);
CollectionWrapper result = converter.read(CollectionWrapper.class, new org.bson.Document("contacts", contacts));
assertThat(result.contacts).isNotNull();
assertThat(result.contacts.size()).isEqualTo(1);
Contact contact = result.contacts.get(0);
assertThat(contact).isInstanceOf(Person.class);
assertThat(((Person) contact).firstname).isEqualTo("Oliver");
}
@Test
void convertsLocalesOutOfTheBox() {
LocaleWrapper wrapper = new LocaleWrapper();
wrapper.locale = Locale.US;
org.bson.Document document = new org.bson.Document();
converter.write(wrapper, document);
Object localeField = document.get("locale");
assertThat(localeField).isInstanceOf(String.class);
assertThat(localeField).isEqualTo("en_US");
LocaleWrapper read = converter.read(LocaleWrapper.class, document);
assertThat(read.locale).isEqualTo(Locale.US);
}
@Test // DATAMONGO-161
void readsNestedMapsCorrectly() {
Map<String, String> secondLevel = new HashMap<String, String>();
secondLevel.put("key1", "value1");
secondLevel.put("key2", "value2");
Map<String, Map<String, String>> firstLevel = new HashMap<String, Map<String, String>>();
firstLevel.put("level1", secondLevel);
firstLevel.put("level2", secondLevel);
ClassWithNestedMaps maps = new ClassWithNestedMaps();
maps.nestedMaps = new LinkedHashMap<String, Map<String, Map<String, String>>>();
maps.nestedMaps.put("afield", firstLevel);
org.bson.Document document = new org.bson.Document();
converter.write(maps, document);
ClassWithNestedMaps result = converter.read(ClassWithNestedMaps.class, document);
Map<String, Map<String, Map<String, String>>> nestedMap = result.nestedMaps;
assertThat(nestedMap).isNotNull();
assertThat(nestedMap.get("afield")).isEqualTo(firstLevel);
}
@Test // DATACMNS-42, DATAMONGO-171
void writesClassWithBigDecimal() {
BigDecimalContainer container = new BigDecimalContainer();
container.value = BigDecimal.valueOf(2.5d);
container.map = Collections.singletonMap("foo", container.value);
org.bson.Document document = new org.bson.Document();
converter.write(container, document);
assertThat(document.get("value")).isInstanceOf(String.class);
assertThat((String) document.get("value")).isEqualTo("2.5");
assertThat(((org.bson.Document) document.get("map")).get("foo")).isInstanceOf(String.class);
}
@Test // DATACMNS-42, DATAMONGO-171
void readsClassWithBigDecimal() {
org.bson.Document document = new org.bson.Document("value", "2.5");
document.put("map", new org.bson.Document("foo", "2.5"));
BasicDBList list = new BasicDBList();
list.add("2.5");
document.put("collection", list);
BigDecimalContainer result = converter.read(BigDecimalContainer.class, document);
assertThat(result.value).isEqualTo(BigDecimal.valueOf(2.5d));
assertThat(result.map.get("foo")).isEqualTo(BigDecimal.valueOf(2.5d));
assertThat(result.collection.get(0)).isEqualTo(BigDecimal.valueOf(2.5d));
}
@Test
void writesNestedCollectionsCorrectly() {
CollectionWrapper wrapper = new CollectionWrapper();
wrapper.strings = Arrays.asList(Arrays.asList("Foo"));
org.bson.Document document = new org.bson.Document();
converter.write(wrapper, document);
Object outerStrings = document.get("strings");
assertThat(outerStrings).isInstanceOf(List.class);
List<Object> typedOuterString = (List<Object>) outerStrings;
assertThat(typedOuterString.size()).isEqualTo(1);
}
@Test // DATAMONGO-192
void readsEmptySetsCorrectly() {
Person person = new Person();
person.addresses = Collections.emptySet();
org.bson.Document document = new org.bson.Document();
converter.write(person, document);
converter.read(Person.class, document);
}
@Test
void convertsObjectIdStringsToObjectIdCorrectly() {
PersonPojoStringId p1 = new PersonPojoStringId("1234567890", "Text-1");
org.bson.Document doc1 = new org.bson.Document();
converter.write(p1, doc1);
assertThat(doc1.get("_id")).isInstanceOf(String.class);
PersonPojoStringId p2 = new PersonPojoStringId(new ObjectId().toString(), "Text-1");
org.bson.Document doc2 = new org.bson.Document();
converter.write(p2, doc2);
assertThat(doc2.get("_id")).isInstanceOf(ObjectId.class);
}
@Test // DATAMONGO-207
void convertsCustomEmptyMapCorrectly() {
org.bson.Document map = new org.bson.Document();
org.bson.Document wrapper = new org.bson.Document("map", map);
ClassWithSortedMap result = converter.read(ClassWithSortedMap.class, wrapper);
assertThat(result).isInstanceOf(ClassWithSortedMap.class);
assertThat(result.map).isInstanceOf(SortedMap.class);
}
@Test // DATAMONGO-211
void maybeConvertHandlesNullValuesCorrectly() {
assertThat(converter.convertToMongoType(null)).isNull();
}
@Test // DATAMONGO-1509
void writesGenericTypeCorrectly() {
GenericType<Address> type = new GenericType<Address>();
type.content = new Address();
type.content.city = "London";
org.bson.Document result = new org.bson.Document();
converter.write(type, result);
org.bson.Document content = (org.bson.Document) result.get("content");
assertTypeHint(content, Address.class);
assertThat(content.get("city")).isNotNull();
}
@Test
void readsGenericTypeCorrectly() {
org.bson.Document address = new org.bson.Document("_class", Address.class.getName());
address.put("city", "London");
GenericType<?> result = converter.read(GenericType.class, new org.bson.Document("content", address));
assertThat(result.content).isInstanceOf(Address.class);
}
@Test // DATAMONGO-228
void writesNullValuesForMaps() {
ClassWithMapProperty foo = new ClassWithMapProperty();
foo.map = Collections.singletonMap(Locale.US, null);
org.bson.Document result = new org.bson.Document();
converter.write(foo, result);
Object map = result.get("map");
assertThat(map).isInstanceOf(org.bson.Document.class);
assertThat(((org.bson.Document) map).keySet()).contains("en_US");
}
@Test
void writesBigIntegerIdCorrectly() {
ClassWithBigIntegerId foo = new ClassWithBigIntegerId();
foo.id = BigInteger.valueOf(23L);
org.bson.Document result = new org.bson.Document();
converter.write(foo, result);
assertThat(result.get("_id")).isInstanceOf(String.class);
}
@Test
void convertsObjectsIfNecessary() {
ObjectId id = new ObjectId();
assertThat(converter.convertToMongoType(id)).isEqualTo(id);
}
@Test // DATAMONGO-235
void writesMapOfListsCorrectly() {
ClassWithMapProperty input = new ClassWithMapProperty();
input.mapOfLists = Collections.singletonMap("Foo", Arrays.asList("Bar"));
org.bson.Document result = new org.bson.Document();
converter.write(input, result);
Object field = result.get("mapOfLists");
assertThat(field).isInstanceOf(org.bson.Document.class);
org.bson.Document map = (org.bson.Document) field;
Object foo = map.get("Foo");
assertThat(foo).isInstanceOf(List.class);
List<Object> value = (List<Object>) foo;
assertThat(value.size()).isEqualTo(1);
assertThat(value.get(0)).isEqualTo("Bar");
}
@Test // DATAMONGO-235
void readsMapListValuesCorrectly() {
BasicDBList list = new BasicDBList();
list.add("Bar");
org.bson.Document source = new org.bson.Document("mapOfLists", new org.bson.Document("Foo", list));
ClassWithMapProperty result = converter.read(ClassWithMapProperty.class, source);
assertThat(result.mapOfLists).isNotNull();
}
@Test // DATAMONGO-235
void writesMapsOfObjectsCorrectly() {
ClassWithMapProperty input = new ClassWithMapProperty();
input.mapOfObjects = new HashMap<String, Object>();
input.mapOfObjects.put("Foo", Arrays.asList("Bar"));
org.bson.Document result = new org.bson.Document();
converter.write(input, result);
Object field = result.get("mapOfObjects");
assertThat(field).isInstanceOf(org.bson.Document.class);
org.bson.Document map = (org.bson.Document) field;
Object foo = map.get("Foo");
assertThat(foo).isInstanceOf(List.class);
List value = (List) foo;
assertThat(value.size()).isEqualTo(1);
assertThat(value.get(0)).isEqualTo("Bar");
}
@Test // DATAMONGO-235
void readsMapOfObjectsListValuesCorrectly() {
BasicDBList list = new BasicDBList();
list.add("Bar");
org.bson.Document source = new org.bson.Document("mapOfObjects", new org.bson.Document("Foo", list));
ClassWithMapProperty result = converter.read(ClassWithMapProperty.class, source);
assertThat(result.mapOfObjects).isNotNull();
}
@Test // DATAMONGO-245
void readsMapListNestedValuesCorrectly() {
BasicDBList list = new BasicDBList();
list.add(new org.bson.Document("Hello", "World"));
org.bson.Document source = new org.bson.Document("mapOfObjects", new org.bson.Document("Foo", list));
ClassWithMapProperty result = converter.read(ClassWithMapProperty.class, source);
Object firstObjectInFoo = ((List<?>) result.mapOfObjects.get("Foo")).get(0);
assertThat(firstObjectInFoo).isInstanceOf(Map.class);
assertThat(((Map<?, ?>) firstObjectInFoo).get("Hello")).isEqualTo("World");
}
@Test // DATAMONGO-245
void readsMapDoublyNestedValuesCorrectly() {
org.bson.Document nested = new org.bson.Document();
org.bson.Document doubly = new org.bson.Document();
doubly.append("Hello", "World");
nested.append("nested", doubly);
org.bson.Document source = new org.bson.Document("mapOfObjects", new org.bson.Document("Foo", nested));
ClassWithMapProperty result = converter.read(ClassWithMapProperty.class, source);
Object foo = result.mapOfObjects.get("Foo");
assertThat(foo).isInstanceOf(Map.class);
Object doublyNestedObject = ((Map<?, ?>) foo).get("nested");
assertThat(doublyNestedObject).isInstanceOf(Map.class);
assertThat(((Map<?, ?>) doublyNestedObject).get("Hello")).isEqualTo("World");
}
@Test // DATAMONGO-245
void readsMapListDoublyNestedValuesCorrectly() {
BasicDBList list = new BasicDBList();
org.bson.Document nested = new org.bson.Document();
org.bson.Document doubly = new org.bson.Document();
doubly.append("Hello", "World");
nested.append("nested", doubly);
list.add(nested);
org.bson.Document source = new org.bson.Document("mapOfObjects", new org.bson.Document("Foo", list));
ClassWithMapProperty result = converter.read(ClassWithMapProperty.class, source);
Object firstObjectInFoo = ((List<?>) result.mapOfObjects.get("Foo")).get(0);
assertThat(firstObjectInFoo).isInstanceOf(Map.class);
Object doublyNestedObject = ((Map<?, ?>) firstObjectInFoo).get("nested");
assertThat(doublyNestedObject).isInstanceOf(Map.class);
assertThat(((Map<?, ?>) doublyNestedObject).get("Hello")).isEqualTo("World");
}
@Test // DATAMONGO-259
void writesListOfMapsCorrectly() {
Map<String, Locale> map = Collections.singletonMap("Foo", Locale.ENGLISH);
CollectionWrapper wrapper = new CollectionWrapper();
wrapper.listOfMaps = new ArrayList<Map<String, Locale>>();
wrapper.listOfMaps.add(map);
org.bson.Document result = new org.bson.Document();
converter.write(wrapper, result);
List<Object> list = (List<Object>) result.get("listOfMaps");
assertThat(list).isNotNull();
assertThat(list.size()).isEqualTo(1);
org.bson.Document document = (org.bson.Document) list.get(0);
assertThat(document.containsKey("Foo")).isTrue();
assertThat((String) document.get("Foo")).isEqualTo(Locale.ENGLISH.toString());
}
@Test // DATAMONGO-259
void readsListOfMapsCorrectly() {
org.bson.Document map = new org.bson.Document("Foo", "en");
BasicDBList list = new BasicDBList();
list.add(map);
org.bson.Document wrapperSource = new org.bson.Document("listOfMaps", list);
CollectionWrapper wrapper = converter.read(CollectionWrapper.class, wrapperSource);
assertThat(wrapper.listOfMaps).isNotNull();
assertThat(wrapper.listOfMaps.size()).isEqualTo(1);
assertThat(wrapper.listOfMaps.get(0)).isNotNull();
assertThat(wrapper.listOfMaps.get(0).get("Foo")).isEqualTo(Locale.ENGLISH);
}
@ParameterizedTest(name = "{4}") // GH-4571
@MethodSource("listMapSetReadingSource")
<T> void initializesListMapSetPropertiesIfRequiredOnRead(org.bson.Document source, Class<T> type,
Function<T, Object> valueFunction, Object expectedValue, String displayName) {
T target = converter.read(type, source);
assertThat(target).extracting(valueFunction).isEqualTo(expectedValue);
}
private static Stream<Arguments> listMapSetReadingSource() {
Stream<Arguments> initialList = fixtureFor("contacts", CollectionWrapper.class, CollectionWrapper::getContacts,
builder -> {
builder.onValue(Collections.emptyList()).expect(Collections.emptyList());
builder.onNull().expect(null);
builder.onEmpty().expect(null);
});
Stream<Arguments> initializedList = fixtureFor("autoInitList", CollectionWrapper.class,
CollectionWrapper::getAutoInitList, builder -> {
builder.onValue(Collections.emptyList()).expect(Collections.emptyList());
builder.onNull().expect(null);
builder.onEmpty().expect(Collections.singletonList("spring"));
});
Stream<Arguments> initialSet = fixtureFor("contactsSet", CollectionWrapper.class, CollectionWrapper::getContactsSet,
builder -> {
builder.onValue(Collections.emptyList()).expect(Collections.emptySet());
builder.onNull().expect(null);
builder.onEmpty().expect(null);
});
Stream<Arguments> initialMap = fixtureFor("map", ClassWithMapProperty.class, ClassWithMapProperty::getMap,
builder -> {
builder.onValue(new org.bson.Document()).expect(Collections.emptyMap());
builder.onNull().expect(null);
builder.onEmpty().expect(null);
});
Stream<Arguments> initializedMap = fixtureFor("autoInitMap", ClassWithMapProperty.class,
ClassWithMapProperty::getAutoInitMap, builder -> {
builder.onValue(new org.bson.Document()).expect(Collections.emptyMap());
builder.onNull().expect(null);
builder.onEmpty().expect(Collections.singletonMap("spring", "data"));
});
return Stream.of(initialList, initializedList, initialSet, initialMap, initializedMap).flatMap(Function.identity());
}
static <T> Stream<Arguments> fixtureFor(String field, Class<T> type, Function<T, Object> valueFunction,
Consumer<FixtureBuilder> builderConsumer) {
FixtureBuilder builder = new FixtureBuilder(field, type, valueFunction);
builderConsumer.accept(builder);
return builder.fixtures.stream();
}
/**
* Builder for fixtures.
*/
static class FixtureBuilder {
private final String field;
private final Class<?> typeUnderTest;
private final Function<?, Object> valueMappingFunction;
final List<Arguments> fixtures = new ArrayList<>();
FixtureBuilder(String field, Class<?> typeUnderTest, Function<?, Object> valueMappingFunction) {
this.field = field;
this.typeUnderTest = typeUnderTest;
this.valueMappingFunction = valueMappingFunction;
}
/**
* If the document value is {@code null}.
*/
FixtureStep onNull() {
return new FixtureStep(false, null);
}
/**
* If the document value is {@code value}.
*/
FixtureStep onValue(@Nullable Object value) {
return new FixtureStep(false, value);
}
/**
* If the document does not contain the field.
*/
FixtureStep onEmpty() {
return new FixtureStep(true, null);
}
class FixtureStep {
private final boolean empty;
private final @Nullable Object documentValue;
public FixtureStep(boolean empty, @Nullable Object documentValue) {
this.empty = empty;
this.documentValue = documentValue;
}
/**
* Then expect {@code expectedValue}.
*
* @param expectedValue
*/
void expect(@Nullable Object expectedValue) {
Arguments fixture;
if (empty) {
fixture = Arguments.of(new org.bson.Document(), typeUnderTest, valueMappingFunction, expectedValue,
"Empty document expecting '%s' at type %s".formatted(expectedValue, typeUnderTest.getSimpleName()));
} else {
String valueDescription = (documentValue == null ? "null"
: (documentValue + " (" + documentValue.getClass().getSimpleName()) + ")");
fixture = Arguments.of(new org.bson.Document(field, documentValue), typeUnderTest, valueMappingFunction,
expectedValue, "Field '%s' with value %s expecting '%s' at type %s".formatted(field, valueDescription,
expectedValue, typeUnderTest.getSimpleName()));
}
fixtures.add(fixture);
}
}
}
@Test // DATAMONGO-259
void writesPlainMapOfCollectionsCorrectly() {
Map<String, List<Locale>> map = Collections.singletonMap("Foo", Arrays.asList(Locale.US));
org.bson.Document result = new org.bson.Document();
converter.write(map, result);
assertThat(result.containsKey("Foo")).isTrue();
assertThat(result.get("Foo")).isNotNull();
assertThat(result.get("Foo")).isInstanceOf(List.class);
List list = (List) result.get("Foo");
assertThat(list.size()).isEqualTo(1);
assertThat(list.get(0)).isEqualTo(Locale.US.toString());
}
@Test // DATAMONGO-285
@SuppressWarnings({ "unchecked", "rawtypes" })
void testSaveMapWithACollectionAsValue() {
Map<String, Object> keyValues = new HashMap<String, Object>();
keyValues.put("string", "hello");
List<String> list = new ArrayList<String>();
list.add("ping");
list.add("pong");
keyValues.put("list", list);
org.bson.Document document = new org.bson.Document();
converter.write(keyValues, document);
Map<String, Object> keyValuesFromMongo = converter.read(Map.class, document);
assertThat(keyValuesFromMongo.size()).isEqualTo(keyValues.size());
assertThat(keyValuesFromMongo.get("string")).isEqualTo(keyValues.get("string"));
assertThat(List.class.isAssignableFrom(keyValuesFromMongo.get("list").getClass())).isTrue();
List<String> listFromMongo = (List) keyValuesFromMongo.get("list");
assertThat(listFromMongo.size()).isEqualTo(list.size());
assertThat(listFromMongo.get(0)).isEqualTo(list.get(0));
assertThat(listFromMongo.get(1)).isEqualTo(list.get(1));
}
@Test // DATAMONGO-309
@SuppressWarnings({ "unchecked" })
void writesArraysAsMapValuesCorrectly() {
ClassWithMapProperty wrapper = new ClassWithMapProperty();
wrapper.mapOfObjects = new HashMap<String, Object>();
wrapper.mapOfObjects.put("foo", new String[] { "bar" });
org.bson.Document result = new org.bson.Document();
converter.write(wrapper, result);
Object mapObject = result.get("mapOfObjects");
assertThat(mapObject).isInstanceOf(org.bson.Document.class);
org.bson.Document map = (org.bson.Document) mapObject;
Object valueObject = map.get("foo");
assertThat(valueObject).isInstanceOf(List.class);
List<Object> list = (List<Object>) valueObject;
assertThat(list.size()).isEqualTo(1);
assertThat(list).contains((Object) "bar");
}
@Test // DATAMONGO-324
void writesDocumentCorrectly() {
org.bson.Document document = new org.bson.Document();
document.put("foo", "bar");
org.bson.Document result = new org.bson.Document();
converter.write(document, result);
result.remove(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY);
assertThat(document).isEqualTo(result);
}
@Test // DATAMONGO-324
void readsDocumentCorrectly() {
org.bson.Document document = new org.bson.Document();
document.put("foo", "bar");
org.bson.Document result = converter.read(org.bson.Document.class, document);
assertThat(result).isEqualTo(document);
}
@Test // DATAMONGO-329
void writesMapAsGenericFieldCorrectly() {
Map<String, A<String>> objectToSave = new HashMap<String, A<String>>();
objectToSave.put("test", new A<String>("testValue"));
A<Map<String, A<String>>> a = new A<Map<String, A<String>>>(objectToSave);
org.bson.Document result = new org.bson.Document();
converter.write(a, result);
assertThat(result.get(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY)).isEqualTo(A.class.getName());
assertThat(result.get("valueType")).isEqualTo(HashMap.class.getName());
org.bson.Document object = (org.bson.Document) result.get("value");
assertThat(object).isNotNull();
org.bson.Document inner = (org.bson.Document) object.get("test");
assertThat(inner).isNotNull();
assertThat(inner.get(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY)).isEqualTo(A.class.getName());
assertThat(inner.get("valueType")).isEqualTo(String.class.getName());
assertThat(inner.get("value")).isEqualTo("testValue");
}
@Test
void writesIntIdCorrectly() {
ClassWithIntId value = new ClassWithIntId();
value.id = 5;
org.bson.Document result = new org.bson.Document();
converter.write(value, result);
assertThat(result.get("_id")).isEqualTo(5);
}
@Test // DATAMONGO-368
@SuppressWarnings("unchecked")
void writesNullValuesForCollection() {
CollectionWrapper wrapper = new CollectionWrapper();
wrapper.contacts = Arrays.asList(new Person(), null);
org.bson.Document result = new org.bson.Document();
converter.write(wrapper, result);
Object contacts = result.get("contacts");
assertThat(contacts).isInstanceOf(Collection.class);
assertThat(((Collection<?>) contacts).size()).isEqualTo(2);
assertThat((Collection<Object>) contacts).containsNull();
}
@Test // DATAMONGO-379
void considersDefaultingExpressionsAtConstructorArguments() {
org.bson.Document document = new org.bson.Document("foo", "bar");
document.put("foobar", 2.5);
DefaultedConstructorArgument result = converter.read(DefaultedConstructorArgument.class, document);
assertThat(result.bar).isEqualTo(-1);
}
@Test // DATAMONGO-379
void usesDocumentFieldIfReferencedInAtValue() {
org.bson.Document document = new org.bson.Document("foo", "bar");
document.put("something", 37);
document.put("foobar", 2.5);
DefaultedConstructorArgument result = converter.read(DefaultedConstructorArgument.class, document);
assertThat(result.bar).isEqualTo(37);
}
@Test // DATAMONGO-379
void rejectsNotFoundConstructorParameterForPrimitiveType() {
org.bson.Document document = new org.bson.Document("foo", "bar");
assertThatThrownBy(() -> converter.read(DefaultedConstructorArgument.class, document))
.isInstanceOf(MappingInstantiationException.class);
}
@Test // DATAMONGO-358
void writesListForObjectPropertyCorrectly() {
Attribute attribute = new Attribute();
attribute.key = "key";
attribute.value = Arrays.asList("1", "2");