-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathXmlSerializerTests.cs
2671 lines (2360 loc) · 125 KB
/
XmlSerializerTests.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
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;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
using System.Runtime.Serialization.Tests;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using SerializationTypes;
using Xunit;
#if !ReflectionOnly && !XMLSERIALIZERGENERATORTESTS
// Many test failures due to trimming and MakeGeneric. XmlSerializer is not currently supported with NativeAOT.
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBuiltWithAggressiveTrimming))]
#endif
public static partial class XmlSerializerTests
{
#if ReflectionOnly || XMLSERIALIZERGENERATORTESTS
private static readonly string SerializationModeSetterName = "set_Mode";
static XmlSerializerTests()
{
MethodInfo method = typeof(XmlSerializer).GetMethod(SerializationModeSetterName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
Assert.True(method != null, $"No method named {SerializationModeSetterName}");
#if ReflectionOnly
method.Invoke(null, new object[] { 1 });
#endif
#if XMLSERIALIZERGENERATORTESTS
method.Invoke(null, new object[] { 3 });
#endif
}
#endif
public static bool DefaultValueAttributeIsSupported => AppContext.TryGetSwitch("System.ComponentModel.DefaultValueAttribute.IsSupported", out bool isEnabled) ? isEnabled : true;
[Fact]
public static void Xml_TypeWithDateTimePropertyAsXmlTime()
{
DateTime localTime = new DateTime(549269870000L, DateTimeKind.Local);
TypeWithDateTimePropertyAsXmlTime localTimeObject = new TypeWithDateTimePropertyAsXmlTime()
{
Value = localTime
};
// This is how we convert DateTime from time to string.
var localTimeDateTime = DateTime.MinValue + localTime.TimeOfDay;
string localTimeString = localTimeDateTime.ToString("HH:mm:ss.fffffffzzzzzz", DateTimeFormatInfo.InvariantInfo);
TypeWithDateTimePropertyAsXmlTime localTimeObjectRoundTrip = SerializeAndDeserialize(localTimeObject,
string.Format(WithXmlHeader(@"<TypeWithDateTimePropertyAsXmlTime xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">{0}</TypeWithDateTimePropertyAsXmlTime>"), localTimeString));
Assert.StrictEqual(localTimeObject.Value, localTimeObjectRoundTrip.Value);
TypeWithDateTimePropertyAsXmlTime utcTimeObject = new TypeWithDateTimePropertyAsXmlTime()
{
Value = new DateTime(549269870000L, DateTimeKind.Utc)
};
TypeWithDateTimePropertyAsXmlTime utcTimeRoundTrip = SerializeAndDeserialize(utcTimeObject,
WithXmlHeader(@"<TypeWithDateTimePropertyAsXmlTime xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">15:15:26.9870000Z</TypeWithDateTimePropertyAsXmlTime>"));
Assert.StrictEqual(utcTimeObject.Value, utcTimeRoundTrip.Value);
}
[Fact]
public static void Xml_NamespaceTypeNameClashTest()
{
var serializer = new XmlSerializer(typeof(NamespaceTypeNameClashContainer));
Assert.NotNull(serializer);
var root = new NamespaceTypeNameClashContainer
{
A = new[] { new SerializationTypes.TypeNameClashA.TypeNameClash { Name = "N1" }, new SerializationTypes.TypeNameClashA.TypeNameClash { Name = "N2" } },
B = new[] { new SerializationTypes.TypeNameClashB.TypeNameClash { Name = "N3" } }
};
var xml = @"<?xml version=""1.0""?>
<Root xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<A>
<Name>N1</Name>
</A>
<A>
<Name>N2</Name>
</A>
<B>
<Name>N3</Name>
</B>
</Root>";
var actualRoot = SerializeAndDeserialize<NamespaceTypeNameClashContainer>(root, xml);
Assert.NotNull(actualRoot);
Assert.NotNull(actualRoot.A);
Assert.NotNull(actualRoot.B);
Assert.Equal(root.A.Length, actualRoot.A.Length);
Assert.Equal(root.B.Length, actualRoot.B.Length);
Assert.Equal(root.A[0].Name, actualRoot.A[0].Name);
Assert.Equal(root.A[1].Name, actualRoot.A[1].Name);
Assert.Equal(root.B[0].Name, actualRoot.B[0].Name);
}
[Fact]
public static void Xml_ArrayAsGetSet()
{
TypeWithGetSetArrayMembers x = new TypeWithGetSetArrayMembers
{
F1 = new SimpleType[] { new SimpleType { P1 = "ab", P2 = 1 }, new SimpleType { P1 = "cd", P2 = 2 } },
F2 = new int[] { -1, 3 },
P1 = new SimpleType[] { new SimpleType { P1 = "ef", P2 = 5 }, new SimpleType { P1 = "gh", P2 = 7 } },
P2 = new int[] { 11, 12 }
};
TypeWithGetSetArrayMembers y = SerializeAndDeserialize<TypeWithGetSetArrayMembers>(x,
@"<?xml version=""1.0""?>
<TypeWithGetSetArrayMembers xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<F1>
<SimpleType>
<P1>ab</P1>
<P2>1</P2>
</SimpleType>
<SimpleType>
<P1>cd</P1>
<P2>2</P2>
</SimpleType>
</F1>
<F2>
<int>-1</int>
<int>3</int>
</F2>
<P1>
<SimpleType>
<P1>ef</P1>
<P2>5</P2>
</SimpleType>
<SimpleType>
<P1>gh</P1>
<P2>7</P2>
</SimpleType>
</P1>
<P2>
<int>11</int>
<int>12</int>
</P2>
</TypeWithGetSetArrayMembers>");
Assert.NotNull(y);
Utils.Equal<SimpleType>(x.F1, y.F1, (a, b) => { return SimpleType.AreEqual(a, b); });
Assert.Equal(x.F2, y.F2);
Utils.Equal<SimpleType>(x.P1, y.P1, (a, b) => { return SimpleType.AreEqual(a, b); });
Assert.Equal(x.P2, y.P2);
// Do it again with null and empty arrays
x = new TypeWithGetSetArrayMembers
{
F1 = null,
F2 = new int[] { },
P1 = new SimpleType[] { },
P2 = null
};
y = SerializeAndDeserialize<TypeWithGetSetArrayMembers>(x,
@"<?xml version=""1.0""?>
<TypeWithGetSetArrayMembers xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<F2 />
<P1 />
</TypeWithGetSetArrayMembers>");
Assert.NotNull(y);
Assert.Null(y.F1); // Arrays stay null
Assert.Empty(y.F2);
Assert.Empty(y.P1);
Assert.Null(y.P2); // Arrays stay null
}
[Fact]
public static void Xml_ArrayAsGetOnly()
{
TypeWithGetOnlyArrayProperties x = new TypeWithGetOnlyArrayProperties();
x.P1[0] = new SimpleType { P1 = "ab", P2 = 1 };
x.P1[1] = new SimpleType { P1 = "cd", P2 = 2 };
x.P2[0] = -1;
x.P2[1] = 3;
TypeWithGetOnlyArrayProperties y = SerializeAndDeserialize<TypeWithGetOnlyArrayProperties>(x, WithXmlHeader(@"<TypeWithGetOnlyArrayProperties xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" />"));
Assert.NotNull(y);
// XmlSerializer seems not complain about missing public setter of Array property
// However, it does not serialize the property. So for this test case, I'll use it to verify there are no complaints about missing public setter
}
[Fact]
public static void Xml_ArraylikeMembers()
{
var assertEqual = (TypeWithArraylikeMembers a, TypeWithArraylikeMembers b) => {
Assert.Equal(a.IntAField, b.IntAField);
Assert.Equal(a.NIntAField, b.NIntAField);
Assert.Equal(a.IntLField, b.IntLField);
Assert.Equal(a.NIntLField, b.NIntLField);
Assert.Equal(a.IntAProp, b.IntAProp);
Assert.Equal(a.NIntAProp, b.NIntAProp);
Assert.Equal(a.IntLProp, b.IntLProp);
Assert.Equal(a.NIntLProp, b.NIntLProp);
};
// Populated array-like members
var x = TypeWithArraylikeMembers.CreateWithPopulatedMembers();
var y = SerializeAndDeserialize<TypeWithArraylikeMembers>(x, null /* Just checking the input and output objects is good enough here */, null, true);
Assert.NotNull(y);
assertEqual(x, y);
// Empty array-like members
x = TypeWithArraylikeMembers.CreateWithEmptyMembers();
y = SerializeAndDeserialize<TypeWithArraylikeMembers>(x, WithXmlHeader("<TypeWithArraylikeMembers xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <IntAField />\r\n <NIntAField />\r\n <IntLField />\r\n <NIntLField />\r\n <IntAProp />\r\n <NIntAProp />\r\n <IntLProp />\r\n <NIntLProp />\r\n</TypeWithArraylikeMembers>"));
Assert.NotNull(y);
assertEqual(x, y);
Assert.Empty(y.IntAField); // Check on a couple fields to be sure they are empty and not null.
Assert.Empty(y.NIntLProp);
// Null array-like members
// Null arrays and collections are omitted from xml output (or set to 'nil'). But they differ in deserialization.
// Null arrays are deserialized as null as expected. Null collections are unintuitively deserialized as empty collections. This behavior is preserved for compatibility with NetFx.
x = TypeWithArraylikeMembers.CreateWithNullMembers();
y = SerializeAndDeserialize<TypeWithArraylikeMembers>(x, WithXmlHeader("<TypeWithArraylikeMembers xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <NIntLField xsi:nil=\"true\" />\r\n <NIntAProp xsi:nil=\"true\" />\r\n</TypeWithArraylikeMembers>"));
Assert.NotNull(y);
Assert.Null(y.IntAField);
Assert.Null(y.NIntAField);
Assert.Empty(y.IntLField);
Assert.Empty(y.NIntLField);
Assert.Null(y.IntAProp);
Assert.Null(y.NIntAProp);
Assert.Empty(y.IntLProp);
Assert.Empty(y.NIntLProp);
}
[Fact]
public static void Xml_ListRoot()
{
MyList x = new MyList("a1", "a2");
MyList y = SerializeAndDeserialize<MyList>(x,
@"<?xml version=""1.0""?>
<ArrayOfAnyType xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<anyType xsi:type=""xsd:string"">a1</anyType>
<anyType xsi:type=""xsd:string"">a2</anyType>
</ArrayOfAnyType>");
Assert.NotNull(y);
Assert.True(y.Count == 2);
Assert.Equal((string)x[0], (string)y[0]);
Assert.Equal((string)x[1], (string)y[1]);
}
// ROC and Immutable types are not types from 'SerializableAssembly.dll', so they were not included in the
// pregenerated serializers for the sgen tests. We could wrap them in a type that does exist there...
// but I think the RO/Immutable story is wonky enough and RefEmit vs Reflection is near enough on the
// horizon that it's not worth the trouble.
#if !XMLSERIALIZERGENERATORTESTS
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/74247", TestPlatforms.tvOS)]
public static void Xml_ReadOnlyCollection()
{
ReadOnlyCollection<string> roc = new ReadOnlyCollection<string>(new string[] { "one", "two" });
#if ReflectionOnly
// Expect exception when _using_ the serializer
var serializer = new XmlSerializer(typeof(ReadOnlyCollection<string>));
var ex = Assert.Throws<InvalidOperationException>(() => Serialize(roc, null, () => serializer));
Assert.Equal("There was an error generating the XML document.", ex.Message);
Assert.NotNull(ex.InnerException);
Assert.IsType<InvalidOperationException>(ex.InnerException);
Assert.StartsWith("To be XML serializable, types which inherit from ICollection must have an implementation of Add(System.String) at all levels of their inheritance hierarchy.", ex.InnerException.Message);
#else
// Expect exception when _creating_ the serializer
var ex = Assert.Throws<InvalidOperationException>(() => new XmlSerializer(typeof(ReadOnlyCollection<string>)));
Assert.StartsWith("To be XML serializable, types which inherit from ICollection must have an implementation of Add(System.String) at all levels of their inheritance hierarchy.", ex.Message);
#endif
}
[Theory]
[MemberData(nameof(Xml_ImmutableCollections_MemberData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/74247", TestPlatforms.tvOS)]
public static void Xml_ImmutableCollections(Type type, object collection, Type createException, Type addException, string expectedXml, string exMsg = null)
{
XmlSerializer serializer;
// Some collections implement the required enumerator/Add combo (ImmutableList, ImmutableArray) and some don't (ImmutableStack,
// ImmutableQueue). If they do not, they will throw upon serializer construction in RefEmit mode. They should throw when
// first using the serializer in Reflection mode.
#if ReflectionOnly
serializer = new XmlSerializer(type);
if (createException != null)
{
var ex = Assert.Throws(createException, () => Serialize(collection, expectedXml, () => serializer));
if (exMsg != null)
Assert.Contains(exMsg, $"{ex.Message} : {ex.InnerException?.Message}");
return;
}
#else
if (createException != null)
{
var ex = Assert.Throws(createException, () => serializer = new XmlSerializer(type));
if (exMsg != null)
Assert.Contains(exMsg, $"{ex.Message} : {ex.InnerException?.Message}");
return;
}
serializer = new XmlSerializer(type);
#endif
// If they do meet the signature requirement, they may succeed or fail depending on whether their Add/Indexer explicitly throw
// or not. (ImmutableArray throws. ImmutableList does not - it returns a new copy instead... which gets ignored and is thus
// essentially a silent failure.) Serializing out to a string first should work though.
string serializedValue = Serialize(collection, expectedXml, () => serializer);
if (addException != null)
{
var ex = Assert.Throws(addException, () => Deserialize(serializer, serializedValue));
if (exMsg != null)
Assert.Contains(exMsg, $"{ex.Message} : {ex.InnerException?.Message}");
return;
}
// In this case, we can execute everything without exception. But since our calls to '.Add()' do nothing, we end up
// with an empty collection
var rttCollection = Deserialize(serializer, serializedValue);
Assert.NotNull(rttCollection);
Assert.Empty((IEnumerable)rttCollection);
}
public static IEnumerable<object[]> Xml_ImmutableCollections_MemberData()
{
string arrayOfInt = WithXmlHeader("<ArrayOfInt xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><int>42</int></ArrayOfInt>");
string arrayOfAny = WithXmlHeader("<ArrayOfAnyType xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><anyType /></ArrayOfAnyType>");
#if ReflectionOnly
yield return new object[] { typeof(ImmutableArray<int>), ImmutableArray.Create(42), null, typeof(InvalidOperationException), arrayOfInt, "Specified method is not supported." };
yield return new object[] { typeof(ImmutableArray<object>), ImmutableArray.Create(new object()), null, typeof(InvalidOperationException), arrayOfAny, "Specified method is not supported." };
yield return new object[] { typeof(ImmutableList<int>), ImmutableList.Create(42), null, typeof(InvalidOperationException), arrayOfInt, "Specified method is not supported." };
yield return new object[] { typeof(ImmutableStack<int>), ImmutableStack.Create(42), typeof(InvalidOperationException), null, arrayOfInt, "To be XML serializable, types which inherit from IEnumerable must have an implementation of Add" };
yield return new object[] { typeof(ImmutableQueue<int>), ImmutableQueue.Create(42), typeof(InvalidOperationException), null, arrayOfInt, "To be XML serializable, types which inherit from IEnumerable must have an implementation of Add" };
yield return new object[] { typeof(ImmutableDictionary<string, int>), new Dictionary<string, int>() { { "one", 1 } }.ToImmutableDictionary(), typeof(InvalidOperationException), null, null, "is not supported because it implements IDictionary." };
#else
yield return new object[] { typeof(ImmutableArray<int>), ImmutableArray.Create(42), null, typeof(InvalidOperationException), arrayOfInt, "Parameterless constructor is required for collections and enumerators." };
yield return new object[] { typeof(ImmutableArray<object>), ImmutableArray.Create(new object()), null, typeof(InvalidOperationException), arrayOfAny, "Parameterless constructor is required for collections and enumerators." };
yield return new object[] { typeof(ImmutableList<int>), ImmutableList.Create(42), null, null, arrayOfInt };
yield return new object[] { typeof(ImmutableStack<int>), ImmutableStack.Create(42), typeof(InvalidOperationException), null, arrayOfInt, "To be XML serializable, types which inherit from IEnumerable must have an implementation of Add" };
yield return new object[] { typeof(ImmutableQueue<int>), ImmutableQueue.Create(42), typeof(InvalidOperationException), null, arrayOfInt, "To be XML serializable, types which inherit from IEnumerable must have an implementation of Add" };
// IDictionary types are denied right from the start with a NotSupportedExcpetion
yield return new object[] { typeof(ImmutableDictionary<string, int>), new Dictionary<string, int>() { { "one", 1 } }.ToImmutableDictionary(), typeof(NotSupportedException), null, null, "is not supported because it implements IDictionary." };
#endif
}
#endif // !XMLSERIALIZERGENERATORTESTS
[Fact]
public static void Xml_EnumAsRoot()
{
Assert.StrictEqual(MyEnum.Two, SerializeAndDeserialize<MyEnum>(MyEnum.Two,
@"<?xml version=""1.0""?>
<MyEnum>Two</MyEnum>"));
Assert.StrictEqual(ByteEnum.Option1, SerializeAndDeserialize<ByteEnum>(ByteEnum.Option1,
@"<?xml version=""1.0""?>
<ByteEnum>Option1</ByteEnum>"));
Assert.StrictEqual(SByteEnum.Option1, SerializeAndDeserialize<SByteEnum>(SByteEnum.Option1,
@"<?xml version=""1.0""?>
<SByteEnum>Option1</SByteEnum>"));
Assert.StrictEqual(ShortEnum.Option1, SerializeAndDeserialize<ShortEnum>(ShortEnum.Option1,
@"<?xml version=""1.0""?>
<ShortEnum>Option1</ShortEnum>"));
Assert.StrictEqual(IntEnum.Option1, SerializeAndDeserialize<IntEnum>(IntEnum.Option1,
@"<?xml version=""1.0""?>
<IntEnum>Option1</IntEnum>"));
Assert.StrictEqual(UIntEnum.Option1, SerializeAndDeserialize<UIntEnum>(UIntEnum.Option1,
@"<?xml version=""1.0""?>
<UIntEnum>Option1</UIntEnum>"));
Assert.StrictEqual(LongEnum.Option1, SerializeAndDeserialize<LongEnum>(LongEnum.Option1,
@"<?xml version=""1.0""?>
<LongEnum>Option1</LongEnum>"));
Assert.StrictEqual(ULongEnum.Option1, SerializeAndDeserialize<ULongEnum>(ULongEnum.Option1,
@"<?xml version=""1.0""?>
<ULongEnum>Option1</ULongEnum>"));
}
[Fact]
public static void Xml_EnumAsMember()
{
TypeWithEnumMembers x = new TypeWithEnumMembers { F1 = MyEnum.Three, P1 = MyEnum.Two };
TypeWithEnumMembers y = SerializeAndDeserialize<TypeWithEnumMembers>(x,
@"<?xml version=""1.0""?>
<TypeWithEnumMembers xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<F1>Three</F1>
<P1>Two</P1>
</TypeWithEnumMembers>");
Assert.NotNull(y);
Assert.StrictEqual(x.F1, y.F1);
Assert.StrictEqual(x.P1, y.P1);
}
#if !XMLSERIALIZERGENERATORTESTS
[Fact]
public static void Xml_EnumAsObject()
{
object o = MyEnum.Three;
object o2 = SerializeAndDeserialize<object>(o,
WithXmlHeader(@"<anyType xmlns:q1=""http://www.w3.org/2001/XMLSchema"" p2:type=""q1:int"" xmlns:p2=""http://www.w3.org/2001/XMLSchema-instance"">2</anyType>"));
Assert.NotNull(o2);
Assert.StrictEqual((int)o, o2);
Assert.Equal(MyEnum.Three, (MyEnum)o2);
}
#endif
[Fact]
public static void Xml_DCClassWithEnumAndStruct()
{
DCClassWithEnumAndStruct value = new DCClassWithEnumAndStruct(true);
DCClassWithEnumAndStruct actual = SerializeAndDeserialize<DCClassWithEnumAndStruct>(value,
@"<?xml version=""1.0""?>
<DCClassWithEnumAndStruct xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<MyStruct>
<Data>Data</Data>
</MyStruct>
<MyEnum1>One</MyEnum1>
</DCClassWithEnumAndStruct>");
Assert.StrictEqual(value.MyEnum1, actual.MyEnum1);
Assert.Equal(value.MyStruct.Data, actual.MyStruct.Data);
}
[Fact]
public static void Xml_BuiltInTypes()
{
BuiltInTypes x = new BuiltInTypes
{
ByteArray = new byte[] { 1, 2 }
};
BuiltInTypes y = SerializeAndDeserialize<BuiltInTypes>(x,
@"<?xml version=""1.0""?>
<BuiltInTypes xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<ByteArray>AQI=</ByteArray>
</BuiltInTypes>");
Assert.NotNull(y);
Assert.Equal(x.ByteArray, y.ByteArray);
}
[Fact]
public static void Xml_TypesWithArrayOfOtherTypes()
{
SerializeAndDeserialize<TypeHasArrayOfASerializedAsB>(new TypeHasArrayOfASerializedAsB(true),
@"<?xml version=""1.0""?>
<TypeHasArrayOfASerializedAsB xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Items>
<TypeA>
<Name>typeAValue</Name>
</TypeA>
<TypeA>
<Name>typeBValue</Name>
</TypeA>
</Items>
</TypeHasArrayOfASerializedAsB>");
}
[Fact]
public static void Xml_TypeNamesWithSpecialCharacters()
{
SerializeAndDeserialize<__TypeNameWithSpecialCharacters\u6F22\u00F1>(
new __TypeNameWithSpecialCharacters\u6F22\u00F1() { PropertyNameWithSpecialCharacters\u6F22\u00F1 = "Test" },
"<?xml version=\"1.0\"?><__TypeNameWithSpecialCharacters\u6F22\u00F1 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <PropertyNameWithSpecialCharacters\u6F22\u00F1>Test</PropertyNameWithSpecialCharacters\u6F22\u00F1></__TypeNameWithSpecialCharacters\u6F22\u00F1>");
}
[Fact]
public static void Xml_KnownTypesThroughConstructor()
{
KnownTypesThroughConstructor value = new KnownTypesThroughConstructor() { EnumValue = MyEnum.One, SimpleTypeValue = new SimpleKnownTypeValue() { StrProperty = "PropertyValue" } };
KnownTypesThroughConstructor actual = SerializeAndDeserialize<KnownTypesThroughConstructor>(value,
@"<?xml version=""1.0""?>
<KnownTypesThroughConstructor xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<EnumValue xsi:type=""MyEnum"">One</EnumValue>
<SimpleTypeValue xsi:type=""SimpleKnownTypeValue"">
<StrProperty>PropertyValue</StrProperty>
</SimpleTypeValue>
</KnownTypesThroughConstructor>",
() => { return new XmlSerializer(typeof(KnownTypesThroughConstructor), new Type[] { typeof(MyEnum), typeof(SimpleKnownTypeValue) }); });
Assert.StrictEqual((MyEnum)value.EnumValue, (MyEnum)actual.EnumValue);
Assert.Equal(((SimpleKnownTypeValue)value.SimpleTypeValue).StrProperty, ((SimpleKnownTypeValue)actual.SimpleTypeValue).StrProperty);
}
[Fact]
public static void Xml_BaseClassAndDerivedClassWithSameProperty()
{
DerivedClassWithSameProperty value = new DerivedClassWithSameProperty() { DateTimeProperty = new DateTime(100), IntProperty = 5, StringProperty = "TestString", ListProperty = new List<string>() };
value.ListProperty.AddRange(new string[] { "one", "two", "three" });
DerivedClassWithSameProperty actual = SerializeAndDeserialize<DerivedClassWithSameProperty>(value,
@"<?xml version=""1.0""?>
<DerivedClassWithSameProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<StringProperty>TestString</StringProperty>
<IntProperty>5</IntProperty>
<DateTimeProperty>0001-01-01T00:00:00.00001</DateTimeProperty>
<ListProperty>
<string>one</string>
<string>two</string>
<string>three</string>
</ListProperty>
</DerivedClassWithSameProperty>");
Assert.StrictEqual(value.DateTimeProperty, actual.DateTimeProperty);
Assert.StrictEqual(value.IntProperty, actual.IntProperty);
Assert.Equal(value.StringProperty, actual.StringProperty);
Assert.Equal(value.ListProperty.ToArray(), actual.ListProperty.ToArray());
BaseClassWithSamePropertyName castAsBase = (BaseClassWithSamePropertyName)actual;
Assert.Equal(default(int), castAsBase.IntProperty);
Assert.Null(castAsBase.StringProperty);
Assert.Null(castAsBase.ListProperty);
// Try again with a null list to ensure the correct property is deserialized to an empty list
value = new DerivedClassWithSameProperty() { DateTimeProperty = new DateTime(100), IntProperty = 5, StringProperty = "TestString", ListProperty = null };
actual = SerializeAndDeserialize<DerivedClassWithSameProperty>(value,
@"<?xml version=""1.0""?>
<DerivedClassWithSameProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<StringProperty>TestString</StringProperty>
<IntProperty>5</IntProperty>
<DateTimeProperty>0001-01-01T00:00:00.00001</DateTimeProperty>
</DerivedClassWithSameProperty>");
Assert.StrictEqual(value.DateTimeProperty, actual.DateTimeProperty);
Assert.StrictEqual(value.IntProperty, actual.IntProperty);
Assert.Equal(value.StringProperty, actual.StringProperty);
Assert.Empty(actual.ListProperty.ToArray());
castAsBase = (BaseClassWithSamePropertyName)actual;
Assert.Equal(default(int), castAsBase.IntProperty);
Assert.Null(castAsBase.StringProperty);
Assert.Null(castAsBase.ListProperty);
}
[Fact]
public static void Xml_EnumFlags()
{
EnumFlags value1 = EnumFlags.One | EnumFlags.Four;
var value2 = SerializeAndDeserialize<EnumFlags>(value1,
@"<?xml version=""1.0""?>
<EnumFlags>One Four</EnumFlags>");
Assert.StrictEqual(value1, value2);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void Xml_SerializeClassThatImplementsInterface()
{
ClassImplementsInterface value = new ClassImplementsInterface() { ClassID = "ClassID", DisplayName = "DisplayName", Id = "Id", IsLoaded = true };
ClassImplementsInterface actual = SerializeAndDeserialize<ClassImplementsInterface>(value,
@"<?xml version=""1.0""?>
<ClassImplementsInterface xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<ClassID>ClassID</ClassID>
<DisplayName>DisplayName</DisplayName>
<Id>Id</Id>
<IsLoaded>true</IsLoaded>
</ClassImplementsInterface>");
Assert.Equal(value.ClassID, actual.ClassID);
Assert.Equal(value.DisplayName, actual.DisplayName);
Assert.Equal(value.Id, actual.Id);
Assert.StrictEqual(value.IsLoaded, actual.IsLoaded);
}
[Fact]
public static void Xml_XmlAttributesTest()
{
var value = new XmlSerializerAttributes();
var actual = SerializeAndDeserialize(value,
@"<?xml version=""1.0""?>
<AttributeTesting xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" XmlAttributeName=""2"">
<Word>String choice value</Word>
<XmlIncludeProperty xsi:type=""ItemChoiceType"">DecimalNumber</XmlIncludeProperty>
<XmlEnumProperty>
<ItemChoiceType>DecimalNumber</ItemChoiceType>
<ItemChoiceType>Number</ItemChoiceType>
<ItemChoiceType>Word</ItemChoiceType>
<ItemChoiceType>None</ItemChoiceType>
</XmlEnumProperty><xml>Hello XML</xml><XmlNamespaceDeclarationsProperty>XmlNamespaceDeclarationsPropertyValue</XmlNamespaceDeclarationsProperty><XmlElementPropertyNode xmlns=""http://element"">1</XmlElementPropertyNode><CustomXmlArrayProperty xmlns=""http://mynamespace""><string>one</string><string>two</string><string>three</string></CustomXmlArrayProperty></AttributeTesting>");
Assert.StrictEqual(actual.EnumType, value.EnumType);
Assert.StrictEqual(actual.MyChoice, value.MyChoice);
object[] stringArray = actual.XmlArrayProperty.Where(x => x != null)
.Select(x => x.ToString())
.ToArray();
Assert.Equal(stringArray, value.XmlArrayProperty);
Assert.StrictEqual(actual.XmlAttributeProperty, value.XmlAttributeProperty);
Assert.StrictEqual(actual.XmlElementProperty, value.XmlElementProperty);
Assert.Equal(actual.XmlEnumProperty, value.XmlEnumProperty);
Assert.StrictEqual(actual.XmlIncludeProperty, value.XmlIncludeProperty);
Assert.Equal(actual.XmlNamespaceDeclarationsProperty, value.XmlNamespaceDeclarationsProperty);
Assert.Equal(actual.XmlTextProperty, value.XmlTextProperty);
}
[Fact]
public static void Xml_XmlAnyAttributeTest()
{
var serializer = new XmlSerializer(typeof(TypeWithAnyAttribute));
string format = WithXmlHeader(@"<TypeWithAnyAttribute xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" GroupType = '{0}' IntProperty = '{1}' GroupBase = '{2}'><Name>{3}</Name></TypeWithAnyAttribute>");
const int intProperty = 42;
const string attribute1 = "Technical";
const string attribute2 = "Red";
const string name = "MyGroup";
using (var stream = new MemoryStream())
{
var writer = new StreamWriter(stream);
writer.Write(format, attribute1, intProperty, attribute2, name);
writer.Flush();
stream.Position = 0;
var obj = (TypeWithAnyAttribute)serializer.Deserialize(stream);
Assert.NotNull(obj);
Assert.StrictEqual(intProperty, obj.IntProperty);
Assert.Equal(name, obj.Name);
Assert.StrictEqual(2, obj.Attributes.Length);
Assert.Equal(attribute1, obj.Attributes[0].Value);
Assert.Equal(attribute2, obj.Attributes[1].Value);
}
}
[Fact]
public static void Xml_Struct()
{
var value = new WithStruct { Some = new SomeStruct { A = 1, B = 2 } };
var result = SerializeAndDeserialize(value,
@"<?xml version=""1.0""?>
<WithStruct xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Some>
<A>1</A>
<B>2</B>
</Some>
</WithStruct>");
// Assert
Assert.StrictEqual(result.Some.A, value.Some.A);
Assert.StrictEqual(result.Some.B, value.Some.B);
}
[Fact]
public static void Xml_Enums()
{
var item = new WithEnums() { Int = IntEnum.Option1, Short = ShortEnum.Option2 };
var actual = SerializeAndDeserialize(item,
@"<?xml version=""1.0""?>
<WithEnums xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Int>Option1</Int>
<Short>Option2</Short>
</WithEnums>");
Assert.StrictEqual(item.Short, actual.Short);
Assert.StrictEqual(item.Int, actual.Int);
}
[Fact]
public static void Xml_Nullables()
{
var item = new WithNullables() { Optional = IntEnum.Option1, OptionalInt = 42, Struct1 = new SomeStruct { A = 1, B = 2 } };
var actual = SerializeAndDeserialize(item,
@"<?xml version=""1.0""?>
<WithNullables xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Optional>Option1</Optional>
<Optionull xsi:nil=""true"" />
<OptionalInt>42</OptionalInt>
<OptionullInt xsi:nil=""true"" />
<Struct1>
<A>1</A>
<B>2</B>
</Struct1>
<Struct2 xsi:nil=""true"" />
</WithNullables>");
Assert.StrictEqual(item.OptionalInt, actual.OptionalInt);
Assert.StrictEqual(item.Optional, actual.Optional);
Assert.StrictEqual(item.Optionull, actual.Optionull);
Assert.StrictEqual(item.OptionullInt, actual.OptionullInt);
Assert.Null(actual.Struct2);
Assert.StrictEqual(item.Struct1.Value.A, actual.Struct1.Value.A);
Assert.StrictEqual(item.Struct1.Value.B, actual.Struct1.Value.B);
}
[Fact]
public static void Xml_DerivedClasses()
{
var dClass = new SimpleDerivedClass() { AttributeString = "derivedClassTest", DateTimeValue = DateTime.Parse("Dec 31, 1999"), BoolValue = true };
var expectedXml = WithXmlHeader(@"<SimpleBaseClass xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xsi:type=""SimpleDerivedClass"" AttributeString=""derivedClassTest"" DateTimeValue=""1999-12-31T00:00:00"" BoolValue=""true"" />");
var fromBase = SerializeAndDeserialize(dClass, expectedXml, () => new XmlSerializer(typeof(SimpleBaseClass)));
Assert.Equal(dClass.AttributeString, fromBase.AttributeString);
Assert.StrictEqual(dClass.DateTimeValue, fromBase.DateTimeValue);
Assert.Equal(dClass.BoolValue, fromBase.BoolValue);
// Derived class does not apply XmlRoot attribute to force itself to be emitted with the base class element name, so update expected xml accordingly.
expectedXml = WithXmlHeader(@"<SimpleDerivedClass xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" AttributeString=""derivedClassTest"" DateTimeValue=""1999-12-31T00:00:00"" BoolValue=""true"" />");
var fromDerived = SerializeAndDeserialize(dClass, expectedXml, () => new XmlSerializer(typeof(SimpleDerivedClass)));
Assert.Equal(dClass.AttributeString, fromDerived.AttributeString);
Assert.StrictEqual(dClass.DateTimeValue, fromDerived.DateTimeValue);
Assert.Equal(dClass.BoolValue, fromDerived.BoolValue);
}
[Fact]
public static void Xml_ClassImplementingIXmlSerializable()
{
var value = new ClassImplementingIXmlSerializable() { StringValue = "Hello world" };
var actual = SerializeAndDeserialize<ClassImplementingIXmlSerializable>(value,
@"<?xml version=""1.0""?>
<ClassImplementingIXmlSerializable StringValue=""Hello world"" BoolValue=""True"" />");
Assert.Equal(value.StringValue, actual.StringValue);
Assert.StrictEqual(value.GetPrivateMember(), actual.GetPrivateMember());
Assert.True(ClassImplementingIXmlSerializable.ReadXmlInvoked);
Assert.True(ClassImplementingIXmlSerializable.WriteXmlInvoked);
}
[Fact]
public static void Xml_TypeWithFieldNameEndBySpecified()
{
var value = new TypeWithPropertyNameSpecified() { MyField = "MyField", MyFieldIgnored = 99, MyFieldSpecified = true, MyFieldIgnoredSpecified = false };
var actual = SerializeAndDeserialize<TypeWithPropertyNameSpecified>(value,
@"<?xml version=""1.0""?><TypeWithPropertyNameSpecified xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><MyField>MyField</MyField></TypeWithPropertyNameSpecified>");
Assert.Equal(value.MyField, actual.MyField);
Assert.StrictEqual(0, actual.MyFieldIgnored);
}
[Fact]
public static void XML_TypeWithXmlSchemaFormAttribute()
{
var value = new TypeWithXmlSchemaFormAttribute() { NoneSchemaFormListProperty = new List<string> { "abc" }, QualifiedSchemaFormListProperty = new List<bool> { true }, UnqualifiedSchemaFormListProperty = new List<int> { 1 } };
var actual = SerializeAndDeserialize<TypeWithXmlSchemaFormAttribute>(value,
@"<?xml version=""1.0""?><TypeWithXmlSchemaFormAttribute xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><UnqualifiedSchemaFormListProperty><int>1</int></UnqualifiedSchemaFormListProperty><NoneSchemaFormListProperty><NoneParameter>abc</NoneParameter></NoneSchemaFormListProperty><QualifiedSchemaFormListProperty><QualifiedParameter>true</QualifiedParameter></QualifiedSchemaFormListProperty></TypeWithXmlSchemaFormAttribute>");
Assert.StrictEqual(value.NoneSchemaFormListProperty.Count, actual.NoneSchemaFormListProperty.Count);
Assert.Equal(value.NoneSchemaFormListProperty[0], actual.NoneSchemaFormListProperty[0]);
Assert.StrictEqual(value.UnqualifiedSchemaFormListProperty.Count, actual.UnqualifiedSchemaFormListProperty.Count);
Assert.StrictEqual(value.UnqualifiedSchemaFormListProperty[0], actual.UnqualifiedSchemaFormListProperty[0]);
Assert.StrictEqual(value.QualifiedSchemaFormListProperty.Count, actual.QualifiedSchemaFormListProperty.Count);
Assert.StrictEqual(value.QualifiedSchemaFormListProperty[0], actual.QualifiedSchemaFormListProperty[0]);
}
[Fact]
public static void XML_TypeWithTypeNameInXmlTypeAttribute()
{
var value = new TypeWithTypeNameInXmlTypeAttribute();
SerializeAndDeserialize<TypeWithTypeNameInXmlTypeAttribute>(value,
@"<?xml version=""1.0""?><MyXmlType xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" />");
}
[Fact]
public static void XML_TypeWithXmlTextAttributeOnArray()
{
var original = new TypeWithXmlTextAttributeOnArray() { Text = new string[] { "val1", "val2" } };
var actual = SerializeAndDeserialize<TypeWithXmlTextAttributeOnArray>(original,
@"<?xml version=""1.0""?>
<TypeWithXmlTextAttributeOnArray xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://schemas.xmlsoap.org/ws/2005/04/discovery"">val1val2</TypeWithXmlTextAttributeOnArray>");
Assert.NotNull(actual.Text);
Assert.StrictEqual(1, actual.Text.Length);
Assert.Equal("val1val2", actual.Text[0]);
}
[Fact]
public static void Xml_TypeWithSchemaFormInXmlAttribute()
{
var value = new TypeWithSchemaFormInXmlAttribute() { TestProperty = "hello" };
var actual = SerializeAndDeserialize<TypeWithSchemaFormInXmlAttribute>(value,
@"<?xml version=""1.0""?><TypeWithSchemaFormInXmlAttribute xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" d1p1:TestProperty=""hello"" xmlns:d1p1=""http://test.com"" />");
Assert.Equal(value.TestProperty, actual.TestProperty);
}
[Fact]
public static void Xml_TypeWithXmlElementProperty()
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(@"<html></html>");
XmlElement productElement = xDoc.CreateElement("Product");
productElement.InnerText = "Product innertext";
XmlElement categoryElement = xDoc.CreateElement("Category");
categoryElement.InnerText = "Category innertext";
var expected = new TypeWithXmlElementProperty() { Elements = new[] { productElement, categoryElement } };
var actual = SerializeAndDeserialize(expected,
WithXmlHeader(@"<TypeWithXmlElementProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><Product>Product innertext</Product><Category>Category innertext</Category></TypeWithXmlElementProperty>"));
Assert.StrictEqual(expected.Elements.Length, actual.Elements.Length);
for (int i = 0; i < expected.Elements.Length; ++i)
{
Assert.Equal(expected.Elements[i].InnerText, actual.Elements[i].InnerText);
}
}
[Fact]
public static void Xml_TypeWithXmlDocumentProperty()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(@"<html><head>Head content</head><body><h1>Heading1</h1><div>Text in body</div></body></html>");
var expected = new TypeWithXmlDocumentProperty() { Document = xmlDoc };
var actual = SerializeAndDeserialize(expected,
@"<TypeWithXmlDocumentProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><Document><html><head>Head content</head><body><h1>Heading1</h1><div>Text in body</div></body></html></Document></TypeWithXmlDocumentProperty>");
Assert.NotNull(actual);
Assert.NotNull(actual.Document);
Assert.Equal(expected.Document.OuterXml, actual.Document.OuterXml);
}
[Fact]
public static void Xml_TypeWithNonPublicDefaultConstructor()
{
System.Reflection.TypeInfo ti = System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(TypeWithNonPublicDefaultConstructor));
TypeWithNonPublicDefaultConstructor value = null;
value = (TypeWithNonPublicDefaultConstructor)FindDefaultConstructor(ti).Invoke(null);
Assert.Equal("Mr. FooName", value.Name);
var actual = SerializeAndDeserialize<TypeWithNonPublicDefaultConstructor>(value,
@"<?xml version=""1.0""?>
<TypeWithNonPublicDefaultConstructor xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Name>Mr. FooName</Name>
</TypeWithNonPublicDefaultConstructor>");
Assert.Equal(value.Name, actual.Name);
}
private static System.Reflection.ConstructorInfo FindDefaultConstructor(System.Reflection.TypeInfo ti)
{
foreach (System.Reflection.ConstructorInfo ci in ti.DeclaredConstructors)
{
if (!ci.IsStatic && ci.GetParameters().Length == 0)
{
return ci;
}
}
return null;
}
[Fact]
public static void Xml_TestIgnoreWhitespaceForDeserialization()
{
string xml = WithXmlHeader(@"<ServerSettings>
<DS2Root>
<![CDATA[ http://wxdata.weather.com/wxdata/]]>
</DS2Root>
<MetricConfigUrl><![CDATA[ http://s3.amazonaws.com/windows-prod-twc/desktop8/beacons.xml ]]></MetricConfigUrl>
</ServerSettings>");
XmlSerializer serializer = new XmlSerializer(typeof(ServerSettings));
StringReader reader = new StringReader(xml);
var value = (ServerSettings)serializer.Deserialize(reader);
Assert.Equal(@" http://s3.amazonaws.com/windows-prod-twc/desktop8/beacons.xml ", value.MetricConfigUrl);
Assert.Equal(@" http://wxdata.weather.com/wxdata/", value.DS2Root);
}
[Fact]
public static void Xml_TypeWithBinaryProperty()
{
var obj = new TypeWithBinaryProperty();
var str = "The quick brown fox jumps over the lazy dog.";
obj.Base64Content = Encoding.Unicode.GetBytes(str);
obj.BinaryHexContent = Encoding.Unicode.GetBytes(str);
var actual = SerializeAndDeserialize(obj,
WithXmlHeader(@"<TypeWithBinaryProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><BinaryHexContent>540068006500200071007500690063006B002000620072006F0077006E00200066006F00780020006A0075006D007000730020006F00760065007200200074006800650020006C0061007A007900200064006F0067002E00</BinaryHexContent><Base64Content>VABoAGUAIABxAHUAaQBjAGsAIABiAHIAbwB3AG4AIABmAG8AeAAgAGoAdQBtAHAAcwAgAG8AdgBlAHIAIAB0AGgAZQAgAGwAYQB6AHkAIABkAG8AZwAuAA==</Base64Content></TypeWithBinaryProperty>"));
Assert.True(Enumerable.SequenceEqual(obj.Base64Content, actual.Base64Content));
Assert.True(Enumerable.SequenceEqual(obj.BinaryHexContent, actual.BinaryHexContent));
}
[Fact]
public static void Xml_DifferentSerializeDeserializeOverloads()
{
var expected = new SimpleType() { P1 = "p1 value", P2 = 123 };
var serializer = new XmlSerializer(typeof(SimpleType));
var writerTypes = new Type[] { typeof(TextWriter), typeof(XmlWriter) };
Assert.Throws<InvalidOperationException>(() =>
{
XmlWriter writer = null;
serializer.Serialize(writer, expected);
});
Assert.Throws<InvalidOperationException>(() =>
{
XmlReader reader = null;
serializer.Deserialize(reader);
});
foreach (var writerType in writerTypes)
{
var stream = new MemoryStream();
if (writerType == typeof(TextWriter))
{
var writer = new StreamWriter(stream);
serializer.Serialize(writer, expected);
}
else
{
var writer = XmlWriter.Create(stream);
serializer.Serialize(writer, expected);
}
stream.Position = 0;
var actualOutput = new StreamReader(stream).ReadToEnd();
string baseline = WithXmlHeader(@"<SimpleType xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><P1>p1 value</P1><P2>123</P2></SimpleType>");
var result = Utils.Compare(baseline, actualOutput);
Assert.True(result.Equal, string.Format("{1}{0}Test failed for input: {2}{0}Expected: {3}{0}Actual: {4}", Environment.NewLine, result.ErrorMessage, expected, baseline, actualOutput));
stream.Position = 0;
// XmlSerializer.CanSerialize(XmlReader)
XmlReader reader = XmlReader.Create(stream);
Assert.True(serializer.CanDeserialize(reader));
// XmlSerializer.Deserialize(XmlReader)
var actual = (SimpleType)serializer.Deserialize(reader);
Assert.Equal(expected.P1, actual.P1);
Assert.StrictEqual(expected.P2, actual.P2);
stream.Dispose();
}
}
[Fact]
public static void Xml_TypeWithTimeSpanProperty()
{
var obj = new TypeWithTimeSpanProperty { TimeSpanProperty = TimeSpan.FromMilliseconds(1) };
var deserializedObj = SerializeAndDeserialize(obj, WithXmlHeader(@"<TypeWithTimeSpanProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<TimeSpanProperty>PT0.001S</TimeSpanProperty>
</TypeWithTimeSpanProperty>"));
Assert.StrictEqual(obj.TimeSpanProperty, deserializedObj.TimeSpanProperty);
}
[ConditionalFact(nameof(DefaultValueAttributeIsSupported))]
public static void Xml_TypeWithDefaultTimeSpanProperty()
{
var obj = new TypeWithDefaultTimeSpanProperty { TimeSpanProperty2 = new TimeSpan(0, 1, 0) };
var deserializedObj = SerializeAndDeserialize(obj, WithXmlHeader(@"<TypeWithDefaultTimeSpanProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><TimeSpanProperty2>PT1M</TimeSpanProperty2></TypeWithDefaultTimeSpanProperty>"));
Assert.NotNull(deserializedObj);
Assert.Equal(obj.TimeSpanProperty, deserializedObj.TimeSpanProperty);
Assert.Equal(obj.TimeSpanProperty2, deserializedObj.TimeSpanProperty2);
}
[Fact]
public static void Xml_DeserializeTypeWithEmptyTimeSpanProperty()
{
string xml =
@"<?xml version=""1.0""?>
<TypeWithTimeSpanProperty xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<TimeSpanProperty />
</TypeWithTimeSpanProperty>";
XmlSerializer serializer = new XmlSerializer(typeof(TypeWithTimeSpanProperty));
using (StringReader reader = new StringReader(xml))
{
TypeWithTimeSpanProperty deserializedObj = (TypeWithTimeSpanProperty)serializer.Deserialize(reader);
Assert.NotNull(deserializedObj);
Assert.Equal(default(TimeSpan), deserializedObj.TimeSpanProperty);
}
}
[Fact]
public static void Xml_DeserializeEmptyTimeSpanType()
{
string xml =
@"<?xml version=""1.0""?>
<TimeSpan />";
XmlSerializer serializer = new XmlSerializer(typeof(TimeSpan));
using (StringReader reader = new StringReader(xml))
{
TimeSpan deserializedObj = (TimeSpan)serializer.Deserialize(reader);
Assert.Equal(default(TimeSpan), deserializedObj);
}
}
[ConditionalFact(nameof(DefaultValueAttributeIsSupported))]
public static void Xml_TypeWithDateTimeOffsetProperty()
{
var now = new DateTimeOffset(DateTime.Now);
var defDTO = default(DateTimeOffset);
var obj = new TypeWithDateTimeOffsetProperties { DTO = now };
var deserializedObj = SerializeAndDeserialize(obj,
@"<?xml version=""1.0""?>
<TypeWithDateTimeOffsetProperties xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<DTO>" + XmlConvert.ToString(now) + @"</DTO>
<DTO2>" + XmlConvert.ToString(defDTO) + @"</DTO2>
<NullableDTO xsi:nil=""true"" />
<NullableDefaultDTO xsi:nil=""true"" />
</TypeWithDateTimeOffsetProperties>");
Assert.StrictEqual(obj.DTO, deserializedObj.DTO);
Assert.StrictEqual(obj.DTO2, deserializedObj.DTO2);
Assert.StrictEqual(defDTO, deserializedObj.DTO2);
Assert.StrictEqual(obj.DTOWithDefault, deserializedObj.DTOWithDefault);
Assert.StrictEqual(defDTO, deserializedObj.DTOWithDefault);
Assert.StrictEqual(obj.NullableDTO, deserializedObj.NullableDTO);
Assert.True(deserializedObj.NullableDTO == null);
Assert.StrictEqual(obj.NullableDTOWithDefault, deserializedObj.NullableDTOWithDefault);
Assert.True(deserializedObj.NullableDTOWithDefault == null);
}
[ConditionalFact(nameof(DefaultValueAttributeIsSupported))]
public static void Xml_DeserializeTypeWithEmptyDateTimeOffsetProperties()
{
//var def = DateTimeOffset.Parse("3/17/1977 5:00:01 PM -05:00"); // "1977-03-17T17:00:01-05:00"
var defDTO = default(DateTimeOffset);
string xml = @"<?xml version=""1.0""?>