File: BinaryFormatterTest.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (726 lines) | stat: -rw-r--r-- 18,351 bytes parent folder | download | duplicates (5)
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
//
// BinaryFormatterTest.cs - Unit tests for 
//	System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
//
// Author:
//      Sebastien Pouliot  <sebastien@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;

using NUnit.Framework;

namespace MonoTests.System.Runtime.Serialization.Formatters.Binary
{
	[Serializable]
	public class SerializationTest
	{
		private int integer;
		[NonSerialized]
		private bool boolean;

		public SerializationTest (bool b, int i)
		{
			boolean = b;
			integer = i;
		}

		public bool Boolean {
			get { return boolean; }
			set { boolean = value; }
		}

		public int Integer {
			get { return integer; }
			set { integer = value; }
		}
	}

	namespace NestedA
	{
		[Serializable]
		public class QualifiedFieldTest
		{
			int value = 0;

			public int ValueA {
				get { return value; }
				set { this.value = value; }
			}
		}
	}

	namespace NestedB
	{
		[Serializable]
		public class QualifiedFieldTest : NestedA.QualifiedFieldTest
		{
			int value = 0;

			public int ValueB {
				get { return value; }
				set { this.value = value; }
			}
		}
	}

	[Serializable]
	public class QualifiedFieldTest : NestedB.QualifiedFieldTest
	{
		int value = 0;

		public int Value {
			get { return value; }
			set { this.value = value; }
		}
	}

	class SurrogateSelector: ISurrogateSelector
	{
		public void ChainSelector (ISurrogateSelector selector)
		{
		}

		public ISurrogateSelector GetNextSelector ()
		{
			return null;
		}

		public ISerializationSurrogate GetSurrogate (Type type, StreamingContext context, out ISurrogateSelector selector)
		{
			selector = null;
			return null;
		}
	}

	[Serializable]
	sealed class ThisObjectReference : IObjectReference
	{
		internal static int Count;

		internal ThisObjectReference()
		{
		}

		public object GetRealObject(StreamingContext context)
		{
			Count++;
			return this;
		}
	}

	[Serializable]
	sealed class NewObjectReference : IObjectReference
	{
		internal static int Count;

		internal NewObjectReference()
		{
		}

		public object GetRealObject(StreamingContext context)
		{
			Count++;
			return new NewObjectReference();
		}
	}

	[Serializable]
	class Foo
	{
		private int privateFoo;
		protected int familyFoo;
		protected internal int familyANDAssemFoo;
		public int publicFoo;
		internal int assemblyFoo;

		public int PrivateFoo {
			get { return privateFoo; }
		}

		public int FamilyFoo {
			get { return familyFoo; }
		}

		public int FamilyANDAssemFoo {
			get { return familyANDAssemFoo; }
		}

		public int PublicFoo {
			get { return publicFoo; }
		}

		public int AssemblyFoo {
			get { return assemblyFoo; }
		}

		public virtual void Init ()
		{
			privateFoo = 1;
			familyFoo = 2;
			familyANDAssemFoo = 4;
			publicFoo = 8;
			assemblyFoo = 16;
		}
	}

	[Serializable]
	class Bar : Foo
	{
		private int privateBar;
		protected int familyBar;
		protected internal int familyANDAssemBar;
		public int publicBar;
		internal int assemblyBar;

		public int PrivateBar {
			get { return privateBar; }
		}

		public int FamilyBar {
			get { return familyBar; }
		}

		public int FamilyANDAssemBar {
			get { return familyANDAssemBar; }
		}

		public int PublicBar {
			get { return publicBar; }
		}

		public int AssemblyBar {
			get { return assemblyBar; }
		}

		public override void Init ()
		{
			privateBar = 1;
			familyBar = 2;
			familyANDAssemBar = 4;
			publicBar = 8;
			assemblyBar = 16;

			base.Init ();
		}
	}

	[Serializable]
	public class Comparable
	{
		public int Foo {
			get;
			set;
		}

