forked from msgpack/msgpack-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoMessagePackSerializerTest.Polymorphism.ttinclude
More file actions
1402 lines (1260 loc) · 48.6 KB
/
AutoMessagePackSerializerTest.Polymorphism.ttinclude
File metadata and controls
1402 lines (1260 loc) · 48.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
<#@ import namespace="System" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Globalization" #>
<#@ import namespace="System.Linq" #>
<#+
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
// Entry Point
private void GeneratePolymorphismTestParts()
{
this.GeneratePolymorphismTestPartsCore( false, true );
}
private void GeneratePolymorphismTestTypes()
{
this.GeneratePolymorphismTestPartsCore( true, false );
}
private IEnumerable<TestTargetType> GetSerialiazablePolymprohicTestTypeNames()
{
return this.GeneratePolymorphismTestPartsCore( false, false );
}
private IEnumerable<TestTargetType> GeneratePolymorphismTestPartsCore( bool generateTypes, bool generateMethods )
{
ICollection<TestTargetType> generatedSerializableTypeNames = new HashSet<TestTargetType>();
Func<Member, bool, IEnumerable<string>> knownAttributeFactory =
( Member member, bool asObject ) =>
{
switch ( member.Targets )
{
case PolymorphismTargets.Item:
{
return
( asObject
? new[] { "[MessagePackRuntimeType]" }
: new string[ 0 ]
).Concat(
member.ActualTypes.Select(
( t, i ) =>
String.Format( CultureInfo.InvariantCulture, "[MessagePackKnownCollectionItemType( \"{0}\", typeof( {1} ) )]", i, t )
)
);
}
case PolymorphismTargets.Key:
{
return
( asObject
? new[] { "[MessagePackRuntimeType]" }
: new string[ 0 ]
).Concat(
member.ActualTypes.Select(
( t, i ) =>
String.Format( CultureInfo.InvariantCulture, "[MessagePackKnownDictionaryKeyType( \"{0}\", typeof( {1} ) )]", i, t )
)
);
}
case PolymorphismTargets.Key | PolymorphismTargets.Item:
{
return
( asObject
? new[] { "[MessagePackRuntimeType]" }
: new string[ 0 ]
).Concat(
member.ActualTypes.Select( ( t, i ) => String.Format( CultureInfo.InvariantCulture, "[MessagePackKnownDictionaryKeyType( \"{0}\", typeof( {1} ) )]", i, t ) )
).Concat(
member.ActualTypes.Select( ( t, i ) => String.Format( CultureInfo.InvariantCulture, "[MessagePackKnownCollectionItemType( \"{0}\", typeof( {1} ) )]", i, t ) )
);
}
case PolymorphismTargets.TupleItem:
{
return
( asObject
? new[] { "[MessagePackRuntimeType]" }
: new string[ 0 ]
).Concat(
member.PolymorphicTupleItemTypes.SelectMany(
kv =>
kv.Value.Select(
( t, i ) =>
String.Format( CultureInfo.InvariantCulture, "[MessagePackKnownTupleItemType( {0}, \"{1}\", typeof( {2} ) )]", kv.Key, i, t )
)
)
);
}
case PolymorphismTargets.Member:
{
return member.ActualTypes.Select( ( t, i ) => String.Format( CultureInfo.InvariantCulture, "[MessagePackKnownType( \"{0}\", typeof( {1} ) )]", i, t ) );
}
default:
{
return Enumerable.Empty<string>();
}
}
};
Func<Member, bool, IEnumerable<string>> runtimeAttributeFactory =
( Member member, bool asObject ) =>
{
switch ( member.Targets )
{
case PolymorphismTargets.Item:
{
return
( asObject
? new[] { "[MessagePackRuntimeType]" }
: new string[ 0 ]
).Concat( new[] { "[MessagePackRuntimeCollectionItemType]" } );
}
case PolymorphismTargets.Key:
{
return
( asObject
? new[] { "[MessagePackRuntimeType]" }
: new string[ 0 ]
).Concat( new[] { "[MessagePackRuntimeDictionaryKeyType]" } );
}
case PolymorphismTargets.Key | PolymorphismTargets.Item:
{
return
( asObject
? new[] { "[MessagePackRuntimeType]" }
: new string[ 0 ]
).Concat(
new[]
{
"[MessagePackRuntimeCollectionItemType]",
"[MessagePackRuntimeDictionaryKeyType]"
}
);
}
case PolymorphismTargets.TupleItem:
{
return
( asObject
? new[] { "[MessagePackRuntimeType]" }
: new string[ 0 ]
).Concat(
member.PolymorphicTupleItemTypes.Select(
kv => String.Format( CultureInfo.InvariantCulture, "[MessagePackRuntimeTupleItemType( {0} )]", kv.Key )
)
);
}
case PolymorphismTargets.Member:
{
return new [] { "[MessagePackRuntimeType]" };
}
default:
{
return Enumerable.Empty<string>();
}
}
};
var attributeTypes =
new []
{
new { Name = "KnownType", AttributeFactory = knownAttributeFactory },
new { Name = "RuntimeType", AttributeFactory = runtimeAttributeFactory },
};
var normalTypes =
new []
{
Member.Of( "Reference", "Version" , PolymorphismTargets.None, null, @"null", @"new Version( 1, 2, 3, 4 )" ),
Member.Of( "Value", "DateTime", PolymorphismTargets.None, null, @"default( DateTime )", @"new DateTime( 1982, 1, 29, 15, 46, 12, DateTimeKind.Utc )" ),
Member.Of( "Primitive", "int", PolymorphismTargets.None, null, @"default( int )", @"123" ),
Member.Of( "String", "string", PolymorphismTargets.None, null, @"null", @"""ABC""" ),
Member.Of( "Polymorphic", "FileSystemEntry", PolymorphismTargets.Member, null, @"null", @"new FileEntry { Name = ""file"", Size = 1 }", "FileEntry", "DirectoryEntry" ),
};
var collectionTypes =
new []
{
Member.Of( "ListStaticItem", "IList<string>", PolymorphismTargets.None, false, @"new List<string>()", @"new List<string>{ ""A"", ""B"" }" ),
Member.Of( "ListPolymorphicItem", "IList<FileSystemEntry>", PolymorphismTargets.Item, false, @"new List<FileSystemEntry>()", @"new List<FileSystemEntry>{ new FileEntry { Name = ""file"", Size = 1L }, new DirectoryEntry { Name = ""dir"", ChildCount = 1 } }", "FileEntry", "DirectoryEntry" ),
Member.Of( "ListObjectItem", "IList<object>", PolymorphismTargets.Item, false, @"new List<object>()", @"new List<object>{ new FileEntry { Name = ""file"", Size = 1L }, new DirectoryEntry { Name = ""dir"", ChildCount = 1 } }", "FileEntry", "DirectoryEntry" ),
Member.Of( "ListPolymorphicItself", "IList<string>", PolymorphismTargets.Member, false, @"new Collection<string>()", @"new Collection<string>{ ""A"", ""B"" }", "Collection<string>", "List<string>" ),
Member.Of( "ListObjectItself", "object", PolymorphismTargets.Member, true, @"new Collection<string>()", @"new Collection<string>{ ""A"", ""B"" }", "Collection<string>", "List<string>" ),
};
var dictionaryTypes =
new []
{
Member.Of( "DictStaticKeyAndStaticItem", "IDictionary<string, string>", PolymorphismTargets.None, false, @"new Dictionary<string, string>()", @"new Dictionary<string, string>{ { ""A"", ""A"" }, { ""B"", ""B"" } }" ),
Member.Of( "DictPolymorphicKeyAndStaticItem", "IDictionary<FileSystemEntry, string>", PolymorphismTargets.Key, false, @"new Dictionary<FileSystemEntry, string>()", @"new Dictionary<FileSystemEntry, string>{ { new FileEntry { Name = ""file"", Size = 1L }, ""A"" }, { new DirectoryEntry { Name = ""dir"", ChildCount = 1 }, ""B"" } }", "FileEntry", "DirectoryEntry" ),
Member.Of( "DictObjectKeyAndStaticItem", "IDictionary<object, string>", PolymorphismTargets.Key, false, @"new Dictionary<object, string>()", @"new Dictionary<object, string>{ { new FileEntry { Name = ""file"", Size = 1L }, ""A"" }, { new DirectoryEntry { Name = ""dir"", ChildCount = 1 }, ""B"" } }", "FileEntry", "DirectoryEntry" ),
Member.Of( "DictStaticKeyAndPolymorphicItem", "IDictionary<string, FileSystemEntry>", PolymorphismTargets.Item, false, @"new Dictionary<string, FileSystemEntry>()", @"new Dictionary<string, FileSystemEntry>{ { ""A"", new FileEntry { Name = ""file"", Size = 1L } }, { ""B"", new DirectoryEntry { Name = ""dir"", ChildCount = 1 } } }", "FileEntry", "DirectoryEntry" ),
Member.Of( "DictStaticKeyAndObjectItem", "IDictionary<string, object>", PolymorphismTargets.Item, false, @"new Dictionary<string, object>()", @"new Dictionary<string, object>{ { ""A"", new FileEntry { Name = ""file"", Size = 1L } }, { ""B"", new DirectoryEntry { Name = ""dir"", ChildCount = 1 } } }", "FileEntry", "DirectoryEntry" ),
Member.Of( "DictPolymorphicKeyAndItem", "IDictionary<FileSystemEntry, FileSystemEntry>", PolymorphismTargets.Key | PolymorphismTargets.Item, false, @"new Dictionary<FileSystemEntry, FileSystemEntry>()", @"new Dictionary<FileSystemEntry, FileSystemEntry>{ { new FileEntry { Name = ""A"", Size = 1L }, new FileEntry { Name = ""file"", Size = 1L } }, { new DirectoryEntry { Name = ""B"", ChildCount = 1 }, new DirectoryEntry { Name = ""dir"", ChildCount = 1 } } }", "FileEntry", "DirectoryEntry" ),
Member.Of( "DictObjectKeyAndItem", "IDictionary<object, object>", PolymorphismTargets.Key | PolymorphismTargets.Item, false, @"new Dictionary<object, object>()", @"new Dictionary<object, object>{ { new FileEntry { Name = ""A"", Size = 1L }, new FileEntry { Name = ""file"", Size = 1L } }, { new DirectoryEntry { Name = ""B"", ChildCount = 1 }, new DirectoryEntry { Name = ""dir"", ChildCount = 1 } } }", "FileEntry", "DirectoryEntry" ),
Member.Of( "DictPolymorphicItself", "IDictionary<string, string>", PolymorphismTargets.Member, false, @"new Dictionary<string, string>()", @"new Dictionary<string, string>{ { ""A"", ""A"" }, { ""B"", ""B"" } }", "Dictionary<string, string>", "SortedDictionary<string, string>" ),
Member.Of( "DictObjectItself", "object", PolymorphismTargets.Member, true, @"new Dictionary<string, string>()", @"new Dictionary<string, string>{ { ""A"", ""A"" }, { ""B"", ""B"" } }", "Dictionary<string, string>", "SortedDictionary<string, string>" ),
};
var tupleMembers =
new []
{
Member.Of( "Tuple1Static", "Tuple<string>",
false,
@"Tuple.Create( ""1"" )" ),
Member.Of( "Tuple1Polymorphic", "Tuple<FileSystemEntry>",
false,
@"Tuple.Create( new FileEntry { Name = ""1"", Size = 1 } as FileSystemEntry )",
new KeyValuePair<int, string[]>( 1, new []{ "FileEntry", "DirectoryEntry" } ) ),
Member.Of( "Tuple1ObjectItem", "Tuple<object>",
false,
@"Tuple.Create( new FileEntry { Name = ""1"", Size = 1 } as object )",
new KeyValuePair<int, string[]>( 1, new []{ "FileEntry", "DirectoryEntry" } ) ),
Member.Of( "Tuple1ObjectItself", "object",
true,
@"Tuple.Create( new FileEntry { Name = ""1"", Size = 1 } as FileEntry )" // Tuple items can be polymorphic only when tuple itself declared as Tuple.
), // Tuple items can be polymorphic only when tuple itself declared as Tuple.
Member.Of( "Tuple7AllStatic", "Tuple<string, string, string, string, string, string, string>",
false,
@"Tuple.Create( " + String.Join( ", ", Enumerable.Range( 1, 7 ).Select( i => String.Format( CultureInfo.InvariantCulture, @"""{0}""", i ) ) ) + " )" ),
Member.Of( "Tuple7FirstPolymorphic", "Tuple<FileSystemEntry, string, string, string, string, string, string>",
false,
@"Tuple.Create( new FileEntry { Name = ""1"", Size = 1 } as FileSystemEntry, " + String.Join( ", ", Enumerable.Range( 2, 6 ).Select( i => String.Format( CultureInfo.InvariantCulture, @"""{0}""", i ) ) ) + ")",
new KeyValuePair<int, string[]>( 1, new []{ "FileEntry", "DirectoryEntry" } ) ),
Member.Of( "Tuple7LastPolymorphic", "Tuple<string, string, string, string, string, string, FileSystemEntry>",
false,
@"Tuple.Create( " + String.Join( ", ", Enumerable.Range( 1, 6 ).Select( i => String.Format( CultureInfo.InvariantCulture, @"""{0}""", i ) ) ) + @", new FileEntry { Name = ""7"", Size = 7 } as FileSystemEntry )",
new KeyValuePair<int, string[]>( 7, new []{ "FileEntry", "DirectoryEntry" } ) ),
Member.Of( "Tuple7MidPolymorphic", "Tuple<string, string, string, FileSystemEntry, string, string, string>",
false,
@"Tuple.Create( " + String.Join( ", ", Enumerable.Range( 1, 3 ).Select( i => String.Format( CultureInfo.InvariantCulture, @"""{0}""", i ) ) ) + @", new FileEntry { Name = ""4"", Size = 4 } as FileSystemEntry, " + String.Join( ", ", Enumerable.Range( 5, 3 ).Select( i => String.Format( CultureInfo.InvariantCulture, @"""{0}""", i ) ) ) + ")",
new KeyValuePair<int, string[]>( 4, new []{ "FileEntry", "DirectoryEntry" } ) ),
Member.Of( "Tuple7AllPolymorphic", "Tuple<FileSystemEntry, FileSystemEntry, FileSystemEntry, FileSystemEntry, FileSystemEntry, FileSystemEntry, FileSystemEntry>",
false,
@"Tuple.Create( " + String.Join( ", ", Enumerable.Range( 1, 7 ).Select( i => String.Format( CultureInfo.InvariantCulture, @"new {0}Entry {{ Name = ""{1}"", {2} = {1} }} as FileSystemEntry", i % 2 == 1 ? "File" : "Directory", i, i % 2 == 1 ? "Size" : "ChildCount" ) ) ) + " )",
Enumerable.Range( 1, 7 ).Select( i => new KeyValuePair<int, string[]>( i, new []{ "FileEntry", "DirectoryEntry" } ) ).ToArray() ),
Member.Of( "Tuple8AllStatic", "Tuple<string, string, string, string, string, string, string, Tuple<string>>",
false,
@"Tuple.Create( " + String.Join( ", ", Enumerable.Range( 1, 7 ).Select( i => String.Format( CultureInfo.InvariantCulture, @"""{0}""", i ) ) ) + @", ""8"" )" ),
Member.Of( "Tuple8LastPolymorphic", "Tuple<string, string, string, string, string, string, string, Tuple<FileSystemEntry>>",
false,
@"Tuple.Create( " + String.Join( ", ", Enumerable.Range( 1, 7 ).Select( i => String.Format( CultureInfo.InvariantCulture, @"""{0}""", i ) ) ) + @", new FileEntry { Name = ""8"", Size = 8 } as FileSystemEntry )",
new KeyValuePair<int, string[]>( 8, new []{ "FileEntry", "DirectoryEntry" } ) ),
Member.Of( "Tuple8AllPolymorphic", "Tuple<FileSystemEntry, FileSystemEntry, FileSystemEntry, FileSystemEntry, FileSystemEntry, FileSystemEntry, FileSystemEntry, Tuple<FileSystemEntry>>",
false,
@"Tuple.Create( " + String.Join( ", ", Enumerable.Range( 1, 7 ).Select( i => String.Format( CultureInfo.InvariantCulture, @"new {0}Entry {{ Name = ""{1}"", {2} = {1} }} as FileSystemEntry", i % 2 == 1 ? "File" : "Directory", i, i % 2 == 1 ? "Size" : "ChildCount" ) ) ) + @", new DirectoryEntry { Name = ""8"", ChildCount = 8 } as FileSystemEntry )",
Enumerable.Range( 1, 8 ).Select( i => new KeyValuePair<int, string[]>( i, new []{ "FileEntry", "DirectoryEntry" } ) ).ToArray() ),
};
if ( generateTypes || generateMethods )
{
#>
#region -- Polymorphism --
<#+
}
foreach ( var attributeType in attributeTypes )
{
if ( generateTypes || generateMethods )
{
#>
#region ---- <#= attributeType.Name #> ----
#region ------ <#= attributeType.Name #>.NormalTypes ------
<#+
}
foreach ( var member in normalTypes )
{
foreach ( var kind in new [] { TypeKind.ReadWriteProperty, TypeKind.ReadWriteField, TypeKind.GetOnlyPropertyAndConstructor, TypeKind.PrivateSetterPropertyAndConstructor, TypeKind.ReadOnlyFieldAndConstructor } )
{
var typeName = GeneratePolymorphicTestType( attributeType.Name + "_Normal_" + member.Name + kind, kind, member, attributeType.AttributeFactory, false, generateTypes );
generatedSerializableTypeNames.Add( new TestTargetType( typeName, true ) );
GeneratePolymorphicTestMethods( typeName, kind, member, generateMethods, false );
var typeNameAsObject = GeneratePolymorphicTestType( attributeType.Name + "_" + member.Name + kind + "AsObject", kind, member, attributeType.AttributeFactory, true, generateTypes );
if ( !WillFail( member.Targets, kind ) )
{
generatedSerializableTypeNames.Add( new TestTargetType( typeNameAsObject, true ) );
}
GeneratePolymorphicTestMethods( typeNameAsObject, kind, member, generateMethods, true );
}
}
if ( generateTypes || generateMethods )
{
#>
#endregion ------ <#= attributeType.Name #>.NormalTypes ------
#region ------ <#= attributeType.Name #>.CollectionTypes ------
<#+
}
foreach( var member in collectionTypes )
{
// Note: combination of deserialization constructor and collection get/read only member is not valid.
foreach ( var kind in new [] { TypeKind.ReadWriteProperty, TypeKind.ReadWriteField, TypeKind.GetOnlyCollectionProperty, TypeKind.PrivateSetterCollectionProperty, TypeKind.ReadOnlyCollectionField } )
{
var typeName = GeneratePolymorphicTestType( attributeType.Name + "_List_" + member.Name + kind, kind, member, attributeType.AttributeFactory, member.AsObject.Value, generateTypes );
if ( !member.AsObject.Value || !WillFail( member.Targets, kind ) )
{
generatedSerializableTypeNames.Add( new TestTargetType( typeName, true ) );
}
GeneratePolymorphicTestMethods( typeName, kind, member, generateMethods, member.AsObject.Value );
}
}
if ( generateTypes || generateMethods )
{
#>
#endregion ------ <#= attributeType.Name #>.CollectionTypes ------
#region ------ <#= attributeType.Name #>.DictionaryTypes ------
<#+
}
foreach( var member in dictionaryTypes )
{
// Note: combination of deserialization constructor and collection get/read only member is not valid.
foreach ( var kind in new [] { TypeKind.ReadWriteProperty, TypeKind.ReadWriteField, TypeKind.GetOnlyCollectionProperty, TypeKind.PrivateSetterCollectionProperty, TypeKind.ReadOnlyCollectionField } )
{
var typeName = GeneratePolymorphicTestType( attributeType.Name + "_Dict_" + member.Name + kind, kind, member, attributeType.AttributeFactory, member.AsObject.Value, generateTypes );
if ( !member.AsObject.Value || !WillFail( member.Targets, kind ) )
{
generatedSerializableTypeNames.Add( new TestTargetType( typeName, true ) );
}
GeneratePolymorphicTestMethods( typeName, kind, member, generateMethods, member.AsObject.Value );
}
}
if ( generateTypes || generateMethods )
{
#>
#endregion ------ <#= attributeType.Name #>.DictionaryTypes ------
#if !NETFX_35 && !UNITY
#region ------ <#= attributeType.Name #>.TupleTypes ------
<#+
}
foreach ( var member in tupleMembers )
{
foreach ( var kind in new [] { TypeKind.ReadWriteProperty, TypeKind.ReadWriteField, TypeKind.GetOnlyPropertyAndConstructor, TypeKind.PrivateSetterPropertyAndConstructor, TypeKind.ReadOnlyFieldAndConstructor } )
{
var typeName = GeneratePolymorphicTestType( attributeType.Name + "_Tuple_" + member.Name + kind, kind, member, attributeType.AttributeFactory, member.AsObject.Value, generateTypes );
if ( !member.AsObject.Value || !WillFail( member.Targets, kind ) )
{
generatedSerializableTypeNames.Add( new TestTargetType( typeName, false ) );
}
GeneratePolymorphicTestMethods( typeName, kind, member, generateMethods, member.AsObject.Value );
}
}
if ( generateTypes || generateMethods )
{
#>
#endregion ------ <#= attributeType.Name #>.TupleTypes ------
#endif // #if !NETFX_35 && !UNITY
#endregion ---- <#= attributeType.Name #> ----
<#+
}
}
// Mixed Patterns
GeneratePolymorphicTestsForMixed( generateTypes, generateMethods, generatedSerializableTypeNames );
// Error Patterns
GenerateErrorPatterns( generateTypes, generateMethods, generatedSerializableTypeNames );
if ( generateTypes )
{
// Add static generated types
generatedSerializableTypeNames.Add( new TestTargetType( "IFileSystemEntry", true ) );
generatedSerializableTypeNames.Add( new TestTargetType( "AbstractFileSystemEntry", true ) );
generatedSerializableTypeNames.Add( new TestTargetType( "FileEntry", true ) );
generatedSerializableTypeNames.Add( new TestTargetType( "DirectoryEntry", true ) );
#>
public interface IFileSystemEntry { }
public abstract class AbstractFileSystemEntry : IFileSystemEntry { }
public abstract class FileSystemEntry : AbstractFileSystemEntry, IComparable<FileSystemEntry>
{
public string Name { get; set; }
public override bool Equals( object obj )
{
var other = obj as FileSystemEntry;
if ( Object.ReferenceEquals( other, null ) )
{
return false;
}
return this.Name == other.Name;
}
public override int GetHashCode()
{
return ( this.Name ?? String.Empty ).GetHashCode();
}
int IComparable<FileSystemEntry>.CompareTo( FileSystemEntry other )
{
return String.Compare( this.Name, other.Name, StringComparison.Ordinal );
}
}
public class FileEntry : FileSystemEntry
{
public long Size { get; set; }
public override bool Equals( object obj )
{
var other = obj as FileEntry;
if ( Object.ReferenceEquals( other, null ) )
{
return false;
}
return this.Name == other.Name && this.Size == other.Size;
}
public override int GetHashCode()
{
return ( this.Name ?? String.Empty ).GetHashCode() ^ this.Size.GetHashCode();
}
public override string ToString()
{
return "File(Name=" + this.Name + ", Size=" + this.Size + ")";
}
}
public class DirectoryEntry : FileSystemEntry
{
public int ChildCount { get; set; }
public override bool Equals( object obj )
{
var other = obj as DirectoryEntry;
if ( Object.ReferenceEquals( other, null ) )
{
return false;
}
return this.Name == other.Name && this.ChildCount == other.ChildCount;
}
public override int GetHashCode()
{
return ( this.Name ?? String.Empty ).GetHashCode() ^ this.ChildCount.GetHashCode();
}
public override string ToString()
{
return "Directory(Name=" + this.Name + ", ChildCount=" + this.ChildCount + ")";
}
}
<#+
}
if ( generateTypes || generateMethods )
{
if ( generateMethods )
{
#>
// Issue 137
[Test]
[Category( "PolymorphicSerialization" )]
public void TestGlobalNamespace()
{
var context = NewSerializationContext( PackerCompatibilityOptions.None );
var target = new HasGlobalNamespaceType { GlobalType = new TypeInGlobalNamespace { Value = "ABC" } };
var serializer = context.GetSerializer<HasGlobalNamespaceType>();
using ( var buffer = new MemoryStream() )
{
serializer.Pack( buffer, target );
buffer.Position = 0;
var result = serializer.Unpack( buffer );
Assert.That( result, Is.Not.Null );
Assert.That( result, Is.Not.SameAs( target ) );
Assert.That( result.GlobalType, Is.Not.Null );
Assert.That( result.GlobalType, Is.Not.SameAs( target.GlobalType ) );
Assert.That( result.GlobalType.Value, Is.EqualTo( target.GlobalType.Value ) );
}
}
<#+
}
#>
#endregion -- Polymorphism --
<#+
}
return generatedSerializableTypeNames;
}
// Types
private string GeneratePolymorphicTestType( string suffix, TypeKind kind, Member member, Func<Member, bool, IEnumerable<string>> attributeFactory, bool asObject, bool generateTypes )
{
var typeName = "PolymorphicMemberType" + suffix;
if ( generateTypes )
{
#>
public class <#= typeName #>
{
<#+
GenerateMember( kind, member, attributeFactory, asObject );
#>
<#+
GenerateConstructor( typeName, kind, asObject, member );
#>
}
<#+
}
return typeName;
}
// Types (private)
private void GenerateMember( TypeKind kind, Member member, Func<Member, bool, IEnumerable<string>> attributeFactory, bool asObject )
{
if ( ( kind & TypeKind.PropertyOrFieldMask ) == TypeKind.Field )
{
GenerateAttributes( member, attributeFactory, asObject );
#>
public <#= ( kind & TypeKind.IsReadOnly ) == TypeKind.IsReadOnly ? "readonly" : String.Empty #> <#= asObject ? "object" : member.Type #> <#= GetMemberNameGenerator( kind )( member.Name ) #>;
<#+
}
else
{
var backingField = GetMemberNameGenerator( TypeKind.Property )( member.Name );
#>
private <#= asObject ? "object" : member.Type #> <#= backingField #>;
<#+
GenerateAttributes( member, attributeFactory, asObject );
#>
public <#= asObject ? "object" : member.Type #> <#= GetMemberNameGenerator( TypeKind.Field )( member.Name ) #>
{
get { return this.<#= backingField #>; }
<#+
if ( ( kind & TypeKind.HasSetter ) == TypeKind.HasSetter )
{
#>
<#= ( kind & TypeKind.IsPublicSetter ) == TypeKind.IsPublicSetter ? String.Empty : "private" #> set { this.<#= backingField #> = value; }
<#+
}
#>
}
<#+
}
}
private void GenerateAttributes( Member member, Func<Member, bool, IEnumerable<string>> attributeFactory, bool asObject )
{
foreach ( var attribute in attributeFactory( member, asObject ) )
{
#>
<#= attribute #>
<#+
}
}
private void GenerateConstructor( string typeName, TypeKind kind, bool asObject, params Member[] members )
{
#>
<#= ( kind & TypeKind.HasConstructor ) == TypeKind.HasConstructor ? "public" : "private" #> <#= typeName #>( <#= String.Join( ", ", members.Select( member => ( asObject ? "object" : member.Type ) + " " + member.Name ) ) #> )
{
<#+
foreach ( var member in members )
{
#>
this.<#= GetMemberNameGenerator( kind )( member.Name ) #> = <#= member.Name #>;
<#+
}
#>
}
<#+
if ( ( kind & TypeKind.HasConstructor ) == 0 )
{
#>
public <#= typeName #>()
{
<#+
foreach ( var member in members )
{
#>
this.<#= GetMemberNameGenerator( kind )( member.Name ) #> = <#= member.EmptyValue #>;
<#+
}
#>
}
public static <#= typeName #> Initialize()
{
return new <#= typeName #>( <#= String.Join( ", ", members.Select( m => m.InitialValue ) ) #> );
}
<#+
}
else
{
#>
public <#= typeName #>() {}
<#+
}
}
private static bool WillFail( PolymorphismTargets targets, TypeKind kind )
{
return
targets != PolymorphismTargets.None
&& ( kind & TypeKind.HasConstructor ) == 0
&& (
( ( kind & TypeKind.HasSetter ) == 0 && ( kind & TypeKind.PropertyOrFieldMask ) == TypeKind.Property )
|| ( kind & TypeKind.IsReadOnly ) != 0
);
}
// Methods
private void GeneratePolymorphicTestMethods( string targetType, TypeKind kind, Member member, bool generateMethods, bool asObject )
{
if ( !generateMethods )
{
return;
}
var label = "Success";
var exceptionInCreation = default( string );
var shouldBeMpo = false;
if ( asObject )
{
switch ( member.Targets )
{
case PolymorphismTargets.None:
{
shouldBeMpo = true;
label = "AsMpo";
break;
}
default:
{
if ( WillFail( member.Targets, kind ) )
{
label = "Fail";
exceptionInCreation = "SerializationException";
}
break;
}
}
}
#>
[Test]
[Category( "PolymorphicSerialization" )]
public void Test<#= targetType + "_" + label #>()
{
var context = NewSerializationContext( PackerCompatibilityOptions.None );
<#+
if ( ( kind & TypeKind.HasConstructor ) == TypeKind.HasConstructor )
{
#>
var target = new <#= targetType #>( <#= member.InitialValue #> );
<#+
}
else
{
#>
var target = <#= targetType #>.Initialize();
<#+
}
if ( exceptionInCreation != null )
{
#>
Assert.Throws<#= "<" + exceptionInCreation + ">" #>( () => context.GetSerializer<#= "<" + targetType + ">" #>() );
<#+
}
else
{
#>
var serializer = context.GetSerializer<#= "<" + targetType + ">" #>();
using ( var buffer = new MemoryStream() )
{
serializer.Pack( buffer, target );
buffer.Position = 0;
var result = serializer.Unpack( buffer );
Assert.That( result, Is.Not.Null );
Assert.That( result, Is.Not.SameAs( target ) );
<#+
if ( shouldBeMpo )
{
#>
Assert.That( result.<#= member.Name #>, Is.InstanceOf( typeof( MessagePackObject ) ) );
<#+
}
else
{
if ( member.PolymorphicTupleItemTypes.Length > 0 && asObject )
{
#>
// Tuple items cannot be polymorphic when the member itself declared as Object.
<#+
}
else
{
#>
Assert.That( result.<#= member.Name #>, Is.EqualTo( target.<#= member.Name #> ) );
<#+
}
#>
Assert.That( result.<#= member.Name #>, Is.InstanceOf( target.<#= member.Name #>.GetType() ) );
<#+
}
#>
}
<#+
}
#>
}
<#+
}
// Mixed Pattern
private void GeneratePolymorphicTestsForMixed( bool generateTypes, bool generateMethods, ICollection<TestTargetType> generatedSerializableTypeNames )
{
/*
Tests only popular cases:
Normal : Plane, Runtime/Object, Known
List : Plain, Plain & Item-Known, Container-Known & Item-Runtime/Object,
Dictionary : Plain, Plaiun & Key-Plain & Item-Known, Container-Known & Key-Plain & Item-Runtime/Object,
Tuple : (Plane, Known, Runtime, Object)
*/
var members =
new []
{
new { Name = "NormalVanilla", Type = "string", InitialValue = @"""ABC""", Attributes = new string[ 0 ], IsTuple = false },
new { Name = "NormalRuntime", Type = "FileSystemEntry", InitialValue = @"new FileEntry { Name = ""File"", Size = 1 }", Attributes = new [] { "[MessagePackRuntimeType]" }, IsTuple = false },
new { Name = "NormalKnown", Type = "FileSystemEntry", InitialValue = @"new FileEntry { Name = ""File"", Size = 2 }", Attributes = new [] { "[MessagePackKnownType( \"1\", typeof( FileEntry ) )]", "[MessagePackKnownType( \"2\", typeof( DirectoryEntry ) )]" }, IsTuple = false },
new { Name = "ObjectRuntime", Type = "Object", InitialValue = @"new FileEntry { Name = ""File"", Size = 3 }", Attributes = new [] { "[MessagePackRuntimeType]" }, IsTuple = false },
new { Name = "ObjectRuntimeOmittedType", Type = "Object", InitialValue = @"new MsgPack.UnitTest.TestTypes.OmittedType { Value = ""ABC"" }", Attributes = new [] { "[MessagePackRuntimeType]" }, IsTuple = false },
new { Name = "ListVanilla", Type = "IList<string>", InitialValue = @"new List<string> { ""ABC"" }", Attributes = new string[ 0 ], IsTuple = false },
new { Name = "ListKnownItem", Type = "IList<FileSystemEntry>", InitialValue = @"new List<FileSystemEntry> { new FileEntry { Name = ""File"", Size = 1 } }", Attributes = new [] { "[MessagePackKnownCollectionItemType( \"1\", typeof( FileEntry ) )]", "[MessagePackKnownCollectionItemType( \"2\", typeof( DirectoryEntry ) )]" }, IsTuple = false },
new { Name = "ListKnwonContainerRuntimeItem", Type = "IList<FileSystemEntry>", InitialValue = @"new List<FileSystemEntry> { new FileEntry { Name = ""File"", Size = 2 } }", Attributes = new [] { "[MessagePackKnownType( \"1\", typeof( Collection<FileSystemEntry> ) )]", "[MessagePackKnownType( \"2\", typeof( List<FileSystemEntry> ) )]", "[MessagePackRuntimeCollectionItemType]" }, IsTuple = false },
new { Name = "ListObjectRuntimeItem", Type = "IList<object>", InitialValue = @"new List<object> { new FileEntry { Name = ""File"", Size = 3 } }", Attributes = new [] { "[MessagePackRuntimeCollectionItemType]" }, IsTuple = false },
new { Name = "DictionaryVanilla", Type = "IDictionary<string, string>", InitialValue = @"new Dictionary<string, string> { { ""Key"", ""ABC"" } }", Attributes = new string[ 0 ], IsTuple = false },
new { Name = "DictionaryKnownValue", Type = "IDictionary<string, FileSystemEntry>", InitialValue = @"new Dictionary<string, FileSystemEntry> { { ""Key"", new FileEntry { Name = ""File"", Size = 1 } } }", Attributes = new [] { "[MessagePackKnownCollectionItemType( \"1\", typeof( FileEntry ) )]", "[MessagePackKnownCollectionItemType( \"2\", typeof( DirectoryEntry ) )]" }, IsTuple = false },
new { Name = "DictionaryKnownContainerRuntimeValue", Type = "IDictionary<string, FileSystemEntry>", InitialValue = @"new Dictionary<string, FileSystemEntry> { { ""Key"", new FileEntry { Name = ""File"", Size = 2 } } }", Attributes = new [] { "[MessagePackKnownType( \"1\", typeof( SortedDictionary<string, FileSystemEntry> ) )]", "[MessagePackKnownType( \"2\", typeof( Dictionary<string, FileSystemEntry> ) )]", "[MessagePackRuntimeCollectionItemType]" }, IsTuple = false },
new { Name = "DictionaryObjectRuntimeValue", Type = "IDictionary<string, object>", InitialValue = @"new Dictionary<string, object> { { ""Key"", new FileEntry { Name = ""File"", Size = 3 } } }", Attributes = new [] { "[MessagePackRuntimeCollectionItemType]" }, IsTuple = false },
new { Name = "Tuple", Type = "Tuple<string, FileSystemEntry, FileSystemEntry, object>", InitialValue = @"Tuple.Create<string, FileSystemEntry, FileSystemEntry, object>( ""ABC"", new FileEntry { Name = ""File"", Size = 1 }, new FileEntry { Name = ""File"", Size = 3 }, new FileEntry { Name = ""File"", Size = 3 } )", Attributes = new [] { "[MessagePackKnownTupleItemType( 2, \"1\", typeof( FileEntry ) )]", "[MessagePackKnownTupleItemType( 2, \"2\", typeof( DirectoryEntry ) )]", "[MessagePackRuntimeTupleItemType( 3 )]","[MessagePackRuntimeTupleItemType( 4 )]" }, IsTuple = true },
};
const string typeName = "PolymorphicMemberTypeMixed";
// Add static generated types
generatedSerializableTypeNames.Add( new TestTargetType( typeName, true ) );
if ( generateTypes )
{
#>
public class <#= typeName #>
{
<#+
foreach ( var member in members )
{
if ( member.IsTuple )
{
#>
#if !NETFX_35 && !UNITY
<#+
}
foreach ( var attribute in member.Attributes )
{
#>
<#= attribute #>
<#+
}
#>
public <#= member.Type #> <#= member.Name #> { get; set; }
<#+
if ( member.IsTuple )
{
#>
#endif // !NETFX_35 && !UNITY
<#+
}
}
#>
public <#= typeName #>() { }
}
<#+
}
if ( generateMethods )
{
#>
[Test]
[Category( "PolymorphicSerialization" )]
public void Test<#= typeName #>_Success()
{
var context = NewSerializationContext( PackerCompatibilityOptions.None );
var target = new <#= typeName #>();
<#+
foreach ( var member in members )
{
if ( member.IsTuple )
{
#>
#if !NETFX_35 && !UNITY
<#+
}
#>
target.<#= member.Name #> = <#= member.InitialValue #>;
<#+
if ( member.IsTuple )
{
#>
#endif // !NETFX_35 && !UNITY
<#+
}
}
#>
var serializer = context.GetSerializer<#= "<" + typeName + ">" #>();
using ( var buffer = new MemoryStream() )
{
serializer.Pack( buffer, target );
buffer.Position = 0;
var result = serializer.Unpack( buffer );
Assert.That( result, Is.Not.Null );
Assert.That( result, Is.Not.SameAs( target ) );
<#+
foreach ( var member in members )
{
if ( member.IsTuple )
{
#>
#if !NETFX_35 && !UNITY
<#+
}
#>
Assert.That( result.<#= member.Name #>, Is.EqualTo( target.<#= member.Name #> ), "<#= member.Name #>" );
Assert.That( result.<#= member.Name #>, Is.InstanceOf( target.<#= member.Name #>.GetType() ), "<#= member.Name #>" );
<#+
if ( member.IsTuple )
{
#>
#endif // !NETFX_35 && !UNITY
<#+
}
}
#>
}
}
[Test]
[Category( "PolymorphicSerialization" )]
public void Test<#= typeName #>_Null_Success()
{
var context = NewSerializationContext( PackerCompatibilityOptions.None );
var target = new <#= typeName #>();
var serializer = context.GetSerializer<#= "<" + typeName + ">" #>();
using ( var buffer = new MemoryStream() )
{
serializer.Pack( buffer, target );
buffer.Position = 0;
var result = serializer.Unpack( buffer );
Assert.That( result, Is.Not.Null );
Assert.That( result, Is.Not.SameAs( target ) );
<#+
foreach ( var member in members )
{
if ( member.IsTuple )
{
#>
#if !NETFX_35 && !UNITY
<#+
}
#>
Assert.That( result.<#= member.Name #>, Is.Null );
<#+
if ( member.IsTuple )
{
#>
#endif // !NETFX_35 && !UNITY
<#+
}
}
#>
}
}
<#+
}
}
// Error Pattern
private void GenerateErrorPatterns( bool generateTypes, bool generateMethods, ICollection<TestTargetType> generatedSerializableTypeNames )
{
var abstractTypes =
new []
{
new { Name = "AbstractClass", Type = "AbstractFileSystemEntry", ShouldRegister = true, },
new { Name = "Interface", Type ="IFileSystemEntry", ShouldRegister = false, },
};
/*
Cartesian of
{Abstract Class | Interface } x { No Attributes | Knwon Attributes | Runtime Attribute } x { Member | Collection Container (Member) | Collection Items | Dictionary Keys}
*/
foreach ( var declarationType in abstractTypes )
{
foreach ( var pattern in
// Note: Collection concrete types must be default collection type.
new []
{
new { Name = "Member", Qualifier = String.Empty, TypeFormat = default( string ), InitializerFormat = "new FileEntry { Name = \"file\", Size = 1 }" },
new { Name = "ListItem", Qualifier = "CollectionItem", TypeFormat = "IList<{0}>", InitializerFormat = "new List<{0}>{{ new FileEntry {{ Name = \"file\", Size = 1 }} }}" },
new { Name = "DictKey", Qualifier = "DictionaryKey", TypeFormat = "IDictionary<{0}, string>", InitializerFormat = "new Dictionary<{0}, string> {{ {{ new FileEntry {{ Name = \"file\", Size = 1 }}, \"ABC\" }} }}" },
}
)
{
foreach ( var attribute in
new []
{
new { Name = "NoAttribute", Attribute = default( string ) },
new { Name = "KnownType", Attribute = String.Format( CultureInfo.InvariantCulture, "[MessagePackKnown{0}Type( \"1\", typeof( FileEntry ) )]", pattern.Qualifier ) },
new { Name = "RuntimeType", Attribute = String.Format( CultureInfo.InvariantCulture, "[MessagePackRuntime{0}Type]", pattern.Qualifier ) },
}
)
{
var typeName = declarationType.Name + pattern.Name + attribute.Name;
if ( attribute.Attribute != null )
{
// will success
generatedSerializableTypeNames.Add( new TestTargetType( typeName, true ) );
}
if ( generateTypes )
{
GenerateAbstractTypeTestClass( typeName, attribute.Attribute, pattern.TypeFormat == null ? declarationType.Type : String.Format( CultureInfo.InvariantCulture, pattern.TypeFormat, declarationType.Type ) );
}
if ( generateMethods )
{
GenerateAbstractTypeTestMethod(
typeName,
pattern.TypeFormat == null ? pattern.InitializerFormat : String.Format( CultureInfo.InvariantCulture, pattern.InitializerFormat, declarationType.Type ),
null,
null,
pattern.TypeFormat != null,
attribute.Attribute != null
);
}
}
}
}
// Cannot be created because open generic type.
// generatedSerializableTypeNames.Add( "EchoKeyedCollection<>" );
if ( generateTypes )
{
#>