-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
RequiredKeywordTests.cs
710 lines (608 loc) · 33.6 KB
/
RequiredKeywordTests.cs
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
// 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.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization.Metadata;
using System.Threading.Tasks;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public abstract partial class RequiredKeywordTests : SerializerTests
{
public RequiredKeywordTests(JsonSerializerWrapper serializer) : base(serializer)
{
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ClassWithRequiredKeywordDeserialization(bool ignoreNullValues)
{
JsonSerializerOptions options = Serializer.CreateOptions(makeReadOnly: false);
options.IgnoreNullValues = ignoreNullValues;
AssertJsonTypeInfoHasRequiredProperties(GetTypeInfo<PersonWithRequiredMembers>(options),
nameof(PersonWithRequiredMembers.FirstName),
nameof(PersonWithRequiredMembers.LastName));
var obj = new PersonWithRequiredMembers()
{
FirstName = "foo",
LastName = "bar"
};
string json = await Serializer.SerializeWrapper(obj, options);
Assert.Equal("""{"FirstName":"foo","MiddleName":"","LastName":"bar"}""", json);
PersonWithRequiredMembers deserialized = await Serializer.DeserializeWrapper<PersonWithRequiredMembers>(json, options);
Assert.Equal(obj.FirstName, deserialized.FirstName);
Assert.Equal(obj.MiddleName, deserialized.MiddleName);
Assert.Equal(obj.LastName, deserialized.LastName);
json = """{"LastName":"bar"}""";
JsonException exception = await Assert.ThrowsAsync<JsonException>(async () => await Serializer.DeserializeWrapper<PersonWithRequiredMembers>(json, options));
Assert.Contains("FirstName", exception.Message);
Assert.DoesNotContain("LastName", exception.Message);
Assert.DoesNotContain("MiddleName", exception.Message);
json = """{"LastName":null}""";
exception = await Assert.ThrowsAsync<JsonException>(async () => await Serializer.DeserializeWrapper<PersonWithRequiredMembers>(json, options));
Assert.Contains("FirstName", exception.Message);
Assert.DoesNotContain("LastName", exception.Message);
Assert.DoesNotContain("MiddleName", exception.Message);
json = "{}";
exception = await Assert.ThrowsAsync<JsonException>(async () => await Serializer.DeserializeWrapper<PersonWithRequiredMembers>(json, options));
Assert.Contains("FirstName", exception.Message);
Assert.Contains("LastName", exception.Message);
Assert.DoesNotContain("MiddleName", exception.Message);
}
[Fact]
public async Task RequiredPropertyOccuringTwiceInThePayloadWorksAsExpected()
{
string json = """{"FirstName":"foo","MiddleName":"","LastName":"bar","FirstName":"newfoo"}""";
PersonWithRequiredMembers deserialized = await Serializer.DeserializeWrapper<PersonWithRequiredMembers>(json);
Assert.Equal("newfoo", deserialized.FirstName);
Assert.Equal("", deserialized.MiddleName);
Assert.Equal("bar", deserialized.LastName);
}
public class PersonWithRequiredMembers
{
public required string FirstName { get; set; }
public string MiddleName { get; set; } = "";
public required string LastName { get; set; }
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ClassWithRequiredKeywordAndSmallParametrizedCtorFailsDeserialization(bool ignoreNullValues)
{
JsonSerializerOptions options = Serializer.CreateOptions(makeReadOnly: false);
options.IgnoreNullValues = ignoreNullValues;
AssertJsonTypeInfoHasRequiredProperties(GetTypeInfo<PersonWithRequiredMembersAndSmallParametrizedCtor>(options),
nameof(PersonWithRequiredMembersAndSmallParametrizedCtor.FirstName),
nameof(PersonWithRequiredMembersAndSmallParametrizedCtor.LastName),
nameof(PersonWithRequiredMembersAndSmallParametrizedCtor.Info1),
nameof(PersonWithRequiredMembersAndSmallParametrizedCtor.Info2));
var obj = new PersonWithRequiredMembersAndSmallParametrizedCtor("badfoo", "badbar")
{
// note: these must be set during initialize or otherwise we get compiler errors
FirstName = "foo",
LastName = "bar",
Info1 = "info1",
Info2 = "info2",
};
string json = await Serializer.SerializeWrapper(obj, options);
Assert.Equal("""{"FirstName":"foo","MiddleName":"","LastName":"bar","Info1":"info1","Info2":"info2"}""", json);
var deserialized = await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndSmallParametrizedCtor>(json, options);
Assert.Equal(obj.FirstName, deserialized.FirstName);
Assert.Equal(obj.MiddleName, deserialized.MiddleName);
Assert.Equal(obj.LastName, deserialized.LastName);
Assert.Equal(obj.Info1, deserialized.Info1);
Assert.Equal(obj.Info2, deserialized.Info2);
json = """{"FirstName":"foo","MiddleName":"","LastName":null,"Info1":null,"Info2":"info2"}""";
deserialized = await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndSmallParametrizedCtor>(json, options);
Assert.Equal(obj.FirstName, deserialized.FirstName);
Assert.Equal(obj.MiddleName, deserialized.MiddleName);
Assert.Null(deserialized.LastName);
Assert.Null(deserialized.Info1);
Assert.Equal(obj.Info2, deserialized.Info2);
json = """{"LastName":"bar","Info1":"info1"}""";
JsonException exception = await Assert.ThrowsAsync<JsonException>(async () => await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndSmallParametrizedCtor>(json, options));
Assert.Contains("FirstName", exception.Message);
Assert.DoesNotContain("LastName", exception.Message);
Assert.DoesNotContain("MiddleName", exception.Message);
Assert.DoesNotContain("Info1", exception.Message);
Assert.Contains("Info2", exception.Message);
json = """{"LastName":null,"Info1":null}""";
exception = await Assert.ThrowsAsync<JsonException>(async () => await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndSmallParametrizedCtor>(json, options));
Assert.Contains("FirstName", exception.Message);
Assert.DoesNotContain("LastName", exception.Message);
Assert.DoesNotContain("MiddleName", exception.Message);
Assert.DoesNotContain("Info1", exception.Message);
Assert.Contains("Info2", exception.Message);
json = "{}";
exception = await Assert.ThrowsAsync<JsonException>(async () => await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndSmallParametrizedCtor>(json, options));
Assert.Contains("FirstName", exception.Message);
Assert.Contains("LastName", exception.Message);
Assert.DoesNotContain("MiddleName", exception.Message);
Assert.Contains("Info1", exception.Message);
Assert.Contains("Info2", exception.Message);
}
[Fact]
public async Task InheritedPersonWithRequiredMembersWorksAsExpected()
{
var options = new JsonSerializerOptions(Serializer.DefaultOptions);
options.MakeReadOnly();
JsonTypeInfo typeInfo = options.GetTypeInfo(typeof(InheritedPersonWithRequiredMembers));
Assert.Equal(3, typeInfo.Properties.Count);
AssertJsonTypeInfoHasRequiredProperties(GetTypeInfo<InheritedPersonWithRequiredMembers>(options),
nameof(InheritedPersonWithRequiredMembers.FirstName),
nameof(InheritedPersonWithRequiredMembers.LastName));
JsonException exception = await Assert.ThrowsAsync<JsonException>(() => Serializer.DeserializeWrapper("{}", typeInfo));
Assert.Contains("FirstName", exception.Message);
Assert.Contains("LastName", exception.Message);
Assert.DoesNotContain("MiddleName", exception.Message);
}
[Fact]
public async Task InheritedPersonWithRequiredMembersWithAdditionalRequiredMembersWorksAsExpected()
{
var options = new JsonSerializerOptions(Serializer.DefaultOptions);
options.MakeReadOnly();
JsonTypeInfo typeInfo = options.GetTypeInfo(typeof(InheritedPersonWithRequiredMembersWithAdditionalRequiredMembers));
Assert.Equal(4, typeInfo.Properties.Count);
AssertJsonTypeInfoHasRequiredProperties(GetTypeInfo<InheritedPersonWithRequiredMembersWithAdditionalRequiredMembers>(options),
nameof(InheritedPersonWithRequiredMembersWithAdditionalRequiredMembers.FirstName),
nameof(InheritedPersonWithRequiredMembersWithAdditionalRequiredMembers.LastName),
nameof(InheritedPersonWithRequiredMembersWithAdditionalRequiredMembers.Post));
JsonException exception = await Assert.ThrowsAsync<JsonException>(() => Serializer.DeserializeWrapper("{}", typeInfo));
Assert.Contains("FirstName", exception.Message);
Assert.Contains("LastName", exception.Message);
Assert.Contains("Post", exception.Message);
Assert.DoesNotContain("MiddleName", exception.Message);
}
[Theory]
[MemberData(nameof(InheritedPersonWithRequiredMembersSetsRequiredMembersWorksAsExpectedSources))]
public async Task InheritedPersonWithRequiredMembersSetsRequiredMembersWorksAsExpected(string jsonValue,
InheritedPersonWithRequiredMembersSetsRequiredMembers expectedValue)
{
var options = new JsonSerializerOptions(Serializer.DefaultOptions);
options.MakeReadOnly();
JsonTypeInfo typeInfo = options.GetTypeInfo(typeof(InheritedPersonWithRequiredMembersSetsRequiredMembers));
Assert.Equal(3, typeInfo.Properties.Count);
AssertJsonTypeInfoHasRequiredProperties(GetTypeInfo<InheritedPersonWithRequiredMembersSetsRequiredMembers>(options));
InheritedPersonWithRequiredMembersSetsRequiredMembers actualValue =
await Serializer.DeserializeWrapper<InheritedPersonWithRequiredMembersSetsRequiredMembers>(jsonValue, options);
Assert.Equal(expectedValue.FirstName, actualValue.FirstName);
Assert.Equal(expectedValue.LastName, actualValue.LastName);
Assert.Equal(expectedValue.MiddleName, actualValue.MiddleName);
}
public class InheritedPersonWithRequiredMembers : PersonWithRequiredMembers
{
}
public class InheritedPersonWithRequiredMembersWithAdditionalRequiredMembers : PersonWithRequiredMembers
{
public required string Post { get; set; }
}
public class InheritedPersonWithRequiredMembersSetsRequiredMembers : PersonWithRequiredMembers
{
[SetsRequiredMembers]
public InheritedPersonWithRequiredMembersSetsRequiredMembers()
{
FirstName = "FirstNameValueFromConstructor";
LastName = "LastNameValueFromConstructor";
MiddleName = "MiddleNameValueFromConstructor";
}
}
public class PersonWithRequiredMembersAndSmallParametrizedCtor
{
public required string FirstName { get; set; }
public string MiddleName { get; set; } = "";
public required string LastName { get; set; }
public required string Info1 { get; set; }
public required string Info2 { get; set; }
public PersonWithRequiredMembersAndSmallParametrizedCtor(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ClassWithRequiredKeywordAndLargeParametrizedCtorFailsDeserialization(bool ignoreNullValues)
{
JsonSerializerOptions options = Serializer.CreateOptions(makeReadOnly: false);
options.IgnoreNullValues = ignoreNullValues;
AssertJsonTypeInfoHasRequiredProperties(GetTypeInfo<PersonWithRequiredMembersAndLargeParametrizedCtor>(options),
nameof(PersonWithRequiredMembersAndLargeParametrizedCtor.AProp),
nameof(PersonWithRequiredMembersAndLargeParametrizedCtor.BProp),
nameof(PersonWithRequiredMembersAndLargeParametrizedCtor.CProp),
nameof(PersonWithRequiredMembersAndLargeParametrizedCtor.DProp),
nameof(PersonWithRequiredMembersAndLargeParametrizedCtor.EProp),
nameof(PersonWithRequiredMembersAndLargeParametrizedCtor.FProp),
nameof(PersonWithRequiredMembersAndLargeParametrizedCtor.GProp),
nameof(PersonWithRequiredMembersAndLargeParametrizedCtor.HProp),
nameof(PersonWithRequiredMembersAndLargeParametrizedCtor.IProp));
var obj = new PersonWithRequiredMembersAndLargeParametrizedCtor("bada", "badb", "badc", "badd", "bade", "badf", "badg")
{
// note: these must be set during initialize or otherwise we get compiler errors
AProp = "a",
BProp = "b",
CProp = "c",
DProp = "d",
EProp = "e",
FProp = "f",
GProp = "g",
HProp = "h",
IProp = "i",
};
string json = await Serializer.SerializeWrapper(obj, options);
Assert.Equal("""{"AProp":"a","BProp":"b","CProp":"c","DProp":"d","EProp":"e","FProp":"f","GProp":"g","HProp":"h","IProp":"i"}""", json);
var deserialized = await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndLargeParametrizedCtor>(json, options);
Assert.Equal(obj.AProp, deserialized.AProp);
Assert.Equal(obj.BProp, deserialized.BProp);
Assert.Equal(obj.CProp, deserialized.CProp);
Assert.Equal(obj.DProp, deserialized.DProp);
Assert.Equal(obj.EProp, deserialized.EProp);
Assert.Equal(obj.FProp, deserialized.FProp);
Assert.Equal(obj.GProp, deserialized.GProp);
Assert.Equal(obj.HProp, deserialized.HProp);
Assert.Equal(obj.IProp, deserialized.IProp);
json = """{"AProp":"a","BProp":"b","CProp":"c","DProp":"d","EProp":null,"FProp":"f","GProp":"g","HProp":null,"IProp":"i"}""";
deserialized = await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndLargeParametrizedCtor>(json, options);
Assert.Equal(obj.AProp, deserialized.AProp);
Assert.Equal(obj.BProp, deserialized.BProp);
Assert.Equal(obj.CProp, deserialized.CProp);
Assert.Equal(obj.DProp, deserialized.DProp);
Assert.Null(deserialized.EProp);
Assert.Equal(obj.FProp, deserialized.FProp);
Assert.Equal(obj.GProp, deserialized.GProp);
Assert.Null(deserialized.HProp);
Assert.Equal(obj.IProp, deserialized.IProp);
json = """{"AProp":"a","IProp":"i"}""";
JsonException exception = await Assert.ThrowsAsync<JsonException>(async () => await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndLargeParametrizedCtor>(json, options));
Assert.DoesNotContain("AProp", exception.Message);
Assert.Contains("BProp", exception.Message);
Assert.Contains("CProp", exception.Message);
Assert.Contains("DProp", exception.Message);
Assert.Contains("EProp", exception.Message);
Assert.Contains("FProp", exception.Message);
Assert.Contains("GProp", exception.Message);
Assert.Contains("HProp", exception.Message);
Assert.DoesNotContain("IProp", exception.Message);
json = """{"AProp":null,"IProp":null}""";
exception = await Assert.ThrowsAsync<JsonException>(async () => await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndLargeParametrizedCtor>(json, options));
Assert.DoesNotContain("AProp", exception.Message);
Assert.Contains("BProp", exception.Message);
Assert.Contains("CProp", exception.Message);
Assert.Contains("DProp", exception.Message);
Assert.Contains("EProp", exception.Message);
Assert.Contains("FProp", exception.Message);
Assert.Contains("GProp", exception.Message);
Assert.Contains("HProp", exception.Message);
Assert.DoesNotContain("IProp", exception.Message);
json = """{"BProp":"b","CProp":"c","DProp":"d","EProp":"e","FProp":"f","HProp":"h"}""";
exception = await Assert.ThrowsAsync<JsonException>(async () => await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndLargeParametrizedCtor>(json, options));
Assert.Contains("AProp", exception.Message);
Assert.DoesNotContain("BProp", exception.Message);
Assert.DoesNotContain("CProp", exception.Message);
Assert.DoesNotContain("DProp", exception.Message);
Assert.DoesNotContain("EProp", exception.Message);
Assert.DoesNotContain("FProp", exception.Message);
Assert.Contains("GProp", exception.Message);
Assert.DoesNotContain("HProp", exception.Message);
Assert.Contains("IProp", exception.Message);
}
public class PersonWithRequiredMembersAndLargeParametrizedCtor
{
// Using suffix for names so that checking if required property is missing can be done with simple string.Contains without false positives
public required string AProp { get; set; }
public required string BProp { get; set; }
public required string CProp { get; set; }
public required string DProp { get; set; }
public required string EProp { get; set; }
public required string FProp { get; set; }
public required string GProp { get; set; }
public required string HProp { get; set; }
public required string IProp { get; set; }
public PersonWithRequiredMembersAndLargeParametrizedCtor(string aprop, string bprop, string cprop, string dprop, string eprop, string fprop, string gprop)
{
AProp = aprop;
BProp = bprop;
CProp = cprop;
DProp = dprop;
EProp = eprop;
FProp = fprop;
GProp = gprop;
}
}
[Fact]
public async Task ClassWithRequiredKeywordAndSetsRequiredMembersOnCtorWorks()
{
AssertJsonTypeInfoHasRequiredProperties(GetTypeInfo<PersonWithRequiredMembersAndSetsRequiredMembers>(Serializer.DefaultOptions)
/* no required members */);
var obj = new PersonWithRequiredMembersAndSetsRequiredMembers()
{
FirstName = "foo",
LastName = "bar"
};
string json = await Serializer.SerializeWrapper(obj);
Assert.Equal("""{"FirstName":"foo","MiddleName":"","LastName":"bar"}""", json);
json = """{"LastName":"bar"}""";
var deserialized = await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndSetsRequiredMembers>(json);
Assert.Equal("", deserialized.FirstName);
Assert.Equal("", deserialized.MiddleName);
Assert.Equal("bar", deserialized.LastName);
}
public class PersonWithRequiredMembersAndSetsRequiredMembers
{
public required string FirstName { get; set; }
public string MiddleName { get; set; } = "";
public required string LastName { get; set; }
[SetsRequiredMembers]
public PersonWithRequiredMembersAndSetsRequiredMembers()
{
FirstName = "";
LastName = "";
}
}
[Fact]
public async Task ClassWithRequiredKeywordSmallParametrizedCtorAndSetsRequiredMembersOnCtorWorks()
{
AssertJsonTypeInfoHasRequiredProperties(GetTypeInfo<PersonWithRequiredMembersAndSmallParametrizedCtorAndSetsRequiredMembers>(Serializer.DefaultOptions)
/* no required members */);
var obj = new PersonWithRequiredMembersAndSmallParametrizedCtorAndSetsRequiredMembers("foo", "bar");
string json = await Serializer.SerializeWrapper(obj);
Assert.Equal("""{"FirstName":"foo","MiddleName":"","LastName":"bar"}""", json);
var deserialized = await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndSmallParametrizedCtorAndSetsRequiredMembers>(json);
Assert.Equal("foo", deserialized.FirstName);
Assert.Equal("", deserialized.MiddleName);
Assert.Equal("bar", deserialized.LastName);
}
public class PersonWithRequiredMembersAndSmallParametrizedCtorAndSetsRequiredMembers
{
public required string FirstName { get; set; }
public string MiddleName { get; set; } = "";
public required string LastName { get; set; }
[SetsRequiredMembers]
public PersonWithRequiredMembersAndSmallParametrizedCtorAndSetsRequiredMembers(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
[Fact]
public async Task ClassWithRequiredKeywordLargeParametrizedCtorAndSetsRequiredMembersOnCtorWorks()
{
AssertJsonTypeInfoHasRequiredProperties(GetTypeInfo<PersonWithRequiredMembersAndLargeParametrizedCtorAndSetsRequiredMembers>(Serializer.DefaultOptions)
/* no required members */);
var obj = new PersonWithRequiredMembersAndLargeParametrizedCtorAndSetsRequiredMembers("a", "b", "c", "d", "e", "f", "g");
string json = await Serializer.SerializeWrapper(obj);
Assert.Equal("""{"A":"a","B":"b","C":"c","D":"d","E":"e","F":"f","G":"g"}""", json);
var deserialized = await Serializer.DeserializeWrapper<PersonWithRequiredMembersAndLargeParametrizedCtorAndSetsRequiredMembers>(json);
Assert.Equal("a", deserialized.A);
Assert.Equal("b", deserialized.B);
Assert.Equal("c", deserialized.C);
Assert.Equal("d", deserialized.D);
Assert.Equal("e", deserialized.E);
Assert.Equal("f", deserialized.F);
Assert.Equal("g", deserialized.G);
}
public class PersonWithRequiredMembersAndLargeParametrizedCtorAndSetsRequiredMembers
{
public required string A { get; set; }
public required string B { get; set; }
public required string C { get; set; }
public required string D { get; set; }
public required string E { get; set; }
public required string F { get; set; }
public required string G { get; set; }
[SetsRequiredMembers]
public PersonWithRequiredMembersAndLargeParametrizedCtorAndSetsRequiredMembers(string a, string b, string c, string d, string e, string f, string g)
{
A = a;
B = b;
C = c;
D = d;
E = e;
F = f;
G = g;
}
}
[Fact]
public async Task ClassWithRequiredFieldWorksAsExpected()
{
var options = new JsonSerializerOptions(Serializer.DefaultOptions) { IncludeFields = true };
options.MakeReadOnly();
JsonTypeInfo typeInfo = options.GetTypeInfo(typeof(ClassWithRequiredField));
Assert.Equal(1, typeInfo.Properties.Count);
JsonPropertyInfo jsonPropertyInfo = typeInfo.Properties[0];
Assert.True(jsonPropertyInfo.IsRequired);
await Assert.ThrowsAsync<JsonException>(() => Serializer.DeserializeWrapper("{}", typeInfo));
}
public class ClassWithRequiredField
{
public required int RequiredField;
}
[Fact]
public async Task RemovingPropertiesWithRequiredKeywordAllowsDeserialization()
{
JsonSerializerOptions options = Serializer.GetDefaultOptionsWithMetadataModifier(static ti =>
{
for (int i = 0; i < ti.Properties.Count; i++)
{
if (ti.Properties[i].Name == nameof(PersonWithRequiredMembers.FirstName))
{
Assert.True(ti.Properties[i].IsRequired);
JsonPropertyInfo property = ti.CreateJsonPropertyInfo(typeof(string), nameof(PersonWithRequiredMembers.FirstName));
property.Get = (obj) => ((PersonWithRequiredMembers)obj).FirstName;
property.Set = (obj, val) => ((PersonWithRequiredMembers)obj).FirstName = (string)val;
ti.Properties[i] = property;
}
else if (ti.Properties[i].Name == nameof(PersonWithRequiredMembers.LastName))
{
Assert.True(ti.Properties[i].IsRequired);
JsonPropertyInfo property = ti.CreateJsonPropertyInfo(typeof(string), nameof(PersonWithRequiredMembers.LastName));
property.Get = (obj) => ((PersonWithRequiredMembers)obj).LastName;
property.Set = (obj, val) => ((PersonWithRequiredMembers)obj).LastName = (string)val;
ti.Properties[i] = property;
}
else
{
Assert.False(ti.Properties[i].IsRequired);
}
}
});
var obj = new PersonWithRequiredMembers()
{
FirstName = "foo",
LastName = "bar"
};
string json = await Serializer.SerializeWrapper(obj, options);
Assert.Equal("""{"FirstName":"foo","MiddleName":"","LastName":"bar"}""", json);
json = """{"LastName":"bar"}""";
PersonWithRequiredMembers deserialized = await Serializer.DeserializeWrapper<PersonWithRequiredMembers>(json, options);
Assert.Null(deserialized.FirstName);
Assert.Equal("", deserialized.MiddleName);
Assert.Equal("bar", deserialized.LastName);
}
[Fact]
public async Task ChangingPropertiesWithRequiredKeywordToNotBeRequiredAllowsDeserialization()
{
JsonSerializerOptions options = Serializer.GetDefaultOptionsWithMetadataModifier(static ti =>
{
for (int i = 0; i < ti.Properties.Count; i++)
{
ti.Properties[i].IsRequired = false;
}
});
var obj = new PersonWithRequiredMembers()
{
FirstName = "foo",
LastName = "bar"
};
string json = await Serializer.SerializeWrapper(obj, options);
Assert.Equal("""{"FirstName":"foo","MiddleName":"","LastName":"bar"}""", json);
json = """{"LastName":"bar"}""";
PersonWithRequiredMembers deserialized = await Serializer.DeserializeWrapper<PersonWithRequiredMembers>(json, options);
Assert.Null(deserialized.FirstName);
Assert.Equal("", deserialized.MiddleName);
Assert.Equal("bar", deserialized.LastName);
}
[Fact]
public async Task RequiredNonDeserializablePropertyThrows()
{
JsonSerializerOptions options = Serializer.GetDefaultOptionsWithMetadataModifier(static ti =>
{
for (int i = 0; i < ti.Properties.Count; i++)
{
if (ti.Properties[i].Name == nameof(PersonWithRequiredMembers.FirstName))
{
ti.Properties[i].Set = null;
}
}
});
string json = """{"FirstName":"foo","MiddleName":"","LastName":"bar"}""";
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => await Serializer.DeserializeWrapper<PersonWithRequiredMembers>(json, options));
Assert.Contains(nameof(PersonWithRequiredMembers.FirstName), exception.Message);
}
[Fact]
public async Task RequiredInitOnlyPropertyDoesNotThrow()
{
string json = """{"Prop":"foo"}""";
ClassWithInitOnlyRequiredProperty deserialized = await Serializer.DeserializeWrapper<ClassWithInitOnlyRequiredProperty>(json);
Assert.Equal("foo", deserialized.Prop);
}
public class ClassWithInitOnlyRequiredProperty
{
public required string Prop { get; init; }
}
[Fact]
public async Task RequiredExtensionDataPropertyThrows()
{
string json = """{"Foo":"foo","Bar":"bar"}""";
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(
async () => await Serializer.DeserializeWrapper<ClassWithRequiredExtensionDataProperty>(json));
Assert.Contains(nameof(ClassWithRequiredExtensionDataProperty.TestExtensionData), exception.Message);
}
public class ClassWithRequiredExtensionDataProperty
{
[JsonExtensionData]
public required Dictionary<string, JsonElement>? TestExtensionData { get; set; }
}
[Fact]
public async Task RequiredKeywordAndJsonRequiredCustomAttributeWorkCorrectlyTogether()
{
JsonSerializerOptions options = Serializer.CreateOptions();
JsonTypeInfo typeInfo = GetTypeInfo<ClassWithRequiredKeywordAndJsonRequiredCustomAttribute>(options);
AssertJsonTypeInfoHasRequiredProperties(typeInfo,
nameof(ClassWithRequiredKeywordAndJsonRequiredCustomAttribute.SomeProperty));
ClassWithRequiredKeywordAndJsonRequiredCustomAttribute obj = new()
{
SomeProperty = "foo"
};
string json = await Serializer.SerializeWrapper(obj, options);
Assert.Equal("""{"SomeProperty":"foo"}""", json);
var deserialized = await Serializer.DeserializeWrapper<ClassWithRequiredKeywordAndJsonRequiredCustomAttribute>(json, options);
Assert.Equal(obj.SomeProperty, deserialized.SomeProperty);
json = "{}";
JsonException exception = await Assert.ThrowsAsync<JsonException>(
async () => await Serializer.DeserializeWrapper<ClassWithRequiredKeywordAndJsonRequiredCustomAttribute>(json, options));
Assert.Contains(nameof(ClassWithRequiredKeywordAndJsonRequiredCustomAttribute.SomeProperty), exception.Message);
}
public class ClassWithRequiredKeywordAndJsonRequiredCustomAttribute
{
[JsonRequired]
public required string SomeProperty { get; set; }
}
[Fact]
public async Task ClassWithCustomRequiredPropertyName_Roundtrip()
{
// Regression test for https://github.com/dotnet/runtime/issues/82730
var value = new ClassWithCustomRequiredPropertyName { Property = 42, PropertyWithInitOnlySetter = 43 };
string json = await Serializer.SerializeWrapper(value);
Assert.Equal("""{"Prop":42,"PropWithInit":43}""", json);
value = await Serializer.DeserializeWrapper<ClassWithCustomRequiredPropertyName>(json);
Assert.Equal(42, value.Property);
Assert.Equal(43, value.PropertyWithInitOnlySetter);
}
public class ClassWithCustomRequiredPropertyName
{
[JsonPropertyName("Prop")]
public required int Property { get; set; }
[JsonPropertyName("PropWithInit")]
public required int PropertyWithInitOnlySetter { get; init; }
}
public static IEnumerable<object[]> InheritedPersonWithRequiredMembersSetsRequiredMembersWorksAsExpectedSources()
{
yield return new object[]
{
"{}",
new InheritedPersonWithRequiredMembersSetsRequiredMembers()
};
yield return new object[]
{
"""{"FirstName": "FirstNameFromJson"}""",
new InheritedPersonWithRequiredMembersSetsRequiredMembers
{
FirstName = "FirstNameFromJson"
}
};
}
private static JsonTypeInfo GetTypeInfo<T>(JsonSerializerOptions options)
{
options.TypeInfoResolver ??= JsonSerializerOptions.Default.TypeInfoResolver;
options.MakeReadOnly();
return options.GetTypeInfo(typeof(T));
}
private static void AssertJsonTypeInfoHasRequiredProperties(JsonTypeInfo typeInfo, params string[] requiredProperties)
{
HashSet<string> requiredPropertiesSet = new(requiredProperties);
foreach (var property in typeInfo.Properties)
{
if (requiredPropertiesSet.Remove(property.Name))
{
Assert.True(property.IsRequired);
}
else
{
Assert.False(property.IsRequired);
}
}
Assert.Empty(requiredPropertiesSet);
}
}
}