		public override bool Equals (object obj)
		{
			var other = obj as Comparable;
			if (other == null)
				return false;
			return other.Foo == Foo;
		}

		public override int GetHashCode ()
		{
			return Foo;
		}
	}

	class Class
	{
		public string Name;

		public virtual Instance NewInstance()
		{
			return new Instance { Class = this };
		}
	}

	class Instance
	{
		public Class Class;
	}


	[Serializable]
	class ClassSerializationProxy : IObjectReference
	{
		string className;

		public ClassSerializationProxy (Class klass)
		{
			this.className = klass.Name;
		}

		public object GetRealObject(StreamingContext context)
		{
			return new Class { Name = className };
		}
	}

	[Serializable]
	class ObjectStreamClass : Class, IObjectReference, ISerializable
	{
		Class klass;

		public ObjectStreamClass (Class klass)
		{
			this.klass = klass;
		}

		public ObjectStreamClass(SerializationInfo info, StreamingContext context)
		{
			klass = (Class)info.GetValue("0", typeof(object));
		}

		public object GetRealObject (StreamingContext context)
		{
			return this;
		}

		public void GetObjectData (SerializationInfo info, StreamingContext context)
		{
			info.AddValue ("0", new ClassSerializationProxy (klass));
		}

		public override Instance NewInstance()
		{
			return klass.NewInstance();
		}
	}

	[Serializable]
	class DynamicProxy: IObjectReference, ISerializable
	{
		Instance obj;

		public DynamicProxy (Instance obj)
		{
			this.obj = obj;
		}

		public DynamicProxy (SerializationInfo info, StreamingContext context)
		{
			ObjectStreamClass osc = (ObjectStreamClass) info.GetValue("0", typeof(object));
			obj = osc.NewInstance();
		}

		public object GetRealObject (StreamingContext context)
		{
			return obj;
		}

		public void GetObjectData (SerializationInfo info, StreamingContext context)
		{
			info.AddValue ("0", new ObjectStreamClass (obj.Class));
		}
	}

	[TestFixture]
	public class BinaryFormatterTest
	{
		[Test]
		public void Constructor_Default ()
		{
			BinaryFormatter bf = new BinaryFormatter ();
			Assert.AreEqual (FormatterAssemblyStyle.Simple, bf.AssemblyFormat, "AssemblyFormat");
			Assert.IsNull (bf.Binder, "Binder");
			Assert.AreEqual (StreamingContextStates.All, bf.Context.State, "Context");
			Assert.AreEqual (TypeFilterLevel.Full, bf.FilterLevel, "FilterLevel");
			Assert.IsNull (bf.SurrogateSelector, "SurrogateSelector");
			Assert.AreEqual (FormatterTypeStyle.TypesAlways, bf.TypeFormat, "TypeFormat");
		}

		[Test]
		public void Constructor ()
		{
			SurrogateSelector ss = new SurrogateSelector ();
			BinaryFormatter bf = new BinaryFormatter (ss, new StreamingContext (StreamingContextStates.CrossMachine));
			Assert.AreEqual (FormatterAssemblyStyle.Simple, bf.AssemblyFormat, "AssemblyFormat");
			Assert.IsNull (bf.Binder, "Binder");
			Assert.AreEqual (StreamingContextStates.CrossMachine, bf.Context.State, "Context");
			Assert.AreEqual (TypeFilterLevel.Full, bf.FilterLevel, "FilterLevel");
			Assert.AreSame (ss, bf.SurrogateSelector, "SurrogateSelector");
			Assert.AreEqual (FormatterTypeStyle.TypesAlways, bf.TypeFormat, "TypeFormat");
		}

