-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathExtensionDataTests.cs
More file actions
1466 lines (1204 loc) · 65.6 KB
/
ExtensionDataTests.cs
File metadata and controls
1466 lines (1204 loc) · 65.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public abstract class ExtensionDataTests : SerializerTests
{
public ExtensionDataTests(JsonSerializerWrapper serializerWrapper) : base(serializerWrapper) { }
[Fact]
public async Task EmptyPropertyName_WinsOver_ExtensionDataEmptyPropertyName()
{
string json = @"{"""":1}";
ClassWithEmptyPropertyNameAndExtensionProperty obj;
// Create a new options instances to re-set any caches.
JsonSerializerOptions options = new JsonSerializerOptions();
// Verify the real property wins over the extension data property.
obj = await Serializer.DeserializeWrapper<ClassWithEmptyPropertyNameAndExtensionProperty>(json, options);
Assert.Equal(1, obj.MyInt1);
Assert.Null(obj.MyOverflow);
}
[Fact]
public async Task EmptyPropertyNameInExtensionData()
{
{
string json = @"{"""":42}";
EmptyClassWithExtensionProperty obj = await Serializer.DeserializeWrapper<EmptyClassWithExtensionProperty>(json);
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Equal(42, obj.MyOverflow[""].GetInt32());
}
{
// Verify that last-in wins.
string json = @"{"""":42, """":43}";
EmptyClassWithExtensionProperty obj = await Serializer.DeserializeWrapper<EmptyClassWithExtensionProperty>(json);
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Equal(43, obj.MyOverflow[""].GetInt32());
}
}
[Fact]
#if BUILDING_SOURCE_GENERATOR_TESTS
[ActiveIssue("Needs SimpleTestClass support.")]
#endif
public async Task ExtensionPropertyNotUsed()
{
string json = @"{""MyNestedClass"":" + SimpleTestClass.s_json + "}";
ClassWithExtensionProperty obj = await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(json);
Assert.Null(obj.MyOverflow);
}
[Fact]
public async Task ExtensionPropertyRoundTrip()
{
ClassWithExtensionProperty obj;
{
string json = @"{""MyIntMissing"":2, ""MyInt"":1, ""MyNestedClassMissing"":" + SimpleTestClass.s_json + "}";
obj = await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(json);
Verify();
}
// Round-trip the json.
{
string json = await Serializer.SerializeWrapper(obj);
obj = await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(json);
Verify();
// The json should not contain the dictionary name.
Assert.DoesNotContain(nameof(ClassWithExtensionProperty.MyOverflow), json);
}
void Verify()
{
Assert.NotNull(obj.MyOverflow);
Assert.Equal(1, obj.MyInt);
Assert.Equal(2, obj.MyOverflow["MyIntMissing"].GetInt32());
JsonProperty[] properties = obj.MyOverflow["MyNestedClassMissing"].EnumerateObject().ToArray();
// Verify a couple properties
Assert.Equal(1, properties.Where(prop => prop.Name == "MyInt16").First().Value.GetInt32());
Assert.True(properties.Where(prop => prop.Name == "MyBooleanTrue").First().Value.GetBoolean());
}
}
[Fact]
#if BUILDING_SOURCE_GENERATOR_TESTS
[ActiveIssue("Needs SimpleTestClass support.")]
#endif
public async Task ExtensionFieldNotUsed()
{
string json = @"{""MyNestedClass"":" + SimpleTestClass.s_json + "}";
ClassWithExtensionField obj = await Serializer.DeserializeWrapper<ClassWithExtensionField>(json);
Assert.Null(obj.MyOverflow);
}
[Fact]
public async Task ExtensionFieldRoundTrip()
{
ClassWithExtensionField obj;
{
string json = @"{""MyIntMissing"":2, ""MyInt"":1, ""MyNestedClassMissing"":" + SimpleTestClass.s_json + "}";
obj = await Serializer.DeserializeWrapper<ClassWithExtensionField>(json);
Verify();
}
// Round-trip the json.
{
string json = await Serializer.SerializeWrapper(obj);
obj = await Serializer.DeserializeWrapper<ClassWithExtensionField>(json);
Verify();
// The json should not contain the dictionary name.
Assert.DoesNotContain(nameof(ClassWithExtensionField.MyOverflow), json);
}
void Verify()
{
Assert.NotNull(obj.MyOverflow);
Assert.Equal(1, obj.MyInt);
Assert.Equal(2, obj.MyOverflow["MyIntMissing"].GetInt32());
JsonProperty[] properties = obj.MyOverflow["MyNestedClassMissing"].EnumerateObject().ToArray();
// Verify a couple properties
Assert.Equal(1, properties.Where(prop => prop.Name == "MyInt16").First().Value.GetInt32());
Assert.True(properties.Where(prop => prop.Name == "MyBooleanTrue").First().Value.GetBoolean());
}
}
[Fact]
public async Task ExtensionPropertyIgnoredWhenWritingDefault()
{
string expected = @"{}";
string actual = await Serializer.SerializeWrapper(new ClassWithExtensionPropertyAsObject());
Assert.Equal(expected, actual);
}
[Fact]
public async Task MultipleExtensionPropertyIgnoredWhenWritingDefault()
{
var obj = new ClassWithMultipleDictionaries();
string actual = await Serializer.SerializeWrapper(obj);
Assert.Equal("{\"ActualDictionary\":null}", actual);
obj = new ClassWithMultipleDictionaries
{
ActualDictionary = new Dictionary<string, object>()
};
actual = await Serializer.SerializeWrapper(obj);
Assert.Equal("{\"ActualDictionary\":{}}", actual);
obj = new ClassWithMultipleDictionaries
{
MyOverflow = new Dictionary<string, object>
{
{ "test", "value" }
}
};
actual = await Serializer.SerializeWrapper(obj);
Assert.Equal("{\"ActualDictionary\":null,\"test\":\"value\"}", actual);
obj = new ClassWithMultipleDictionaries
{
ActualDictionary = new Dictionary<string, object>(),
MyOverflow = new Dictionary<string, object>
{
{ "test", "value" }
}
};
actual = await Serializer.SerializeWrapper(obj);
Assert.Equal("{\"ActualDictionary\":{},\"test\":\"value\"}", actual);
}
[Fact]
public async Task ExtensionPropertyInvalidJsonFail()
{
const string BadJson = @"{""Good"":""OK"",""Bad"":!}";
JsonException jsonException = await Assert.ThrowsAsync<JsonException>(async () => await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsObject>(BadJson));
Assert.Contains("Path: $.Bad | LineNumber: 0 | BytePositionInLine: 19.", jsonException.ToString());
Assert.NotNull(jsonException.InnerException);
Assert.IsAssignableFrom<JsonException>(jsonException.InnerException);
Assert.Contains("!", jsonException.InnerException.ToString());
}
[Fact]
public async Task ExtensionPropertyAlreadyInstantiated()
{
Assert.NotNull(new ClassWithExtensionPropertyAlreadyInstantiated().MyOverflow);
string json = @"{""MyIntMissing"":2}";
ClassWithExtensionProperty obj = await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(json);
Assert.Equal(2, obj.MyOverflow["MyIntMissing"].GetInt32());
}
[Fact]
public async Task ExtensionPropertyAsObject()
{
string json = @"{""MyIntMissing"":2}";
ClassWithExtensionPropertyAsObject obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsObject>(json);
Assert.IsType<JsonElement>(obj.MyOverflow["MyIntMissing"]);
Assert.Equal(2, ((JsonElement)obj.MyOverflow["MyIntMissing"]).GetInt32());
}
[Fact]
public async Task ExtensionPropertyCamelCasing()
{
// Currently we apply no naming policy. If we do (such as a ExtensionPropertyNamingPolicy), we'd also have to add functionality to the JsonDocument.
ClassWithExtensionProperty obj;
const string jsonWithProperty = @"{""MyIntMissing"":1}";
const string jsonWithPropertyCamelCased = @"{""myIntMissing"":1}";
{
// Baseline Pascal-cased json + no casing option.
obj = await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(jsonWithProperty);
Assert.Equal(1, obj.MyOverflow["MyIntMissing"].GetInt32());
string json = await Serializer.SerializeWrapper(obj);
Assert.Contains(@"""MyIntMissing"":1", json);
}
{
// Pascal-cased json + camel casing option.
JsonSerializerOptions options = new JsonSerializerOptions();
options.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
obj = await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(jsonWithProperty, options);
Assert.Equal(1, obj.MyOverflow["MyIntMissing"].GetInt32());
string json = await Serializer.SerializeWrapper(obj, options);
Assert.Contains(@"""MyIntMissing"":1", json);
}
{
// Baseline camel-cased json + no casing option.
obj = await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(jsonWithPropertyCamelCased);
Assert.Equal(1, obj.MyOverflow["myIntMissing"].GetInt32());
string json = await Serializer.SerializeWrapper(obj);
Assert.Contains(@"""myIntMissing"":1", json);
}
{
// Baseline camel-cased json + camel casing option.
JsonSerializerOptions options = new JsonSerializerOptions();
options.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
obj = await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(jsonWithPropertyCamelCased, options);
Assert.Equal(1, obj.MyOverflow["myIntMissing"].GetInt32());
string json = await Serializer.SerializeWrapper(obj, options);
Assert.Contains(@"""myIntMissing"":1", json);
}
}
[Fact]
public async Task NullValuesIgnored()
{
const string json = @"{""MyNestedClass"":null}";
const string jsonMissing = @"{""MyNestedClassMissing"":null}";
{
// Baseline with no missing.
ClassWithExtensionProperty obj = await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(json);
Assert.Null(obj.MyOverflow);
string outJson = await Serializer.SerializeWrapper(obj);
Assert.Contains(@"""MyNestedClass"":null", outJson);
}
{
// Baseline with missing.
ClassWithExtensionProperty obj = await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(jsonMissing);
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Equal(JsonValueKind.Null, obj.MyOverflow["MyNestedClassMissing"].ValueKind);
}
{
JsonSerializerOptions options = new JsonSerializerOptions();
options.IgnoreNullValues = true;
ClassWithExtensionProperty obj = await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(jsonMissing, options);
// Currently we do not ignore nulls in the extension data. The JsonDocument would also need to support this mode
// for any lower-level nulls.
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Equal(JsonValueKind.Null, obj.MyOverflow["MyNestedClassMissing"].ValueKind);
}
}
public class ClassWithInvalidExtensionProperty
{
[JsonExtensionData]
public Dictionary<string, int> MyOverflow { get; set; }
}
public class ClassWithTwoExtensionProperties
{
[JsonExtensionData]
public Dictionary<string, object> MyOverflow1 { get; set; }
[JsonExtensionData]
public Dictionary<string, object> MyOverflow2 { get; set; }
}
[Fact]
#if BUILDING_SOURCE_GENERATOR_TESTS
[ActiveIssue("https://github.com/dotnet/runtime/issues/58945")]
#endif
public async Task InvalidExtensionPropertyFail()
{
// Baseline
await Serializer.DeserializeWrapper<ClassWithExtensionProperty>(@"{}");
await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsObject>(@"{}");
await Assert.ThrowsAsync<InvalidOperationException>(async () => await Serializer.DeserializeWrapper<ClassWithInvalidExtensionProperty>(@"{}"));
await Assert.ThrowsAsync<InvalidOperationException>(async () => await Serializer.DeserializeWrapper<ClassWithTwoExtensionProperties>(@"{}"));
}
public class ClassWithIgnoredData
{
[JsonExtensionData]
public Dictionary<string, object> MyOverflow { get; set; }
[JsonIgnore]
public int MyInt { get; set; }
}
[Fact]
public async Task IgnoredDataShouldNotBeExtensionData()
{
ClassWithIgnoredData obj = await Serializer.DeserializeWrapper<ClassWithIgnoredData>(@"{""MyInt"":1}");
Assert.Equal(0, obj.MyInt);
Assert.Null(obj.MyOverflow);
}
public class ClassWithExtensionData<T>
{
[JsonExtensionData]
public T Overflow { get; set; }
}
public class CustomOverflowDictionary<T> : Dictionary<string, T>
{
}
public class DictionaryOverflowConverter : JsonConverter<Dictionary<string, object>>
{
public override Dictionary<string, object> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, Dictionary<string, object> value, JsonSerializerOptions options)
{
writer.WriteString("MyCustomOverflowWrite", "OverflowValueWrite");
}
}
public class JsonElementOverflowConverter : JsonConverter<Dictionary<string, JsonElement>>
{
public override Dictionary<string, JsonElement> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, Dictionary<string, JsonElement> value, JsonSerializerOptions options)
{
writer.WriteString("MyCustomOverflowWrite", "OverflowValueWrite");
}
}
public class JsonObjectOverflowConverter : JsonConverter<JsonObject>
{
public override JsonObject Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, JsonObject value, JsonSerializerOptions options)
{
writer.WriteString("MyCustomOverflowWrite", "OverflowValueWrite");
}
}
public class CustomObjectDictionaryOverflowConverter : JsonConverter<CustomOverflowDictionary<object>>
{
public override CustomOverflowDictionary<object> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, CustomOverflowDictionary<object> value, JsonSerializerOptions options)
{
writer.WriteString("MyCustomOverflowWrite", "OverflowValueWrite");
}
}
public class CustomJsonElementDictionaryOverflowConverter : JsonConverter<CustomOverflowDictionary<JsonElement>>
{
public override CustomOverflowDictionary<JsonElement> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, CustomOverflowDictionary<JsonElement> value, JsonSerializerOptions options)
{
writer.WriteString("MyCustomOverflowWrite", "OverflowValueWrite");
}
}
[Theory]
[InlineData(typeof(Dictionary<string, object>), typeof(DictionaryOverflowConverter))]
[InlineData(typeof(Dictionary<string, JsonElement>), typeof(JsonElementOverflowConverter))]
[InlineData(typeof(CustomOverflowDictionary<object>), typeof(CustomObjectDictionaryOverflowConverter))]
[InlineData(typeof(CustomOverflowDictionary<JsonElement>), typeof(CustomJsonElementDictionaryOverflowConverter))]
public void ExtensionProperty_SupportsWritingToCustomSerializerWithOptions(Type overflowType, Type converterType)
{
typeof(ExtensionDataTests)
.GetMethod(nameof(ExtensionProperty_SupportsWritingToCustomSerializerWithOptionsInternal), BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(overflowType, converterType)
.Invoke(null, null);
}
private static void ExtensionProperty_SupportsWritingToCustomSerializerWithOptionsInternal<TDictionary, TConverter>()
where TDictionary : new()
where TConverter : JsonConverter, new()
{
var root = new ClassWithExtensionData<TDictionary>()
{
Overflow = new TDictionary()
};
var options = new JsonSerializerOptions();
options.Converters.Add(new TConverter());
string json = JsonSerializer.Serialize(root, options);
Assert.Equal(@"{""MyCustomOverflowWrite"":""OverflowValueWrite""}", json);
}
private interface IClassWithOverflow<T>
{
public T Overflow { get; set; }
}
public class ClassWithExtensionDataWithAttributedConverter : IClassWithOverflow<Dictionary<string, object>>
{
[JsonExtensionData]
[JsonConverter(typeof(DictionaryOverflowConverter))]
public Dictionary<string, object> Overflow { get; set; }
}
public class ClassWithJsonElementExtensionDataWithAttributedConverter : IClassWithOverflow<Dictionary<string, JsonElement>>
{
[JsonExtensionData]
[JsonConverter(typeof(JsonElementOverflowConverter))]
public Dictionary<string, JsonElement> Overflow { get; set; }
}
public class ClassWithCustomElementExtensionDataWithAttributedConverter : IClassWithOverflow<CustomOverflowDictionary<object>>
{
[JsonExtensionData]
[JsonConverter(typeof(CustomObjectDictionaryOverflowConverter))]
public CustomOverflowDictionary<object> Overflow { get; set; }
}
public class ClassWithCustomJsonElementExtensionDataWithAttributedConverter : IClassWithOverflow<CustomOverflowDictionary<JsonElement>>
{
[JsonExtensionData]
[JsonConverter(typeof(CustomJsonElementDictionaryOverflowConverter))]
public CustomOverflowDictionary<JsonElement> Overflow { get; set; }
}
[Theory]
[InlineData(typeof(ClassWithExtensionDataWithAttributedConverter), typeof(Dictionary<string, object>))]
[InlineData(typeof(ClassWithJsonElementExtensionDataWithAttributedConverter), typeof(Dictionary<string, JsonElement>))]
[InlineData(typeof(ClassWithCustomElementExtensionDataWithAttributedConverter), typeof(CustomOverflowDictionary<object>))]
[InlineData(typeof(ClassWithCustomJsonElementExtensionDataWithAttributedConverter), typeof(CustomOverflowDictionary<JsonElement>))]
public void ExtensionProperty_SupportsWritingToCustomSerializerWithExplicitConverter(Type attributedType, Type dictionaryType)
{
typeof(ExtensionDataTests)
.GetMethod(nameof(ExtensionProperty_SupportsWritingToCustomSerializerWithExplicitConverterInternal), BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(attributedType, dictionaryType)
.Invoke(null, null);
}
private static void ExtensionProperty_SupportsWritingToCustomSerializerWithExplicitConverterInternal<TRoot, TDictionary>()
where TRoot : IClassWithOverflow<TDictionary>, new()
where TDictionary : new()
{
var root = new TRoot()
{
Overflow = new TDictionary()
};
string json = JsonSerializer.Serialize(root);
Assert.Equal(@"{""MyCustomOverflowWrite"":""OverflowValueWrite""}", json);
}
[Theory]
[InlineData(typeof(Dictionary<string, object>), typeof(DictionaryOverflowConverter), typeof(object))]
[InlineData(typeof(Dictionary<string, JsonElement>), typeof(JsonElementOverflowConverter), typeof(JsonElement))]
[InlineData(typeof(CustomOverflowDictionary<object>), typeof(CustomObjectDictionaryOverflowConverter), typeof(object))]
[InlineData(typeof(CustomOverflowDictionary<JsonElement>), typeof(CustomJsonElementDictionaryOverflowConverter), typeof(JsonElement))]
public void ExtensionProperty_IgnoresCustomSerializerWithOptions(Type overflowType, Type converterType, Type elementType)
{
typeof(ExtensionDataTests)
.GetMethod(nameof(ExtensionProperty_IgnoresCustomSerializerWithOptionsInternal), BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(overflowType, elementType, converterType)
.Invoke(null, null);
}
[Fact]
public async Task ExtensionProperty_IgnoresCustomSerializerWithOptions_JsonObject()
{
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonObjectOverflowConverter());
// A custom converter for JsonObject is not allowed on an extension property.
InvalidOperationException ex = await Assert.ThrowsAsync<InvalidOperationException>(async () =>
await Serializer.DeserializeWrapper<ClassWithExtensionData<JsonObject>>(@"{""TestKey"":""TestValue""}", options));
Assert.Contains("JsonObject", ex.ToString());
}
private static void ExtensionProperty_IgnoresCustomSerializerWithOptionsInternal<TDictionary, TOverflowItem, TConverter>()
where TConverter : JsonConverter, new()
where TDictionary : IDictionary<string, TOverflowItem>
{
var options = new JsonSerializerOptions();
options.Converters.Add(new TConverter());
ClassWithExtensionData<TDictionary> obj
= JsonSerializer.Deserialize<ClassWithExtensionData<TDictionary>>(@"{""TestKey"":""TestValue""}", options);
Assert.Equal("TestValue", ((JsonElement)(object)obj.Overflow["TestKey"]).GetString());
}
[Theory]
[InlineData(typeof(ClassWithExtensionDataWithAttributedConverter), typeof(Dictionary<string, object>), typeof(object))]
[InlineData(typeof(ClassWithJsonElementExtensionDataWithAttributedConverter), typeof(Dictionary<string, JsonElement>), typeof(JsonElement))]
[InlineData(typeof(ClassWithCustomElementExtensionDataWithAttributedConverter), typeof(CustomOverflowDictionary<object>), typeof(object))]
[InlineData(typeof(ClassWithCustomJsonElementExtensionDataWithAttributedConverter), typeof(CustomOverflowDictionary<JsonElement>), typeof(JsonElement))]
public void ExtensionProperty_IgnoresCustomSerializerWithExplicitConverter(Type attributedType, Type dictionaryType, Type elementType)
{
typeof(ExtensionDataTests)
.GetMethod(nameof(ExtensionProperty_IgnoresCustomSerializerWithExplicitConverterInternal), BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(attributedType, dictionaryType, elementType)
.Invoke(null, null);
}
[Fact]
public async Task ExtensionProperty_IgnoresCustomSerializerWithExplicitConverter_JsonObject()
{
ClassWithExtensionData<JsonObject> obj
= await Serializer.DeserializeWrapper<ClassWithExtensionData<JsonObject>>(@"{""TestKey"":""TestValue""}");
Assert.Equal("TestValue", obj.Overflow["TestKey"].GetValue<string>());
}
private static void ExtensionProperty_IgnoresCustomSerializerWithExplicitConverterInternal<TRoot, TDictionary, TOverflowItem>()
where TRoot : IClassWithOverflow<TDictionary>, new()
where TDictionary : IDictionary<string, TOverflowItem>
{
ClassWithExtensionData<TDictionary> obj
= JsonSerializer.Deserialize<ClassWithExtensionData<TDictionary>>(@"{""TestKey"":""TestValue""}");
Assert.Equal("TestValue", ((JsonElement)(object)obj.Overflow["TestKey"]).GetString());
}
[Fact]
public async Task ExtensionPropertyObjectValue_Empty()
{
ClassWithExtensionPropertyAlreadyInstantiated obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAlreadyInstantiated>(@"{}");
Assert.Equal(@"{}", await Serializer.SerializeWrapper(obj));
}
[Fact]
public async Task ExtensionPropertyObjectValue_SameAsExtensionPropertyName()
{
const string json = @"{""MyOverflow"":{""Key1"":""V""}}";
// Deserializing directly into the overflow is not supported by design.
ClassWithExtensionPropertyAsObject obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsObject>(json);
// The JSON is treated as normal overflow.
Assert.NotNull(obj.MyOverflow["MyOverflow"]);
Assert.Equal(json, await Serializer.SerializeWrapper(obj));
}
public class ClassWithExtensionPropertyAsObjectAndNameProperty
{
public string Name { get; set; }
[JsonExtensionData]
public Dictionary<string, object> MyOverflow { get; set; }
}
public static IEnumerable<object[]> JsonSerializerOptions()
{
yield return new object[] { null };
yield return new object[] { new JsonSerializerOptions() };
yield return new object[] { new JsonSerializerOptions { UnknownTypeHandling = JsonUnknownTypeHandling.JsonElement } };
yield return new object[] { new JsonSerializerOptions { UnknownTypeHandling = JsonUnknownTypeHandling.JsonNode } };
}
[Theory]
[MemberData(nameof(JsonSerializerOptions))]
public async Task ExtensionPropertyDuplicateNames(JsonSerializerOptions options)
{
var obj = new ClassWithExtensionPropertyAsObjectAndNameProperty();
obj.Name = "Name1";
obj.MyOverflow = new Dictionary<string, object>();
obj.MyOverflow["Name"] = "Name2";
string json = await Serializer.SerializeWrapper(obj, options);
Assert.Equal(@"{""Name"":""Name1"",""Name"":""Name2""}", json);
// The overflow value comes last in the JSON so it overwrites the original value.
obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsObjectAndNameProperty>(json, options);
Assert.Equal("Name2", obj.Name);
// Since there was no overflow, this should be null.
Assert.Null(obj.MyOverflow);
}
[Theory]
[MemberData(nameof(JsonSerializerOptions))]
public async Task Null_SystemObject(JsonSerializerOptions options)
{
const string json = @"{""MissingProperty"":null}";
{
ClassWithExtensionPropertyAsObject obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsObject>(json, options);
// A null value maps to <object>, so the value is null.
object elem = obj.MyOverflow["MissingProperty"];
Assert.Null(elem);
}
{
ClassWithExtensionPropertyAsJsonObject obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsJsonObject>(json, options);
JsonObject jObject = obj.MyOverflow;
JsonNode jNode = jObject["MissingProperty"];
// Since JsonNode is a reference type the value is null.
Assert.Null(jNode);
}
}
[Fact]
public async Task Null_JsonElement()
{
const string json = @"{""MissingProperty"":null}";
ClassWithExtensionPropertyAsJsonElement obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsJsonElement>(json);
object elem = obj.MyOverflow["MissingProperty"];
// Since JsonElement is a struct, it treats null as JsonValueKind.Null.
Assert.IsType<JsonElement>(elem);
Assert.Equal(JsonValueKind.Null, ((JsonElement)elem).ValueKind);
}
[Fact]
public async Task Null_JsonObject()
{
const string json = @"{""MissingProperty"":null}";
ClassWithExtensionPropertyAsJsonObject obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsJsonObject>(json);
object elem = obj.MyOverflow["MissingProperty"];
// Since JsonNode is a reference type the value is null.
Assert.Null(elem);
}
[Fact]
public async Task ExtensionPropertyObjectValue()
{
// Baseline
ClassWithExtensionPropertyAlreadyInstantiated obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAlreadyInstantiated>(@"{}");
obj.MyOverflow.Add("test", new object());
obj.MyOverflow.Add("test1", 1);
Assert.Equal(@"{""test"":{},""test1"":1}", await Serializer.SerializeWrapper(obj));
}
public class DummyObj
{
public string Prop { get; set; }
}
public struct DummyStruct
{
public string Prop { get; set; }
}
[Theory]
[MemberData(nameof(JsonSerializerOptions))]
public async Task ExtensionPropertyObjectValue_RoundTrip(JsonSerializerOptions options)
{
// Baseline
ClassWithExtensionPropertyAlreadyInstantiated obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAlreadyInstantiated>(@"{}", options);
obj.MyOverflow.Add("test", new object());
obj.MyOverflow.Add("test1", 1);
obj.MyOverflow.Add("test2", "text");
obj.MyOverflow.Add("test3", new DummyObj() { Prop = "ObjectProp" });
obj.MyOverflow.Add("test4", new DummyStruct() { Prop = "StructProp" });
obj.MyOverflow.Add("test5", new Dictionary<string, object>() { { "Key", "Value" }, { "Key1", "Value1" }, });
string json = await Serializer.SerializeWrapper(obj);
ClassWithExtensionPropertyAlreadyInstantiated roundTripObj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAlreadyInstantiated>(json, options);
Assert.Equal(6, roundTripObj.MyOverflow.Count);
if (options?.UnknownTypeHandling == JsonUnknownTypeHandling.JsonNode)
{
Assert.IsAssignableFrom<JsonNode>(roundTripObj.MyOverflow["test"]);
Assert.IsAssignableFrom<JsonNode>(roundTripObj.MyOverflow["test1"]);
Assert.IsAssignableFrom<JsonNode>(roundTripObj.MyOverflow["test2"]);
Assert.IsAssignableFrom<JsonNode>(roundTripObj.MyOverflow["test3"]);
Assert.IsType<JsonObject>(roundTripObj.MyOverflow["test"]);
Assert.IsAssignableFrom<JsonValue>(roundTripObj.MyOverflow["test1"]);
Assert.Equal(1, ((JsonValue)roundTripObj.MyOverflow["test1"]).GetValue<int>());
Assert.Equal(1, ((JsonValue)roundTripObj.MyOverflow["test1"]).GetValue<long>());
Assert.IsAssignableFrom<JsonValue>(roundTripObj.MyOverflow["test2"]);
Assert.Equal("text", ((JsonValue)roundTripObj.MyOverflow["test2"]).GetValue<string>());
Assert.IsType<JsonObject>(roundTripObj.MyOverflow["test3"]);
Assert.Equal("ObjectProp", ((JsonObject)roundTripObj.MyOverflow["test3"])["Prop"].GetValue<string>());
Assert.IsType<JsonObject>(roundTripObj.MyOverflow["test4"]);
Assert.Equal("StructProp", ((JsonObject)roundTripObj.MyOverflow["test4"])["Prop"].GetValue<string>());
Assert.IsType<JsonObject>(roundTripObj.MyOverflow["test5"]);
Assert.Equal("Value", ((JsonObject)roundTripObj.MyOverflow["test5"])["Key"].GetValue<string>());
Assert.Equal("Value1", ((JsonObject)roundTripObj.MyOverflow["test5"])["Key1"].GetValue<string>());
}
else
{
Assert.IsType<JsonElement>(roundTripObj.MyOverflow["test"]);
Assert.IsType<JsonElement>(roundTripObj.MyOverflow["test1"]);
Assert.IsType<JsonElement>(roundTripObj.MyOverflow["test2"]);
Assert.IsType<JsonElement>(roundTripObj.MyOverflow["test3"]);
Assert.Equal(JsonValueKind.Object, ((JsonElement)roundTripObj.MyOverflow["test"]).ValueKind);
Assert.Equal(JsonValueKind.Number, ((JsonElement)roundTripObj.MyOverflow["test1"]).ValueKind);
Assert.Equal(1, ((JsonElement)roundTripObj.MyOverflow["test1"]).GetInt32());
Assert.Equal(1, ((JsonElement)roundTripObj.MyOverflow["test1"]).GetInt64());
Assert.Equal(JsonValueKind.String, ((JsonElement)roundTripObj.MyOverflow["test2"]).ValueKind);
Assert.Equal("text", ((JsonElement)roundTripObj.MyOverflow["test2"]).GetString());
Assert.Equal(JsonValueKind.Object, ((JsonElement)roundTripObj.MyOverflow["test3"]).ValueKind);
Assert.Equal("ObjectProp", ((JsonElement)roundTripObj.MyOverflow["test3"]).GetProperty("Prop").GetString());
Assert.Equal(JsonValueKind.Object, ((JsonElement)roundTripObj.MyOverflow["test4"]).ValueKind);
Assert.Equal("StructProp", ((JsonElement)roundTripObj.MyOverflow["test4"]).GetProperty("Prop").GetString());
Assert.Equal(JsonValueKind.Object, ((JsonElement)roundTripObj.MyOverflow["test5"]).ValueKind);
Assert.Equal("Value", ((JsonElement)roundTripObj.MyOverflow["test5"]).GetProperty("Key").GetString());
Assert.Equal("Value1", ((JsonElement)roundTripObj.MyOverflow["test5"]).GetProperty("Key1").GetString());
}
}
[Fact]
public async Task DeserializeIntoJsonObjectProperty()
{
string json = @"{""MyDict"":{""Property1"":1}}";
ClassWithExtensionPropertyAsJsonObject obj =
await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsJsonObject>(json);
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Equal(1, obj.MyOverflow["MyDict"]["Property1"].GetValue<int>());
}
[Fact]
#if BUILDING_SOURCE_GENERATOR_TESTS
[ActiveIssue("https://github.com/dotnet/runtime/issues/58945")]
#endif
public async Task DeserializeIntoSystemObjectProperty()
{
string json = @"{""MyDict"":{""Property1"":1}}";
await Assert.ThrowsAsync<InvalidOperationException>(async () =>
await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsSystemObject>(json));
// Cannot deserialize into System.Object overflow even if UnknownTypeHandling is set to use JsonNode.
var options = new JsonSerializerOptions { UnknownTypeHandling = JsonUnknownTypeHandling.JsonNode };
await Assert.ThrowsAsync<InvalidOperationException>(async () =>
await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsSystemObject>(json));
}
public class ClassWithReference
{
[JsonExtensionData]
public Dictionary<string, JsonElement> MyOverflow { get; set; }
public ClassWithExtensionProperty MyReference { get; set; }
}
[Theory]
[InlineData(@"{""MyIntMissing"":2,""MyReference"":{""MyIntMissingChild"":3}}")]
[InlineData(@"{""MyReference"":{""MyIntMissingChild"":3},""MyIntMissing"":2}")]
[InlineData(@"{""MyReference"":{""MyNestedClass"":null,""MyInt"":0,""MyIntMissingChild"":3},""MyIntMissing"":2}")]
public async Task NestedClass(string json)
{
ClassWithReference obj;
void Verify()
{
Assert.IsType<JsonElement>(obj.MyOverflow["MyIntMissing"]);
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Equal(2, obj.MyOverflow["MyIntMissing"].GetInt32());
ClassWithExtensionProperty child = obj.MyReference;
Assert.IsType<JsonElement>(child.MyOverflow["MyIntMissingChild"]);
Assert.IsType<JsonElement>(child.MyOverflow["MyIntMissingChild"]);
Assert.Equal(1, child.MyOverflow.Count);
Assert.Equal(3, child.MyOverflow["MyIntMissingChild"].GetInt32());
Assert.Null(child.MyNestedClass);
Assert.Equal(0, child.MyInt);
}
obj = await Serializer.DeserializeWrapper<ClassWithReference>(json);
Verify();
// Round-trip the json and verify.
json = await Serializer.SerializeWrapper(obj);
obj = await Serializer.DeserializeWrapper<ClassWithReference>(json);
Verify();
}
public class ParentClassWithObject
{
public string Text { get; set; }
public ChildClassWithObject Child { get; set; }
[JsonExtensionData]
public Dictionary<string, object> ExtensionData { get; set; } = new Dictionary<string, object>();
}
public class ChildClassWithObject
{
public int Number { get; set; }
[JsonExtensionData]
public Dictionary<string, object> ExtensionData { get; set; } = new Dictionary<string, object>();
}
[Fact]
public async Task NestedClassWithObjectExtensionDataProperty()
{
var child = new ChildClassWithObject { Number = 2 };
child.ExtensionData.Add("SpecialInformation", "I am child class");
var parent = new ParentClassWithObject { Text = "Hello World" };
parent.ExtensionData.Add("SpecialInformation", "I am parent class");
parent.Child = child;
// The extension data is based on the raw strings added above and not JsonElement.
Assert.Equal("Hello World", parent.Text);
Assert.IsType<string>(parent.ExtensionData["SpecialInformation"]);
Assert.Equal("I am parent class", (string)parent.ExtensionData["SpecialInformation"]);
Assert.Equal(2, parent.Child.Number);
Assert.IsType<string>(parent.Child.ExtensionData["SpecialInformation"]);
Assert.Equal("I am child class", (string)parent.Child.ExtensionData["SpecialInformation"]);
// Round-trip and verify. Extension data is now based on JsonElement.
string json = await Serializer.SerializeWrapper(parent);
parent = await Serializer.DeserializeWrapper<ParentClassWithObject>(json);
Assert.Equal("Hello World", parent.Text);
Assert.IsType<JsonElement>(parent.ExtensionData["SpecialInformation"]);
Assert.Equal("I am parent class", ((JsonElement)parent.ExtensionData["SpecialInformation"]).GetString());
Assert.Equal(2, parent.Child.Number);
Assert.IsType<JsonElement>(parent.Child.ExtensionData["SpecialInformation"]);
Assert.Equal("I am child class", ((JsonElement)parent.Child.ExtensionData["SpecialInformation"]).GetString());
}
public class ParentClassWithJsonElement
{
public string Text { get; set; }
public List<ChildClassWithJsonElement> Children { get; set; } = new List<ChildClassWithJsonElement>();
[JsonExtensionData]
// Use SortedDictionary as verification of supporting derived dictionaries.
public SortedDictionary<string, JsonElement> ExtensionData { get; set; } = new SortedDictionary<string, JsonElement>();
}
public class ChildClassWithJsonElement
{
public int Number { get; set; }
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; } = new Dictionary<string, JsonElement>();
}
[Fact]
public async Task NestedClassWithJsonElementExtensionDataProperty()
{
var child = new ChildClassWithJsonElement { Number = 4 };
child.ExtensionData.Add("SpecialInformation", JsonDocument.Parse(await Serializer.SerializeWrapper("I am child class")).RootElement);
var parent = new ParentClassWithJsonElement { Text = "Hello World" };
parent.ExtensionData.Add("SpecialInformation", JsonDocument.Parse(await Serializer.SerializeWrapper("I am parent class")).RootElement);
parent.Children.Add(child);
Verify();
// Round-trip and verify.
string json = await Serializer.SerializeWrapper(parent);
parent = await Serializer.DeserializeWrapper<ParentClassWithJsonElement>(json);
Verify();
void Verify()
{
Assert.Equal("Hello World", parent.Text);
Assert.Equal("I am parent class", parent.ExtensionData["SpecialInformation"].GetString());
Assert.Equal(1, parent.Children.Count);
Assert.Equal(4, parent.Children[0].Number);
Assert.Equal("I am child class", parent.Children[0].ExtensionData["SpecialInformation"].GetString());
}
}
[Fact]
public async Task DeserializeIntoObjectProperty()
{
ClassWithExtensionPropertyAsObject obj;
string json;
// Baseline dictionary.
json = @"{""MyDict"":{""Property1"":1}}";
obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsObject>(json);
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Equal(1, ((JsonElement)obj.MyOverflow["MyDict"]).EnumerateObject().First().Value.GetInt32());
// Attempt to deserialize directly into the overflow property; this is just added as a normal missing property like MyDict above.
json = @"{""MyOverflow"":{""Property1"":1}}";
obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsObject>(json);
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Equal(1, ((JsonElement)obj.MyOverflow["MyOverflow"]).EnumerateObject().First().Value.GetInt32());
// Attempt to deserialize null into the overflow property. This is also treated as a missing property.
json = @"{""MyOverflow"":null}";
obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsObject>(json);
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Null(obj.MyOverflow["MyOverflow"]);
// Attempt to deserialize object into the overflow property. This is also treated as a missing property.
json = @"{""MyOverflow"":{}}";
obj = await Serializer.DeserializeWrapper<ClassWithExtensionPropertyAsObject>(json);
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Equal(JsonValueKind.Object, ((JsonElement)obj.MyOverflow["MyOverflow"]).ValueKind);
}
[Fact]
public async Task DeserializeIntoMultipleDictionaries()
{
ClassWithMultipleDictionaries obj;
string json;
// Baseline dictionary.
json = @"{""ActualDictionary"":{""Key"": {""Property0"":-1}},""MyDict"":{""Property1"":1}}";
obj = await Serializer.DeserializeWrapper<ClassWithMultipleDictionaries>(json);
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Equal(1, ((JsonElement)obj.MyOverflow["MyDict"]).EnumerateObject().First().Value.GetInt32());
Assert.Equal(1, obj.ActualDictionary.Count);
Assert.Equal(-1, ((JsonElement)obj.ActualDictionary["Key"]).EnumerateObject().First().Value.GetInt32());
// Attempt to deserialize null into the dictionary and overflow property. This is also treated as a missing property.
json = @"{""ActualDictionary"":null,""MyOverflow"":null}";
obj = await Serializer.DeserializeWrapper<ClassWithMultipleDictionaries>(json);
Assert.Equal(1, obj.MyOverflow.Count);
Assert.Null(obj.MyOverflow["MyOverflow"]);
Assert.Null(obj.ActualDictionary);