Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Tests/HeuristicLab.Persistence-3.3/UseCases.cs @ 14821

Last change on this file since 14821 was 9363, checked in by spimming, 12 years ago

#1888:

  • Merged revisions from trunk
File size: 46.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections;
24using System.Collections.Generic;
25using System.Drawing;
26using System.IO;
27using System.Linq;
28using System.Reflection;
29using System.Text;
30using System.Text.RegularExpressions;
31using System.Threading.Tasks;
32using HeuristicLab.Algorithms.GeneticAlgorithm;
33using HeuristicLab.Persistence.Auxiliary;
34using HeuristicLab.Persistence.Core;
35using HeuristicLab.Persistence.Core.Tokens;
36using HeuristicLab.Persistence.Default.CompositeSerializers;
37using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
38using HeuristicLab.Persistence.Default.DebugString;
39using HeuristicLab.Persistence.Default.Xml;
40using HeuristicLab.Persistence.Default.Xml.Primitive;
41using HeuristicLab.Persistence.Interfaces;
42using HeuristicLab_33.Tests;
43using Microsoft.VisualStudio.TestTools.UnitTesting;
44
45namespace HeuristicLab.Persistence_33.Tests {
46
47  [StorableClass]
48  public class NumberTest {
49    [Storable]
50    private bool _bool = true;
51    [Storable]
52    private byte _byte = 0xFF;
53    [Storable]
54    private sbyte _sbyte = 0xF;
55    [Storable]
56    private short _short = -123;
57    [Storable]
58    private ushort _ushort = 123;
59    [Storable]
60    private int _int = -123;
61    [Storable]
62    private uint _uint = 123;
63    [Storable]
64    private long _long = 123456;
65    [Storable]
66    private ulong _ulong = 123456;
67    public override bool Equals(object obj) {
68      NumberTest nt = obj as NumberTest;
69      if (nt == null)
70        throw new NotSupportedException();
71      return
72        nt._bool == _bool &&
73        nt._byte == _byte &&
74        nt._sbyte == _sbyte &&
75        nt._short == _short &&
76        nt._ushort == _ushort &&
77        nt._int == _int &&
78        nt._uint == _uint &&
79        nt._long == _long &&
80        nt._ulong == _ulong;
81    }
82    public override int GetHashCode() {
83      return
84        _bool.GetHashCode() ^
85        _byte.GetHashCode() ^
86        _sbyte.GetHashCode() ^
87        _short.GetHashCode() ^
88        _short.GetHashCode() ^
89        _int.GetHashCode() ^
90        _uint.GetHashCode() ^
91        _long.GetHashCode() ^
92        _ulong.GetHashCode();
93    }
94  }
95
96  [StorableClass]
97  public class NonDefaultConstructorClass {
98    [Storable]
99    int value;
100    public NonDefaultConstructorClass(int value) {
101      this.value = value;
102    }
103  }
104
105  [StorableClass]
106  public class IntWrapper {
107
108    [Storable]
109    public int Value;
110
111    private IntWrapper() { }
112
113    public IntWrapper(int value) {
114      this.Value = value;
115    }
116
117    public override bool Equals(object obj) {
118      if (obj as IntWrapper == null)
119        return false;
120      return Value.Equals(((IntWrapper)obj).Value);
121    }
122    public override int GetHashCode() {
123      return Value.GetHashCode();
124    }
125
126  }
127
128  [StorableClass]
129  public class PrimitivesTest : NumberTest {
130    [Storable]
131    private char c = 'e';
132    [Storable]
133    private long[,] _long_array =
134      new long[,] { { 123, 456, }, { 789, 123 } };
135    [Storable]
136    public List<int> list = new List<int> { 1, 2, 3, 4, 5 };
137    [Storable]
138    private object o = new object();
139    public override bool Equals(object obj) {
140      PrimitivesTest pt = obj as PrimitivesTest;
141      if (pt == null)
142        throw new NotSupportedException();
143      return base.Equals(obj) &&
144        c == pt.c &&
145        _long_array == pt._long_array &&
146        list == pt.list &&
147        o == pt.o;
148    }
149    public override int GetHashCode() {
150      return base.GetHashCode() ^
151        c.GetHashCode() ^
152        _long_array.GetHashCode() ^
153        list.GetHashCode() ^
154        o.GetHashCode();
155    }
156  }
157
158  public enum TestEnum { va1, va2, va3, va8 } ;
159
160  [StorableClass]
161  public class RootBase {
162    [Storable]
163    private string baseString = "   Serial  ";
164    [Storable]
165    public TestEnum myEnum = TestEnum.va3;
166    public override bool Equals(object obj) {
167      RootBase rb = obj as RootBase;
168      if (rb == null)
169        throw new NotSupportedException();
170      return baseString == rb.baseString &&
171        myEnum == rb.myEnum;
172    }
173    public override int GetHashCode() {
174      return baseString.GetHashCode() ^
175        myEnum.GetHashCode();
176    }
177  }
178
179  [StorableClass]
180  public class Root : RootBase {
181    [Storable]
182    public Stack<int> intStack = new Stack<int>();
183    [Storable]
184    public int[] i = new[] { 3, 4, 5, 6 };
185    [Storable(Name = "Test String")]
186    public string s;
187    [Storable]
188    public ArrayList intArray = new ArrayList(new[] { 1, 2, 3 });
189    [Storable]
190    public List<int> intList = new List<int>(new[] { 321, 312, 321 });
191    [Storable]
192    public Custom c;
193    [Storable]
194    public List<Root> selfReferences;
195    [Storable]
196    public double[,] multiDimArray = new double[,] { { 1, 2, 3 }, { 3, 4, 5 } };
197    [Storable]
198    public bool boolean = true;
199    [Storable]
200    public DateTime dateTime;
201    [Storable]
202    public KeyValuePair<string, int> kvp = new KeyValuePair<string, int>("Serial", 123);
203    [Storable]
204    public Dictionary<string, int> dict = new Dictionary<string, int>();
205    [Storable(DefaultValue = "default")]
206    public string uninitialized;
207  }
208
209  public enum SimpleEnum { one, two, three }
210  public enum ComplexEnum { one = 1, two = 2, three = 3 }
211  [FlagsAttribute]
212  public enum TrickyEnum { zero = 0, one = 1, two = 2 }
213
214  [StorableClass]
215  public class EnumTest {
216    [Storable]
217    public SimpleEnum simpleEnum = SimpleEnum.one;
218    [Storable]
219    public ComplexEnum complexEnum = (ComplexEnum)2;
220    [Storable]
221    public TrickyEnum trickyEnum = (TrickyEnum)15;
222  }
223
224  [StorableClass]
225  public class Custom {
226    [Storable]
227    public int i;
228    [Storable]
229    public Root r;
230    [Storable]
231    public string name = "<![CDATA[<![CDATA[Serial]]>]]>";
232  }
233
234  [StorableClass]
235  public class Manager {
236
237    public DateTime lastLoadTime;
238    [Storable]
239    private DateTime lastLoadTimePersistence {
240      get { return lastLoadTime; }
241      set { lastLoadTime = DateTime.Now; }
242    }
243    [Storable]
244    public double? dbl;
245  }
246
247  [StorableClass]
248  public class C {
249    [Storable]
250    public C[][] allCs;
251    [Storable]
252    public KeyValuePair<List<C>, C> kvpList;
253  }
254
255  public class NonSerializable {
256    int x = 0;
257    public override bool Equals(object obj) {
258      NonSerializable ns = obj as NonSerializable;
259      if (ns == null)
260        throw new NotSupportedException();
261      return ns.x == x;
262    }
263    public override int GetHashCode() {
264      return x.GetHashCode();
265    }
266  }
267
268
269  [TestClass]
270  public class UseCases {
271
272    private string tempFile;
273
274    [TestInitialize()]
275    public void CreateTempFile() {
276      tempFile = Path.GetTempFileName();
277    }
278
279    [TestCleanup()]
280    public void ClearTempFile() {
281      StreamReader reader = new StreamReader(tempFile);
282      string s = reader.ReadToEnd();
283      reader.Close();
284      File.Delete(tempFile);
285    }
286
287    [TestMethod]
288    public void ComplexStorable() {
289      Root r = InitializeComplexStorable();
290      XmlGenerator.Serialize(r, tempFile);
291      Root newR = (Root)XmlParser.Deserialize(tempFile);
292      CompareComplexStorables(r, newR);
293    }
294
295    [TestMethod]
296    public void ComplexEasyStorable() {
297      Root r = InitializeComplexStorable();
298      ReadableXmlGenerator.Serialize(r, tempFile);
299      using (var reader = new StreamReader(tempFile)) {
300        string text = reader.ReadToEnd();
301        Assert.IsTrue(text.StartsWith("<Root"));
302      }
303    }
304
305    private static void CompareComplexStorables(Root r, Root newR) {
306      Assert.AreEqual(
307        DebugStringGenerator.Serialize(r),
308        DebugStringGenerator.Serialize(newR));
309      Assert.AreSame(newR, newR.selfReferences[0]);
310      Assert.AreNotSame(r, newR);
311      Assert.AreEqual(r.myEnum, TestEnum.va1);
312      Assert.AreEqual(r.i[0], 7);
313      Assert.AreEqual(r.i[1], 5);
314      Assert.AreEqual(r.i[2], 6);
315      Assert.AreEqual(r.s, "new value");
316      Assert.AreEqual(r.intArray[0], 3);
317      Assert.AreEqual(r.intArray[1], 2);
318      Assert.AreEqual(r.intArray[2], 1);
319      Assert.AreEqual(r.intList[0], 9);
320      Assert.AreEqual(r.intList[1], 8);
321      Assert.AreEqual(r.intList[2], 7);
322      Assert.AreEqual(r.multiDimArray[0, 0], 5);
323      Assert.AreEqual(r.multiDimArray[0, 1], 4);
324      Assert.AreEqual(r.multiDimArray[0, 2], 3);
325      Assert.AreEqual(r.multiDimArray[1, 0], 1);
326      Assert.AreEqual(r.multiDimArray[1, 1], 4);
327      Assert.AreEqual(r.multiDimArray[1, 2], 6);
328      Assert.IsFalse(r.boolean);
329      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
330      Assert.AreEqual(r.kvp.Key, "string key");
331      Assert.AreEqual(r.kvp.Value, 321);
332      Assert.IsNull(r.uninitialized);
333      Assert.AreEqual(newR.myEnum, TestEnum.va1);
334      Assert.AreEqual(newR.i[0], 7);
335      Assert.AreEqual(newR.i[1], 5);
336      Assert.AreEqual(newR.i[2], 6);
337      Assert.AreEqual(newR.s, "new value");
338      Assert.AreEqual(newR.intArray[0], 3);
339      Assert.AreEqual(newR.intArray[1], 2);
340      Assert.AreEqual(newR.intArray[2], 1);
341      Assert.AreEqual(newR.intList[0], 9);
342      Assert.AreEqual(newR.intList[1], 8);
343      Assert.AreEqual(newR.intList[2], 7);
344      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
345      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
346      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
347      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
348      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
349      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
350      Assert.AreEqual(newR.intStack.Pop(), 3);
351      Assert.AreEqual(newR.intStack.Pop(), 2);
352      Assert.AreEqual(newR.intStack.Pop(), 1);
353      Assert.IsFalse(newR.boolean);
354      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
355      Assert.AreEqual(newR.kvp.Key, "string key");
356      Assert.AreEqual(newR.kvp.Value, 321);
357      Assert.IsNull(newR.uninitialized);
358    }
359
360    private static Root InitializeComplexStorable() {
361      Root r = new Root();
362      r.intStack.Push(1);
363      r.intStack.Push(2);
364      r.intStack.Push(3);
365      r.selfReferences = new List<Root> { r, r };
366      r.c = new Custom { r = r };
367      r.dict.Add("one", 1);
368      r.dict.Add("two", 2);
369      r.dict.Add("three", 3);
370      r.myEnum = TestEnum.va1;
371      r.i = new[] { 7, 5, 6 };
372      r.s = "new value";
373      r.intArray = new ArrayList { 3, 2, 1 };
374      r.intList = new List<int> { 9, 8, 7 };
375      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
376      r.boolean = false;
377      r.dateTime = DateTime.Now;
378      r.kvp = new KeyValuePair<string, int>("string key", 321);
379      r.uninitialized = null;
380
381      return r;
382    }
383
384    [TestMethod]
385    public void SelfReferences() {
386      C c = new C();
387      C[][] cs = new C[2][];
388      cs[0] = new C[] { c };
389      cs[1] = new C[] { c };
390      c.allCs = cs;
391      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
392      XmlGenerator.Serialize(cs, tempFile);
393      object o = XmlParser.Deserialize(tempFile);
394      Assert.AreEqual(
395        DebugStringGenerator.Serialize(cs),
396        DebugStringGenerator.Serialize(o));
397      Assert.AreSame(c, c.allCs[0][0]);
398      Assert.AreSame(c, c.allCs[1][0]);
399      Assert.AreSame(c, c.kvpList.Key[0]);
400      Assert.AreSame(c, c.kvpList.Value);
401      C[][] newCs = (C[][])o;
402      C newC = newCs[0][0];
403      Assert.AreSame(newC, newC.allCs[0][0]);
404      Assert.AreSame(newC, newC.allCs[1][0]);
405      Assert.AreSame(newC, newC.kvpList.Key[0]);
406      Assert.AreSame(newC, newC.kvpList.Value);
407    }
408
409    [TestMethod]
410    public void ArrayCreation() {
411      ArrayList[] arrayListArray = new ArrayList[4];
412      arrayListArray[0] = new ArrayList();
413      arrayListArray[0].Add(arrayListArray);
414      arrayListArray[0].Add(arrayListArray);
415      arrayListArray[1] = new ArrayList();
416      arrayListArray[1].Add(arrayListArray);
417      arrayListArray[2] = new ArrayList();
418      arrayListArray[2].Add(arrayListArray);
419      arrayListArray[2].Add(arrayListArray);
420      Array a = Array.CreateInstance(
421                              typeof(object),
422                              new[] { 1, 2 }, new[] { 3, 4 });
423      arrayListArray[2].Add(a);
424      XmlGenerator.Serialize(arrayListArray, tempFile);
425      object o = XmlParser.Deserialize(tempFile);
426      Assert.AreEqual(
427        DebugStringGenerator.Serialize(arrayListArray),
428        DebugStringGenerator.Serialize(o));
429      ArrayList[] newArray = (ArrayList[])o;
430      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
431      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
432      Assert.AreSame(newArray, newArray[0][0]);
433      Assert.AreSame(newArray, newArray[2][1]);
434    }
435
436    [TestMethod]
437    public void CustomSerializationProperty() {
438      Manager m = new Manager();
439      XmlGenerator.Serialize(m, tempFile);
440      Manager newM = (Manager)XmlParser.Deserialize(tempFile);
441      Assert.AreNotEqual(
442        DebugStringGenerator.Serialize(m),
443        DebugStringGenerator.Serialize(newM));
444      Assert.AreEqual(m.dbl, newM.dbl);
445      Assert.AreEqual(m.lastLoadTime, new DateTime());
446      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
447      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
448    }
449
450    [TestMethod]
451    public void Primitives() {
452      PrimitivesTest sdt = new PrimitivesTest();
453      XmlGenerator.Serialize(sdt, tempFile);
454      object o = XmlParser.Deserialize(tempFile);
455      Assert.AreEqual(
456        DebugStringGenerator.Serialize(sdt),
457        DebugStringGenerator.Serialize(o));
458    }
459
460    [TestMethod]
461    public void MultiDimensionalArray() {
462      string[,] mDimString = new string[,] {
463        {"ora", "et", "labora"},
464        {"Beten", "und", "Arbeiten"}
465      };
466      XmlGenerator.Serialize(mDimString, tempFile);
467      object o = XmlParser.Deserialize(tempFile);
468      Assert.AreEqual(
469        DebugStringGenerator.Serialize(mDimString),
470        DebugStringGenerator.Serialize(o));
471    }
472
473    [StorableClass]
474    public class NestedType {
475      [Storable]
476      private string value = "value";
477      public override bool Equals(object obj) {
478        NestedType nt = obj as NestedType;
479        if (nt == null)
480          throw new NotSupportedException();
481        return nt.value == value;
482      }
483      public override int GetHashCode() {
484        return value.GetHashCode();
485      }
486    }
487
488    [TestMethod]
489    public void NestedTypeTest() {
490      NestedType t = new NestedType();
491      XmlGenerator.Serialize(t, tempFile);
492      object o = XmlParser.Deserialize(tempFile);
493      Assert.AreEqual(
494        DebugStringGenerator.Serialize(t),
495        DebugStringGenerator.Serialize(o));
496      Assert.IsTrue(t.Equals(o));
497    }
498
499
500    [TestMethod]
501    public void SimpleArray() {
502      string[] strings = { "ora", "et", "labora" };
503      XmlGenerator.Serialize(strings, tempFile);
504      object o = XmlParser.Deserialize(tempFile);
505      Assert.AreEqual(
506        DebugStringGenerator.Serialize(strings),
507        DebugStringGenerator.Serialize(o));
508    }
509
510    [TestMethod]
511    public void PrimitiveRoot() {
512      XmlGenerator.Serialize(12.3f, tempFile);
513      object o = XmlParser.Deserialize(tempFile);
514      Assert.AreEqual(
515        DebugStringGenerator.Serialize(12.3f),
516        DebugStringGenerator.Serialize(o));
517    }
518
519    private string formatFullMemberName(MemberInfo mi) {
520      return new StringBuilder()
521        .Append(mi.DeclaringType.Assembly.GetName().Name)
522        .Append(": ")
523        .Append(mi.DeclaringType.Namespace)
524        .Append('.')
525        .Append(mi.DeclaringType.Name)
526        .Append('.')
527        .Append(mi.Name).ToString();
528    }
529
530    public void CodingConventions() {
531      List<string> lowerCaseMethodNames = new List<string>();
532      List<string> lowerCaseProperties = new List<string>();
533      List<string> lowerCaseFields = new List<string>();
534      foreach (Assembly a in PluginLoader.Assemblies) {
535        if (!a.GetName().Name.StartsWith("HeuristicLab"))
536          continue;
537        foreach (Type t in a.GetTypes()) {
538          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
539            if (mi.DeclaringType.Name.StartsWith("<>"))
540              continue;
541            if (char.IsLower(mi.Name[0])) {
542              if (mi.MemberType == MemberTypes.Field)
543                lowerCaseFields.Add(formatFullMemberName(mi));
544              if (mi.MemberType == MemberTypes.Property)
545                lowerCaseProperties.Add(formatFullMemberName(mi));
546              if (mi.MemberType == MemberTypes.Method &&
547                !mi.Name.StartsWith("get_") &&
548                !mi.Name.StartsWith("set_") &&
549                !mi.Name.StartsWith("add_") &&
550                !mi.Name.StartsWith("remove_") &&
551                !mi.Name.StartsWith("op_"))
552                lowerCaseMethodNames.Add(formatFullMemberName(mi));
553            }
554          }
555        }
556      }
557      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
558      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
559      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
560    }
561
562    [TestMethod]
563    public void Number2StringDecomposer() {
564      NumberTest sdt = new NumberTest();
565      XmlGenerator.Serialize(sdt, tempFile,
566        new Configuration(new XmlFormat(),
567          new List<IPrimitiveSerializer> { new String2XmlSerializer() },
568          new List<ICompositeSerializer> {
569            new StorableSerializer(),
570            new Number2StringSerializer() }));
571      object o = XmlParser.Deserialize(tempFile);
572      Assert.AreEqual(
573        DebugStringGenerator.Serialize(sdt),
574        DebugStringGenerator.Serialize(o));
575      Assert.IsTrue(sdt.Equals(o));
576    }
577
578    [TestMethod]
579    public void Enums() {
580      EnumTest et = new EnumTest();
581      et.simpleEnum = SimpleEnum.two;
582      et.complexEnum = ComplexEnum.three;
583      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
584      XmlGenerator.Serialize(et, tempFile);
585      EnumTest newEt = (EnumTest)XmlParser.Deserialize(tempFile);
586      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
587      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
588      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
589    }
590
591    [TestMethod]
592    public void TestAliasingWithOverriddenEquals() {
593      List<IntWrapper> ints = new List<IntWrapper>();
594      ints.Add(new IntWrapper(1));
595      ints.Add(new IntWrapper(1));
596      Assert.AreEqual(ints[0], ints[1]);
597      Assert.AreNotSame(ints[0], ints[1]);
598      XmlGenerator.Serialize(ints, tempFile);
599      List<IntWrapper> newInts = (List<IntWrapper>)XmlParser.Deserialize(tempFile);
600      Assert.AreEqual(newInts[0].Value, 1);
601      Assert.AreEqual(newInts[1].Value, 1);
602      Assert.AreEqual(newInts[0], newInts[1]);
603      Assert.AreNotSame(newInts[0], newInts[1]);
604    }
605
606    [TestMethod]
607    public void NonDefaultConstructorTest() {
608      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
609      try {
610        XmlGenerator.Serialize(c, tempFile);
611        Assert.Fail("Exception not thrown");
612      }
613      catch (PersistenceException) {
614      }
615    }
616
617    [TestMethod]
618    public void TestSavingException() {
619      List<int> list = new List<int> { 1, 2, 3 };
620      XmlGenerator.Serialize(list, tempFile);
621      NonSerializable s = new NonSerializable();
622      try {
623        XmlGenerator.Serialize(s, tempFile);
624        Assert.Fail("Exception expected");
625      }
626      catch (PersistenceException) { }
627      List<int> newList = (List<int>)XmlParser.Deserialize(tempFile);
628      Assert.AreEqual(list[0], newList[0]);
629      Assert.AreEqual(list[1], newList[1]);
630    }
631
632    [TestMethod]
633    public void TestTypeStringConversion() {
634      string name = typeof(List<int>[]).AssemblyQualifiedName;
635      string shortName =
636        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
637      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
638      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
639      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
640    }
641
642    [TestMethod]
643    public void TestHexadecimalPublicKeyToken() {
644      string name = "TestClass, TestAssembly, Version=1.2.3.4, PublicKey=1234abc";
645      string shortName = "TestClass, TestAssembly";
646      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
647      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
648    }
649
650    [TestMethod]
651    public void TestMultipleFailure() {
652      List<NonSerializable> l = new List<NonSerializable>();
653      l.Add(new NonSerializable());
654      l.Add(new NonSerializable());
655      l.Add(new NonSerializable());
656      try {
657        Serializer s = new Serializer(l,
658          ConfigurationService.Instance.GetConfiguration(new XmlFormat()),
659          "ROOT", true);
660        StringBuilder tokens = new StringBuilder();
661        foreach (var token in s) {
662          tokens.Append(token.ToString());
663        }
664        Assert.Fail("Exception expected");
665      }
666      catch (PersistenceException px) {
667        Assert.AreEqual(3, px.Data.Count);
668      }
669    }
670
671    [TestMethod]
672    public void TestAssemblyVersionCheck() {
673      IntWrapper i = new IntWrapper(1);
674      Serializer s = new Serializer(i, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
675      XmlGenerator g = new XmlGenerator();
676      StringBuilder dataString = new StringBuilder();
677      foreach (var token in s) {
678        dataString.Append(g.Format(token));
679      }
680      StringBuilder typeString = new StringBuilder();
681      foreach (var line in g.Format(s.TypeCache))
682        typeString.Append(line);
683      Deserializer d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(typeString.ToString())));
684      XmlParser p = new XmlParser(new StringReader(dataString.ToString()));
685      IntWrapper newI = (IntWrapper)d.Deserialize(p);
686      Assert.AreEqual(i.Value, newI.Value);
687
688      string newTypeString = Regex.Replace(typeString.ToString(),
689        "Version=\\d+\\.\\d+\\.\\d+\\.\\d+",
690        "Version=0.0.9999.9999");
691      try {
692        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
693        Assert.Fail("Exception expected");
694      }
695      catch (PersistenceException x) {
696        Assert.IsTrue(x.Message.Contains("incompatible"));
697      }
698      newTypeString = Regex.Replace(typeString.ToString(),
699        "Version=(\\d+\\.\\d+)\\.\\d+\\.\\d+",
700        "Version=$1.9999.9999");
701      try {
702        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
703        Assert.Fail("Exception expected");
704      }
705      catch (PersistenceException x) {
706        Assert.IsTrue(x.Message.Contains("newer"));
707      }
708    }
709
710    [TestMethod]
711    public void InheritanceTest() {
712      New n = new New();
713      XmlGenerator.Serialize(n, tempFile);
714      New nn = (New)XmlParser.Deserialize(tempFile);
715      Assert.AreEqual(n.Name, nn.Name);
716      Assert.AreEqual(((Override)n).Name, ((Override)nn).Name);
717    }
718
719    [StorableClass]
720    class Child {
721      [Storable]
722      public GrandParent grandParent;
723    }
724
725    [StorableClass]
726    class Parent {
727      [Storable]
728      public Child child;
729    }
730
731    [StorableClass]
732    class GrandParent {
733      [Storable]
734      public Parent parent;
735    }
736
737    [TestMethod]
738    public void InstantiateParentChainReference() {
739      GrandParent gp = new GrandParent();
740      gp.parent = new Parent();
741      gp.parent.child = new Child();
742      gp.parent.child.grandParent = gp;
743      Assert.AreSame(gp, gp.parent.child.grandParent);
744      XmlGenerator.Serialize(gp, tempFile);
745      GrandParent newGp = (GrandParent)XmlParser.Deserialize(tempFile);
746      Assert.AreSame(newGp, newGp.parent.child.grandParent);
747    }
748
749    struct TestStruct {
750      int value;
751      int PropertyValue { get; set; }
752      public TestStruct(int value)
753        : this() {
754        this.value = value;
755        PropertyValue = value;
756      }
757    }
758
759    [TestMethod]
760    public void StructTest() {
761      TestStruct s = new TestStruct(10);
762      XmlGenerator.Serialize(s, tempFile);
763      TestStruct newS = (TestStruct)XmlParser.Deserialize(tempFile);
764      Assert.AreEqual(s, newS);
765    }
766
767    [TestMethod]
768    public void PointTest() {
769      Point p = new Point(12, 34);
770      XmlGenerator.Serialize(p, tempFile);
771      Point newP = (Point)XmlParser.Deserialize(tempFile);
772      Assert.AreEqual(p, newP);
773    }
774
775    [TestMethod]
776    public void NullableValueTypes() {
777      double?[] d = new double?[] { null, 1, 2, 3 };
778      XmlGenerator.Serialize(d, tempFile);
779      double?[] newD = (double?[])XmlParser.Deserialize(tempFile);
780      Assert.AreEqual(d[0], newD[0]);
781      Assert.AreEqual(d[1], newD[1]);
782      Assert.AreEqual(d[2], newD[2]);
783      Assert.AreEqual(d[3], newD[3]);
784    }
785
786    [TestMethod]
787    public void BitmapTest() {
788      Icon icon = System.Drawing.SystemIcons.Hand;
789      Bitmap bitmap = icon.ToBitmap();
790      XmlGenerator.Serialize(bitmap, tempFile);
791      Bitmap newBitmap = (Bitmap)XmlParser.Deserialize(tempFile);
792
793      Assert.AreEqual(bitmap.Size, newBitmap.Size);
794      for (int i = 0; i < bitmap.Size.Width; i++)
795        for (int j = 0; j < bitmap.Size.Height; j++)
796          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
797    }
798
799    [StorableClass]
800    private class PersistenceHooks {
801      [Storable]
802      public int a;
803      [Storable]
804      public int b;
805      public int sum;
806      public bool WasSerialized { get; private set; }
807      [StorableHook(HookType.BeforeSerialization)]
808      void PreSerializationHook() {
809        WasSerialized = true;
810      }
811      [StorableHook(HookType.AfterDeserialization)]
812      void PostDeserializationHook() {
813        sum = a + b;
814      }
815    }
816
817    [TestMethod]
818    public void HookTest() {
819      PersistenceHooks hookTest = new PersistenceHooks();
820      hookTest.a = 2;
821      hookTest.b = 5;
822      Assert.IsFalse(hookTest.WasSerialized);
823      Assert.AreEqual(hookTest.sum, 0);
824      XmlGenerator.Serialize(hookTest, tempFile);
825      Assert.IsTrue(hookTest.WasSerialized);
826      Assert.AreEqual(hookTest.sum, 0);
827      PersistenceHooks newHookTest = (PersistenceHooks)XmlParser.Deserialize(tempFile);
828      Assert.AreEqual(newHookTest.a, hookTest.a);
829      Assert.AreEqual(newHookTest.b, hookTest.b);
830      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
831      Assert.IsFalse(newHookTest.WasSerialized);
832    }
833
834    [StorableClass]
835    private class CustomConstructor {
836      public string Value = "none";
837      public CustomConstructor() {
838        Value = "default";
839      }
840      [StorableConstructor]
841      private CustomConstructor(bool deserializing) {
842        Assert.IsTrue(deserializing);
843        Value = "persistence";
844      }
845    }
846
847    [TestMethod]
848    public void TestCustomConstructor() {
849      CustomConstructor cc = new CustomConstructor();
850      Assert.AreEqual(cc.Value, "default");
851      XmlGenerator.Serialize(cc, tempFile);
852      CustomConstructor newCC = (CustomConstructor)XmlParser.Deserialize(tempFile);
853      Assert.AreEqual(newCC.Value, "persistence");
854    }
855
856    [StorableClass]
857    public class ExplodingDefaultConstructor {
858      public ExplodingDefaultConstructor() {
859        throw new Exception("this constructor will always fail");
860      }
861      public ExplodingDefaultConstructor(string password) {
862      }
863    }
864
865    [TestMethod]
866    public void TestConstructorExceptionUnwrapping() {
867      ExplodingDefaultConstructor x = new ExplodingDefaultConstructor("password");
868      XmlGenerator.Serialize(x, tempFile);
869      try {
870        ExplodingDefaultConstructor newX = (ExplodingDefaultConstructor)XmlParser.Deserialize(tempFile);
871        Assert.Fail("Exception expected");
872      }
873      catch (PersistenceException pe) {
874        Assert.AreEqual(pe.InnerException.Message, "this constructor will always fail");
875      }
876    }
877
878    [TestMethod]
879    public void TestRejectionJustifications() {
880      NonSerializable ns = new NonSerializable();
881      try {
882        XmlGenerator.Serialize(ns, tempFile);
883        Assert.Fail("PersistenceException expected");
884      }
885      catch (PersistenceException x) {
886        Assert.IsTrue(x.Message.Contains(new StorableSerializer().JustifyRejection(typeof(NonSerializable))));
887      }
888    }
889
890    [TestMethod]
891    public void TestStreaming() {
892      using (MemoryStream stream = new MemoryStream()) {
893        Root r = InitializeComplexStorable();
894        XmlGenerator.Serialize(r, stream);
895        using (MemoryStream stream2 = new MemoryStream(stream.ToArray())) {
896          Root newR = (Root)XmlParser.Deserialize(stream2);
897          CompareComplexStorables(r, newR);
898        }
899      }
900    }
901
902    [StorableClass]
903    public class HookInheritanceTestBase {
904      [Storable]
905      public object a;
906      public object link;
907      [StorableHook(HookType.AfterDeserialization)]
908      private void relink() {
909        link = a;
910      }
911    }
912
913    [StorableClass]
914    public class HookInheritanceTestDerivedClass : HookInheritanceTestBase {
915      [Storable]
916      public object b;
917      [StorableHook(HookType.AfterDeserialization)]
918      private void relink() {
919        Assert.AreSame(a, link);
920        link = b;
921      }
922    }
923
924    [TestMethod]
925    public void TestLinkInheritance() {
926      HookInheritanceTestDerivedClass c = new HookInheritanceTestDerivedClass();
927      c.a = new object();
928      XmlGenerator.Serialize(c, tempFile);
929      HookInheritanceTestDerivedClass newC = (HookInheritanceTestDerivedClass)XmlParser.Deserialize(tempFile);
930      Assert.AreSame(c.b, c.link);
931    }
932
933    [StorableClass(StorableClassType.AllFields)]
934    public class AllFieldsStorable {
935      public int Value1 = 1;
936      [Storable]
937      public int Value2 = 2;
938      public int Value3 { get; private set; }
939      public int Value4 { get; private set; }
940      [StorableConstructor]
941      public AllFieldsStorable(bool isDeserializing) {
942        if (!isDeserializing) {
943          Value1 = 12;
944          Value2 = 23;
945          Value3 = 34;
946          Value4 = 56;
947        }
948      }
949    }
950
951    [TestMethod]
952    public void TestStorableClassDiscoveryAllFields() {
953      AllFieldsStorable afs = new AllFieldsStorable(false);
954      XmlGenerator.Serialize(afs, tempFile);
955      AllFieldsStorable newAfs = (AllFieldsStorable)XmlParser.Deserialize(tempFile);
956      Assert.AreEqual(afs.Value1, newAfs.Value1);
957      Assert.AreEqual(afs.Value2, newAfs.Value2);
958      Assert.AreEqual(0, newAfs.Value3);
959      Assert.AreEqual(0, newAfs.Value4);
960    }
961
962    [StorableClass(StorableClassType.AllProperties)]
963    public class AllPropertiesStorable {
964      public int Value1 = 1;
965      [Storable]
966      public int Value2 = 2;
967      public int Value3 { get; private set; }
968      public int Value4 { get; private set; }
969      [StorableConstructor]
970      public AllPropertiesStorable(bool isDeserializing) {
971        if (!isDeserializing) {
972          Value1 = 12;
973          Value2 = 23;
974          Value3 = 34;
975          Value4 = 56;
976        }
977      }
978    }
979
980    [TestMethod]
981    public void TestStorableClassDiscoveryAllProperties() {
982      AllPropertiesStorable afs = new AllPropertiesStorable(false);
983      XmlGenerator.Serialize(afs, tempFile);
984      AllPropertiesStorable newAfs = (AllPropertiesStorable)XmlParser.Deserialize(tempFile);
985      Assert.AreEqual(1, newAfs.Value1);
986      Assert.AreEqual(2, newAfs.Value2);
987      Assert.AreEqual(afs.Value3, newAfs.Value3);
988      Assert.AreEqual(afs.Value4, newAfs.Value4);
989
990    }
991
992    [StorableClass(StorableClassType.AllFieldsAndAllProperties)]
993    public class AllFieldsAndAllPropertiesStorable {
994      public int Value1 = 1;
995      [Storable]
996      public int Value2 = 2;
997      public int Value3 { get; private set; }
998      public int Value4 { get; private set; }
999      [StorableConstructor]
1000      public AllFieldsAndAllPropertiesStorable(bool isDeserializing) {
1001        if (!isDeserializing) {
1002          Value1 = 12;
1003          Value2 = 23;
1004          Value3 = 34;
1005          Value4 = 56;
1006        }
1007      }
1008    }
1009
1010    [TestMethod]
1011    public void TestStorableClassDiscoveryAllFieldsAndAllProperties() {
1012      AllFieldsAndAllPropertiesStorable afs = new AllFieldsAndAllPropertiesStorable(false);
1013      XmlGenerator.Serialize(afs, tempFile);
1014      AllFieldsAndAllPropertiesStorable newAfs = (AllFieldsAndAllPropertiesStorable)XmlParser.Deserialize(tempFile);
1015      Assert.AreEqual(afs.Value1, newAfs.Value1);
1016      Assert.AreEqual(afs.Value2, newAfs.Value2);
1017      Assert.AreEqual(afs.Value3, newAfs.Value3);
1018      Assert.AreEqual(afs.Value4, newAfs.Value4);
1019    }
1020
1021    [StorableClass(StorableClassType.MarkedOnly)]
1022    public class MarkedOnlyStorable {
1023      public int Value1 = 1;
1024      [Storable]
1025      public int Value2 = 2;
1026      public int Value3 { get; private set; }
1027      public int Value4 { get; private set; }
1028      [StorableConstructor]
1029      public MarkedOnlyStorable(bool isDeserializing) {
1030        if (!isDeserializing) {
1031          Value1 = 12;
1032          Value2 = 23;
1033          Value3 = 34;
1034          Value4 = 56;
1035        }
1036      }
1037    }
1038
1039    [TestMethod]
1040    public void TestStorableClassDiscoveryMarkedOnly() {
1041      MarkedOnlyStorable afs = new MarkedOnlyStorable(false);
1042      XmlGenerator.Serialize(afs, tempFile);
1043      MarkedOnlyStorable newAfs = (MarkedOnlyStorable)XmlParser.Deserialize(tempFile);
1044      Assert.AreEqual(1, newAfs.Value1);
1045      Assert.AreEqual(afs.Value2, newAfs.Value2);
1046      Assert.AreEqual(0, newAfs.Value3);
1047      Assert.AreEqual(0, newAfs.Value4);
1048    }
1049
1050    [TestMethod]
1051    public void TestLineEndings() {
1052      List<string> lineBreaks = new List<string> { "\r\n", "\n", "\r", "\n\r", Environment.NewLine };
1053      List<string> lines = new List<string>();
1054      foreach (var br in lineBreaks)
1055        lines.Add("line1" + br + "line2");
1056      XmlGenerator.Serialize(lines, tempFile);
1057      List<string> newLines = XmlParser.Deserialize<List<string>>(tempFile);
1058      Assert.AreEqual(lines.Count, newLines.Count);
1059      for (int i = 0; i < lineBreaks.Count; i++) {
1060        Assert.AreEqual(lines[i], newLines[i]);
1061      }
1062    }
1063
1064    [TestMethod]
1065    public void TestSpecialNumbers() {
1066      List<double> specials = new List<double>() { 1.0 / 0, -1.0 / 0, 0.0 / 0 };
1067      Assert.IsTrue(double.IsPositiveInfinity(specials[0]));
1068      Assert.IsTrue(double.IsNegativeInfinity(specials[1]));
1069      Assert.IsTrue(double.IsNaN(specials[2]));
1070      XmlGenerator.Serialize(specials, tempFile);
1071      List<double> newSpecials = XmlParser.Deserialize<List<double>>(tempFile);
1072      Assert.IsTrue(double.IsPositiveInfinity(newSpecials[0]));
1073      Assert.IsTrue(double.IsNegativeInfinity(newSpecials[1]));
1074      Assert.IsTrue(double.IsNaN(newSpecials[2]));
1075    }
1076
1077    [TestMethod]
1078    public void TestStringSplit() {
1079      string s = "1.2;2.3;3.4;;;4.9";
1080      var l = s.EnumerateSplit(';').ToList();
1081      Assert.AreEqual("1.2", l[0]);
1082      Assert.AreEqual("2.3", l[1]);
1083      Assert.AreEqual("3.4", l[2]);
1084      Assert.AreEqual("4.9", l[3]);
1085    }
1086
1087    [TestMethod]
1088    public void TestCompactNumberArraySerializer() {
1089      System.Random r = new System.Random();
1090      double[] a = new double[CompactNumberArray2StringSerializer.SPLIT_THRESHOLD * 2 + 1];
1091      for (int i = 0; i < a.Length; i++)
1092        a[i] = r.Next(10);
1093      var config = ConfigurationService.Instance.GetDefaultConfig(new XmlFormat());
1094      config = new Configuration(config.Format,
1095        config.PrimitiveSerializers.Where(s => s.SourceType != typeof(double[])),
1096        config.CompositeSerializers);
1097      XmlGenerator.Serialize(a, tempFile, config);
1098      double[] newA = XmlParser.Deserialize<double[]>(tempFile);
1099      Assert.AreEqual(a.Length, newA.Length);
1100      for (int i = 0; i < a.Rank; i++) {
1101        Assert.AreEqual(a.GetLength(i), newA.GetLength(i));
1102        Assert.AreEqual(a.GetLowerBound(i), newA.GetLowerBound(i));
1103      }
1104      for (int i = 0; i < a.Length; i++) {
1105        Assert.AreEqual(a[i], newA[i]);
1106      }
1107    }
1108    private class IdentityComparer<T> : IEqualityComparer<T> {
1109
1110      public bool Equals(T x, T y) {
1111        return x.Equals(y);
1112      }
1113
1114      public int GetHashCode(T obj) {
1115        return obj.GetHashCode();
1116      }
1117    }
1118
1119    [TestMethod]
1120    public void TestHashSetSerializer() {
1121      var hashSets = new List<HashSet<int>>() {
1122        new HashSet<int>(new[] { 1, 2, 3 }),
1123        new HashSet<int>(new[] { 4, 5, 6 }, new IdentityComparer<int>()),
1124      };
1125      XmlGenerator.Serialize(hashSets, tempFile);
1126      var newHashSets = XmlParser.Deserialize<List<HashSet<int>>>(tempFile);
1127      Assert.IsTrue(newHashSets[0].Contains(1));
1128      Assert.IsTrue(newHashSets[0].Contains(2));
1129      Assert.IsTrue(newHashSets[0].Contains(3));
1130      Assert.IsTrue(newHashSets[1].Contains(4));
1131      Assert.IsTrue(newHashSets[1].Contains(5));
1132      Assert.IsTrue(newHashSets[1].Contains(6));
1133      Assert.AreEqual(newHashSets[0].Comparer.GetType(), new HashSet<int>().Comparer.GetType());
1134      Assert.AreEqual(newHashSets[1].Comparer.GetType(), typeof(IdentityComparer<int>));
1135    }
1136
1137    [TestMethod]
1138    public void TestConcreteDictionarySerializer() {
1139      var dictionaries = new List<Dictionary<int, int>>() {
1140        new Dictionary<int, int>(),
1141        new Dictionary<int, int>(new IdentityComparer<int>()),
1142      };
1143      dictionaries[0].Add(1, 1);
1144      dictionaries[0].Add(2, 2);
1145      dictionaries[0].Add(3, 3);
1146      dictionaries[1].Add(4, 4);
1147      dictionaries[1].Add(5, 5);
1148      dictionaries[1].Add(6, 6);
1149      XmlGenerator.Serialize(dictionaries, tempFile, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
1150      var newDictionaries = XmlParser.Deserialize<List<Dictionary<int, int>>>(tempFile);
1151      Assert.IsTrue(newDictionaries[0].ContainsKey(1));
1152      Assert.IsTrue(newDictionaries[0].ContainsKey(2));
1153      Assert.IsTrue(newDictionaries[0].ContainsKey(3));
1154      Assert.IsTrue(newDictionaries[1].ContainsKey(4));
1155      Assert.IsTrue(newDictionaries[1].ContainsKey(5));
1156      Assert.IsTrue(newDictionaries[1].ContainsKey(6));
1157      Assert.IsTrue(newDictionaries[0].ContainsValue(1));
1158      Assert.IsTrue(newDictionaries[0].ContainsValue(2));
1159      Assert.IsTrue(newDictionaries[0].ContainsValue(3));
1160      Assert.IsTrue(newDictionaries[1].ContainsValue(4));
1161      Assert.IsTrue(newDictionaries[1].ContainsValue(5));
1162      Assert.IsTrue(newDictionaries[1].ContainsValue(6));
1163      Assert.AreEqual(new Dictionary<int, int>().Comparer.GetType(), newDictionaries[0].Comparer.GetType());
1164      Assert.AreEqual(typeof(IdentityComparer<int>), newDictionaries[1].Comparer.GetType());
1165    }
1166
1167    [StorableClass]
1168    public class ReadOnlyFail {
1169      [Storable]
1170      public string ReadOnly {
1171        get { return "fail"; }
1172      }
1173    }
1174
1175    [TestMethod]
1176    public void TestReadOnlyFail() {
1177      try {
1178        XmlGenerator.Serialize(new ReadOnlyFail(), tempFile);
1179        Assert.Fail("Exception expected");
1180      }
1181      catch (PersistenceException) {
1182      }
1183      catch {
1184        Assert.Fail("PersistenceException expected");
1185      }
1186    }
1187
1188
1189    [StorableClass]
1190    public class WriteOnlyFail {
1191      [Storable]
1192      public string WriteOnly {
1193        set { throw new InvalidOperationException("this property should never be set."); }
1194      }
1195    }
1196
1197    [TestMethod]
1198    public void TestWriteOnlyFail() {
1199      try {
1200        XmlGenerator.Serialize(new WriteOnlyFail(), tempFile);
1201        Assert.Fail("Exception expected");
1202      }
1203      catch (PersistenceException) {
1204      }
1205      catch {
1206        Assert.Fail("PersistenceException expected.");
1207      }
1208    }
1209
1210    [StorableClass]
1211    public class OneWayTest {
1212      public OneWayTest() { this.value = "default"; }
1213      public string value;
1214      [Storable(AllowOneWay = true)]
1215      public string ReadOnly {
1216        get { return "ReadOnly"; }
1217      }
1218      [Storable(AllowOneWay = true)]
1219      public string WriteOnly {
1220        set { this.value = value; }
1221      }
1222    }
1223
1224    [TestMethod]
1225    public void TestOneWaySerialization() {
1226      var test = new OneWayTest();
1227      var serializer = new Serializer(test, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
1228      var it = serializer.GetEnumerator();
1229      it.MoveNext();
1230      Assert.AreEqual("ROOT", ((BeginToken)it.Current).Name); it.MoveNext();
1231      Assert.AreEqual("ReadOnly", ((PrimitiveToken)it.Current).Name); it.MoveNext();
1232      Assert.AreEqual("ROOT", ((EndToken)it.Current).Name); it.MoveNext();
1233      var deserializer = new Deserializer(new[] {
1234        new TypeMapping(0, typeof(OneWayTest).AssemblyQualifiedName, typeof(StorableSerializer).AssemblyQualifiedName),
1235        new TypeMapping(1, typeof(string).AssemblyQualifiedName, typeof(String2XmlSerializer).AssemblyQualifiedName) });
1236      var newTest = (OneWayTest)deserializer.Deserialize(new ISerializationToken[] {
1237        new BeginToken("ROOT", 0, 0),
1238        new PrimitiveToken("WriteOnly", 1, 1, new XmlString("<![CDATA[serial data]]>")),
1239        new EndToken("ROOT", 0, 0)
1240      });
1241      Assert.AreEqual("serial data", newTest.value);
1242    }
1243
1244    [TestMethod]
1245    public void TestTypeCacheExport() {
1246      var test = new List<List<int>>();
1247      test.Add(new List<int>() { 1, 2, 3 });
1248      IEnumerable<Type> types;
1249      using (var stream = new MemoryStream()) {
1250        XmlGenerator.Serialize(test, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, out types);
1251      }
1252      List<Type> t = new List<Type>(types);
1253      // Assert.IsTrue(t.Contains(typeof(int))); not serialized as an int list is directly transformed into a string
1254      Assert.IsTrue(t.Contains(typeof(List<int>)));
1255      Assert.IsTrue(t.Contains(typeof(List<List<int>>)));
1256      Assert.AreEqual(t.Count, 2);
1257    }
1258
1259    [TestMethod]
1260    public void TupleTest() {
1261      var t1 = Tuple.Create(1);
1262      var t2 = Tuple.Create('1', "2");
1263      var t3 = Tuple.Create(3.0, 3f, 5);
1264      var t4 = Tuple.Create(Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6), Tuple.Create(8, 9, 10));
1265      var tuple = Tuple.Create(t1, t2, t3, t4);
1266      XmlGenerator.Serialize(tuple, tempFile);
1267      var newTuple = XmlParser.Deserialize<Tuple<Tuple<int>, Tuple<char, string>, Tuple<double, float, int>, Tuple<Tuple<int, int, int>, Tuple<int, int, int>, Tuple<int, int, int>>>>(tempFile);
1268      Assert.AreEqual(tuple, newTuple);
1269    }
1270
1271    [TestMethod]
1272    public void FontTest() {
1273      List<Font> fonts = new List<Font>() {
1274        new Font(FontFamily.GenericSansSerif, 12),
1275        new Font("Times New Roman", 21, FontStyle.Bold, GraphicsUnit.Pixel),
1276        new Font("Courier New", 10, FontStyle.Underline, GraphicsUnit.Document),
1277        new Font("Helvetica", 21, FontStyle.Strikeout, GraphicsUnit.Inch, 0, true),
1278      };
1279      XmlGenerator.Serialize(fonts, tempFile);
1280      var newFonts = XmlParser.Deserialize<List<Font>>(tempFile);
1281      Assert.AreEqual(fonts[0], newFonts[0]);
1282      Assert.AreEqual(fonts[1], newFonts[1]);
1283      Assert.AreEqual(fonts[2], newFonts[2]);
1284      Assert.AreEqual(fonts[3], newFonts[3]);
1285    }
1286
1287    [TestMethod]
1288    public void ConcurrencyTest() {
1289      int n = 20;
1290      Task[] tasks = new Task[n];
1291      for (int i = 0; i < n; i++) {
1292        tasks[i] = Task.Factory.StartNew((idx) => {
1293          byte[] data;
1294          using (var stream = new MemoryStream()) {
1295            XmlGenerator.Serialize(new GeneticAlgorithm(), stream);
1296            data = stream.ToArray();
1297          }
1298        }, i);
1299      }
1300      Task.WaitAll(tasks);
1301    }
1302
1303    [TestMethod]
1304    public void ConcurrentBitmapTest() {
1305      Bitmap b = new Bitmap(300, 300);
1306      System.Random r = new System.Random();
1307      for (int x = 0; x < b.Height; x++) {
1308        for (int y = 0; y < b.Width; y++) {
1309          b.SetPixel(x, y, Color.FromArgb(r.Next()));
1310        }
1311      }
1312      Task[] tasks = new Task[20];
1313      byte[][] datas = new byte[tasks.Length][];
1314      for (int i = 0; i < tasks.Length; i++) {
1315        tasks[i] = Task.Factory.StartNew((idx) => {
1316          using (var stream = new MemoryStream()) {
1317            XmlGenerator.Serialize(b, stream);
1318            datas[(int)idx] = stream.ToArray();
1319          }
1320        }, i);
1321      }
1322      Task.WaitAll(tasks);
1323    }
1324
1325    public class G<T,T2> {
1326      public class S {}
1327      public class S2<T3,T4> {}
1328    }
1329
1330    [TestMethod]
1331    public void TestInternalClassOfGeneric() {
1332      var s = new G<int, char>.S();
1333      var typeName = s.GetType().AssemblyQualifiedName;
1334      Assert.AreEqual(
1335        "UseCases.G<Int32,Char>.S",
1336        TypeNameParser.Parse(typeName).GetTypeNameInCode(false));
1337      XmlGenerator.Serialize(s, tempFile);
1338      var s1 = XmlParser.Deserialize(tempFile);
1339    }
1340
1341    [TestMethod]
1342    public void TestInternalClassOfGeneric2() {
1343      var s = new G<int, float>.S2<int, char>();
1344      var typeName = s.GetType().AssemblyQualifiedName;
1345      Assert.AreEqual(
1346        "UseCases.G<Int32,Single>.S2<Int32,Char>",
1347        TypeNameParser.Parse(typeName).GetTypeNameInCode(false));
1348      XmlGenerator.Serialize(s, tempFile);
1349      var s1 = XmlParser.Deserialize(tempFile);
1350    }
1351
1352    [ClassInitialize]
1353    public static void Initialize(TestContext testContext) {
1354      ConfigurationService.Instance.Reset();
1355    }
1356  }
1357}
Note: See TracBrowser for help on using the repository browser.