		[Test]
		public void Inheritance ()
		{
			MemoryStream ms = new MemoryStream ();
			BinaryFormatter bf = new BinaryFormatter ();

			Bar bar = new Bar ();
			bar.Init ();

			bf.Serialize (ms, bar);
			ms.Position = 0;

			Bar clone = (Bar) bf.Deserialize (ms);
			Assert.AreEqual (bar.PrivateBar, clone.PrivateBar, "#1");
			Assert.AreEqual (bar.FamilyBar, clone.FamilyBar, "#2");
			Assert.AreEqual (bar.FamilyANDAssemBar, clone.FamilyANDAssemBar, "#3");
			Assert.AreEqual (bar.PublicBar, clone.PublicBar, "#4");
			Assert.AreEqual (bar.AssemblyBar, clone.AssemblyBar, "#5");
			Assert.AreEqual (bar.PrivateFoo, clone.PrivateFoo, "#6");
			Assert.AreEqual (bar.FamilyFoo, clone.FamilyFoo, "#7");
			Assert.AreEqual (bar.FamilyANDAssemFoo, clone.FamilyANDAssemFoo, "#8");
			Assert.AreEqual (bar.PublicFoo, clone.PublicFoo, "#9");
			Assert.AreEqual (bar.AssemblyFoo, clone.AssemblyFoo, "#10");
		}

		[Test]
		public void SerializationRoundtrip ()
		{
			Stream s = GetSerializedStream ();
			BinaryFormatter bf = new BinaryFormatter ();
			SerializationTest clone = (SerializationTest) bf.Deserialize (s);
			Assert.AreEqual (Int32.MinValue, clone.Integer, "Integer");
			Assert.IsFalse (clone.Boolean, "Boolean");
		}

		[Test]
		public void SerializationUnsafeRoundtrip ()
		{
			Stream s = GetSerializedStream ();
			BinaryFormatter bf = new BinaryFormatter ();
			SerializationTest clone = (SerializationTest) bf.UnsafeDeserialize (s, null);
			Assert.AreEqual (Int32.MinValue, clone.Integer, "Integer");
			Assert.IsFalse (clone.Boolean, "Boolean");
		}
		
		[Test]
		[Category ("Remoting")]
		public void NestedObjectReference ()
		{
			MemoryStream ms = new MemoryStream();
			BinaryFormatter bf = new BinaryFormatter();

			bf.Serialize(ms, new ThisObjectReference());
			bf.Serialize(ms, new NewObjectReference());
			ms.Position = 0;
			Assert.AreEqual (0, ThisObjectReference.Count, "#1");

			bf.Deserialize(ms);
			Assert.AreEqual (2, ThisObjectReference.Count, "#2");
			Assert.AreEqual (0, NewObjectReference.Count, "#3");
			try {
				bf.Deserialize(ms);
			} catch (SerializationException) {
			}
			Assert.AreEqual (101, NewObjectReference.Count, "#4");
		}

		[Test]
		public void DateTimeArray ()
		{
			DateTime [] e = new DateTime [6];
			string [] names = new string [6];

			names [0] = "Today";  e [0] = DateTime.Today;
			names [1] = "Min";    e [1] = DateTime.MinValue;
			names [2] = "Max";    e [2] = DateTime.MaxValue;
			names [3] = "BiCent"; e [3] = new DateTime (1976, 07, 04);
			names [4] = "Now";    e [4] = DateTime.Now;
			names [5] = "UtcNow"; e [5] = DateTime.UtcNow;

			BinaryFormatter bf = new BinaryFormatter ();
			MemoryStream ms = new MemoryStream ();

			bf.Serialize (ms, e);

			ms.Position = 0;
			DateTime [] a = (DateTime []) bf.Deserialize (ms);

			Assert.AreEqual (e.Length, a.Length);
			for (int i = 0; i < e.Length; ++i)
				Assert.AreEqual (e [i], a [i], names [i]);
		}

		[Test]
		public void GenericArray ()
		{
			Comparable [] a = new Comparable [1];
			a [0] = new Comparable ();

			BinaryFormatter bf = new BinaryFormatter ();
			MemoryStream ms = new MemoryStream ();

			bf.Serialize (ms, a);

			ms.Position = 0;
			Comparable [] b = (Comparable []) bf.Deserialize (ms);

			Assert.AreEqual (a.Length, b.Length, "#1");
			Assert.AreEqual (a [0], b [0], "#2");
		}

		public Stream GetSerializedStream ()
		{
			SerializationTest test = new SerializationTest (true, Int32.MinValue);
			BinaryFormatter bf = new BinaryFormatter ();
			MemoryStream ms = new MemoryStream ();
			bf.Serialize (ms, test);
			ms.Position = 0;
			return ms;
		}

		[Test]
		public void QualifiedField()
		{
			QualifiedFieldTest a = new QualifiedFieldTest ();
			a.ValueA = 1;
			a.ValueB = 2;
			a.Value = 3;
			Stream ms = new MemoryStream ();
			BinaryFormatter bf = new BinaryFormatter ();
			bf.Serialize(ms, a);
			ms.Position = 0;
			QualifiedFieldTest b = (QualifiedFieldTest)bf.Deserialize (ms);
			Assert.AreEqual (a.ValueA, b.ValueA, "#1");
			Assert.AreEqual (a.ValueB, b.ValueB, "#2");
			Assert.AreEqual (a.Value, b.Value, "#3");
		}

		[Test]
		public void SerializationBindToName ()
		{
			BinaryFormatter bf = new BinaryFormatter ();
			bf.AssemblyFormat = FormatterAssemblyStyle.Full;
			bf.Binder = new SimpleSerializationBinder ();
			MemoryStream ms = new MemoryStream ();

			SimpleSerializableObject o = new SimpleSerializableObject ();
			o.Name = "MonoObject";
			o.Id = 666;

			bf.Serialize (ms, o);
			ms.Position = 0;

			o = (SimpleSerializableObject)bf.Deserialize (ms);
			Assert.AreEqual ("MonoObject", o.Name);
			Assert.AreEqual (666, o.Id);
		}

		class SimpleSerializationBinder : SerializationBinder
		{
			public override Type BindToType (string assemblyName, string typeName)
			{
				// We *should* be getting a SimpleSerializableObject2 instance
				// Otherwise it means we are not getting called our BindToName method.
				if (!typeName.EndsWith ("SimpleSerializableObject2"))
					Assert.Fail ("#BindToType-TypeName");

				// We are also supposed to be getting a 9.9.9.9 version here,
				// and if we get a different version, it likely means BindToName was called.
				AssemblyName aname = Assembly.GetExecutingAssembly ().GetName ();
				aname.Version = new Version (9, 9, 9, 9);
				if (aname.ToString () != assemblyName)
					Assert.Fail ("#BindToType-AssemblyName");

				// No need to call Type.GetType
				return typeof (SimpleSerializableObject);
			}

			public override void BindToName (Type serializedType, out string assemblyName, out string typeName)
			{
				AssemblyName aname = Assembly.GetExecutingAssembly ().GetName ();
				aname.Version = new Version (9, 9, 9, 9);

				// Serialize mapping to this same assembly with 9.9.9.9 version
				// and a different type name.
				assemblyName = aname.ToString ();
				typeName = serializedType.FullName.Replace ("SimpleSerializableObject", "SimpleSerializableObject2");
			}
		}

		[Serializable]
		class SimpleSerializableObject
		{
			public string Name { get; set; }
			public int Id { get; set; }
		}

		[Test]
		public void SerializationBindToName2 ()
		{
			BinaryFormatter bf = new BinaryFormatter ();
			bf.AssemblyFormat = FormatterAssemblyStyle.Full;
			bf.Binder = new SimpleSerializationBinder2 ();
			MemoryStream ms = new MemoryStream ();

			SimpleISerializableObject o = new SimpleISerializableObject ();
			o.Name = "MonoObject";
			o.Id = 666;

			bf.Serialize (ms, o);
			ms.Position = 0;

			o = (SimpleISerializableObject)bf.Deserialize (ms);
			Assert.AreEqual ("MonoObject", o.Name);
			Assert.AreEqual (666, o.Id);

			ms.Close ();
		}

		[Test]
		[Category ("Remoting")]
		public void NestedObjectReferences ()
		{
			MemoryStream ms = new MemoryStream ();

			var cls = new Class { Name = "MyClass" };
			var ob = cls.NewInstance ();

			BinaryFormatter bf = new BinaryFormatter();
			bf.Serialize (ms, new DynamicProxy (ob));

			ms.Position = 0;

			Instance ins = (Instance) bf.Deserialize (ms);
			Assert.AreEqual ("MyClass", ins.Class.Name);
		}

		class SimpleSerializationBinder2 : SerializationBinder
		{
			public override void BindToName (Type serializedType, out string assemblyName, out string typeName)
			{
				AssemblyName aname = Assembly.GetExecutingAssembly ().GetName ();
				aname.Version = new Version (9, 9, 9, 9);

				// Serialize mapping to this same assembly with 9.9.9.9 version
				// and a different type name.
				assemblyName = aname.ToString ();
				typeName = serializedType.FullName.Replace ("SimpleISerializableObject", "SimpleISerializableObject2");
			}

			public override Type BindToType (string assemblyName, string typeName)
			{
				// We *should* be getting a SimpleISerializableObject2 instance
				if (!typeName.EndsWith ("SimpleISerializableObject2"))
					Assert.Fail ("#BindToType-TypeName");

				// We are also supposed to be getting a 9.9.9.9 version here,
				// and if we get a different version, it likely means BindToName was called.
				AssemblyName aname = Assembly.GetExecutingAssembly ().GetName ();
				aname.Version = new Version (9, 9, 9, 9);
				if (aname.ToString () != assemblyName)
					Assert.Fail ("#BindToType-AssemblyName");

				return typeof (SimpleISerializableObject);
			}
		}

		[Serializable]
		class SimpleISerializableObject : ISerializable
		{
			public string Name { get; set; }
			public int Id { get; set; }

			public SimpleISerializableObject ()
			{
			}

			protected SimpleISerializableObject (SerializationInfo info, StreamingContext context)
			{
				Name = info.GetString ("Name");
				Id = info.GetInt32 ("Id");
			}

			public void GetObjectData (SerializationInfo info, StreamingContext context)
			{
				info.AddValue ("Name", Name);
				info.AddValue ("Id", Id);
			}
		}

		[Serializable]
		public class OtherClass
		{
		}

		[Serializable]
		public class BaseClass
		{
			public OtherClass Other { get; set; }
		}

		public class CustomSerBinder: SerializationBinder
		{
			public override void BindToName (Type serializedType, out string assemblyName, out string typeName)
			{
				assemblyName = null;
				if (serializedType == typeof (BaseClass))
					typeName = "base";
				else if (serializedType == typeof (OtherClass))
					typeName = "other";
				else
					throw new ArgumentException ("Unknown type", "serializedType");
			}

			public override Type BindToType (string assemblyName, string typeName)
			{
				switch (typeName) {
				case "base":
					return typeof (BaseClass);
				case "other":
					return typeof (OtherClass);
				default:
					throw new ArgumentException ("Unknown type name", "typeName");
				}
			}
		}

		[Test]
		public void BinderShouldBeUsedForProperties ()
		{
			using (var serStream = new MemoryStream ()) {
				var binder = new CustomSerBinder ();

				// serialize
				var original = new BaseClass () {
					Other = new OtherClass ()
				};
				var formatter = new BinaryFormatter ();
				formatter.Binder = binder;
				formatter.Serialize (serStream, original);

				// deserialize, making sure we're using a new formatter, just to be thorough
				formatter = new BinaryFormatter ();
				formatter.Binder = binder;
				serStream.Seek (0, SeekOrigin.Begin);
				var deserialized = formatter.Deserialize (serStream);

				Assert.AreEqual (original.GetType (), deserialized.GetType ());
				Assert.AreEqual (original.Other.GetType (), ((BaseClass)deserialized).Other.GetType ());
			}
		}
	}
}